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_fulfilment_action_races.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_fulfilment_action_races.py · 11.8 KB · 265 lines
1"""The fulfilment actions under a double click, raced for real.
2
3Each action here reads the state it decides on (what has shipped, what has
4been received, whether a return was dispositioned, whether the order is
5already drop-shipped), then writes the documents that follow from it.
6Without a claim, two submits that both read before either wrote both
7wrote: two shipments for one order, two receipts for one pallet, two
8refunds for one returned mug, two purchase orders to a vendor.
9
10The races are released together by a barrier (tests/test_commerce_action_
11races.race) and widened with a short sleep after the read each action
12decides from, so every thread has read before any writes. Every test here
13was run against the unfixed action and failed.
14
15NO NETWORK. Nothing in these actions calls out, and an autouse fixture
16refuses sockets and urllib so a regression that tried would fail here.
17"""
18
19from __future__ import annotations
20
21import socket
22import urllib.request
23
24import pytest
25
26import object_records
27import test_commerce_action_races as tcr
28
29ROUNDS = 3
30
31
32@pytest.fixture(autouse=True)
33def no_network(monkeypatch):
34 def refuse(*args, **kwargs):
35 raise AssertionError("a test in this file tried to reach the network")
36
37 monkeypatch.setattr(socket.socket, "connect", refuse)
38 monkeypatch.setattr(socket.socket, "connect_ex", refuse)
39 monkeypatch.setattr(socket, "create_connection", refuse)
40 monkeypatch.setattr(urllib.request, "urlopen", refuse)
41 monkeypatch.setattr(urllib.request.OpenerDirector, "open", refuse)
42
43
44def _busy_or_ok(result):
45 return result.get("ok") or result.get("code") == "in_progress"
46
47
48# --- disposition_return ---------------------------------------------------------
49
50@pytest.mark.parametrize("round_", range(ROUNDS))
51def test_racing_dispositions_of_one_return_move_and_refund_once(
52 tmp_path, monkeypatch, round_):
53 """Four clicks on "restock and refund". Every one read the parcel as
54 `received` before any wrote; only one may put the mug back and send the
55 money."""
56 import test_returns as tr
57 data_dir, root = tr.shop_with_a_return(tmp_path, monkeypatch)
58 created = tr.authorized_return(root)
59 tr.receive(data_dir, created["shipment_id"])
60 line_id = tr.shipment_lines(data_dir, created["shipment_id"])[0]["id"]
61 before = tr.on_shelf(data_dir)
62 tcr.widen(monkeypatch, "shipment_lines") # between the status look and the writes
63
64 results = tcr.race(4, lambda i: tr.disposition(
65 root, shipment_id=created["shipment_id"], refund="full",
66 lines=[{"shipment_line_id": line_id, "disposition": "restock",
67 "quantity": "1"}]))
68
69 refunds = tr.refunds(data_dir)
70 assert len(refunds) == 1, f"{len(refunds)} refunds for one returned mug"
71 assert len(tr.moves(data_dir, "return")) == 1
72 assert tr.on_shelf(data_dir) == before + 1
73 assert all(_busy_or_ok(r) for r in results), results
74 assert sum(1 for r in results if r.get("refund_id")) == 1, results
75 parcel = object_records.get_collection_record(
76 "shipments", created["shipment_id"], base_dir=data_dir)
77 assert parcel["status"] == "dispositioned"
78 assert parcel["action_claim"] == ""
79
80
81# --- receive_goods --------------------------------------------------------------
82
83@pytest.mark.parametrize("round_", range(ROUNDS))
84def test_racing_receipts_of_one_pallet_book_it_once(tmp_path, monkeypatch, round_):
85 """A double click on "Receive everything" for a PO of 10: every submit
86 read 10 outstanding before any wrote. Stock posting follows the
87 receipt lines, so a second receipt is 10 mugs nobody delivered."""
88 import test_receiving as trc
89 data_dir, root = trc.stocked_shop(tmp_path, monkeypatch)
90 tcr.widen(monkeypatch, "receipt_lines")
91
92 results = tcr.race(4, lambda i: trc.receive(root, order_id="po-1"))
93
94 received = sum(int(line["quantity_received"])
95 for line in trc.receipt_lines(data_dir))
96 assert received == 10, f"{received} received against a PO of 10"
97 assert len(trc.receipts(data_dir)) == 1
98 assert all(_busy_or_ok(r) for r in results), results
99 assert sum(1 for r in results if r.get("receipt_id")) == 1, results
100 po = object_records.get_collection_record("orders", "po-1", base_dir=data_dir)
101 assert po["action_claim"] == ""
102
103
104# --- create_shipment ------------------------------------------------------------
105
106@pytest.mark.parametrize("round_", range(ROUNDS))
107def test_racing_ship_it_clicks_raise_one_shipment(tmp_path, monkeypatch, round_):
108 """Two boxes for one order: the second is a second set of goods leaving
109 the shelf the moment either reaches `shipped`."""
110 import test_shipping as tsh
111 data_dir, root = tsh.stocked_shop(tmp_path, monkeypatch)
112 tcr.widen(monkeypatch, "shipment_lines")
113
114 results = tcr.race(4, lambda i: tsh.create_shipment(root, order_id="ord-1"))
115
116 shipped = sum(int(line["quantity"]) for line in tsh.shipment_lines(data_dir))
117 assert shipped == 3, f"{shipped} units on shipments for an order of 3"
118 assert len(tsh.shipments(data_dir)) == 1
119 assert all(_busy_or_ok(r) for r in results), results
120 assert sum(1 for r in results if r.get("shipment_id")) == 1, results
121
122
123# --- dropship_order -------------------------------------------------------------
124
125@pytest.mark.parametrize("round_", range(ROUNDS))
126def test_racing_dropships_of_one_order_raise_one_purchase_order(
127 tmp_path, monkeypatch, round_):
128 """"One sale order spawns exactly one PO" was checked against
129 linked_order_id as read at the start; four clicks all read it blank."""
130 import test_dropship as tds
131 data_dir, root = tds.shop_that_can_dropship(tmp_path, monkeypatch)
132 tcr.widen(monkeypatch, "order_lines")
133
134 results = tcr.race(4, lambda i: tds.dropship(root))
135
136 pos = tds.orders_of(data_dir, "purchase")
137 assert len(pos) == 1, f"{len(pos)} purchase orders for one sale"
138 assert len(tds.lines_of(data_dir, pos[0]["id"])) == 1
139 sale = object_records.get_collection_record("orders", "ord-1", base_dir=data_dir)
140 assert sale["linked_order_id"] == pos[0]["id"]
141 assert sale["action_claim"] == ""
142 assert all(r.get("ok") or r.get("status") == 409 for r in results), results
143 assert sum(1 for r in results if r.get("ok")) == 1, results
144
145
146# --- authorize_return -----------------------------------------------------------
147
148@pytest.mark.parametrize("round_", range(ROUNDS))
149def test_racing_return_authorizations_cannot_promise_more_than_shipped(
150 tmp_path, monkeypatch, round_):
151 """Three mugs went out. Four people on the phone each authorize the
152 return of three: before the claim every one read 3 returnable."""
153 import test_returns as tr
154 data_dir, root = tr.shop_with_a_return(tmp_path, monkeypatch)
155 tcr.widen(monkeypatch, "shipment_lines")
156
157 results = tcr.race(4, lambda i: tr.authorized_return(
158 root, lines=[{"order_line_id": "line-1", "quantity": "3"}]))
159
160 inbound = {s["id"] for s in tr.shipments(data_dir) if s["direction"] == "inbound"}
161 promised = sum(int(line["quantity"]) for line in tr.shipment_lines(data_dir)
162 if line["shipment_id"] in inbound)
163 assert promised == 3, f"{promised} authorized back of 3 shipped"
164 assert len(tr.rmas(data_dir)) == 1
165 assert all(r.get("ok") or r.get("status") == 409 for r in results), results
166
167
168# --- the claim itself -----------------------------------------------------------
169
170def _claim_stamp(minutes_ago):
171 from datetime import datetime, timedelta, timezone
172 when = datetime.now(timezone.utc) - timedelta(minutes=minutes_ago)
173 return f"someone-else {when.isoformat(timespec='seconds')}"
174
175
176def _plant_claim(data_dir, collection, record_id, claim):
177 object_records.update_collection_record(
178 collection, record_id, {"action_claim": claim},
179 base_dir=data_dir, actor="test", preserve_read_only=True)
180
181
182def test_a_held_claim_turns_the_next_request_away_with_nothing_written(
183 tmp_path, monkeypatch):
184 import test_shipping as tsh
185 data_dir, root = tsh.stocked_shop(tmp_path, monkeypatch)
186 _plant_claim(data_dir, "orders", "ord-1", _claim_stamp(1))
187
188 result = tsh.create_shipment(root, order_id="ord-1")
189
190 assert result["status"] == 409 and result["code"] == "in_progress", result
191 assert tsh.shipments(data_dir) == []
192 held = object_records.get_collection_record("orders", "ord-1", base_dir=data_dir)
193 assert held["action_claim"].startswith("someone-else "), "not ours to clear"
194
195
196def test_a_dead_requests_claim_is_taken_over_after_ten_minutes(
197 tmp_path, monkeypatch):
198 """A worker killed between claiming and releasing must not lock the
199 order for ever; what it did write is in the history the next one reads."""
200 import test_shipping as tsh
201 data_dir, root = tsh.stocked_shop(tmp_path, monkeypatch)
202 _plant_claim(data_dir, "orders", "ord-1", _claim_stamp(11))
203
204 result = tsh.create_shipment(root, order_id="ord-1")
205
206 assert result["ok"] and result["lines"] == 1, result
207 order = object_records.get_collection_record("orders", "ord-1", base_dir=data_dir)
208 assert order["action_claim"] == ""
209
210
211def test_a_refused_request_releases_its_claim(tmp_path, monkeypatch):
212 import test_receiving as trc
213 data_dir, root = trc.stocked_shop(tmp_path, monkeypatch)
214 refused = trc.receive(root, order_id="po-1",
215 lines=[{"order_line_id": "po-line-1",
216 "quantity_received": "11"}])
217 assert refused["status"] == 409 and refused["over_receive"]
218 po = object_records.get_collection_record("orders", "po-1", base_dir=data_dir)
219 assert po["action_claim"] == ""
220 assert trc.receive(root, order_id="po-1")["ok"]
221
222
223def test_a_request_that_fails_part_way_releases_its_claim(tmp_path, monkeypatch):
224 """A write that raises is still a request that ended: the next click
225 must be able to see what landed and carry on, not wait ten minutes."""
226 import test_returns as tr
227 data_dir, root = tr.shop_with_a_return(tmp_path, monkeypatch)
228 created = tr.authorized_return(root)
229 tr.receive(data_dir, created["shipment_id"])
230 line_id = tr.shipment_lines(data_dir, created["shipment_id"])[0]["id"]
231 real = object_records.create_collection_record
232
233 def failing(collection, *a, **k):
234 if collection == "refunds":
235 raise OSError("disk full while writing the refund")
236 return real(collection, *a, **k)
237
238 monkeypatch.setattr(object_records, "create_collection_record", failing)
239 outcome = tr.run(root, "action_disposition_return", "POST", {
240 "_identity": {"user_id": "shop"}, "shipment_id": created["shipment_id"],
241 "refund": "full", "lines": [{"shipment_line_id": line_id,
242 "disposition": "restock", "quantity": "1"}]})
243 monkeypatch.setattr(object_records, "create_collection_record", real)
244 assert outcome is None or not outcome.get("ok")
245 parcel = object_records.get_collection_record(
246 "shipments", created["shipment_id"], base_dir=data_dir)
247 assert parcel["action_claim"] == "" and parcel["status"] == "received"
248
249
250@pytest.mark.parametrize("collection,record", [
251 ("orders", {"id": "o-squat", "doc_type": "sale", "number": "SO-9",
252 "customer_name": "x", "currency": "USD", "status": "draft"}),
253 ("shipments", {"id": "s-squat", "order_id": "o", "direction": "outbound",
254 "status": "open", "service": "ground"}),
255])
256def test_no_client_write_can_set_an_action_claim(tmp_path, monkeypatch,
257 collection, record):
258 """read_only: an ordinary write cannot plant a claim that would lock an
259 order (or a return) away from the people who work it."""
260 import test_shipping as tsh
261 data_dir, _root = tsh.stocked_shop(tmp_path, monkeypatch)
262 with pytest.raises(ValueError):
263 object_records.create_collection_record(
264 collection, {**record, "action_claim": _claim_stamp(0)},
265 base_dir=data_dir)