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_cafe_findings.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_cafe_findings.py · 20.8 KB · 446 lines
1"""Findings from a simulated café run, each checked through the real HTTP API.
2
3A café is a shop whose customers sign in to order coffee, which makes every
4customer a registered user and every public object a door anyone can push.
5These tests call the app the way a customer would -- the ASGI app in this
6process, permission enforcement ON, scripts/try_package.py's Sandbox -- because
7the bugs they pin were all invisible to the in-process tests: those call an
8object as server code, and the server code was trusting what only a request
9could have said.
10"""
11
12from __future__ import annotations
13
14import json
15from datetime import datetime, timedelta
16from pathlib import Path
17
18import pytest
19
20import object_records
21from scripts.try_package import Sandbox
22
23ROOT = Path(__file__).resolve().parents[1]
24
25
26def _soon(hours=3):
27 return (datetime.now() + timedelta(hours=hours)).replace(microsecond=0)
28
29
30@pytest.fixture()
31def cafe():
32 with Sandbox(["app-shop", "app-pickup", "app-promotions", "app-payments",
33 "app-settings"]) as box:
34 box.add_user("alice")
35 box.add_user("mallory")
36 box.add_user("maria", roles=["manager"])
37 status, _ = box.call("admin", "POST", "/collections/products/records",
38 {"id": "latte", "name": "Latte", "price_cents": "400",
39 "product_type": "service", "is_active": "true",
40 "owner_id": "shop"})
41 assert status == 201
42 start = _soon()
43 status, _ = box.call("admin", "POST", "/collections/pickup_slots/records",
44 {"id": "slot1", "starts_at": start.isoformat(),
45 "ends_at": (start + timedelta(minutes=15)).isoformat(),
46 "capacity": "1", "orders_taken": "0",
47 "is_open": "true", "owner_id": "shop"})
48 assert status == 201
49 yield box
50
51
52# -- 1. the slot board is shop configuration ----------------------------------
53
54def test_a_customer_cannot_resize_close_or_add_a_pickup_slot(cafe):
55 """One PUT from any signed-in customer raised a full window to 99 places.
56
57 Slots are what a shop can physically hand over; a customer who can edit
58 them can book a window the kitchen cannot serve, or post a window of
59 their own onto the public picker."""
60 status, _ = cafe.call("alice", "PUT", "/collections/pickup_slots/records/slot1",
61 {"capacity": "99"})
62 assert status == 403
63 status, _ = cafe.call("alice", "PUT", "/collections/pickup_slots/records/slot1",
64 {"orders_taken": "0", "is_open": "true"})
65 assert status == 403
66 status, _ = cafe.call("alice", "POST", "/collections/pickup_slots/records",
67 {"starts_at": _soon().isoformat(), "capacity": "5"})
68 assert status == 403
69 status, body = cafe.call("admin", "GET", "/collections/pickup_slots/records/slot1")
70 assert body["record"]["capacity"] == "1"
71
72
73def test_a_customer_still_reads_the_board_and_a_manager_runs_it(cafe):
74 """Read stays open to signed-in users (storefront renders read it); the
75 shift is run by role:manager, and still cannot delete a window."""
76 status, body = cafe.call("alice", "GET", "/collections/pickup_slots/records/slot1")
77 assert status == 200 and body["record"]["id"] == "slot1"
78 status, body = cafe.call("maria", "PUT", "/collections/pickup_slots/records/slot1",
79 {"capacity": "3"})
80 assert status == 200 and body["record"]["capacity"] == "3"
81 status, body = cafe.call("maria", "POST", "/collections/pickup_slots/records",
82 {"starts_at": _soon(4).isoformat(), "capacity": "2"})
83 assert status == 201
84 status, _ = cafe.call("maria", "DELETE", "/collections/pickup_slots/records/slot1")
85 assert status == 403
86
87
88def test_a_manager_who_loses_the_role_cannot_edit_their_own_slot(cafe):
89 """The owner fallback is off for update: a slot a manager created is the
90 shop's, not theirs, once they no longer run the shift."""
91 # Created by an admin on alice's behalf: a manager may not name another
92 # owner on create (the owner_id rule refuses that without an on_behalf grant).
93 status, body = cafe.call("admin", "POST", "/collections/pickup_slots/records",
94 {"starts_at": _soon(5).isoformat(), "capacity": "2",
95 "owner_id": "alice"})
96 assert status == 201
97 status, _ = cafe.call("alice", "PUT",
98 f"/collections/pickup_slots/records/{body['record']['id']}",
99 {"capacity": "50"})
100 assert status == 403
101
102
103def test_the_withdrawn_slot_grant_is_retracted_so_an_upgrade_removes_it():
104 """A box installed before 0.1.3 holds the old registered create/read/update
105 rule; only a `retracted` entry identical to it removes it there."""
106 fragment = json.loads((ROOT / "packages/app-pickup/permissions/rules.json").read_text())
107 retracted = [{k: v for k, v in rule.items() if k != "reason"}
108 for rule in fragment["retracted"]]
109 assert {"effect": "allow", "principal": "registered",
110 "actions": ["create", "read", "update"],
111 "collection": "pickup_slots"} in retracted
112 for rule in fragment["rules"]:
113 if rule.get("collection") == "pickup_slots" and rule["principal"] == "registered":
114 assert rule["actions"] == ["read"]
115
116
117# -- 2. nothing a shopper sends sets a price ----------------------------------
118
119def _cart(box, **payload):
120 """An anonymous shopper's basket call. The first add carries no token;
121 the shop mints one and every later call sends it back."""
122 body = {"action": "add", **payload}
123 if getattr(box, "basket", ""):
124 body["session_token"] = box.basket
125 status, answer = box.call("anon", "POST", "/objects/action_cart", body)
126 if isinstance(answer, dict) and answer.get("session_token"):
127 box.basket = answer["session_token"]
128 return status, answer
129
130
131def _checkout(box, **payload):
132 return box.call("anon", "POST", "/objects/action_checkout",
133 {"session_token": getattr(box, "basket", ""), **payload})
134
135
136def _rows(box, collection):
137 return object_records.read_collection_records(collection, base_dir=box.data_dir)
138
139
140def _declare_oat_milk(box):
141 status, _ = box.call("admin", "PUT", "/collections/products/records/latte",
142 {"modifiers": '{"Oat milk": 60, "No foam": 0}'})
143 assert status == 200
144
145
146def test_oat_milk_written_into_the_note_at_no_charge_is_refused(cafe):
147 """The café run's order: a latte, note "oat milk", modifier_cents 0.
148 The cook reads the note; the till read the 0."""
149 _declare_oat_milk(cafe)
150 status, body = _cart(cafe, product_id="latte", line_note="oat milk",
151 modifier_cents="0")
152 assert status == 400 and "Oat milk" in body["error"]
153 assert _rows(cafe, "cart_items") == []
154
155
156def test_a_price_the_request_states_is_refused_unless_it_is_the_shops(cafe):
157 """A delta for an extra nobody declared, or the wrong price for one
158 that is declared, is a stranger pricing their own lunch."""
159 status, _ = _cart(cafe, product_id="latte", modifier_cents="1",
160 line_note="extra shot")
161 assert status == 400
162 _declare_oat_milk(cafe)
163 status, body = _cart(cafe, product_id="latte", modifiers=["Oat milk"],
164 modifier_cents="0")
165 assert status == 400 and body["modifier_cents"] == 60
166 status, body = _cart(cafe, product_id="latte", modifiers=["Soy milk"])
167 assert status == 400 and "Oat milk" in body["error"]
168 assert _rows(cafe, "cart_items") == []
169
170
171def test_a_named_extra_is_priced_by_the_shop_and_charged_at_checkout(cafe):
172 _declare_oat_milk(cafe)
173 status, body = _cart(cafe, product_id="latte", modifiers="oat milk, no foam")
174 assert status == 200, body
175 line = body["lines"][0]
176 assert (line["modifier_cents"], line["line_total_cents"]) == (60, 460)
177 assert line["modifiers"] == ["Oat milk", "No foam"]
178 status, body = _checkout(cafe, preview="true")
179 assert status == 200 and body["total_cents"] == 460
180
181
182def test_a_line_priced_by_its_client_before_the_fix_cannot_be_checked_out(cafe):
183 """A basket line already in the store with a delta no declared extra
184 explains is refused at checkout, not charged as it stands."""
185 _cart(cafe, product_id="latte")
186 item = _rows(cafe, "cart_items")[0]
187 object_records.update_collection_record(
188 "cart_items", item["id"], {"modifier_cents": "1"}, base_dir=cafe.data_dir)
189 status, body = _checkout(cafe, customer_email="ada@example.test")
190 assert status == 409 and body["inactive"][0]["cart_item_id"] == item["id"]
191 assert _rows(cafe, "orders") == []
192
193
194def test_a_changed_extra_price_is_shown_and_confirmed_like_a_unit_price(cafe):
195 _declare_oat_milk(cafe)
196 _cart(cafe, product_id="latte", modifiers=["Oat milk"])
197 cafe.call("admin", "PUT", "/collections/products/records/latte",
198 {"modifiers": '{"Oat milk": 75}'})
199 status, body = _checkout(cafe, customer_email="ada@example.test")
200 assert status == 409
201 change = body["price_changes"][0]
202 assert (change["kind"], change["was_cents"], change["now_cents"]) == ("modifier", 60, 75)
203 status, body = _checkout(cafe, customer_email="ada@example.test",
204 confirm_prices="true")
205 assert status == 200 and body["total_cents"] == 475
206
207
208@pytest.mark.parametrize("quantity", ["0.001", "1.5", "Infinity", "NaN"])
209def test_a_quantity_cannot_make_a_latte_cost_nothing(cafe, quantity):
210 """0.001 of a 400c latte rounded to a 0c line and a free order."""
211 status, body = _cart(cafe, product_id="latte", quantity=quantity)
212 assert status == 400, body
213 assert _rows(cafe, "cart_items") == []
214
215
216def test_a_public_checkout_cannot_choose_the_date_a_promotion_is_judged_on(cafe):
217 """`today` from the request redeemed a code that ended in 2020."""
218 status, _ = cafe.call("admin", "POST", "/collections/promotions/records",
219 {"code": "SUMMER", "kind": "percent", "value": "50",
220 "is_active": "true", "starts_on": "2020-06-01",
221 "ends_on": "2020-08-31", "owner_id": "shop"})
222 assert status == 201
223 _cart(cafe, product_id="latte")
224 status, body = _checkout(cafe, preview="true", promo_code="SUMMER",
225 today="2020-07-01")
226 assert status == 409 and "ended" in body["error"]
227
228
229def test_a_line_the_new_rules_would_refuse_can_still_be_taken_out(cafe):
230 """Setting a line to nothing removes it, whatever its note says: a
231 basket from before the fix must not trap a shopper's line."""
232 _cart(cafe, product_id="latte", line_note="oat milk")
233 _declare_oat_milk(cafe)
234 item = _rows(cafe, "cart_items")[0]
235 status, body = _cart(cafe, action="set", cart_item_id=item["id"], quantity="0")
236 assert status == 200 and body["lines"] == []
237
238
239def test_the_extras_and_the_note_must_fit_the_order_line(cafe):
240 """They travel to order_lines.line_note together (300 characters), so
241 an overlong pair is refused in the basket, not half-way through the
242 order."""
243 _declare_oat_milk(cafe)
244 status, body = _cart(cafe, product_id="latte", modifiers=["Oat milk"],
245 line_note="x" * 295)
246 assert status == 400 and "300" in body["error"]
247
248
249def test_a_mistyped_extras_list_declares_nothing_rather_than_something():
250 """Bad JSON, a negative, a fraction or a boolean price sell no extra;
251 they never sell one at a price nobody set."""
252 import object_cart
253 assert object_cart.declared_modifiers({"modifiers": "{oat"}) == {}
254 assert object_cart.declared_modifiers({"modifiers": '["Oat milk"]'}) == {}
255 assert object_cart.declared_modifiers(
256 {"modifiers": '{"A": -5, "B": 0.5, "C": true, "": 9, "D": "70"}'}) == {"D": 70}
257 assert object_cart.note_names_a_priced_extra(
258 "no oat milk", {"modifiers": '{"Oat milk": 60}'}, []) == ""
259 assert object_cart.note_names_a_priced_extra(
260 "extra hot; + oat milk", {"modifiers": '{"Oat milk": 60}'}, []) == "Oat milk"
261
262
263# -- 3. the shop mints the basket token ---------------------------------------
264
265def test_a_client_chosen_basket_token_is_refused_and_the_shop_mints_one(cafe):
266 """A basket opened on whatever token the request named, so the token
267 was whatever the client chose -- "a" included."""
268 for chosen in ("a", "my-chosen-token"):
269 status, body = cafe.call("anon", "POST", "/objects/action_cart",
270 {"session_token": chosen, "action": "add",
271 "product_id": "latte"})
272 assert status == 400 and body["code"] == "unknown_session_token"
273 long_but_chosen = "x" * 40
274 status, body = cafe.call("anon", "POST", "/objects/action_cart",
275 {"session_token": long_but_chosen, "action": "add",
276 "product_id": "latte"})
277 assert status == 404 and body["code"] == "unknown_session_token"
278 assert _rows(cafe, "carts") == []
279
280 status, body = cafe.call("anon", "POST", "/objects/action_cart",
281 {"action": "add", "product_id": "latte"})
282 assert status == 200
283 minted = body["session_token"]
284 assert len(minted) >= 32
285 status, body = cafe.call("anon", "POST", "/objects/action_cart",
286 {"session_token": minted, "action": "add",
287 "product_id": "latte"})
288 assert status == 200 and body["lines"][0]["quantity"] == "2"
289
290
291def test_another_caller_cannot_read_a_basket_by_guessing_its_token(cafe):
292 _cart(cafe, product_id="latte")
293 status, body = cafe.call("mallory", "POST", "/objects/action_cart",
294 {"session_token": "my-chosen-token", "action": "get"})
295 assert status == 400
296 status, body = cafe.call("mallory", "POST", "/objects/action_cart",
297 {"session_token": "y" * 32, "action": "get"})
298 assert status == 200 and body["lines"] == [] and body["cart_id"] == ""
299 status, body = cafe.call("mallory", "POST", "/objects/action_cart",
300 {"action": "get"})
301 assert status == 200 and body["lines"] == [] and body["session_token"] == ""
302
303
304def test_a_short_token_no_longer_reaches_its_checked_out_order(cafe):
305 """A basket opened on "a" before the fix and checked out answered a
306 repeat checkout on "a" with its order's pay and tracking links."""
307 object_records.create_collection_record(
308 "carts", {"id": "old", "session_token": "a", "status": "open",
309 "owner_id": "shop"}, base_dir=cafe.data_dir)
310 object_records.create_collection_record(
311 "cart_items", {"id": "old-1", "cart_id": "old", "product_id": "latte",
312 "description": "Latte", "quantity": "1",
313 "unit_price_cents": "400", "owner_id": "shop"},
314 base_dir=cafe.data_dir)
315 status, body = cafe.call("anon", "POST", "/objects/action_checkout",
316 {"session_token": "a",
317 "customer_email": "ada@example.test"})
318 assert status == 404 and "pay_path" not in body
319 assert _rows(cafe, "orders") == []
320
321
322def test_the_shop_page_takes_its_token_from_the_cart_not_from_the_visitor(cafe):
323 """site_shop passed a cookie or form token straight through. It now
324 forwards _identity, so action_cart mints, and the page sets the cookie
325 from what it was handed."""
326 chosen = "z" * 30
327 status, body = cafe.call("anon", "POST", "/objects/site_shop",
328 {"do": "add", "product_id": "latte",
329 "session_token": chosen})
330 assert status == 200, body
331 tokens = {row["session_token"] for row in _rows(cafe, "carts")}
332 assert chosen not in tokens and len(tokens) == 1
333 assert len(next(iter(tokens))) >= 32
334
335
336# -- 4. an unpaid booking's hold lapses -----------------------------------------
337
338def _book_slot1(box, email):
339 box.basket = ""
340 _cart(box, product_id="latte")
341 return _checkout(box, customer_email=email, fulfillment_method="pickup",
342 pickup_slot_id="slot1")
343
344
345def _age(box, order_id, minutes):
346 """Pretend the order was raised `minutes` ago (created_at is the record
347 store's own stamp, UTC with a Z)."""
348 from datetime import timezone
349 raised = (datetime.now(timezone.utc) - timedelta(minutes=minutes))
350 object_records.update_collection_record(
351 "orders", order_id,
352 {"created_at": raised.isoformat().replace("+00:00", "Z")},
353 base_dir=box.data_dir, preserve_read_only=True)
354
355
356def _picker_has_slot1(box):
357 status, body = box.call("anon", "POST", "/objects/action_pickup_slots", {})
358 assert status == 200
359 return any(slot["id"] == "slot1" for slot in body["slots"])
360
361
362def test_an_unpaid_checkout_stops_holding_its_window_after_the_hold(cafe):
363 """One unpaid order filled a one-place 6pm for good: the window refused
364 every later shopper and dropped off the picker."""
365 status, first = _book_slot1(cafe, "ghost@example.test")
366 assert status == 200, first
367 status, body = _book_slot1(cafe, "late@example.test")
368 assert status == 409 and "full" in body["error"]
369 assert not _picker_has_slot1(cafe)
370
371 _age(cafe, first["order_id"], 31) # default hold: 30 minutes
372 assert _picker_has_slot1(cafe)
373 status, body = _book_slot1(cafe, "late@example.test")
374 assert status == 200, body
375
376
377def test_a_paid_booking_keeps_its_place_however_old(cafe):
378 status, first = _book_slot1(cafe, "paid@example.test")
379 assert status == 200
380 object_records.create_collection_record(
381 "payments", {"id": "pay-1", "invoice_id": first["invoice_id"],
382 "amount_cents": "400", "status": "received",
383 "method": "card", "received_on": "2026-11-30",
384 "owner_id": "shop"},
385 base_dir=cafe.data_dir)
386 _age(cafe, first["order_id"], 600)
387 assert not _picker_has_slot1(cafe)
388 status, body = _book_slot1(cafe, "late@example.test")
389 assert status == 409
390
391
392def test_the_hold_is_a_setting_and_zero_keeps_every_hold(cafe):
393 status, first = _book_slot1(cafe, "ghost@example.test")
394 assert status == 200
395 status, setting = cafe.call("admin", "POST", "/collections/app_settings/records",
396 {"key": "pickup.hold_minutes", "value": "0"})
397 assert status == 201, setting
398 _age(cafe, first["order_id"], 600)
399 assert not _picker_has_slot1(cafe) # 0: holds never lapse
400 status, _ = cafe.call("admin", "PUT", "/collections/app_settings/records/"
401 + setting["record"]["id"], {"value": "120"})
402 assert status == 200
403 _age(cafe, first["order_id"], 60)
404 assert not _picker_has_slot1(cafe) # inside a two-hour hold
405 _age(cafe, first["order_id"], 121)
406 assert _picker_has_slot1(cafe)
407
408
409def test_a_public_caller_cannot_move_the_clock_the_slots_are_judged_by(cafe):
410 """`now` from the request decided "too soon" and "already passed"."""
411 status, body = cafe.call("anon", "POST", "/objects/action_pickup_slots",
412 {"now": "2000-01-01T00:00:00"})
413 assert status == 200 and not body["now"].startswith("2000")
414
415
416def test_which_bookings_lapse_is_decided_from_evidence_and_fails_closed():
417 """Pure: cancelled always lapses; an unpaid draft lapses only past the
418 hold; unreadable payments lapse nothing; "Z" and "+00:00" are one
419 instant."""
420 import object_pickup
421 from datetime import timezone
422 now = datetime(2026, 11, 30, 12, 0, tzinfo=timezone.utc)
423 orders = [
424 {"status": "draft", "invoice_id": "i1", "notes": "Web [pickup_slots/s1]",
425 "created_at": "2026-11-30T11:00:00Z"}, # old, unpaid
426 {"status": "draft", "invoice_id": "i2", "notes": "[pickup_slots/s1]",
427 "created_at": "2026-11-30T11:50:00+00:00"}, # inside hold
428 {"status": "draft", "invoice_id": "i3", "notes": "[pickup_slots/s1]",
429 "created_at": "2026-11-30T09:00:00Z"}, # old, paid
430 {"status": "cancelled", "notes": "[pickup_slots/s2]"},
431 {"status": "confirmed", "notes": "[pickup_slots/s2]",
432 "created_at": "2026-01-01T00:00:00Z"},
433 {"status": "draft", "invoice_id": "i4", "notes": "[pickup_slots/s1]"}, # no age
434 ]
435 paid = object_pickup.paid_invoice_ids(
436 [], [{"invoice_id": "i3", "status": "received"},
437 {"invoice_id": "i1", "status": "bounced"}])
438 assert object_pickup.lapsed_holds(orders, paid_invoice_ids=paid, now=now,
439 minutes=30) == {"s1": 1, "s2": 1}
440 assert object_pickup.lapsed_holds(orders, paid_invoice_ids=None, now=now,
441 minutes=30) == {"s2": 1}
442 assert object_pickup.lapsed_holds(orders, paid_invoice_ids=paid, now=now,
443 minutes=0) == {"s2": 1}
444 assert object_pickup.orders_holding({"id": "s1", "orders_taken": "3"},
445 {"s1": 1}) == 2
446 assert object_pickup.hold_minutes("") == 30