Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/tests/test_findings_actions.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 19 minutes ago History
test_findings_actions.py · 47.0 KB · 1056 lines
1"""Reproductions of suspected bugs in ACTION objects.
2
3Source: config-inventory/hooks-actions.md (read-only inventory), then
4verified here by running the real action objects against a tmp data dir.
5
6Convention: every test asserts the CORRECT behaviour. A finding that is real
7is marked ``xfail(strict=True)`` with the reason it fails today, so the suite
8is green now and fails loudly the day it is fixed. A finding that is refuted
9is a plain passing test that pins the correct behaviour. Races are made
10deterministic by running the second request INSIDE a monkeypatched write of
11the first (no threads, no sleeps): the patched call is the exact point between
12"read" and "write" at which the interleaving happens.
13
14Nothing here touches the network; external clients are stubbed.
15"""
16
17import json
18import pathlib
19import shutil
20
21import pytest
22from conftest import stage_collection
23
24import object_execution
25import object_ids
26import object_records
27import python_object_runtime
28
29REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
30PACKAGES = REPO_ROOT / "packages"
31RUNTIME = python_object_runtime.PythonObjectRuntime()
32
33
34def install(tmp_path, monkeypatch, collections, packages, settings=()):
35 """A data dir with the named collections, and ONE object root holding
36 every named package's objects (what an installed server looks like)."""
37 data_dir = tmp_path / "data"
38 for pkg, name in collections:
39 stage_collection(data_dir, pkg, name)
40 rows = "".join(f"s{i}\t{k}\t{v}\t\n" for i, (k, v) in enumerate(settings))
41 stage_collection(data_dir, "app-settings", "app_settings", rows=rows)
42 objects_root = tmp_path / "objects"
43 for pkg in packages:
44 shutil.copytree(PACKAGES / pkg / "objects", objects_root,
45 dirs_exist_ok=True)
46 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
47 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root))
48 return data_dir, objects_root
49
50
51def run(objects_root, object_id, payload, method="POST"):
52 return object_execution.execute_object(
53 RUNTIME,
54 object_execution.ObjectExecutionRequest(
55 object_id, method=method, payload=payload),
56 roots=[objects_root]).result
57
58
59def rows(data_dir, collection):
60 return object_records.read_collection_records(collection, base_dir=data_dir)
61
62
63def make(data_dir, collection, **fields):
64 fields.setdefault("id", object_ids.new_uuid4())
65 return object_records.create_collection_record(
66 collection, {k: str(v) for k, v in fields.items()}, base_dir=data_dir)
67
68
69def interleave_once(monkeypatch, collection, fn_name, inner, when=None):
70 """Patch object_records.<fn_name>: the first time it is called for
71 `collection` (and `when(args, kwargs)` holds), run `inner()` BEFORE
72 performing the real call. Returns a list that receives inner()'s result.
73 """
74 real = getattr(object_records, fn_name)
75 seen = []
76 state = {"active": False}
77
78 def wrapper(coll, *args, **kwargs):
79 if (coll == collection and not state["active"] and not seen
80 and (when is None or when(args, kwargs))):
81 state["active"] = True
82 try:
83 seen.append(inner())
84 finally:
85 state["active"] = False
86 return real(coll, *args, **kwargs)
87
88 monkeypatch.setattr(object_records, fn_name, wrapper)
89 return seen
90
91
92# =============================================================================
93# 1. checkout
94# =============================================================================
95
96SHOP_COLLECTIONS = [
97 ("app-shop", "carts"), ("app-shop", "cart_items"),
98 ("app-catalog", "products"), ("app-catalog", "locations"),
99 ("app-catalog", "stock_moves"), ("app-catalog", "backorders"),
100 ("app-orders", "orders"), ("app-orders", "order_lines"),
101 ("app-invoices", "invoices"), ("app-invoices", "invoice_lines"),
102 ("app-payments", "payments"),
103 ("app-billing", "wallets"), ("app-billing", "wallet_entries"),
104 ("app-promotions", "promotions"), ("app-promotions", "promotion_redemptions"),
105 ("app-pickup", "pickup_slots"),
106]
107SHOP_PACKAGES = ["app-shop", "app-billing", "app-promotions", "app-pickup",
108 "app-orders"]
109TODAY = "2026-06-15"
110
111
112def shop(tmp_path, monkeypatch):
113 data_dir, root = install(tmp_path, monkeypatch, SHOP_COLLECTIONS,
114 SHOP_PACKAGES)
115 make(data_dir, "locations", id="loc-shelf", name="Shelf",
116 location_type="warehouse", owner_id="shop")
117 make(data_dir, "products", id="p1", name="Mug", sku="P1",
118 product_type="service", price_cents=1000, currency="USD",
119 is_active="true", owner_id="shop")
120 return data_dir, root
121
122
123def add_to_cart(root, token, quantity="1"):
124 return run(root, "action_cart", {"session_token": token, "action": "add",
125 "product_id": "p1", "quantity": quantity})
126
127
128def checkout(root, token, **payload):
129 payload.setdefault("today", TODAY)
130 payload.setdefault("customer_email", "buyer@example.test")
131 return run(root, "action_checkout", {"session_token": token, **payload})
132
133
134def test_two_submits_of_one_cart_create_exactly_one_order(tmp_path, monkeypatch):
135 """A double click: submit B reads the cart between submit A's read and
136 A's stamp. Both see an open cart. B is run inside A's cart-stamp write."""
137 data_dir, root = shop(tmp_path, monkeypatch)
138 add_to_cart(root, "tok-1", "2")
139
140 inner = interleave_once(
141 monkeypatch, "carts", "update_collection_record",
142 lambda: checkout(root, "tok-1"),
143 when=lambda a, k: a[1].get("status") == "checked_out")
144 first = checkout(root, "tok-1")
145
146 assert first["ok"] is True and inner, "interleave did not fire"
147 # Both submits must have been served by the SAME order.
148 assert len(rows(data_dir, "orders")) == 1, (
149 f"{len(rows(data_dir, 'orders'))} orders, "
150 f"{len(rows(data_dir, 'invoices'))} invoices for one cart")
151 assert len(rows(data_dir, "invoices")) == 1
152
153
154def test_a_sequential_resubmit_of_one_cart_is_a_no_op(tmp_path, monkeypatch):
155 """The guard that DOES work: a resubmit AFTER the stamp lands is
156 answered with the original order (duplicate:true). The bug above is only
157 the window before the stamp."""
158 data_dir, root = shop(tmp_path, monkeypatch)
159 add_to_cart(root, "tok-1")
160 first = checkout(root, "tok-1")
161 second = checkout(root, "tok-1")
162 assert second["duplicate"] is True and second["order_id"] == first["order_id"]
163 assert len(rows(data_dir, "orders")) == 1
164
165
166def test_pickup_counter_loses_an_update_when_two_orders_book_one_slot(
167 tmp_path, monkeypatch):
168 """Two different shoppers book the same pickup window. The second order
169 is created while the first is between its read of orders_taken and its
170 write. orders_taken must end at 2: it is the only record of how many
171 orders hold the window."""
172 from datetime import datetime, timedelta
173 now = datetime(2026, 7, 27, 12, 0, 0)
174 data_dir, root = shop(tmp_path, monkeypatch)
175 make(data_dir, "pickup_slots", id="s1",
176 starts_at=(now + timedelta(minutes=60)).isoformat(),
177 ends_at=(now + timedelta(minutes=75)).isoformat(),
178 capacity=5, orders_taken=0, is_open="true", location_id="", owner_id="")
179 add_to_cart(root, "tok-a")
180 add_to_cart(root, "tok-b")
181 args = dict(fulfillment_method="pickup", pickup_slot_id="s1",
182 now=now.isoformat())
183
184 inner = interleave_once(
185 monkeypatch, "pickup_slots", "update_collection_record",
186 lambda: checkout(root, "tok-b", **args))
187 first = checkout(root, "tok-a", **args)
188
189 assert first["ok"] is True and inner and inner[0]["ok"] is True
190 assert len(rows(data_dir, "orders")) == 2
191 taken = rows(data_dir, "pickup_slots")[0]["orders_taken"]
192 assert taken == "2", f"two orders hold the slot but orders_taken={taken}"
193
194
195
196
197def gift_card_shop(tmp_path, monkeypatch, balance=1000):
198 data_dir, root = shop(tmp_path, monkeypatch)
199 make(data_dir, "wallets", id="gc1", owner_id="shop", kind="gift_card",
200 code="GC-TEST", is_active="true")
201 make(data_dir, "wallet_entries", id="seed", wallet_id="gc1",
202 amount_minor=balance, kind="topup", owner_id="shop")
203 add_to_cart(root, "tok-a") # 1000 each
204 add_to_cart(root, "tok-b")
205 return data_dir, root
206
207
208def balance(data_dir):
209 return sum(int(r["amount_minor"]) for r in rows(data_dir, "wallet_entries")
210 if r["wallet_id"] == "gc1")
211
212
213def test_a_gift_card_cannot_be_spent_twice_by_sequential_checkouts(
214 tmp_path, monkeypatch):
215 """REFUTED in the sequential case: the second checkout is refused by
216 hook_wallet_entries (which sums the ledger) and told it owes the lot."""
217 data_dir, root = gift_card_shop(tmp_path, monkeypatch)
218 a = checkout(root, "tok-a", gift_card_code="GC-TEST")
219 b = checkout(root, "tok-b", gift_card_code="GC-TEST")
220 assert a["gift_card_applied_cents"] == 1000
221 # B's gate already sees an empty card and refuses the code outright.
222 assert b["status"] == 409 and "nothing left" in " ".join(b["gift_card_problems"])
223 assert balance(data_dir) == 0
224
225
226def test_a_gift_card_cannot_be_spent_twice_by_racing_checkouts(
227 tmp_path, monkeypatch):
228 """Checkout B runs wholly between A's gate and A's debit write."""
229 data_dir, root = gift_card_shop(tmp_path, monkeypatch)
230 inner = interleave_once(
231 monkeypatch, "wallet_entries", "create_collection_record",
232 lambda: checkout(root, "tok-b", gift_card_code="GC-TEST"),
233 when=lambda a, k: a[0].get("kind") == "debit")
234 a = checkout(root, "tok-a", gift_card_code="GC-TEST")
235 assert inner and inner[0]["gift_card_applied_cents"] == 1000
236 assert a["gift_card_applied_cents"] in (0, 1000)
237 assert balance(data_dir) >= 0, f"card balance is {balance(data_dir)}"
238
239
240# =============================================================================
241# 2. confirm_scan
242# =============================================================================
243
244def intake(tmp_path, monkeypatch):
245 return install(tmp_path, monkeypatch,
246 [("app-intake", "scans"), ("app-finance", "expenses"),
247 ("app-projects", "projects")], ["app-intake"])
248
249
250def execute(root, object_id, payload, method="POST"):
251 """Like run() but returns the whole outcome, so an exception inside the
252 object is visible rather than reduced to None."""
253 return object_execution.execute_object(
254 RUNTIME,
255 object_execution.ObjectExecutionRequest(
256 object_id, method=method, payload=payload),
257 roots=[root])
258
259
260def test_retrying_confirm_on_a_scan_that_cannot_transition_books_one_expense(
261 tmp_path, monkeypatch):
262 """The scan is still `pending` (the reader has not run) and the person
263 types the amount in. The pending -> confirmed transition is illegal.
264 Whatever the response, a retry must not add a second expense for the
265 same scan. Fixed 2026-11-28: the action refuses before writing (409),
266 so the answer is no expense at all -- the original finding asserted
267 exactly one, which was the best a write-then-fail order could do; the
268 precondition accepted only a raised error, and the refusal is now a
269 409 that names the same illegal move."""
270 data_dir, root = intake(tmp_path, monkeypatch)
271 make(data_dir, "scans", id="sc1", filename="r.png", status="pending",
272 owner_id="dana", source="web", category_hint="receipt")
273 payload = {"scan_id": "sc1", "amount_cents": "1079",
274 "description": "Lunch", "incurred_on": "2026-06-15",
275 "_identity": {"user_id": "dana"}} # the scan's owner
276
277 outcomes = [execute(root, "action_confirm_scan", payload) for _ in range(3)]
278
279 scan = rows(data_dir, "scans")[0]
280 n = len(rows(data_dir, "expenses"))
281 assert scan["status"] == "pending" and scan["confirmed_record"] == "", (
282 "precondition: the scan transition did not happen")
283 assert all(o.ok and o.result.get("status") == 409
284 and "cannot move from 'pending' to 'confirmed'"
285 in o.result.get("error", "") for o in outcomes), (
286 "precondition: every attempt is refused on the scan transition")
287 assert n <= 1, f"{n} expenses for one scan after 3 attempts"
288 assert n == 0, "the refusal must come before the expense write"
289
290
291# =============================================================================
292# 3. disposition_return
293# =============================================================================
294# The scenario builders (a shop that sold three mugs, was paid, and got a
295# parcel back) are the ones tests/test_returns.py already uses; reuse them so
296# this file cannot drift from how the package is really installed.
297
298import test_returns as tr # noqa: E402
299
300
301def a_return(tmp_path, monkeypatch, **kwargs):
302 data_dir, root = tr.shop_with_a_return(tmp_path, monkeypatch, **kwargs)
303 created = tr.authorized_return(root)
304 assert created["ok"], created
305 tr.receive(data_dir, created["shipment_id"])
306 return data_dir, root, created
307
308
309def test_full_refund_of_a_discounted_line_is_what_was_paid(tmp_path, monkeypatch):
310 """3 mugs at 1200 with a 20% line discount: the customer paid 2880 (960
311 each). Returning one mug must refund 960, not 1200."""
312 data_dir, root = tr.shop_with_a_return(
313 tmp_path, monkeypatch,
314 line_fields={"discount_bps": "2000", "line_total_cents": "2880"},
315 paid_cents=2880)
316 created = tr.authorized_return(root)
317 tr.receive(data_dir, created["shipment_id"])
318
319 result = tr.dispositioned(root, data_dir, created, refund="full")
320 assert result["ok"] is True
321 assert result["refund_cents"] == "960", (
322 f"refunded {result['refund_cents']} for a unit that cost 960")
323
324
325def test_full_refund_of_a_line_with_a_modifier_includes_the_modifier(
326 tmp_path, monkeypatch):
327 """A latte at 1200 with oat milk +60 is sold at 1260. Refunding the
328 return gives back 1260 (or the customer is short-changed 60)."""
329 data_dir, root = tr.shop_with_a_return(
330 tmp_path, monkeypatch,
331 line_fields={"modifier_cents": "60", "line_total_cents": "3780"},
332 paid_cents=3780)
333 created = tr.authorized_return(root)
334 tr.receive(data_dir, created["shipment_id"])
335
336 result = tr.dispositioned(root, data_dir, created, refund="full")
337 assert result["ok"] is True
338 assert result["refund_cents"] == "1260", result["refund_cents"]
339
340
341def test_a_duplicated_shipment_line_does_not_double_the_refund(
342 tmp_path, monkeypatch):
343 """One mug came back (shipment line quantity 1). The request names that
344 line twice. Money may go back for one mug (1200) at most."""
345 data_dir, root, created = a_return(tmp_path, monkeypatch)
346 line_id = tr.shipment_lines(data_dir, created["shipment_id"])[0]["id"]
347 entry = {"shipment_line_id": line_id, "disposition": "restock",
348 "quantity": "1"}
349 result = tr.disposition(root, shipment_id=created["shipment_id"],
350 lines=[entry, dict(entry)], refund="full")
351
352 refunded = sum(int(r["amount_cents"]) for r in tr.refunds(data_dir))
353 # either refused, or refunded once; never 2400 for a 1200 mug
354 assert result.get("status") == 409 or refunded <= 1200, (
355 f"refunded {refunded} for one returned unit worth 1200; "
356 f"stock moves written: {len(tr.moves(data_dir, 'return'))}")
357
358
359def test_a_declined_rma_is_not_refunded(tmp_path, monkeypatch):
360 """authorized -> declined is the documented path for 'the return turns
361 out to be fraudulent before the parcel arrives'. The parcel then
362 arrives. No money may go back against a declined RMA."""
363 data_dir, root = tr.shop_with_a_return(tmp_path, monkeypatch)
364 created = tr.authorized_return(root)
365 object_records.update_collection_record(
366 "return_authorizations", created["return_id"], {"status": "declined"},
367 base_dir=data_dir, actor="test")
368 tr.receive(data_dir, created["shipment_id"])
369
370 outcome = execute(root, "action_disposition_return", {
371 "_identity": {"user_id": "shop"}, # the return's owner
372 "shipment_id": created["shipment_id"], "refund": "full",
373 "lines": [{"shipment_line_id": tr.shipment_lines(
374 data_dir, created["shipment_id"])[0]["id"],
375 "disposition": "restock", "quantity": "1"}]})
376 result = outcome.result or {}
377 assert (not outcome.ok) or result.get("status") in (409, 403) , (
378 f"declined RMA was dispositioned: {result}")
379 assert tr.refunds(data_dir) == []
380
381
382# =============================================================================
383# 4. receive_goods / authorize_return
384# =============================================================================
385
386import test_receiving as trc # noqa: E402
387
388
389def total_received(data_dir, order_line_id="po-line-1"):
390 return sum(int(float(r["quantity_received"]))
391 for r in trc.receipt_lines(data_dir)
392 if r["order_line_id"] == order_line_id)
393
394
395def test_duplicate_order_line_entries_cannot_receive_more_than_ordered(
396 tmp_path, monkeypatch):
397 """PO line orders 10. Two entries of 8 each pass the 10 cap alone."""
398 data_dir, root = trc.stocked_shop(tmp_path, monkeypatch, quantity="10")
399 entry = {"order_line_id": "po-line-1", "quantity_received": "8"}
400 result = trc.receive(root, order_id="po-1", lines=[entry, dict(entry)])
401 got = total_received(data_dir)
402 if result.get("receipt_id"):
403 # what the dispatcher does next: the posting handler shelves stock
404 trc.post_receipt(root, result["receipt_id"])
405 shelved = sum(float(m["quantity"]) for m in trc.purchases(data_dir))
406 assert result.get("status") == 409 or (got <= 10 and shelved <= 10), (
407 f"ordered 10, receipt lines record {got} received, "
408 f"{shelved} units shelved")
409
410
411def test_a_single_over_receive_is_refused(tmp_path, monkeypatch):
412 """The cap itself works for one entry (so the bug above is purely the
413 duplicate-entry bypass)."""
414 data_dir, root = trc.stocked_shop(tmp_path, monkeypatch, quantity="10")
415 result = trc.receive(root, order_id="po-1", lines=[
416 {"order_line_id": "po-line-1", "quantity_received": "11"}])
417 assert result["status"] == 409 and result["over_receive"]
418 assert total_received(data_dir) == 0
419
420
421@pytest.mark.parametrize("lines", [[], "garbage", {"order_line_id": "po-line-1"}])
422def test_an_explicit_but_empty_or_malformed_lines_value_does_not_receive_all(
423 tmp_path, monkeypatch, lines):
424 """Omitting `lines` is the documented 'one button' default. Sending a
425 `lines` value that names nothing usable is not the same request."""
426 data_dir, root = trc.stocked_shop(tmp_path, monkeypatch, quantity="10")
427 result = trc.receive(root, order_id="po-1", lines=lines)
428 assert total_received(data_dir) == 0, (
429 f"lines={lines!r} received {total_received(data_dir)} of 10")
430
431
432def test_omitting_lines_receives_the_whole_order_as_documented(
433 tmp_path, monkeypatch):
434 """Pins the documented default so the two tests above are about the
435 malformed forms only."""
436 data_dir, root = trc.stocked_shop(tmp_path, monkeypatch, quantity="10")
437 result = trc.receive(root, order_id="po-1")
438 assert result["ok"] and total_received(data_dir) == 10
439
440
441def test_duplicate_order_line_entries_cannot_authorise_more_than_shipped(
442 tmp_path, monkeypatch):
443 """3 mugs shipped. Two entries of 3 each pass the cap of 3 alone."""
444 data_dir, root = tr.shop_with_a_return(tmp_path, monkeypatch)
445 entry = {"order_line_id": "line-1", "quantity": "3"}
446 result = tr.authorize(root, order_id="ord-1", reason="no_longer_wanted",
447 lines=[entry, dict(entry)])
448 authorised = sum(int(float(r["quantity"])) for r in tr.shipment_lines(data_dir)
449 if r["order_line_id"] == "line-1"
450 and r["shipment_id"] != "ship-out")
451 assert result.get("status") == 409 or authorised <= 3, (
452 f"3 shipped, {authorised} authorised to come back")
453
454
455def test_authorize_return_refuses_an_empty_lines_list(tmp_path, monkeypatch):
456 """REFUTED for authorize_return: the inventory said `lines: []` receives
457 everything; here it is refused (only receive_goods has that default)."""
458 data_dir, root = tr.shop_with_a_return(tmp_path, monkeypatch)
459 result = tr.authorize(root, order_id="ord-1", reason="damaged", lines=[])
460 assert result["status"] == 409 and result["bad_quantities"]
461 assert tr.rmas(data_dir) == []
462
463
464# =============================================================================
465# 5. resolve_dispute
466# =============================================================================
467
468import test_disputes as td # noqa: E402
469
470
471def test_a_credit_cannot_exceed_what_the_order_was_worth(tmp_path, monkeypatch):
472 data_dir, root = td.shop_with_a_dispute(tmp_path, monkeypatch, cents=3600)
473 td.wallet(data_dir)
474 result = td.resolve(root, dispute_id="dis-1", resolution_kind="credit",
475 amount_cents="99999900", note="oops extra zeros")
476 credited = sum(int(e["amount_minor"]) for e in td.entries(data_dir))
477 assert result.get("status") in (400, 409, 422) and credited <= 3600, (
478 f"order was 3600, credit issued: {credited}, result ok={result.get('ok')}")
479
480
481def test_a_refund_beyond_the_payment_is_refused(tmp_path, monkeypatch):
482 """Contrast: the refund path DOES have a ceiling (hook_refunds)."""
483 data_dir, root = td.shop_with_a_dispute(tmp_path, monkeypatch, cents=3600)
484 refused = td.resolve(root, dispute_id="dis-1", resolution_kind="refund",
485 amount_cents="99999900")
486 assert refused["status"] == 409 and "exceeds the refundable" in refused["error"]
487 assert td.refunds(data_dir) == []
488
489
490def test_two_concurrent_resolutions_of_one_dispute_refund_once(
491 tmp_path, monkeypatch):
492 """B (a double click) runs wholly between A's marker check and A's refund
493 write. Both are inside the payment's ceiling, so the ceiling gate passes
494 both.
495
496 B may answer either way -- ok, or the 409 `in_progress` the fix gives a
497 request that finds another one holding the dispute's claim -- as long as
498 the money goes back once. (This test first demanded B answer ok; that
499 pinned the bug's own behaviour, since B could only answer ok by
500 refunding.)"""
501 data_dir, root = td.shop_with_a_dispute(tmp_path, monkeypatch, cents=3600)
502 inner = interleave_once(
503 monkeypatch, "refunds", "create_collection_record",
504 lambda: td.resolve(root, dispute_id="dis-1", resolution_kind="refund",
505 amount_cents="1200"))
506 first = td.resolve(root, dispute_id="dis-1", resolution_kind="refund",
507 amount_cents="1200")
508 assert first["ok"] is True and inner, "interleave did not fire"
509 assert inner[0].get("ok") is True or inner[0].get("code") == "in_progress", inner
510 total = sum(int(r["amount_cents"]) for r in td.refunds(data_dir))
511 assert len(td.refunds(data_dir)) == 1, (
512 f"{len(td.refunds(data_dir))} refunds, {total} cents sent back for "
513 f"one dispute")
514
515
516# =============================================================================
517# 6. create_shipment fails open
518# =============================================================================
519
520import test_shipping as ts # noqa: E402
521
522
523def break_reads(monkeypatch, *collections):
524 """Make the public read of the named collections raise, as a corrupt or
525 locked file would. Writes do not go through this entry point."""
526 real = object_records.read_collection_records
527
528 def broken(collection, *a, **k):
529 if collection in collections:
530 raise OSError(f"simulated unreadable {collection}")
531 return real(collection, *a, **k)
532
533 monkeypatch.setattr(object_records, "read_collection_records", broken)
534 return real
535
536
537def test_the_shipment_line_hook_fails_closed_when_history_is_unreadable(
538 tmp_path, monkeypatch):
539 """Contrast: the generic-path hook refuses with 503 rather than guess."""
540 data_dir, root = ts.stocked_shop(tmp_path, monkeypatch, quantity="3")
541 first = ts.create_shipment(root, order_id="ord-1")
542 assert first["ok"]
543 break_reads(monkeypatch, "shipment_lines")
544 verdict = ts.hook(root, {"id": object_ids.new_uuid4(),
545 "shipment_id": first["shipment_id"],
546 "order_line_id": "line-1", "quantity": "3"})
547 assert verdict["status"] == 503
548
549
550def test_create_shipment_refuses_when_it_cannot_read_what_already_shipped(
551 tmp_path, monkeypatch):
552 data_dir, root = ts.stocked_shop(tmp_path, monkeypatch, quantity="3")
553 first = ts.create_shipment(root, order_id="ord-1")
554 assert first["ok"] and first["lines"] == 1
555 before = len(ts.shipment_lines(data_dir)) # 1 line of 3 mugs
556
557 real = break_reads(monkeypatch, "shipment_lines")
558 second = ts.create_shipment(root, order_id="ord-1")
559
560 monkeypatch.setattr(object_records, "read_collection_records", real)
561 shipped = sum(int(float(r["quantity"])) for r in ts.shipment_lines(data_dir))
562 assert second.get("status") in (409, 503) and shipped <= 3, (
563 f"order of 3 now has {shipped} units on shipments "
564 f"(was {before} line before); second result ok={second.get('ok')}")
565
566
567# =============================================================================
568# 7. reverse_journal / record_count
569# =============================================================================
570
571import test_period_locking as tpl # noqa: E402
572
573
574def posted_journal_in_q1(data_dir):
575 """A balanced posted journal dated 2026-02-10, written BEFORE Q1 closes
576 (the normal order of events), then the period is closed."""
577 object_records.create_collection_record(
578 "fin_journals",
579 {"id": "j-q1", "date": "2026-02-10", "description": "Q1 sale",
580 "status": "draft", "kind": "standard", "owner_id": "dan"},
581 base_dir=data_dir)
582 for lid, dr, cr in (("l1", "500", "0"), ("l2", "0", "500")):
583 object_records.create_collection_record(
584 "fin_journal_lines",
585 {"id": lid, "journal_id": "j-q1", "account_id": "acct-cash",
586 "debit_cents": dr, "credit_cents": cr, "owner_id": "dan"},
587 base_dir=data_dir)
588 object_records.update_collection_record(
589 "fin_journals", "j-q1", {"status": "posted"}, base_dir=data_dir)
590 tpl.close_period(data_dir) # 2026-01-01 .. 2026-03-31
591
592
593def test_the_period_gate_does_refuse_a_direct_write_into_a_closed_period(
594 tmp_path, monkeypatch):
595 """Control for the test below: the hook (the door a form uses) refuses."""
596 data_dir = tpl.setup_env(tmp_path, monkeypatch)
597 posted_journal_in_q1(data_dir)
598 verdict = tpl.journal_hook("create", record={
599 "id": "jx", "date": "2026-02-10", "owner_id": "dan"})
600 assert verdict["status"] == 409 and "are closed" in verdict["error"]
601
602
603def test_reversing_a_journal_in_a_closed_period_does_not_post_into_it(
604 tmp_path, monkeypatch):
605 data_dir = tpl.setup_env(tmp_path, monkeypatch)
606 posted_journal_in_q1(data_dir)
607 outcome = execute(PACKAGES / "app-finance" / "objects",
608 "action_reverse_journal",
609 {"journal_id": "j-q1",
610 "_identity": {"user_id": "dan", "roles": []}})
611 assert outcome.ok, outcome.error
612 result = outcome.result
613 mirrors = [j for j in rows(data_dir, "fin_journals")
614 if j.get("generated_from") == "reversal:j-q1"]
615 refused = result.get("status") in (403, 409)
616 in_closed = [m["date"] for m in mirrors if "2026-01-01" <= m["date"] <= "2026-03-31"]
617 assert refused or not in_closed, (
618 f"mirror journal posted dated {in_closed} inside the closed Q1 "
619 f"({result})")
620
621
622def test_record_count_books_the_variance_journal_with_a_count_row(
623 tmp_path, monkeypatch):
624 """Happy path pinned: journal and count row agree."""
625 import test_cash_counts as tcc
626 data_dir = tcc.setup_env(tmp_path, monkeypatch)
627 tcc.make_till(data_dir)
628 tcc.book_cash(data_dir, 20000)
629 result = tcc.count({"value_account_id": tcc.TILL, "counted_minor": 19750,
630 "counted_on": "2026-07-31"})
631 assert result["status"] == 200
632 assert tcc.counts(data_dir)[0]["journal_id"] == result["journal"]["journal_id"]
633
634
635def test_a_failed_count_write_leaves_no_orphan_journal(tmp_path, monkeypatch):
636 import test_cash_counts as tcc
637 data_dir = tcc.setup_env(tmp_path, monkeypatch)
638 tcc.make_till(data_dir)
639 tcc.book_cash(data_dir, 20000)
640
641 real = object_records.create_collection_record
642
643 def failing(collection, *a, **k):
644 if collection == "value_account_counts":
645 raise OSError("disk full while writing the count row")
646 return real(collection, *a, **k)
647
648 monkeypatch.setattr(object_records, "create_collection_record", failing)
649 outcome = execute(tcc.BANKING_OBJECTS, "action_record_count", {
650 "_identity": {"user_id": "dan"}, "value_account_id": tcc.TILL,
651 "counted_minor": 19750, "counted_on": "2026-07-31"})
652 monkeypatch.setattr(object_records, "create_collection_record", real)
653
654 assert not outcome.ok and "disk full" in outcome.error.message, (
655 "precondition: the caller is told the count failed")
656 assert tcc.counts(data_dir) == []
657 orphans = [j for j in rows(data_dir, "fin_journals")
658 if j.get("generated_from", "").startswith("value_account_counts/")]
659 assert orphans == [], (
660 f"{len(orphans)} posted journal(s) {[o['generated_from'] for o in orphans]}"
661 f" for a count that does not exist; the till's book balance is now "
662 f"{sum(int(l['debit_cents'])-int(l['credit_cents']) for l in rows(data_dir,'fin_journal_lines') if l['account_id']==tcc.CASH)}")
663
664
665# =============================================================================
666# 8. resolve_bank_line: NSF with the books mapping gone
667# =============================================================================
668
669import test_bank_reconciliation as tbr # noqa: E402
670
671
672def _post_payment_journal(payment_id):
673 """What the dispatcher does when a payment is created."""
674 return object_execution.execute_object(
675 RUNTIME,
676 object_execution.ObjectExecutionRequest(
677 "system_books", method="EVENT",
678 payload={"event": "payments.record.created",
679 "collection": "payments", "record_id": payment_id,
680 "action": "create"}),
681 roots=[PACKAGES / "app-payments" / "objects"])
682
683
684def nsf_shop(tmp_path, monkeypatch):
685 data_dir = tbr.setup_env(tmp_path, monkeypatch, settings=(
686 ("payments.accounting_basis", "cash"),
687 ("payments.journal.cash_account", tbr.CASH),
688 ("payments.journal.revenue_account", tbr.REV)))
689 tbr.make_invoice(data_dir)
690 tbr.make_payment(data_dir, "p1", cents=150000, reference="INV-1001")
691 tbr.make_line(data_dir, "L1", amount=-150000, desc="RETURNED ITEM NSF")
692 posted = _post_payment_journal("p1")
693 assert posted.ok and not posted.result.get("skipped"), posted.result
694 assert [j["generated_from"] for j in tbr.journals(data_dir)] == ["payments/p1"]
695 return data_dir
696
697
698def test_nsf_with_no_books_mapping_is_refused_not_a_silent_200(
699 tmp_path, monkeypatch):
700 """The payment was journaled while the mapping existed. The mapping is
701 later gone (basis switched to accrual with no receivable account, or a
702 setting cleared). The bounce must either refuse (nothing changed) or book
703 the reversal. It must not bounce, resolve and report 200."""
704 data_dir = nsf_shop(tmp_path, monkeypatch)
705 # basis flips to accrual; no receivable account was ever configured
706 settings = rows(data_dir, "app_settings")
707 basis = next(s for s in settings if s["key"] == "payments.accounting_basis")
708 object_records.update_collection_record(
709 "app_settings", basis["id"], {"value": "accrual"},
710 base_dir=data_dir, actor="test")
711
712 result = tbr.run_object("action_resolve_bank_line",
713 {"line_id": "L1", "kind": "nsf", "payment_id": "p1"})
714
715 payment = object_records.get_collection_record("payments", "p1",
716 base_dir=data_dir)
717 reversal = [j for j in tbr.journals(data_dir)
718 if j["generated_from"] == "payments/p1:bounced"]
719 if result.get("status") == 200:
720 assert reversal, (
721 f"200 returned, payment is {payment['status']}, bank line "
722 f"{tbr.line(data_dir, 'L1')['match_status']}, journal="
723 f"{result['journal']}, but no reversal journal exists")
724 else:
725 assert payment["status"] != "bounced"
726 assert tbr.line(data_dir, "L1")["match_status"] != "resolved"
727
728
729# =============================================================================
730# 9. bank statement imports: import row first, lines after
731# =============================================================================
732
733import test_bank_import as tbi # noqa: E402
734import test_bank_import_ofx as tbo # noqa: E402
735
736
737def fail_nth_write(monkeypatch, collection, nth):
738 """Make the nth create of `collection` raise (a crash mid-import); every
739 other write, before and after, is real. Returns a restore() callable."""
740 real = object_records.create_collection_record
741 count = {"n": 0}
742
743 def flaky(coll, *a, **k):
744 if coll == collection:
745 count["n"] += 1
746 if count["n"] == nth:
747 raise OSError("simulated crash while writing a statement line")
748 return real(coll, *a, **k)
749
750 monkeypatch.setattr(object_records, "create_collection_record", flaky)
751 return lambda: monkeypatch.setattr(object_records,
752 "create_collection_record", real)
753
754
755def test_a_crashed_csv_import_can_be_retried_to_completion(tmp_path, monkeypatch):
756 data_dir = tbi.setup_env(tmp_path, monkeypatch)
757 restore = fail_nth_write(monkeypatch, "bank_lines", 2)
758 crashed = execute(tbi.BANKING_OBJECTS, "action_import_bank_csv", {
759 "_identity": {"user_id": "dan"}, "bank_account_id": tbi.ACCOUNT,
760 "profile_id": tbi.PROFILE, "content": tbi.STATEMENT,
761 "opening_balance_cents": 0, "closing_balance_cents": 133265})
762 restore()
763 assert not crashed.ok and "simulated crash" in crashed.error.message, (
764 "precondition: the import crashed mid-way")
765 assert len(rows(data_dir, "bank_lines")) == 1, "precondition: partial load"
766
767 retry = tbi.import_statement()
768 n = len(rows(data_dir, "bank_lines"))
769 assert n == 3, (
770 f"after the retry the account has {n} of 3 lines; retry answered "
771 f"already_imported={retry.get('already_imported')} "
772 f"imported={retry.get('imported')}; import rows: "
773 f"{len(rows(data_dir, 'bank_statement_imports'))}")
774
775
776def test_a_crashed_ofx_import_can_be_retried_to_completion(tmp_path, monkeypatch):
777 data_dir = tbo.setup_env(tmp_path, monkeypatch)
778 restore = fail_nth_write(monkeypatch, "bank_lines", 2)
779 crashed = execute(tbo.BANKING_OBJECTS, "action_import_ofx", {
780 "_identity": {"user_id": "dan"}, "bank_account_id": tbo.ACCOUNT,
781 "content": tbo.JULY})
782 restore()
783 assert not crashed.ok and "simulated crash" in crashed.error.message
784 assert len(rows(data_dir, "bank_lines")) == 1
785
786 retry = tbo.run({"bank_account_id": tbo.ACCOUNT, "content": tbo.JULY})
787 n = len(rows(data_dir, "bank_lines"))
788 assert n == 2, (
789 f"after the retry the account has {n} of 2 lines; retry answered "
790 f"already_imported={retry.get('already_imported')}")
791
792
793# =============================================================================
794# 10. buy_label with a PAID carrier (stubbed: no network, no real adapter)
795# =============================================================================
796
797import test_tracking as ttr # noqa: E402
798
799PAID_CARRIER = '''
800import os
801PROVIDER = "fakeco"
802
803def _spend():
804 # the "paid, non-idempotent external call": one line per purchase
805 with open(os.environ["FAKECO_LEDGER"], "a") as handle:
806 handle.write("purchase\\n")
807 with open(os.environ["FAKECO_LEDGER"]) as handle:
808 return len(handle.read().split())
809
810def buy_label(shipment, *, base_dir=None, tracking_number="", label_bytes=None,
811 label_content_type="", label_filename=""):
812 n = _spend()
813 if os.environ.get("FAKECO_RAISE_AFTER_PURCHASE"):
814 raise RuntimeError("socket closed after the carrier accepted the order")
815 return {"ok": True, "tracking_number": f"PAID-{n}", "label_bytes": b"%PDF-fake",
816 "label_content_type": "application/pdf"}
817
818def reconcile(record, *, base_dir=None):
819 return {"skip": True}
820'''
821
822
823def paid_carrier_shop(tmp_path, monkeypatch):
824 data_dir, root = ttr.shop(tmp_path, monkeypatch, provider="fakeco")
825 ttr.shipment(data_dir, tracking="")
826 packages = tmp_path / "carrier-packages"
827 package = packages / "app-fakeco"
828 (package / "connectors").mkdir(parents=True)
829 (package / "connectors" / "fakeco.py").write_text(PAID_CARRIER)
830 (package / "dbbasic-package.json").write_text(json.dumps({
831 "id": "app-fakeco", "name": "FakeCo", "version": "1.0.0",
832 "connectors": [{"collection": "shipments",
833 "module": "connectors/fakeco.py", "entry": "reconcile"}],
834 }))
835 ledger = tmp_path / "fakeco-ledger.txt"
836 monkeypatch.setenv("DBBASIC_PACKAGES_DIR", str(packages))
837 monkeypatch.setenv("FAKECO_LEDGER", str(ledger))
838
839 def purchases():
840 return len(ledger.read_text().split()) if ledger.exists() else 0
841 return data_dir, root, purchases
842
843
844def test_a_paid_label_is_bought_and_recorded_once(tmp_path, monkeypatch):
845 """Pinned: the happy path through the stubbed paid carrier."""
846 data_dir, root, purchases = paid_carrier_shop(tmp_path, monkeypatch)
847 result = ttr.buy_label(root, shipment_id="shp-1")
848 assert result["ok"] and result["tracking_number"] == "PAID-1"
849 assert purchases() == 1
850 assert ttr.read(data_dir)["tracking_number"] == "PAID-1"
851
852
853def test_a_double_click_does_not_buy_a_second_paid_label(tmp_path, monkeypatch):
854 data_dir, root, purchases = paid_carrier_shop(tmp_path, monkeypatch)
855 ttr.buy_label(root, shipment_id="shp-1")
856 ttr.buy_label(root, shipment_id="shp-1")
857 assert purchases() == 1, (
858 f"{purchases()} paid purchases for one shipment; tracking number now "
859 f"{ttr.read(data_dir)['tracking_number']!r}")
860
861
862def test_a_failure_after_a_paid_call_is_not_presented_as_a_clean_retry(
863 tmp_path, monkeypatch):
864 data_dir, root, purchases = paid_carrier_shop(tmp_path, monkeypatch)
865 monkeypatch.setenv("FAKECO_RAISE_AFTER_PURCHASE", "1")
866 first = ttr.buy_label(root, shipment_id="shp-1")
867 assert first["status"] == 502 and purchases() == 1, (
868 "precondition: the carrier took the order, the connector then raised")
869 assert ttr.read(data_dir)["tracking_number"] == ""
870
871 message = first["error"].lower()
872 assert any(w in message for w in ("may have", "might have", "check with",
873 "verify", "already been charged",
874 "do not retry")), (
875 f"error gives the operator no hint that money may have been spent: "
876 f"{first['error']!r}")
877
878
879# =============================================================================
880# 11. stripe_checkout (transport stubbed: no network)
881# =============================================================================
882
883import json as _json # noqa: E402
884import object_stripe # noqa: E402
885import test_stripe_wiring as tsw # noqa: E402
886
887
888_REAL_CREATE_SESSION = object_stripe.create_checkout_session
889
890
891def stripe_checkout_call(monkeypatch, token="tok-abcdefghijklmnop"):
892 """Run the action with Stripe's transport replaced; returns (result,
893 calls) where calls carries the headers actually sent."""
894 calls = []
895
896 def fake_transport(url, data, headers, method):
897 calls.append({"url": url, "headers": dict(headers)})
898 return 200, _json.dumps({"id": "cs_new",
899 "url": "https://checkout.stripe.com/pay/x"}).encode()
900
901 monkeypatch.setattr(
902 object_stripe, "create_checkout_session",
903 lambda config, **kw: _REAL_CREATE_SESSION(
904 config, transport=fake_transport, **kw))
905 result = object_execution.execute_object(
906 RUNTIME,
907 object_execution.ObjectExecutionRequest(
908 "action_stripe_checkout", method="POST", payload={"token": token}),
909 roots=[tsw.PAYMENTS_OBJECTS]).result
910 return result, calls
911
912
913def stripe_shop(tmp_path, monkeypatch, *, paid_cents=0):
914 data_dir = tsw.setup_env(tmp_path, monkeypatch)
915 object_records.create_collection_record(
916 "app_settings", {"id": "s1", "key": "portal.base_url",
917 "value": "https://books.example"}, base_dir=data_dir)
918 if paid_cents:
919 object_records.create_collection_record(
920 "payments", {"id": "p-full", "invoice_id": "inv-1",
921 "amount_cents": str(paid_cents), "method": "card",
922 "received_on": "2026-07-10", "status": "received",
923 "owner_id": "dan"}, base_dir=data_dir)
924 return data_dir
925
926
927def test_unreadable_payments_do_not_become_an_open_balance(tmp_path, monkeypatch):
928 stripe_shop(tmp_path, monkeypatch, paid_cents=250000) # paid in full
929 ok, _ = stripe_checkout_call(monkeypatch)
930 assert ok["status"] == 409, "precondition: readable payments -> refused"
931
932 real = break_reads(monkeypatch, "payments")
933 result, calls = stripe_checkout_call(monkeypatch)
934 monkeypatch.setattr(object_records, "read_collection_records", real)
935 assert result["status"] in (409, 502, 503) and calls == [], (
936 f"paid-in-full invoice, payments unreadable: status={result['status']} "
937 f"amount_cents={result.get('amount_cents')} stripe calls={len(calls)}")
938
939
940def test_two_clicks_on_pay_use_the_same_idempotency_key(tmp_path, monkeypatch):
941 stripe_shop(tmp_path, monkeypatch)
942 first, calls1 = stripe_checkout_call(monkeypatch)
943 second, calls2 = stripe_checkout_call(monkeypatch)
944 assert first["status"] == second["status"] == 200
945 key1 = calls1[0]["headers"].get("Idempotency-Key")
946 key2 = calls2[0]["headers"].get("Idempotency-Key")
947 assert key1 and key1 == key2, (
948 f"key sent on click 1: {key1!r}, on click 2: {key2!r}")
949
950
951# =============================================================================
952# 12. generate_tm_invoice
953# =============================================================================
954
955import test_tm_billing as ttm # noqa: E402
956
957
958def billable_hour(data_dir, log_id="t1", project="proj-acme"):
959 ttm.log_time(data_dir, log_id, status="submitted", project_id=project)
960 assert ttm.approve(data_dir, log_id)["ok"]
961
962
963def test_two_tm_invoices_never_share_a_number(tmp_path, monkeypatch):
964 data_dir = ttm.setup_env(tmp_path, monkeypatch)
965 ttm.rate_card(data_dir, "house", 15000)
966 billable_hour(data_dir, "t1")
967 ttm.generate({"project_id": "proj-acme", "through_date": "2026-06-30"})
968 billable_hour(data_dir, "t2") # approved after the first run
969 second = ttm.generate({"project_id": "proj-acme", "through_date": "2026-06-30"})
970 assert second["invoiced"] == 1
971
972 numbers = [i["number"] for i in ttm.invoices(data_dir)]
973 assert len(numbers) == 2 and len(set(numbers)) == 2, numbers
974
975
976def test_two_overlapping_runs_do_not_bill_the_same_hours_twice(
977 tmp_path, monkeypatch):
978 """Fixed 2026-11-28: entries are claimed with expected_rev after the
979 header is written, so the run that started first and claims second
980 finds the hour taken and invoices nothing. The original precondition
981 (both runs invoiced 1) described the bug; what is pinned now is that the
982 second run did start inside the first one's window, and one invoice
983 carries the hour."""
984 data_dir = ttm.setup_env(tmp_path, monkeypatch)
985 ttm.rate_card(data_dir, "house", 15000)
986 billable_hour(data_dir, "t1") # 1 hour at 150.00
987
988 inner = interleave_once(
989 monkeypatch, "invoices", "create_collection_record",
990 lambda: ttm.generate({"project_id": "proj-acme"}))
991 first = ttm.generate({"project_id": "proj-acme"})
992
993 assert inner, "precondition: the second run ran inside the first's window"
994 assert first["invoiced"] + inner[0]["invoiced"] == 1, (first, inner[0])
995 assert len(ttm.invoices(data_dir)) == 1, "the losing run left no empty header"
996 billed = sum(int(i["total_cents"]) for i in ttm.invoices(data_dir))
997 assert billed == 15000, (
998 f"1 approved hour (15000) appears on {len(ttm.invoices(data_dir))} "
999 f"invoices totalling {billed}")
1000
1001
1002# =============================================================================
1003# 13. export_subject_data completeness
1004# =============================================================================
1005
1006def test_the_export_includes_or_admits_every_collection_keyed_by_the_email(
1007 tmp_path, monkeypatch):
1008 """Four more collections on this box hold the subject's email in
1009 customer_email (backorders, promotion_redemptions, return_authorizations,
1010 subscriptions). An export that neither returns them nor names them in
1011 `not_searchable` reads as 'we hold nothing else'. Either is acceptable;
1012 silence is not."""
1013 import test_privacy as tp
1014 from conftest import schema_header
1015 data_dir = tmp_path / "data"
1016 for package_id, collection in (("app-orders", "orders"),
1017 ("app-invoices", "invoices"),
1018 ("app-payments", "payments"),
1019 ("app-shipping", "shipments"),
1020 ("app-shop", "carts"),
1021 ("app-disputes", "disputes"),
1022 ("app-contacts", "contacts"),
1023 ("app-analytics", "conversions")):
1024 stage_collection(data_dir, package_id, collection)
1025 held = []
1026 extra = (("app-catalog", "backorders", {"id": "bo1", "product_id": "p1",
1027 "kind": "backorder"}),
1028 ("app-promotions", "promotion_redemptions",
1029 {"id": "pr1", "promotion_id": "promo1"}),
1030 ("app-returns", "return_authorizations",
1031 {"id": "rma1", "order_id": "o1", "reason": "damaged",
1032 "status": "requested"}),
1033 ("app-billing", "subscriptions", {"id": "sub1", "plan_id": "plan1"}))
1034 for package_id, collection, fields in extra:
1035 # Staged straight into the TSV (the way tests/test_books_spine.py
1036 # seeds rows): the point is what the export does with rows that
1037 # exist, not relation validation on their creation.
1038 values = {**fields, "customer_email": tp.ANNA}
1039 header = schema_header(package_id, collection).strip("\n").split("\t")
1040 stage_collection(data_dir, package_id, collection,
1041 rows="\t".join(values.get(f, "") for f in header) + "\n")
1042 held.append(collection)
1043 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
1044 assert [r["customer_email"] for r in rows(data_dir, "backorders")] == [tp.ANNA], (
1045 "precondition: the subject's row is on disk")
1046
1047 result = tp.export({**tp.ADMIN, "email": tp.ANNA})
1048 assert result["ok"] is True
1049 returned = set(result["collections"])
1050 declared = {entry["collection"] for entry in result["not_searchable"]}
1051 silent = [c for c in held if c not in returned and c not in declared
1052 and c not in result["unavailable"]]
1053 assert silent == [], (
1054 f"rows keyed by {tp.ANNA} in {silent} are neither exported nor "
1055 f"declared not_searchable (exported: {sorted(returned)}, declared: "
1056 f"{sorted(declared)})")