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

0 downloads

dbbasic-object-server/tests/test_merchandising.py
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.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
test_merchandising.py · 23.5 KB · 540 lines
1"""Merchandising: categories, variants, images, and two words from the
2shopper.
3
4The design decision under test is that A VARIANT IS A PRODUCT. Nothing in
5the basket, the checkout, the stock ledger or the books needed a line
6changed to sell sizes and colours, because all of them were already keyed
7on product_id -- so what is worth testing is the seam where that decision
8becomes visible: one card per parent rather than one per size, a heading
9that cannot be bought, a picker whose radios post a child's product_id,
10and an out-of-stock size that is SHOWN rather than hidden (hiding it is
11how a shopper concludes this shop does not sell their size).
12
13The rest is the two things a text-only shop is missing: a photograph,
14which is a pointer to the file endpoint that already exists and an honest
15blank when there is none, and the two optional fields a shopper types at
16checkout that the person packing the box is the only one who needs.
17"""
18
19import json
20import pathlib
21import shutil
22
23from conftest import stage_collection
24
25import object_execution
26import object_ids
27import object_records
28import python_object_runtime
29
30REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
31PACKAGES = REPO_ROOT / "packages"
32SHOP_OBJECTS = PACKAGES / "app-shop" / "objects"
33SHIPPING_OBJECTS = PACKAGES / "app-shipping" / "objects"
34RUNTIME = python_object_runtime.PythonObjectRuntime()
35
36TOKEN = "sess-merch-1"
37COOKIE = "cart"
38
39
40def setup_env(tmp_path, monkeypatch, *, settings=()):
41 """A data dir with every collection this slice touches, and ONE object
42 root holding the shop's and the shipping package's objects.
43
44 The merged root is what an installed server actually looks like, and
45 the only way site_shop's sibling calls (action_cart, action_checkout)
46 and the packing slip resolve the way they will in production.
47 """
48 data_dir = tmp_path / "data"
49 for pkg, name in (("app-shop", "carts"), ("app-shop", "cart_items"),
50 ("app-catalog", "products"), ("app-catalog", "locations"),
51 ("app-catalog", "stock_moves"),
52 ("app-orders", "orders"), ("app-orders", "order_lines"),
53 ("app-invoices", "invoices"), ("app-invoices", "invoice_lines"),
54 ("app-payments", "payments"),
55 ("app-shipping", "shipments"),
56 ("app-shipping", "shipment_lines")):
57 stage_collection(data_dir, pkg, name)
58 rows = "".join(f"s{i}\t{k}\t{v}\t\n" for i, (k, v) in enumerate(settings))
59 stage_collection(data_dir, "app-settings", "app_settings", rows=rows)
60
61 objects_root = tmp_path / "objects"
62 for source in (SHOP_OBJECTS, SHIPPING_OBJECTS):
63 shutil.copytree(source, objects_root, dirs_exist_ok=True)
64
65 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
66 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root))
67 return data_dir, objects_root
68
69
70def teach_orders_the_note_fields(data_dir):
71 """No-op since orders v4 carries the columns; kept as the seam's name.
72
73 When these tests were written the fields lived only on the cart and
74 this helper doctored the staged schema to prove the day-it-lands
75 branch. orders v4 shipped them, so the real schema now answers yes and
76 the helper has nothing to add -- but the call sites still read as
77 "this test is about the columns existing", which is worth more than
78 deleting it.
79 """
80 return
81
82
83def hide_the_note_fields(data_dir):
84 """Strip customer_note/gift_message from the STAGED orders schema.
85
86 The inverse of the original helper, and now the one doing real work:
87 action_checkout asks the schema (`_has_field`) rather than assuming,
88 exactly as it does for shipping_cents, so BOTH branches deserve a
89 test -- including the one an operator running an older app-orders
90 still lives in.
91 """
92 path = data_dir / "schemas" / "orders.json"
93 schema = json.loads(path.read_text())
94 schema["fields"] = [field for field in schema["fields"]
95 if field["name"] not in ("customer_note", "gift_message")]
96 path.write_text(json.dumps(schema))
97
98
99def run(objects_root, object_id, method, payload):
100 return object_execution.execute_object(
101 RUNTIME,
102 object_execution.ObjectExecutionRequest(
103 object_id, method=method, payload=payload),
104 roots=[objects_root]).result
105
106
107def cart(objects_root, action="get", **payload):
108 return run(objects_root, "action_cart", "POST",
109 {"session_token": TOKEN, "action": action, **payload})
110
111
112def checkout(objects_root, **payload):
113 return run(objects_root, "action_checkout", "POST",
114 {"session_token": TOKEN, **payload})
115
116
117def page(objects_root, **payload):
118 payload.setdefault("_cookies", {COOKIE: TOKEN})
119 return run(objects_root, "site_shop", "GET", payload)
120
121
122def product(data_dir, product_id, name, cents=1200, **fields):
123 record = {"id": product_id, "name": name, "sku": product_id.upper(),
124 "product_type": "physical", "price_cents": str(cents),
125 "currency": "USD", "is_active": "true", "owner_id": "shop"}
126 record.update({key: str(value) for key, value in fields.items()})
127 return object_records.create_collection_record("products", record,
128 base_dir=data_dir)
129
130
131def location(data_dir, location_id, name, kind="warehouse"):
132 return object_records.create_collection_record(
133 "locations",
134 {"id": location_id, "name": name, "location_type": kind,
135 "owner_id": "shop"},
136 base_dir=data_dir)
137
138
139def stock_in(data_dir, product_id, quantity, *, to="loc-shelf"):
140 return object_records.create_collection_record(
141 "stock_moves",
142 {"id": object_ids.new_uuid4(), "product_id": product_id,
143 "to_location_id": to, "quantity": str(quantity), "reason": "purchase",
144 "occurred_at": "2026-06-01", "owner_id": "shop"},
145 base_dir=data_dir)
146
147
148def tote_with_variants(data_dir, *, parent_cents=0):
149 """A parent that is a heading and two variants that are real things.
150
151 parent_cents stays 0 by default: that is what makes the parent
152 unsellable, and it is the ordinary case -- nobody sells "a tote bag",
153 they sell the medium navy one.
154 """
155 product(data_dir, "tote", "Tote Bag", parent_cents, category="Bags")
156 product(data_dir, "tote-m", "Tote Bag, medium", 2000, category="Bags",
157 parent_product_id="tote", options='{"size": "M", "colour": "navy"}')
158 product(data_dir, "tote-l", "Tote Bag, large", 2500, category="Bags",
159 parent_product_id="tote", options='{"size": "L", "colour": "navy"}')
160
161
162# --- categories: one flat field, grouped, and nothing hidden -----------------
163
164def test_the_index_groups_cards_under_category_headings(tmp_path, monkeypatch):
165 """Alphabetical, because there is no ordering field and inventing one
166 would be the first plank of the taxonomy tree this deliberately is
167 not."""
168 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
169 product(data_dir, "p1", "Enamel Mug", 1200, category="Kitchen")
170 product(data_dir, "p2", "Tea Towel", 800, category="Kitchen")
171 product(data_dir, "p3", "Linocut Print", 4000, category="Art")
172 body = page(objects_root)["body"]
173
174 assert '<h2 class="shop-category">Art</h2>' in body
175 assert '<h2 class="shop-category">Kitchen</h2>' in body
176 assert body.index("Art</h2>") < body.index("Kitchen</h2>")
177 # The cards land under the right heading, not merely on the page.
178 kitchen = body[body.index("Kitchen</h2>"):]
179 assert "Enamel Mug" in kitchen and "Tea Towel" in kitchen
180 assert "Linocut Print" not in kitchen
181
182
183def test_an_uncategorised_product_lands_in_everything_else_and_is_still_sold(
184 tmp_path, monkeypatch):
185 """Never hidden. A product nobody got round to filing is still stock
186 somebody paid for, and a shop that dropped it off the page would be
187 losing sales it could not see it was losing."""
188 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
189 product(data_dir, "p1", "Enamel Mug", 1200, category="Kitchen")
190 product(data_dir, "p2", "Odd Thing", 500) # no category
191 body = page(objects_root)["body"]
192
193 assert '<h2 class="shop-category">Everything else</h2>' in body
194 assert body.index("Kitchen</h2>") < body.index("Everything else</h2>")
195 tail = body[body.index("Everything else</h2>"):]
196 assert "Odd Thing" in tail
197 assert 'name="product_id" value="p2"' in tail # still addable
198
199
200def test_a_shop_that_categorises_nothing_gets_the_grid_it_always_had(
201 tmp_path, monkeypatch):
202 """It is not a shop with one category called "Everything else": it is
203 a shop that does not use categories, and a heading over the whole page
204 would be furniture pretending to be information."""
205 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
206 product(data_dir, "p1", "Enamel Mug", 1200)
207 product(data_dir, "p2", "Tea Towel", 800)
208 body = page(objects_root)["body"]
209
210 assert '<h2 class="shop-category">' not in body
211 assert "Everything else" not in body
212 assert body.count('<div class="shop-grid">') == 1
213
214
215# --- variants: a variant IS a product ----------------------------------------
216
217def test_one_card_per_parent_and_the_variants_are_not_cards_of_their_own(
218 tmp_path, monkeypatch):
219 """A grid showing Small, Medium and Large as three tiles is a grid
220 nobody can read: the shopper is looking for a tote bag, not for the
221 medium."""
222 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
223 tote_with_variants(data_dir)
224 body = page(objects_root)["body"]
225
226 assert body.count('<div class="shop-card">') == 1
227 assert '<a href="/shop/tote">Tote Bag</a>' in body
228 assert "Tote Bag, medium" not in body
229 assert 'name="product_id" value="tote-m"' not in body
230
231 # The parent is a heading, so the card offers the only thing that is
232 # possible -- go and choose -- and prices itself from the cheapest
233 # child rather than printing a 0.00 nobody can buy anything at.
234 assert "Choose options" in body
235 assert "from USD 20.00" in body
236 assert 'name="do" value="add"' not in body
237
238
239def test_a_parent_with_variants_cannot_go_in_a_basket_and_the_refusal_names_them(
240 tmp_path, monkeypatch):
241 """A "no" that does not say what to do instead is a lost sale."""
242 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
243 tote_with_variants(data_dir)
244
245 refused = cart(objects_root, "add", product_id="tote")
246 assert refused["status"] == 409
247 assert "size and colour" in refused["error"] # the seller's words
248 assert "M / navy" in refused["error"] and "L / navy" in refused["error"]
249 # And the same answer as data, for an API client or an agent that has
250 # to choose one without scraping prose.
251 assert {choice["product_id"] for choice in refused["options"]} == {
252 "tote-m", "tote-l"}
253 assert {choice["label"] for choice in refused["options"]} == {
254 "M / navy", "L / navy"}
255 assert object_records.read_collection_records(
256 "cart_items", base_dir=data_dir) == []
257
258
259def test_a_parent_that_carries_its_own_price_is_still_sellable(
260 tmp_path, monkeypatch):
261 """Having variants does not make a product a heading -- having no price
262 of its own does. A base model that is genuinely for sale stays for
263 sale."""
264 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
265 location(data_dir, "loc-shelf", "Shelf")
266 tote_with_variants(data_dir, parent_cents=1800)
267 stock_in(data_dir, "tote", 4)
268 assert cart(objects_root, "add", product_id="tote")["subtotal_cents"] == 1800
269 # And it appears in its own picker beside the variants, under its own
270 # name rather than a set of options it does not have.
271 body = page(objects_root, product_id="tote")["body"]
272 assert 'value="tote" required> Tote Bag' in body
273
274
275def test_adding_a_variant_works_and_the_line_says_which_one(
276 tmp_path, monkeypatch):
277 """The whole argument in one assertion: the basket took a product_id
278 and stamped a description, exactly as it does for anything else. No
279 code in this path knows the word "variant"."""
280 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
281 tote_with_variants(data_dir)
282
283 result = cart(objects_root, "add", product_id="tote-m", quantity="2")
284 assert result["subtotal_cents"] == 4000
285 item = object_records.read_collection_records("cart_items",
286 base_dir=data_dir)[0]
287 assert item["product_id"] == "tote-m"
288 assert item["description"] == "Tote Bag, medium"
289 assert item["unit_price_cents"] == "2000"
290
291
292def test_the_parent_page_renders_a_picker_holding_every_variant(
293 tmp_path, monkeypatch):
294 """Radios posting a CHILD's product_id into the same add form every
295 card uses -- one path into a basket, still, and no JavaScript."""
296 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
297 location(data_dir, "loc-shelf", "Shelf")
298 tote_with_variants(data_dir)
299 stock_in(data_dir, "tote-m", 3)
300 stock_in(data_dir, "tote-l", 2)
301 body = page(objects_root, product_id="tote")["body"]
302
303 assert 'name="do" value="add"' in body
304 assert '<fieldset class="options">' in body
305 assert 'name="product_id" value="tote-m"' in body
306 assert 'name="product_id" value="tote-l"' in body
307 assert "M / navy" in body and "L / navy" in body
308 assert "USD 20.00" in body and "USD 25.00" in body
309 # Nothing pre-selected: a default that quietly ships the small is a
310 # wrong parcel, a return and a refund.
311 assert "checked" not in body
312 # The heading has no price of its own to print.
313 assert "from USD 20.00" in body
314
315
316def test_an_out_of_stock_variant_is_shown_and_not_addable(
317 tmp_path, monkeypatch):
318 """Hiding the medium is how a shopper concludes this shop does not
319 sell their size and goes to one that does. Saying so tells them to
320 come back."""
321 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
322 location(data_dir, "loc-shelf", "Shelf")
323 tote_with_variants(data_dir)
324 stock_in(data_dir, "tote-l", 3) # medium has none
325 body = page(objects_root, product_id="tote")["body"]
326
327 assert 'value="tote-m" disabled' in body
328 assert "Out of stock" in body
329 assert "M / navy" in body # shown, not hidden
330 assert 'value="tote-l" required' in body
331
332
333def test_a_variant_page_says_what_it_is_and_finds_its_way_back(
334 tmp_path, monkeypatch):
335 """A shopper who landed on the medium from a search result needs the
336 other sizes, or the only size this shop appears to sell is the one a
337 search engine happened to index."""
338 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
339 tote_with_variants(data_dir)
340 body = page(objects_root, product_id="tote-m")["body"]
341
342 assert "size: M, colour: navy" in body
343 assert '<a href="/shop/tote">All options of Tote Bag</a>' in body
344 # It is a product like any other: its own price and its own add form.
345 assert "USD 20.00" in body
346 assert 'name="product_id" value="tote-m"' in body
347
348
349def test_a_variant_whose_parent_is_withdrawn_is_still_a_product(
350 tmp_path, monkeypatch):
351 """Otherwise it would be collapsed under a card that is not on the
352 page at all -- stock nobody can see and nobody can buy."""
353 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
354 tote_with_variants(data_dir)
355 object_records.update_collection_record(
356 "products", "tote", {"is_active": "false"}, base_dir=data_dir,
357 actor="test")
358 body = page(objects_root)["body"]
359
360 assert "Tote Bag, medium" in body
361 assert 'name="product_id" value="tote-m"' in body # addable
362 assert body.count('<div class="shop-card">') == 2
363
364
365# --- images: a pointer, and an honest blank ----------------------------------
366
367def test_a_product_with_an_image_renders_one_from_the_file_endpoint(
368 tmp_path, monkeypatch):
369 """The catalogue stores an id and the bytes come from the endpoint
370 app-files already serves. A shop-specific image route would be a
371 second way to read the same bytes with its own permission story to get
372 wrong."""
373 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
374 product(data_dir, "p1", "Enamel Mug", 1200, image_file_id="file-abc")
375 for body in (page(objects_root)["body"],
376 page(objects_root, product_id="p1")["body"]):
377 assert '<img class="shop-image" src="/api/files/file-abc"' in body
378 assert 'alt="Enamel Mug"' in body # the name, as alt text
379 assert '<div class="shop-image placeholder">' not in body
380
381
382def test_a_product_with_no_image_gets_a_blank_block_not_a_broken_one(
383 tmp_path, monkeypatch):
384 """A broken-image icon reads as a shop whose pages do not work, which
385 is worse than a product nobody has photographed yet."""
386 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
387 product(data_dir, "p1", "Enamel Mug", 1200)
388 for body in (page(objects_root)["body"],
389 page(objects_root, product_id="p1")["body"]):
390 assert '<div class="shop-image placeholder"></div>' in body
391 assert "<img" not in body
392
393
394# --- gift and special instructions -------------------------------------------
395
396NOTE = "Leave it with the neighbour at number 12"
397GIFT = "Happy birthday, Ada"
398
399
400def test_the_checkout_form_offers_both_fields_and_no_gift_flag(
401 tmp_path, monkeypatch):
402 """No tickbox, because the slip carries no prices by construction and
403 every parcel is already gift-safe. A flag somebody forgets is how the
404 amount paid ends up stapled to a present."""
405 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
406 product(data_dir, "p1", "Mug", 1200, product_type="service")
407 cart(objects_root, "add", product_id="p1")
408 body = page(objects_root)["body"]
409
410 assert '<textarea name="customer_note"' in body
411 assert '<textarea name="gift_message"' in body
412 assert "which never shows prices" in body
413 assert 'name="is_gift"' not in body
414
415
416def test_checkout_stamps_both_notes_on_the_order_when_orders_has_them(
417 tmp_path, monkeypatch):
418 """The packer reads the ORDER. A note that lives only on a basket is a
419 note nobody in the warehouse ever sees."""
420 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
421 teach_orders_the_note_fields(data_dir)
422 product(data_dir, "p1", "Mug", 1200, product_type="service")
423 cart(objects_root, "add", product_id="p1")
424
425 result = checkout(objects_root, customer_email="ada@example.test",
426 customer_note=NOTE, gift_message=GIFT)
427 assert result["ok"]
428 assert "notes_on_cart_only" not in result
429
430 order = object_records.get_collection_record("orders", result["order_id"],
431 base_dir=data_dir)
432 assert order["customer_note"] == NOTE
433 assert order["gift_message"] == GIFT
434
435
436def test_without_the_columns_the_notes_stay_on_the_cart_and_it_is_reported(
437 tmp_path, monkeypatch):
438 """Schema-aware, exactly as shipping_cents is: a missing column costs
439 the packer a note, a rejected write would cost the shopper the order.
440 Saying so is the difference between a degraded outcome and a silent
441 one."""
442 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
443 hide_the_note_fields(data_dir)
444 product(data_dir, "p1", "Mug", 1200, product_type="service")
445 cart(objects_root, "add", product_id="p1")
446
447 result = checkout(objects_root, customer_email="ada@example.test",
448 customer_note=NOTE, gift_message=GIFT)
449 assert result["ok"]
450 assert sorted(result["notes_on_cart_only"]) == ["customer_note",
451 "gift_message"]
452 basket = object_records.get_collection_record("carts", result["cart_id"],
453 base_dir=data_dir)
454 assert basket["customer_note"] == NOTE
455 assert basket["gift_message"] == GIFT
456
457
458def test_a_checkout_with_no_notes_writes_none_and_says_nothing(
459 tmp_path, monkeypatch):
460 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
461 teach_orders_the_note_fields(data_dir)
462 product(data_dir, "p1", "Mug", 1200, product_type="service")
463 cart(objects_root, "add", product_id="p1")
464
465 result = checkout(objects_root, customer_email="ada@example.test")
466 assert "notes_on_cart_only" not in result
467 order = object_records.get_collection_record("orders", result["order_id"],
468 base_dir=data_dir)
469 assert not order.get("customer_note") and not order.get("gift_message")
470
471
472def test_the_packing_slip_prints_both_and_still_shows_no_prices(
473 tmp_path, monkeypatch):
474 """The end of the chain the shopper started at a textarea. And the
475 property that makes the gift message safe to print at all: this page
476 has no prices on it, ever, so there is nothing to suppress."""
477 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
478 teach_orders_the_note_fields(data_dir)
479 product(data_dir, "p1", "Enamel Mug", 1200, product_type="service")
480 cart(objects_root, "add", product_id="p1", quantity="2")
481 placed = checkout(objects_root, customer_email="ada@example.test",
482 customer_name="Ada Lovelace",
483 customer_note=NOTE, gift_message=GIFT)
484
485 order_line = [row for row in object_records.read_collection_records(
486 "order_lines", base_dir=data_dir)
487 if row["order_id"] == placed["order_id"]][0]
488 shipment = object_records.create_collection_record(
489 "shipments",
490 {"id": "shp-1", "order_id": placed["order_id"], "status": "shipped",
491 "shipped_on": "2026-06-16", "ship_to_name": "Ada Lovelace",
492 "owner_id": "shop"},
493 base_dir=data_dir)
494 object_records.create_collection_record(
495 "shipment_lines",
496 {"id": "shl-1", "shipment_id": shipment["id"],
497 "order_line_id": order_line["id"],
498 "description": "Enamel Mug", "quantity": "2", "owner_id": "shop"},
499 base_dir=data_dir)
500
501 body = run(objects_root, "site_packing_slip", "GET",
502 {"shipment_id": "shp-1"})["body"]
503 assert "Special instructions" in body and NOTE in body
504 assert "Gift message" in body and GIFT in body
505 assert "$" not in body
506 assert "12.00" not in body and "24.00" not in body
507 assert "_cents" not in body
508
509
510# --- the regression guard ----------------------------------------------------
511
512def test_a_product_with_no_variants_behaves_exactly_as_it_always_did(
513 tmp_path, monkeypatch):
514 """Every field this slice added is optional, and a shop that sets none
515 of them must not be able to tell the slice happened -- except for the
516 photograph placeholder, which is the one deliberate change to a page
517 that was text-only."""
518 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
519 location(data_dir, "loc-shelf", "Shelf")
520 product(data_dir, "p1", "Enamel Mug", 1200,
521 description="Twelve ounces. Chips beautifully.")
522 stock_in(data_dir, "p1", 5)
523
524 index = page(objects_root)["body"]
525 assert '<a href="/shop/p1">Enamel Mug</a>' in index
526 assert "USD 12.00" in index
527 assert 'name="product_id" value="p1"' in index
528 assert '<h2 class="shop-category">' not in index
529 assert "Choose options" not in index
530
531 detail = page(objects_root, product_id="p1")["body"]
532 assert "Twelve ounces. Chips beautifully." in detail
533 assert "In stock" in detail
534 assert "<fieldset" not in detail # no picker
535 assert "All options of" not in detail
536
537 assert cart(objects_root, "add", product_id="p1", quantity="2")[
538 "subtotal_cents"] == 2400
539 placed = checkout(objects_root, customer_email="ada@example.test")
540 assert placed["ok"] and placed["total_cents"] == 2400