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_commerce_action_fixes.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_commerce_action_fixes.py · 19.4 KB · 408 lines
1"""Pins for the commerce-action fixes of 2026-11-28 that the findings files
2do not already cover: the fail-closed reads added alongside them, and the
3legitimate shapes the new caps must still allow.
4
5The reproductions themselves live in tests/test_findings_actions.py (and
6tests/test_findings_money_gates.py); the races are raced for real, with
7threads, in tests/test_commerce_action_races.py.
8"""
9
10import pytest
11
12import object_records
13import test_findings_actions as tfa
14import test_receiving as trc
15import test_returns as tr
16import test_tracking as ttr
17
18
19def _break_reads(monkeypatch, *collections):
20 real = object_records.read_collection_records
21
22 def broken(collection, *a, **k):
23 if collection in collections:
24 raise OSError(f"simulated unreadable {collection}")
25 return real(collection, *a, **k)
26
27 monkeypatch.setattr(object_records, "read_collection_records", broken)
28 return real
29
30
31# --- receive_goods --------------------------------------------------------------
32
33@pytest.mark.parametrize("unreadable", ["receipts", "receipt_lines"])
34def test_receive_goods_refuses_when_what_was_received_cannot_be_read(
35 tmp_path, monkeypatch, unreadable):
36 """Read as empty, an unreadable history says nothing has arrived, and the
37 whole PO is received (and shelved) a second time."""
38 data_dir, root = trc.stocked_shop(tmp_path, monkeypatch, quantity="10")
39 first = trc.receive(root, order_id="po-1")
40 assert first["ok"] and first["lines"] == 1
41
42 real = _break_reads(monkeypatch, unreadable)
43 second = trc.receive(root, order_id="po-1")
44 monkeypatch.setattr(object_records, "read_collection_records", real)
45
46 assert second["status"] == 503, second
47 assert len(trc.receipt_lines(data_dir)) == 1
48
49
50def test_two_entries_for_one_po_line_may_still_add_up_to_what_was_ordered(
51 tmp_path, monkeypatch):
52 """The running cap refuses the excess, not the shape: 4 + 6 of 10 is a
53 perfectly good (if oddly typed) delivery."""
54 data_dir, root = trc.stocked_shop(tmp_path, monkeypatch, quantity="10")
55 result = trc.receive(root, order_id="po-1", lines=[
56 {"order_line_id": "po-line-1", "quantity_received": "4"},
57 {"order_line_id": "po-line-1", "quantity_received": "6"}])
58 assert result["ok"], result
59 assert sum(float(r["quantity_received"])
60 for r in trc.receipt_lines(data_dir)) == 10
61
62
63def test_the_over_receive_report_counts_what_earlier_entries_claimed(
64 tmp_path, monkeypatch):
65 data_dir, root = trc.stocked_shop(tmp_path, monkeypatch, quantity="10")
66 result = trc.receive(root, order_id="po-1", lines=[
67 {"order_line_id": "po-line-1", "quantity_received": "8"},
68 {"order_line_id": "po-line-1", "quantity_received": "8"}])
69 assert result["status"] == 409
70 assert result["over_receive"] == [{
71 "order_line_id": "po-line-1", "description": result["over_receive"][0]["description"],
72 "ordered": "10", "already_received": "8", "asked_for": "8",
73 "would_make": "16"}]
74 assert trc.receipt_lines(data_dir) == []
75
76
77# --- authorize_return -----------------------------------------------------------
78
79def test_two_entries_for_one_order_line_may_still_add_up_to_what_shipped(
80 tmp_path, monkeypatch):
81 data_dir, root = tr.shop_with_a_return(tmp_path, monkeypatch)
82 result = tr.authorize(root, order_id="ord-1", reason="damaged", lines=[
83 {"order_line_id": "line-1", "quantity": "1"},
84 {"order_line_id": "line-1", "quantity": "2"}])
85 assert result["ok"], result
86 returned = [r for r in tr.shipment_lines(data_dir)
87 if r["shipment_id"] == result["shipment_id"]]
88 assert sum(float(r["quantity"]) for r in returned) == 3
89
90
91# --- disposition_return ---------------------------------------------------------
92
93def _received(tmp_path, monkeypatch, **kwargs):
94 data_dir, root = tr.shop_with_a_return(tmp_path, monkeypatch, **kwargs)
95 created = tr.authorized_return(root, lines=[
96 {"order_line_id": "line-1", "quantity": "3"}])
97 assert created["ok"], created
98 tr.receive(data_dir, created["shipment_id"])
99 line_id = tr.shipment_lines(data_dir, created["shipment_id"])[0]["id"]
100 return data_dir, root, created, line_id
101
102
103def test_disposition_refuses_when_the_rma_cannot_be_read(tmp_path, monkeypatch):
104 """No RMA is a path this action allows, so an unreadable RMA collection
105 must not be read as one: the RMA may say declined."""
106 data_dir, root, created, line_id = _received(tmp_path, monkeypatch)
107 real = _break_reads(monkeypatch, "return_authorizations")
108 result = tr.disposition(root, shipment_id=created["shipment_id"], refund="full",
109 lines=[{"shipment_line_id": line_id,
110 "disposition": "restock", "quantity": "3"}])
111 monkeypatch.setattr(object_records, "read_collection_records", real)
112 assert result["status"] == 503, result
113 assert tr.refunds(data_dir) == [] and tr.moves(data_dir, "return") == []
114
115
116@pytest.mark.parametrize("unreadable", ["stock_moves", "shipment_lines", "payments"])
117def test_disposition_refuses_when_what_it_decides_from_cannot_be_read(
118 tmp_path, monkeypatch, unreadable):
119 """An unreadable stock ledger read as "stock is not installed", and the
120 return was closed with its moves silently missing -- the one outcome
121 the module docstring says it must refuse, because a dispositioned
122 parcel never comes back for a second pass. Unreadable lines or
123 payments read as "no such line" and "no payment", which refused with
124 words that were not true."""
125 data_dir, root, created, line_id = _received(tmp_path, monkeypatch)
126 real = _break_reads(monkeypatch, unreadable)
127 result = tr.disposition(root, shipment_id=created["shipment_id"], refund="full",
128 lines=[{"shipment_line_id": line_id,
129 "disposition": "restock", "quantity": "3"}])
130 monkeypatch.setattr(object_records, "read_collection_records", real)
131 assert result["status"] == 503, result
132 assert unreadable in result["error"]
133 assert tr.refunds(data_dir) == [] and tr.moves(data_dir, "return") == []
134 parcel = object_records.get_collection_record(
135 "shipments", created["shipment_id"], base_dir=data_dir)
136 assert parcel["status"] == "received" and parcel["action_claim"] == ""
137
138
139def test_a_requested_rma_that_was_never_granted_is_not_dispositioned(
140 tmp_path, monkeypatch):
141 data_dir, root, created, line_id = _received(tmp_path, monkeypatch)
142 # authorized -> requested is not a legal move, so replace the row with
143 # the one the return form would have written.
144 rma = object_records.get_collection_record(
145 "return_authorizations", created["return_id"], base_dir=data_dir)
146 object_records.delete_collection_record(
147 "return_authorizations", created["return_id"], base_dir=data_dir)
148 object_records.create_collection_record(
149 "return_authorizations", {**{k: v for k, v in rma.items()
150 if k not in ("created_at", "updated_at")},
151 "status": "requested"}, base_dir=data_dir)
152 result = tr.disposition(root, shipment_id=created["shipment_id"], refund="full",
153 lines=[{"shipment_line_id": line_id,
154 "disposition": "restock", "quantity": "3"}])
155 assert result["status"] == 409 and result["status_of_return"] == "requested"
156 assert tr.refunds(data_dir) == []
157
158
159def test_one_line_split_between_restock_and_dispose_moves_both_halves(
160 tmp_path, monkeypatch):
161 """Three mugs back: two fine, one broken. Each half is its own move, and
162 the full refund prices the line once, for all three."""
163 data_dir, root, created, line_id = _received(tmp_path, monkeypatch)
164 result = tr.disposition(root, shipment_id=created["shipment_id"], refund="full",
165 lines=[{"shipment_line_id": line_id,
166 "disposition": "restock", "quantity": "2"},
167 {"shipment_line_id": line_id,
168 "disposition": "dispose", "quantity": "1"}])
169 assert result["ok"], result
170 assert result["moved"] == 2
171 assert result["refund_cents"] == "3600"
172 reasons = sorted(m["reason"] for m in tr.moves(data_dir) if "returns/" in m["reference"])
173 assert reasons == ["return", "waste"]
174
175
176def test_two_entries_naming_the_same_line_and_disposition_are_one_move(
177 tmp_path, monkeypatch):
178 data_dir, root, created, line_id = _received(tmp_path, monkeypatch)
179 entry = {"shipment_line_id": line_id, "disposition": "restock", "quantity": "1"}
180 result = tr.disposition(root, shipment_id=created["shipment_id"], refund="full",
181 lines=[entry, dict(entry)])
182 assert result["ok"], result
183 restocked = [m for m in tr.moves(data_dir) if "returns/" in m["reference"]]
184 assert len(restocked) == 1 and float(restocked[0]["quantity"]) == 2
185 assert result["refund_cents"] == "2400"
186
187
188def test_a_partial_return_of_a_discounted_line_refunds_the_discounted_units(
189 tmp_path, monkeypatch):
190 """Two of three 20%-off mugs back: 2 x 960, priced by object_lines."""
191 data_dir, root = tr.shop_with_a_return(
192 tmp_path, monkeypatch,
193 line_fields={"discount_bps": "2000", "line_total_cents": "2880"})
194 created = tr.authorized_return(root, lines=[
195 {"order_line_id": "line-1", "quantity": "2"}])
196 tr.receive(data_dir, created["shipment_id"])
197 result = tr.dispositioned(root, data_dir, created, refund="full", quantity="2")
198 assert result["ok"] and result["refund_cents"] == "1920", result
199
200
201# --- buy_label with a PAID carrier (the stub from test_findings_actions) --------
202
203def test_after_an_unknown_outcome_the_next_click_is_refused_until_replace(
204 tmp_path, monkeypatch):
205 data_dir, root, purchases = tfa.paid_carrier_shop(tmp_path, monkeypatch)
206 monkeypatch.setenv("FAKECO_RAISE_AFTER_PURCHASE", "1")
207 first = ttr.buy_label(root, shipment_id="shp-1")
208 assert first["status"] == 502 and first["outcome"] == "unknown"
209 assert ttr.read(data_dir)["label_purchase"].startswith("unknown ")
210
211 monkeypatch.delenv("FAKECO_RAISE_AFTER_PURCHASE")
212 again = ttr.buy_label(root, shipment_id="shp-1")
213 assert again["status"] == 409 and "check with the carrier" in again["error"].lower()
214 assert purchases() == 1
215
216 # Somebody checked with the carrier and decided to buy again.
217 replaced = ttr.buy_label(root, shipment_id="shp-1", replace=True)
218 assert replaced["ok"] and purchases() == 2
219 assert ttr.read(data_dir)["label_purchase"] == ""
220 assert ttr.read(data_dir)["tracking_number"] == "PAID-2"
221
222
223def test_replace_buys_a_second_paid_label_on_purpose(tmp_path, monkeypatch):
224 data_dir, root, purchases = tfa.paid_carrier_shop(tmp_path, monkeypatch)
225 assert ttr.buy_label(root, shipment_id="shp-1")["ok"]
226 refused = ttr.buy_label(root, shipment_id="shp-1")
227 assert refused["status"] == 409 and refused["tracking_number"] == "PAID-1"
228 assert ttr.buy_label(root, shipment_id="shp-1", replace="true")["ok"]
229 assert purchases() == 2 and ttr.read(data_dir)["tracking_number"] == "PAID-2"
230
231
232def test_a_carrier_that_says_no_releases_the_claim(tmp_path, monkeypatch):
233 """ok=false is the connector's own word that nothing was bought, so the
234 next click may try again without `replace`."""
235 data_dir, root, purchases = tfa.paid_carrier_shop(tmp_path, monkeypatch)
236 real = ttr.read(data_dir)
237 assert real["label_purchase"] == ""
238 connector = tmp_path / "carrier-packages" / "app-fakeco" / "connectors" / "fakeco.py"
239 connector.write_text(connector.read_text().replace(
240 " n = _spend()\n",
241 " if os.environ.get('FAKECO_DECLINE'):\n"
242 " return {'ok': False, 'error': 'address not served'}\n"
243 " n = _spend()\n"))
244 monkeypatch.setenv("FAKECO_DECLINE", "1")
245 declined = ttr.buy_label(root, shipment_id="shp-1")
246 assert declined["status"] == 502 and purchases() == 0
247 assert ttr.read(data_dir)["label_purchase"] == ""
248 monkeypatch.delenv("FAKECO_DECLINE")
249 assert ttr.buy_label(root, shipment_id="shp-1")["ok"] and purchases() == 1
250
251
252# --- stripe_checkout (transport stubbed by the findings helper) -----------------
253
254def test_unreadable_refunds_do_not_become_an_open_balance_either(tmp_path, monkeypatch):
255 tfa.stripe_shop(tmp_path, monkeypatch)
256 real = _break_reads(monkeypatch, "refunds")
257 result, calls = tfa.stripe_checkout_call(monkeypatch)
258 monkeypatch.setattr(object_records, "read_collection_records", real)
259 assert result["status"] == 503 and calls == []
260
261
262def test_a_part_payment_gets_a_fresh_session_for_what_is_left(tmp_path, monkeypatch):
263 data_dir = tfa.stripe_shop(tmp_path, monkeypatch)
264 first, calls1 = tfa.stripe_checkout_call(monkeypatch)
265 object_records.create_collection_record(
266 "payments", {"id": "p-part", "invoice_id": "inv-1", "amount_cents": "1000",
267 "method": "card", "received_on": "2026-07-10",
268 "status": "received", "owner_id": "dan"}, base_dir=data_dir)
269 second, calls2 = tfa.stripe_checkout_call(monkeypatch)
270 assert first["amount_cents"] == 250000 and second["amount_cents"] == 249000
271 assert (calls1[0]["headers"]["Idempotency-Key"]
272 != calls2[0]["headers"]["Idempotency-Key"])
273
274
275# --- resolve_dispute ------------------------------------------------------------
276
277import test_disputes as td # noqa: E402
278
279
280def _entries_for(data_dir, dispute_id):
281 return [e for e in td.entries(data_dir)
282 if e.get("generated_from") == f"disputes/{dispute_id}"]
283
284
285def test_a_credit_up_to_what_was_paid_is_issued(tmp_path, monkeypatch):
286 data_dir, root = td.shop_with_a_dispute(tmp_path, monkeypatch, cents=3600)
287 td.wallet(data_dir)
288 result = td.resolve(root, dispute_id="dis-1", resolution_kind="credit",
289 amount_cents="3600")
290 assert result["ok"], result
291 assert [e["amount_minor"] for e in _entries_for(data_dir, "dis-1")] == ["3600"]
292 assert td.disputes(data_dir)[0]["resolution_claim"] == ""
293
294
295def test_the_credit_ceiling_subtracts_refunds_and_other_disputes_credits(
296 tmp_path, monkeypatch):
297 data_dir, root = td.shop_with_a_dispute(tmp_path, monkeypatch, cents=3600)
298 td.wallet(data_dir)
299 td.dispute(data_dir, "dis-2")
300 assert td.resolve(root, dispute_id="dis-2", resolution_kind="refund",
301 amount_cents="1000")["ok"]
302 td.dispute(data_dir, "dis-3")
303 assert td.resolve(root, dispute_id="dis-3", resolution_kind="credit",
304 amount_cents="2000")["ok"]
305
306 refused = td.resolve(root, dispute_id="dis-1", resolution_kind="credit",
307 amount_cents="601")
308 assert refused["status"] == 409 and refused["ceiling_cents"] == "600", refused
309 assert _entries_for(data_dir, "dis-1") == []
310 # Refused means unclaimed: the operator can simply ask for less.
311 assert td.resolve(root, dispute_id="dis-1", resolution_kind="credit",
312 amount_cents="600")["ok"]
313
314
315def test_an_admin_may_knowingly_credit_more_than_was_paid(tmp_path, monkeypatch):
316 data_dir, root = td.shop_with_a_dispute(tmp_path, monkeypatch, cents=3600)
317 td.wallet(data_dir)
318 admin = {"user_id": "boss", "roles": ["admin"]}
319 refused = td.resolve(root, dispute_id="dis-1", resolution_kind="credit",
320 amount_cents="5000", _identity=admin)
321 assert refused["status"] == 409, "an admin still has to say so"
322 owner_flag = td.resolve(root, dispute_id="dis-1", resolution_kind="credit",
323 amount_cents="5000", over_ceiling="true")
324 assert owner_flag["status"] == 409, "the flag is an admin's, not the owner's"
325 granted = td.resolve(root, dispute_id="dis-1", resolution_kind="credit",
326 amount_cents="5000", over_ceiling="true", _identity=admin)
327 assert granted["ok"], granted
328
329
330def test_a_credit_on_an_unpaid_order_is_refused(tmp_path, monkeypatch):
331 data_dir, root = td.shop_with_a_dispute(tmp_path, monkeypatch, cents=3600)
332 td.wallet(data_dir)
333 object_records.update_collection_record(
334 "payments", "pay-1", {"status": "bounced"}, base_dir=data_dir, actor="test")
335 refused = td.resolve(root, dispute_id="dis-1", resolution_kind="credit",
336 amount_cents="100")
337 assert refused["status"] == 409 and refused["ceiling_cents"] == "0"
338
339
340def test_a_live_claim_refuses_and_a_dead_one_is_taken_over(tmp_path, monkeypatch):
341 from datetime import datetime, timedelta, timezone
342 data_dir, root = td.shop_with_a_dispute(tmp_path, monkeypatch, cents=3600)
343 now = datetime.now(timezone.utc)
344
345 def hold(when):
346 object_records.update_collection_record(
347 "disputes", "dis-1",
348 {"resolution_claim": f"other {when.isoformat(timespec='seconds')}"},
349 base_dir=data_dir, actor="test", preserve_read_only=True)
350
351 hold(now)
352 busy = td.resolve(root, dispute_id="dis-1", resolution_kind="refund",
353 amount_cents="1200")
354 assert busy["status"] == 409 and busy["code"] == "in_progress"
355 assert td.refunds(data_dir) == []
356
357 hold(now - timedelta(minutes=30)) # the request that held it died
358 done = td.resolve(root, dispute_id="dis-1", resolution_kind="refund",
359 amount_cents="1200")
360 assert done["ok"] and len(td.refunds(data_dir)) == 1
361
362
363# --- checkout: a session token that outlives its first cart ---------------------
364
365def _second_basket_on_one_token(tmp_path, monkeypatch):
366 """action_cart opens a NEW cart for a token whose cart was checked out,
367 so a shopper who buys, keeps browsing and buys again has two carts on
368 one token: the old one checked out, the new one open."""
369 data_dir, root = tfa.shop(tmp_path, monkeypatch)
370 tfa.add_to_cart(root, "tok-1")
371 first = tfa.checkout(root, "tok-1")
372 assert first["ok"] and not first.get("duplicate")
373 tfa.add_to_cart(root, "tok-1", "2")
374 carts = tfa.rows(data_dir, "carts")
375 assert len(carts) == 2 and {c["session_token"] for c in carts} == {"tok-1"}
376 return data_dir, root, first
377
378
379def test_a_retried_second_checkout_names_the_second_order_not_the_first(
380 tmp_path, monkeypatch):
381 """The retry (a reload, a double click landing after the first finished)
382 used to be answered with the FIRST cart on the token that had a claim,
383 which is the older purchase: the shopper was shown, and sent to pay,
384 an order they had already paid."""
385 data_dir, root, first = _second_basket_on_one_token(tmp_path, monkeypatch)
386 second = tfa.checkout(root, "tok-1")
387 assert second["ok"] and not second.get("duplicate")
388 assert second["order_id"] != first["order_id"]
389
390 retry = tfa.checkout(root, "tok-1")
391 assert retry["duplicate"] is True
392 assert retry["order_id"] == second["order_id"], (retry, first, second)
393 assert len(tfa.rows(data_dir, "orders")) == 2
394
395
396def test_a_click_during_the_second_checkout_names_the_one_being_written(
397 tmp_path, monkeypatch):
398 """While the second basket is claimed (its order is being written), the
399 overlapping click must be told about THAT order, not the old one."""
400 data_dir, root, first = _second_basket_on_one_token(tmp_path, monkeypatch)
401 basket = next(c for c in tfa.rows(data_dir, "carts") if c["status"] == "open")
402 object_records.update_collection_record(
403 "carts", basket["id"], {"checkout_claim": "order-being-written"},
404 base_dir=data_dir, actor="test", preserve_read_only=True)
405
406 overlap = tfa.checkout(root, "tok-1")
407 assert overlap["duplicate"] is True
408 assert overlap["order_id"] == "order-being-written", (overlap, first)