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_app_orders_totals.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_app_orders_totals.py · 13.7 KB · 347 lines
1"""Behavior tests for packages/app-orders: the order_totals HANDLES
2handler (integer-cents arithmetic, floor-not-round tax, idempotence,
3delete handling) and the guarded status transitions on orders.status.
4
5Mirrors tests/test_app_invoices_totals.py. Structural/manifest/permission
6tests live in tests/test_app_orders_package.py.
7"""
8
9import os
10from pathlib import Path
11
12import pytest
13
14import object_execution
15import object_packages
16import object_permissions
17import object_record_changes
18import object_records
19import python_object_runtime
20
21PACKAGES_ROOT = Path(__file__).resolve().parents[1] / "packages"
22
23
24@pytest.fixture(autouse=True)
25def _objects_dir_is_restored():
26 """_install points DBBASIC_OBJECTS_DIR at this test's object root; put
27 back whatever was there before, after the test."""
28 saved = os.environ.get("DBBASIC_OBJECTS_DIR")
29 yield
30 if saved is None:
31 os.environ.pop("DBBASIC_OBJECTS_DIR", None)
32 else:
33 os.environ["DBBASIC_OBJECTS_DIR"] = saved
34
35
36def _install(tmp_path):
37 """Install app-orders into an isolated data dir/object root and return
38 (data_dir, object_root, runtime).
39 """
40 data_dir = tmp_path / "data"
41 object_root = tmp_path / "objects"
42 object_root.mkdir()
43 # conftest's isolated_default_data_dir fixture already points
44 # DBBASIC_DATA_DIR at tmp_path / "data" for this test process; keep
45 # them in sync so order_totals.py's own env-based _data_dir()
46 # resolves to the same directory this test writes into.
47 os.environ["DBBASIC_DATA_DIR"] = str(data_dir)
48 # order_lines declares a locked check (stock_hold) whose object lives
49 # in this package: a write to a line must be able to find it, and a
50 # declared check that is not installed refuses the write (fails closed).
51 os.environ["DBBASIC_OBJECTS_DIR"] = str(object_root)
52
53 object_packages.install_package(
54 "app-orders", root=PACKAGES_ROOT, base_dir=data_dir, object_roots=[object_root]
55 )
56 runtime = python_object_runtime.PythonObjectRuntime(base_dir=data_dir)
57 return data_dir, object_root, runtime
58
59
60def _fire(runtime, object_root, record_id, action):
61 return object_execution.execute_object(
62 runtime,
63 object_execution.ObjectExecutionRequest(
64 "system_order_totals",
65 method="EVENT",
66 payload={
67 "event": f"order_lines.record.{action}",
68 "collection": "order_lines",
69 "record_id": record_id,
70 "action": action,
71 },
72 ),
73 roots=[object_root],
74 )
75
76
77def _make_order(data_dir, **overrides):
78 record = {
79 "id": "ord_1",
80 "number": "SO-0001",
81 "customer_name": "Example Consulting LLC",
82 "owner_id": "u1",
83 }
84 record.update(overrides)
85 return object_records.create_collection_record("orders", record, base_dir=data_dir, actor="test")
86
87
88def _make_line(data_dir, **overrides):
89 record = {
90 "order_id": "ord_1",
91 "description": "Line item",
92 "quantity": "1",
93 "unit_price_cents": "100",
94 "owner_id": "u1",
95 }
96 record.update(overrides)
97 return object_records.create_collection_record("order_lines", record, base_dir=data_dir, actor="test")
98
99
100def test_line_total_is_quantity_times_unit_price_floored(tmp_path):
101 data_dir, object_root, runtime = _install(tmp_path)
102 _make_order(data_dir)
103 _make_line(data_dir, id="ol_1", quantity="3", unit_price_cents="1999")
104
105 result = _fire(runtime, object_root, "ol_1", "created")
106 assert result.ok is True
107
108 line = object_records.get_collection_record("order_lines", "ol_1", base_dir=data_dir)
109 assert line["line_total_cents"] == "5997" # 3 * 1999
110
111
112def test_line_tax_uses_basis_points_rounded_half_up(tmp_path):
113 """8.25% (825 bps) of 5997 cents is 494.7525 cents -- 495, half-up.
114 It floored to 494, while the cart rounded the same line half-up
115 (finding M18). Decision 2 (owner, 2026-11-30): tax is rounded half-up,
116 once per rate group.
117 """
118 data_dir, object_root, runtime = _install(tmp_path)
119 _make_order(data_dir)
120 _make_line(data_dir, id="ol_1", quantity="3", unit_price_cents="1999", tax_rate_bps="825")
121
122 _fire(runtime, object_root, "ol_1", "created")
123
124 line = object_records.get_collection_record("order_lines", "ol_1", base_dir=data_dir)
125 assert line["line_total_cents"] == "5997"
126 assert line["line_tax_cents"] == "495"
127
128
129def test_multi_line_order_totals_match_hand_computed_cents(tmp_path):
130 """The worked example this package's report cites:
131
132 Line 1: qty 3, unit_price_cents 1999, tax_rate_bps 825
133 line_total = 3 * 1999 = 5997
134 line_tax = half-up(5997 * 825 / 10000) = 495 (494.7525)
135 Line 2: qty 1, unit_price_cents 5000, tax_rate_bps 0
136 line_total = 5000
137 line_tax = 0
138 subtotal_cents = 5997 + 5000 = 10997
139 tax_cents = 495 + 0 = 495
140 total_cents = 10997 + 495 = 11492
141 """
142 data_dir, object_root, runtime = _install(tmp_path)
143 _make_order(data_dir)
144 _make_line(data_dir, id="ol_1", description="Widgets",
145 quantity="3", unit_price_cents="1999", tax_rate_bps="825")
146 _make_line(data_dir, id="ol_2", description="Shipping",
147 quantity="1", unit_price_cents="5000", tax_rate_bps="0")
148
149 _fire(runtime, object_root, "ol_1", "created")
150 _fire(runtime, object_root, "ol_2", "created")
151
152 order = object_records.get_collection_record("orders", "ord_1", base_dir=data_dir)
153 assert order["subtotal_cents"] == "10997"
154 assert order["tax_cents"] == "495"
155 assert order["total_cents"] == "11492"
156
157
158def test_fractional_quantity_uses_decimal_not_float(tmp_path):
159 """2.5 hours at 10000 cents/hr must floor to exactly 25000 cents --
160 Decimal arithmetic, never a bare float multiplication that could
161 introduce binary rounding error.
162 """
163 data_dir, object_root, runtime = _install(tmp_path)
164 _make_order(data_dir)
165 _make_line(data_dir, id="ol_1", quantity="2.5", unit_price_cents="10000")
166
167 _fire(runtime, object_root, "ol_1", "created")
168
169 line = object_records.get_collection_record("order_lines", "ol_1", base_dir=data_dir)
170 assert line["line_total_cents"] == "25000"
171
172
173def test_recompute_is_idempotent_and_skips_a_no_op_write(tmp_path):
174 data_dir, object_root, runtime = _install(tmp_path)
175 _make_order(data_dir)
176 _make_line(data_dir, id="ol_1", quantity="3", unit_price_cents="1999", tax_rate_bps="825")
177
178 first = _fire(runtime, object_root, "ol_1", "created")
179 assert first.result["changed"] is True
180
181 changes_before = object_record_changes.list_record_changes(
182 "orders", record_id="ord_1", base_dir=data_dir
183 )["total"]
184
185 second = _fire(runtime, object_root, "ol_1", "updated")
186 assert second.result["changed"] is False
187
188 changes_after = object_record_changes.list_record_changes(
189 "orders", record_id="ord_1", base_dir=data_dir
190 )["total"]
191 assert changes_after == changes_before # no redundant write/record_change
192
193
194def test_deleting_a_line_recovers_order_id_from_record_changes_and_resums(tmp_path):
195 """The deleted line is already gone by the time this handler's
196 post-commit dispatch fires -- it must recover order_id from the
197 record_changes log's own 'before' snapshot, not the (now 404) live
198 record.
199 """
200 data_dir, object_root, runtime = _install(tmp_path)
201 _make_order(data_dir)
202 _make_line(data_dir, id="ol_1", quantity="3", unit_price_cents="1999", tax_rate_bps="825")
203 _make_line(data_dir, id="ol_2", quantity="1", unit_price_cents="5000")
204 _fire(runtime, object_root, "ol_1", "created")
205 _fire(runtime, object_root, "ol_2", "created")
206
207 order = object_records.get_collection_record("orders", "ord_1", base_dir=data_dir)
208 assert order["total_cents"] == "11492"
209
210 object_records.delete_collection_record("order_lines", "ol_2", base_dir=data_dir, actor="test")
211 result = _fire(runtime, object_root, "ol_2", "delete")
212 assert result.ok is True
213 assert result.result["order_id"] == "ord_1"
214
215 order_after = object_records.get_collection_record("orders", "ord_1", base_dir=data_dir)
216 assert order_after["subtotal_cents"] == "5997"
217 assert order_after["tax_cents"] == "495"
218 assert order_after["total_cents"] == "6492"
219
220
221def test_deleting_a_line_with_the_real_dispatcher_verb_resums_the_order(tmp_path):
222 """object_server's dispatcher passes the RAW change verb ("create" /
223 "update" / "delete") in request["action"] -- only request["event"] uses
224 the past-participle form (see object_change_dispatch's payload-parity
225 note). The handler once compared against "deleted", so a real delete
226 fell through to the live-record lookup, found nothing, and silently
227 skipped the recompute.
228 """
229 data_dir, object_root, runtime = _install(tmp_path)
230 _make_order(data_dir)
231 _make_line(data_dir, id="ol_1", quantity="3", unit_price_cents="1999", tax_rate_bps="825")
232 _make_line(data_dir, id="ol_2", quantity="1", unit_price_cents="5000")
233 _fire(runtime, object_root, "ol_1", "create")
234 _fire(runtime, object_root, "ol_2", "create")
235
236 before = object_records.get_collection_record("orders", "ord_1", base_dir=data_dir)
237 assert before["total_cents"] == "11492"
238
239 object_records.delete_collection_record("order_lines", "ol_2", base_dir=data_dir, actor="test")
240 result = _fire(runtime, object_root, "ol_2", "delete")
241 assert result.ok is True
242 assert result.result["order_id"] == "ord_1"
243
244 after = object_records.get_collection_record("orders", "ord_1", base_dir=data_dir)
245 assert after["subtotal_cents"] == "5997"
246 assert after["total_cents"] == "6492"
247
248
249def test_zero_lines_leaves_order_at_zero_totals(tmp_path):
250 data_dir, object_root, runtime = _install(tmp_path)
251 _make_order(data_dir)
252
253 order = object_records.get_collection_record("orders", "ord_1", base_dir=data_dir)
254 assert order["subtotal_cents"] == "0"
255 assert order["total_cents"] == "0"
256
257
258def test_event_for_an_unrelated_collection_is_a_no_op(tmp_path):
259 data_dir, object_root, runtime = _install(tmp_path)
260 result = object_execution.execute_object(
261 runtime,
262 object_execution.ObjectExecutionRequest(
263 "system_order_totals",
264 method="EVENT",
265 payload={"event": "notes.record.created", "collection": "notes",
266 "record_id": "n1", "action": "created"},
267 ),
268 roots=[object_root],
269 )
270 assert result.ok is True
271 assert result.result["skipped"] == "not an order_lines event"
272
273
274# -- Guarded status transitions -------------------------------------------
275#
276# Exercised directly against object_records' own guard (the same function
277# update_collection_record calls internally) rather than round-tripping
278# through the full HTTP server for one field's worth of behavior --
279# requires the schema actually installed in a data dir first, since
280# get_schema resolves from base_dir, not from package source.
281
282def test_owner_may_move_draft_to_confirmed(tmp_path):
283 data_dir, _object_root, _runtime = _install(tmp_path)
284 subject = object_permissions.PermissionSubject(user_id="u1")
285 existing = {"status": "draft", "owner_id": "u1"}
286 updated = {"status": "confirmed", "owner_id": "u1"}
287
288 object_records._validate_field_transitions(
289 "orders", existing, updated, base_dir=data_dir, roots=None, subject=subject,
290 ) # no exception == allowed
291
292
293def test_non_owner_may_not_move_draft_to_confirmed(tmp_path):
294 data_dir, _object_root, _runtime = _install(tmp_path)
295 subject = object_permissions.PermissionSubject(user_id="someone_else")
296 existing = {"status": "draft", "owner_id": "u1"}
297 updated = {"status": "confirmed", "owner_id": "u1"}
298
299 with pytest.raises(object_records.TransitionNotAllowedError):
300 object_records._validate_field_transitions(
301 "orders", existing, updated, base_dir=data_dir, roots=None, subject=subject,
302 )
303
304
305def test_delivered_and_cancelled_are_terminal(tmp_path):
306 data_dir, _object_root, _runtime = _install(tmp_path)
307 subject = object_permissions.PermissionSubject(user_id="u1")
308
309 for terminal_status in ("delivered", "cancelled"):
310 existing = {"status": terminal_status, "owner_id": "u1"}
311 updated = {"status": "draft", "owner_id": "u1"}
312 with pytest.raises(object_records.InvalidRecordPayloadError):
313 object_records._validate_field_transitions(
314 "orders", existing, updated, base_dir=data_dir, roots=None, subject=subject,
315 )
316
317
318def test_full_happy_path_lifecycle_is_legal(tmp_path):
319 """draft -> confirmed -> processing -> shipped -> delivered, the real
320 order lifecycle end to end.
321 """
322 data_dir, _object_root, _runtime = _install(tmp_path)
323 subject = object_permissions.PermissionSubject(user_id="u1")
324
325 path = ["draft", "confirmed", "processing", "shipped", "delivered"]
326 for before, after in zip(path, path[1:]):
327 object_records._validate_field_transitions(
328 "orders", {"status": before, "owner_id": "u1"}, {"status": after, "owner_id": "u1"},
329 base_dir=data_dir, roots=None, subject=subject,
330 )
331
332
333def test_cancel_is_legal_from_draft_confirmed_and_processing_but_not_shipped(tmp_path):
334 data_dir, _object_root, _runtime = _install(tmp_path)
335 subject = object_permissions.PermissionSubject(user_id="u1")
336
337 for cancellable in ("draft", "confirmed", "processing"):
338 object_records._validate_field_transitions(
339 "orders", {"status": cancellable, "owner_id": "u1"}, {"status": "cancelled", "owner_id": "u1"},
340 base_dir=data_dir, roots=None, subject=subject,
341 )
342
343 with pytest.raises(object_records.InvalidRecordPayloadError):
344 object_records._validate_field_transitions(
345 "orders", {"status": "shipped", "owner_id": "u1"}, {"status": "cancelled", "owner_id": "u1"},
346 base_dir=data_dir, roots=None, subject=subject,
347 )