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_list_modes_spec.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, 18 minutes ago History
test_list_modes_spec.py · 29.5 KB · 750 lines
1"""Tests for plan/vocabulary/60-list-modes-spec.md: board/tree/calendar
2list-modes on the shared list generator (window.dbbasicList, list.py).
3
4Mirrors tests/test_detail_related_spec.py's testing style for the same
5generator family: source-assertion + structural-install checks for the
6JS-side pieces, plus real HTTP/library-level tests for the parts that
7actually execute in Python (the permission-gated fetch every mode reuses
8from 58, and the transition-guarded write board's drag reuses from the
9platform's existing `_validate_field_transitions`). Where node is on PATH,
10the PURE bucketing/nesting helpers (defaultGroupField, groupByColumn,
11buildTree, bucketByDate, ...) are also run behaviorally, the same pattern
12tests/test_app_talk_object.py uses for its own pure JS helpers -- these
13functions take plain data in and return plain data out, no DOM, so they
14run standalone under node with no shim beyond the extracted source.
15"""
16
17import json
18import re
19import shutil
20import subprocess
21from pathlib import Path
22
23import pytest
24
25from test_object_server import auth_headers, enable_admin_token, request, write_records
26
27import object_records
28import object_schemas
29import object_server
30
31pytestmark = pytest.mark.node # needs the `node` binary; `pytest -m node` selects these (scripts/release_gate.sh node)
32
33PACKAGES_ROOT = Path(__file__).resolve().parents[1] / "packages"
34APP_THEME_DIR = PACKAGES_ROOT / "app-theme"
35LIST_PATH = APP_THEME_DIR / "objects" / "site" / "list.py"
36STYLE_PATH = APP_THEME_DIR / "objects" / "site" / "style.py"
37
38
39def _list_source():
40 return LIST_PATH.read_text()
41
42
43def _style_source():
44 return STYLE_PATH.read_text()
45
46
47def _list_js():
48 """The `_JS` string literal body only -- source assertions below run
49 against the whole file (docstring included), but the node probes need
50 just the script so a shim doesn't have to fake out Python syntax."""
51 text = _list_source()
52 before, _, rest = text.partition('_JS = r"""\n')
53 assert rest, "_JS block not found in list.py"
54 js, _, _after = rest.partition('\n"""\n')
55 return js
56
57
58def _pure_helpers_js():
59 """The self-contained block of 60's pure functions (whereQueryString
60 through bucketByDate) -- no closure over `mount`/`cfg`/`document`, so
61 this excerpt runs standalone under node with zero shimming, the same
62 extract-and-probe approach test_app_talk_object.py uses."""
63 js = _list_js()
64 start = js.index(" function whereQueryString")
65 end = js.index(" // ---- feature flag + schema-driven mode resolution")
66 return js[start:end]
67
68
69def _run_node_probe(js_prelude, expression):
70 node = shutil.which("node")
71 if not node:
72 pytest.skip("node not on PATH")
73 probe = js_prelude + "\nconsole.log(JSON.stringify(" + expression + "));\n"
74 result = subprocess.run([node, "-e", probe], capture_output=True, text=True)
75 assert result.returncode == 0, f"node probe failed:\n{result.stderr}"
76 return json.loads(result.stdout)
77
78
79# ---------------------------------------------------------------------
80# Structural: list.py is still the one public static script (unchanged
81# object identity/permissions -- 60 extends the existing generator, it
82# does not add a new object, route, or execute rule).
83# ---------------------------------------------------------------------
84
85
86def test_site_list_is_still_the_one_public_static_script():
87 manifest = json.loads((APP_THEME_DIR / "dbbasic-package.json").read_text())
88 object_ids = {obj["id"] for obj in manifest["objects"]}
89 assert "site_list" in object_ids
90
91 rules = json.loads((APP_THEME_DIR / "permissions" / "rules.json").read_text())["rules"]
92 list_rules = [r for r in rules if r.get("object_id") == "site_list"]
93 assert len(list_rules) == 1
94 assert list_rules[0]["effect"] == "allow"
95 assert list_rules[0]["principal"] == "public"
96 assert list_rules[0]["actions"] == ["execute"]
97
98
99def test_list_generator_still_serves_window_dbbasicList():
100 import object_execution
101 import python_object_runtime
102
103 runtime = python_object_runtime.PythonObjectRuntime()
104 result = object_execution.execute_object(
105 runtime,
106 object_execution.ObjectExecutionRequest("site_list", payload={}),
107 roots=[APP_THEME_DIR / "objects"],
108 )
109 assert result.ok is True
110 assert result.result["content_type"] == "application/javascript; charset=utf-8"
111 assert "window.dbbasicList = function" in result.result["body"]
112
113
114def test_list_js_is_syntactically_valid_under_node():
115 node = shutil.which("node")
116 if not node:
117 pytest.skip("node not on PATH")
118 js = _list_js()
119 result = subprocess.run([node, "--check", "-"], input=js, capture_output=True, text=True)
120 assert result.returncode == 0, f"node --check failed:\n{result.stderr}"
121
122
123# ---------------------------------------------------------------------
124# 58 dependency: all three modes fetch through the SAME query builder and
125# endpoint shape the plain row list already uses -- no bespoke fetch, no
126# new operator beyond 58's own eq/gte/lte.
127# ---------------------------------------------------------------------
128
129
130def test_all_three_modes_reuse_the_58_where_query_builder_and_endpoint():
131 source = _list_source()
132 assert 'function whereQueryString(where, extra)' in source
133 assert 'encodeURIComponent(k) + "=" + encodeURIComponent(v)' in source
134 # Every fetch (row list, board, tree, calendar) hits the identical
135 # endpoint shape -- four call sites, one query-string builder.
136 assert source.count('"/collections/" + collection + "/records?limit=500"') == 4
137 # Calendar layers 58's own gte/lte range operators on top -- no new
138 # operator invented for this spec.
139 assert '".gte"' in source and '".lte"' in source
140
141
142def test_board_group_field_derivation_chain_documented_and_present():
143 source = _list_source()
144 assert "function defaultGroupField(schema)" in source
145 assert "schema.flow && schema.flow.field" in source
146 assert "f.transitions && Object.keys(f.transitions).length > 0" in source
147
148
149# ---------------------------------------------------------------------
150# 10-flow dependency: board's drag issues the ordinary PUT that already
151# runs _validate_field_transitions -- documented AND proven live below.
152# ---------------------------------------------------------------------
153
154
155def test_board_drag_issues_the_ordinary_put_no_new_write_path():
156 source = _list_source()
157 assert "_validate_field_transitions" in source
158 assert 'method: "PUT"' in source
159 assert '"/collections/" + collection + "/records/" + encodeURIComponent(id)' in source
160 # Nothing applied client-side before the response -- a rejected move
161 # reverts by re-drawing from the unmodified `all`, not an explicit undo.
162 assert "draw();" in source
163
164
165def test_board_is_one_mode_for_kanban_and_pipeline_not_two():
166 source = _list_source()
167 assert "ONE mode, not two" in source
168 assert "contacts.lead_status" in source
169 # The honest gap this spec is explicit about NOT closing here.
170 assert "Stage-6" in source
171
172
173def _write_transition_schema(data_dir, collection="board_items"):
174 path = data_dir / "schemas" / f"{collection}.json"
175 path.parent.mkdir(parents=True, exist_ok=True)
176 path.write_text(json.dumps({
177 "fields": [
178 {"name": "id"},
179 {"name": "title", "type": "text"},
180 {
181 "name": "status",
182 "type": "enum",
183 "enum": ["open", "assigned", "done", "cancelled"],
184 "transitions": {
185 "open": ["assigned", "cancelled"],
186 "assigned": ["done", {"to": "open", "when": {"owner_id": "$user_id"}}],
187 },
188 },
189 ],
190 }))
191 return collection
192
193
194def test_board_drag_shaped_put_is_rejected_for_an_illegal_column_move(tmp_path, monkeypatch):
195 """Proves 60's headline board claim at the HTTP layer, not just in
196 object_records.py's own unit tests: the exact PUT a board drag issues
197 (`PUT /collections/{c}/records/{id}` with the group field's new value)
198 is validated by the platform's existing, flow-independent
199 `_validate_field_transitions` -- an illegal `to` (not in the source
200 value's transitions list) comes back non-2xx, so the client-side
201 revert-by-redraw in list.py has something real to react to."""
202 data_dir = tmp_path / "data"
203 collection = _write_transition_schema(data_dir)
204 write_records(data_dir, collection, "id\ttitle\tstatus\nb1\tShip it\topen\n")
205 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
206 enable_admin_token(monkeypatch)
207
208 # "open" has no legal move straight to "done" -- exactly the shape of
209 # dragging a card two columns over that the source column's
210 # transitions map does not allow.
211 illegal_status, _, illegal_payload = request(
212 f"/collections/{collection}/records/b1",
213 method="PUT",
214 body=json.dumps({"status": "done"}).encode(),
215 headers=auth_headers(),
216 )
217 assert illegal_status in (400, 403)
218 assert illegal_payload["status"] == "error"
219
220 # The record was never mutated by the rejected drag.
221 unchanged = object_records.get_collection_record(collection, "b1", base_dir=data_dir)
222 assert unchanged["status"] == "open"
223
224
225def test_board_drag_shaped_put_succeeds_for_a_legal_column_move(tmp_path, monkeypatch):
226 data_dir = tmp_path / "data"
227 collection = _write_transition_schema(data_dir)
228 write_records(data_dir, collection, "id\ttitle\tstatus\nb1\tShip it\topen\n")
229 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
230 enable_admin_token(monkeypatch)
231
232 status, _, payload = request(
233 f"/collections/{collection}/records/b1",
234 method="PUT",
235 body=json.dumps({"status": "assigned"}).encode(),
236 headers=auth_headers(),
237 )
238 assert status == 200
239 assert payload["record"]["status"] == "assigned"
240
241
242def test_board_drag_out_of_a_guarded_column_honors_the_when_clause(tmp_path, monkeypatch):
243 """The 'assigned' -> 'open' move is guarded (owner_id must match the
244 caller) -- flow's own gates/flow_configs are Stage-6+ wiring this spec
245 doesn't build, but the underlying guard clause on the field's own
246 transitions map (10-flow's substrate, already shipped) is exactly what
247 a board drag rides, with or without flow installed on top."""
248 data_dir = tmp_path / "data"
249 path = data_dir / "schemas" / "board_items.json"
250 path.parent.mkdir(parents=True, exist_ok=True)
251 path.write_text(json.dumps({
252 "fields": [
253 {"name": "id"}, {"name": "owner_id"},
254 {
255 "name": "status", "type": "enum", "enum": ["open", "assigned"],
256 "transitions": {"assigned": [{"to": "open", "when": {"owner_id": "$user_id"}}]},
257 },
258 ],
259 }))
260 write_records(data_dir, "board_items", "id\towner_id\tstatus\nb1\towner-a\tassigned\n")
261 import object_permission_store
262 object_permission_store.replace_policy(
263 {
264 "access_mode": "role_based",
265 "rules": [
266 {
267 "effect": "allow",
268 "principal": "registered",
269 "actions": ["read", "update"],
270 "collection": "board_items",
271 "reason": "any signed-in user may drag any card -- the field's own "
272 "'when' guard is what's under test here, not row scoping",
273 }
274 ],
275 },
276 data_dir,
277 )
278 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
279 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
280 monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true")
281 enable_admin_token(monkeypatch)
282
283 other_status, _, other_payload = request(
284 "/collections/board_items/records/b1",
285 method="PUT",
286 body=json.dumps({"status": "open"}).encode(),
287 headers=[("x-dbbasic-user-id", "owner-b"), ("x-dbbasic-roles", "registered")],
288 )
289 owner_status, _, owner_payload = request(
290 "/collections/board_items/records/b1",
291 method="PUT",
292 body=json.dumps({"status": "open"}).encode(),
293 headers=[("x-dbbasic-user-id", "owner-a"), ("x-dbbasic-roles", "registered")],
294 )
295
296 assert other_status == 403
297 assert owner_status == 200
298 assert owner_payload["record"]["status"] == "open"
299
300
301# ---------------------------------------------------------------------
302# Board pure helpers, run behaviorally under node.
303# ---------------------------------------------------------------------
304
305
306def test_default_group_field_chain_behaves_under_node():
307 helpers = _pure_helpers_js()
308 probe = helpers + "\nconsole.log(JSON.stringify({" + """
309 flowWins: defaultGroupField({
310 flow: {field: "stage"},
311 fields: [{name: "stage", type: "enum", enum: ["a", "b"]},
312 {name: "other", type: "enum", enum: ["x"], transitions: {x: ["y"]}}],
313 }),
314 guardedEnumWins: defaultGroupField({
315 fields: [{name: "kind", type: "enum", enum: ["a"]},
316 {name: "status", type: "enum", enum: ["open", "closed"], transitions: {open: ["closed"]}}],
317 }),
318 bareEnumFallback: defaultGroupField({
319 fields: [{name: "lead_status", type: "enum", enum: ["new", "hot"]}],
320 }),
321 none: defaultGroupField({fields: [{name: "title", type: "text"}]}),
322 }));
323 """
324 node = shutil.which("node")
325 if node is None:
326 pytest.skip("node not on PATH")
327 result = subprocess.run([node, "-e", probe], capture_output=True, text=True)
328 assert result.returncode == 0, f"node probe failed:\n{result.stderr}"
329 out = json.loads(result.stdout)
330 assert out["flowWins"] == "stage"
331 assert out["guardedEnumWins"] == "status"
332 assert out["bareEnumFallback"] == "lead_status"
333 assert out["none"] is None
334
335
336def test_board_columns_and_grouping_behave_under_node():
337 helpers = _pure_helpers_js()
338 expr = """
339 (function () {
340 const field = {enum: ["draft", "open", "assigned", "cancelled"]};
341 const columns = boardColumns(field);
342 const records = [
343 {id: "r1", status: "open"},
344 {id: "r2", status: "assigned"},
345 {id: "r3"},
346 {id: "r4", status: "not_a_real_value"},
347 {id: "r5", status: "open"},
348 ];
349 const buckets = groupByColumn(records, "status", columns);
350 return {
351 columns: columns,
352 unsetIds: buckets[""].map((r) => r.id).sort(),
353 openIds: buckets["open"].map((r) => r.id).sort(),
354 assignedIds: buckets["assigned"].map((r) => r.id).sort(),
355 totalBucketed: Object.values(buckets).reduce((n, b) => n + b.length, 0),
356 };
357 })()
358 """
359 out = _run_node_probe(helpers, expr)
360 assert out["columns"] == ["", "draft", "open", "assigned", "cancelled"]
361 assert out["columns"][0] == "" # (unset) column is first
362 # r3 (no value) and r4 (stray/unknown value) both fold into unset --
363 # never dropped.
364 assert out["unsetIds"] == ["r3", "r4"]
365 assert out["openIds"] == ["r1", "r5"]
366 assert out["assignedIds"] == ["r2"]
367 assert out["totalBucketed"] == 5 # every record accounted for
368
369
370def test_resolve_board_config_error_when_no_enum_field_exists():
371 helpers = _pure_helpers_js()
372 expr = 'resolveBoardConfig({name: "things", fields: [{name: "title", type: "text"}]})'
373 out = _run_node_probe(helpers, expr)
374 assert "error" in out
375 assert "enum" in out["error"]
376
377
378# ---------------------------------------------------------------------
379# Tree pure helpers: nesting order, cycle guard, depth cap.
380# ---------------------------------------------------------------------
381
382
383def test_is_self_relation_and_resolve_tree_config_behave_under_node():
384 helpers = _pure_helpers_js()
385 expr = """
386 (function () {
387 const selfSchema = {
388 name: "fin_accounts",
389 fields: [{name: "parent_id", type: "relation", relation: {collection: "fin_accounts"}}],
390 };
391 const crossSchema = {
392 name: "contacts",
393 fields: [{name: "organization_id", type: "relation", relation: {collection: "organizations"}}],
394 };
395 return {
396 selfOk: resolveTreeConfig(selfSchema),
397 crossError: resolveTreeConfig({
398 name: "contacts",
399 fields: [{name: "parent_id", type: "relation", relation: {collection: "organizations"}}],
400 }),
401 noFieldError: resolveTreeConfig({name: "x", fields: []}),
402 };
403 })()
404 """
405 out = _run_node_probe(helpers, expr)
406 assert out["selfOk"]["config"] == {"parentField": "parent_id", "maxDepth": 10}
407 assert "error" in out["crossError"]
408 assert "error" in out["noFieldError"]
409
410
411def test_build_tree_nests_in_parent_order_under_node():
412 helpers = _pure_helpers_js()
413 expr = """
414 buildTree([
415 {id: "root1", parent_id: ""},
416 {id: "child1", parent_id: "root1"},
417 {id: "child2", parent_id: "root1"},
418 {id: "grandchild1", parent_id: "child1"},
419 ], {parentField: "parent_id", maxDepth: 10})
420 """
421 out = _run_node_probe(helpers, expr)
422 assert out["cycleDetected"] is False
423 assert len(out["nodes"]) == 1
424 root = out["nodes"][0]
425 assert root["record"]["id"] == "root1"
426 assert root["depth"] == 0
427 child_ids = sorted(n["record"]["id"] for n in root["children"])
428 assert child_ids == ["child1", "child2"]
429 child1 = next(n for n in root["children"] if n["record"]["id"] == "child1")
430 assert child1["depth"] == 1
431 assert [n["record"]["id"] for n in child1["children"]] == ["grandchild1"]
432
433
434def test_build_tree_cycle_guard_renders_once_and_never_hangs_under_node():
435 """A malformed parent_id chain: 'root' -> 'mid' -> a SECOND row that
436 reuses id 'root' again as mid's child (duplicate id, the kind of
437 data-quality bug neither fin_accounts nor locations' own schema
438 enforces against). Without the visited-id guard this would recurse
439 forever; with it, the second 'root' row is rendered once at first
440 encounter and never re-descended -- proven here by the probe actually
441 returning (a real infinite loop would hang/crash the node process)."""
442 helpers = _pure_helpers_js()
443 expr = """
444 buildTree([
445 {id: "root", parent_id: ""},
446 {id: "mid", parent_id: "root"},
447 {id: "root", parent_id: "mid"},
448 ], {parentField: "parent_id", maxDepth: 10})
449 """
450 out = _run_node_probe(helpers, expr)
451 assert out["cycleDetected"] is True
452 assert len(out["nodes"]) == 1
453 mid = out["nodes"][0]["children"][0]
454 assert mid["record"]["id"] == "mid"
455 # The re-encountered "root" is skipped, not appended as a child of mid.
456 assert mid["children"] == []
457
458
459def test_build_tree_depth_cap_stops_descent_and_flags_truncation_under_node():
460 # A straight-line chain 12 deep, capped at max_depth=3.
461 ids = [f"n{i}" for i in range(12)]
462 chain = [{"id": ids[0], "parent_id": ""}]
463 for i in range(1, len(ids)):
464 chain.append({"id": ids[i], "parent_id": ids[i - 1]})
465 helpers = _pure_helpers_js()
466 expr = "buildTree(" + json.dumps(chain) + ", {parentField: 'parent_id', maxDepth: 3})"
467 out = _run_node_probe(helpers, expr)
468 assert out["cycleDetected"] is False
469
470 depths = []
471 node = out["nodes"][0]
472 while True:
473 depths.append(node["depth"])
474 if not node["children"]:
475 assert node["truncated"] is True
476 break
477 node = node["children"][0]
478 assert depths == [0, 1, 2] # exactly max_depth levels rendered, no more
479
480
481# ---------------------------------------------------------------------
482# Calendar pure helpers: month bucketing + undated overflow.
483# ---------------------------------------------------------------------
484
485
486def test_default_date_field_skips_read_only_under_node():
487 helpers = _pure_helpers_js()
488 expr = """
489 defaultDateField({
490 fields: [
491 {name: "created_at", type: "datetime", read_only: true},
492 {name: "due_date", type: "date"},
493 ],
494 })
495 """
496 out = _run_node_probe(helpers, expr)
497 assert out == "due_date"
498
499
500def test_bucket_by_date_keys_by_day_and_never_drops_undated_under_node():
501 helpers = _pure_helpers_js()
502 expr = """
503 (function () {
504 const records = [
505 {id: "e1", due_date: "2026-07-04"},
506 {id: "e2", due_date: "2026-07-04T09:00:00"},
507 {id: "e3", due_date: "2026-07-05"},
508 {id: "e4", due_date: ""},
509 {id: "e5"},
510 ];
511 const bucketed = bucketByDate(records, "due_date");
512 return {
513 july4Ids: bucketed.byDay["2026-07-04"].map((r) => r.id).sort(),
514 july5Ids: bucketed.byDay["2026-07-05"].map((r) => r.id).sort(),
515 undatedIds: bucketed.undated.map((r) => r.id).sort(),
516 totalDated: Object.values(bucketed.byDay).reduce((n, b) => n + b.length, 0),
517 };
518 })()
519 """
520 out = _run_node_probe(helpers, expr)
521 assert out["july4Ids"] == ["e1", "e2"]
522 assert out["july5Ids"] == ["e3"]
523 assert out["undatedIds"] == ["e4", "e5"] # empty string AND missing key both count as undated
524 assert out["totalDated"] == 3
525
526
527def test_month_grid_has_42_cells_with_correct_in_month_flags_under_node():
528 helpers = _pure_helpers_js()
529 # July 2026: 31 days, starts on a Wednesday.
530 out = _run_node_probe(helpers, "monthGridDays(2026, 6)")
531 assert len(out) == 42
532 in_month_dates = [c["date"] for c in out if c["inMonth"]]
533 assert in_month_dates[0] == "2026-07-01"
534 assert in_month_dates[-1] == "2026-07-31"
535 assert len(in_month_dates) == 31
536 assert any(not c["inMonth"] for c in out) # leading/trailing filler present
537
538
539def test_resolve_calendar_config_error_when_no_date_field_exists():
540 helpers = _pure_helpers_js()
541 expr = 'resolveCalendarConfig({fields: [{name: "title", type: "text"}]})'
542 out = _run_node_probe(helpers, expr)
543 assert "error" in out
544
545
546# ---------------------------------------------------------------------
547# 58 permissions posture inherited verbatim: the calendar range fetch
548# (58's gte/lte, newly exercised in this spec's own context) still
549# applies the permission row filter FIRST -- proven live, not just
550# asserted from the JS source, mirroring 59's own
551# test_related_query_shape_cannot_leak_a_row_outside_the_row_filter.
552# ---------------------------------------------------------------------
553
554
555def test_calendar_shaped_range_fetch_cannot_leak_a_row_outside_the_row_filter(tmp_path, monkeypatch):
556 import object_permission_store
557
558 data_dir = tmp_path / "data"
559 write_records(
560 data_dir,
561 "bookings",
562 "id\tstart_date\towner_id\n"
563 "bk1\t2026-07-10\towner-a\n"
564 "bk2\t2026-07-12\towner-b\n",
565 )
566 object_permission_store.replace_policy(
567 {
568 "access_mode": "role_based",
569 "rules": [
570 {
571 "effect": "allow",
572 "principal": "registered",
573 "actions": ["create", "read", "update", "delete"],
574 "collection": "bookings",
575 "row_filter": {"owner_id": "$user_id"},
576 }
577 ],
578 },
579 data_dir,
580 )
581 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
582 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
583 monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true")
584 enable_admin_token(monkeypatch)
585
586 # The exact query shape renderCalendar's load() compiles to for a
587 # visible July 2026 -- 58's gte/lte range operators on the date field.
588 owner_status, _, owner_payload = request(
589 "/collections/bookings/records",
590 query_string="start_date.gte=2026-07-01&start_date.lte=2026-07-31",
591 headers=[("x-dbbasic-user-id", "owner-a"), ("x-dbbasic-roles", "registered")],
592 )
593 other_status, _, other_payload = request(
594 "/collections/bookings/records",
595 query_string="start_date.gte=2026-07-01&start_date.lte=2026-07-31",
596 headers=[("x-dbbasic-user-id", "owner-c"), ("x-dbbasic-roles", "registered")],
597 )
598 admin_status, _, admin_payload = request(
599 "/collections/bookings/records",
600 query_string="start_date.gte=2026-07-01&start_date.lte=2026-07-31",
601 headers=auth_headers(),
602 )
603
604 assert owner_status == 200
605 assert [r["id"] for r in owner_payload["records"]] == ["bk1"]
606
607 assert other_status == 200
608 assert other_payload["records"] == []
609 assert "bk1" not in json.dumps(other_payload)
610 assert "bk2" not in json.dumps(other_payload)
611
612 assert admin_status == 200
613 assert {r["id"] for r in admin_payload["records"]} == {"bk1", "bk2"}
614
615
616# ---------------------------------------------------------------------
617# Feature flag: list_modes_enabled defaults ON, off falls back to table.
618# ---------------------------------------------------------------------
619
620
621def test_list_modes_enabled_flag_defaults_on_and_gates_the_three_modes():
622 source = _list_source()
623 assert "async function listModesEnabled()" in source
624 assert 'v !== "off" && v !== "false"' in source
625 assert "dbbasicFlags" in source
626
627
628def test_degradation_notices_are_visible_not_silent():
629 source = _list_source()
630 assert "board mode needs an enum field" in source
631 assert "tree mode needs a self-relation field" in source
632 assert "calendar mode needs a date field" in source
633 # The row-list render() actually shows the notice -- not just a string
634 # that's built and discarded.
635 assert '<div class="state notice">' in source
636
637
638def test_mode_resolution_falls_back_to_the_row_list_on_any_non_match():
639 source = _list_source()
640 assert "activeReload = startRowList(resolved.notice);" in source
641
642
643# ---------------------------------------------------------------------
644# Schema surfacing: `flow` now survives normalization (whitelisted,
645# additive, board's default-group-field chain has something real to read
646# the moment a schema declares it) and is exposed on the public schema
647# endpoint list.py's resolveListMode() fetches.
648# ---------------------------------------------------------------------
649
650
651def test_flow_key_survives_schema_normalization(tmp_path):
652 data_dir = tmp_path / "data"
653 path = data_dir / "schemas" / "widgets.json"
654 path.parent.mkdir(parents=True, exist_ok=True)
655 path.write_text(json.dumps({
656 "fields": [{"name": "id"}, {"name": "stage", "type": "enum", "enum": ["a", "b"]}],
657 "flow": {"field": "stage"},
658 }))
659 schema = object_schemas.get_schema("widgets", base_dir=data_dir, roots=[])
660 assert schema["flow"] == {"field": "stage"}
661
662
663def test_public_schema_endpoint_exposes_flow(tmp_path, monkeypatch):
664 data_dir = tmp_path / "data"
665 write_records(data_dir, "widgets", "id\tstage\nw1\ta\n")
666 path = data_dir / "schemas" / "widgets.json"
667 path.parent.mkdir(parents=True, exist_ok=True)
668 path.write_text(json.dumps({
669 "fields": [{"name": "id"}, {"name": "stage", "type": "enum", "enum": ["a", "b"]}],
670 "flow": {"field": "stage"},
671 }))
672 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
673 status, _, payload = request("/api/schema/widgets")
674 assert status == 200
675 assert payload["schema"]["flow"] == {"field": "stage"}
676
677
678# ---------------------------------------------------------------------
679# CSS: board/tree/calendar chrome lives in /style, per convention (same
680# global stylesheet every other generated surface's classes live in).
681# ---------------------------------------------------------------------
682
683
684def test_board_tree_calendar_css_classes_are_in_the_shared_stylesheet():
685 style_source = _style_source()
686 for cls in (".board", ".boardcol", ".boardcard", ".tree", ".treenode",
687 ".calgrid", ".calcell", ".calevent"):
688 assert cls in style_source
689
690
691# ---------------------------------------------------------------------
692# Out of scope, stated in-line (v1 tree/calendar are read-only; no
693# persisted board rank) -- regression guard against silently growing scope.
694# ---------------------------------------------------------------------
695
696
697def test_tree_and_calendar_issue_no_writes_in_v1():
698 js = _list_js()
699 tree_fn = re.search(r"function renderTree\(collection, cfg, mount, treeCfg\) \{(.*?)\n \}\n\n function renderCalendar", js, re.S)
700 assert tree_fn, "renderTree not found"
701 assert "method:" not in tree_fn.group(1)
702
703 cal_fn = re.search(r"function renderCalendar\(collection, cfg, mount, calCfg\) \{(.*?)\n \}\n\n // ---- the plain row list", js, re.S)
704 assert cal_fn, "renderCalendar not found"
705 assert "method:" not in cal_fn.group(1)
706
707
708def test_no_persisted_board_rank_field_invented():
709 source = _list_source()
710 assert "board_rank" not in source
711 assert "Persisted card order within a board column" not in source # that's the spec's own text, not this file's
712
713
714# ---------------------------------------------------------------------
715# Scroll-parity open question carried forward verbatim, per the task's
716# explicit instruction not to silently resolve it.
717# ---------------------------------------------------------------------
718
719
720def test_scroll_parity_open_question_is_carried_forward_in_the_docstring():
721 source = _list_source()
722 assert "Open question carried forward verbatim" in source
723 assert "31-wizard-kanban-stub.md" in source
724 assert "mid-scroll" in source
725
726
727# ---------------------------------------------------------------------
728# Repo hygiene: no internal org/codename references in anything touched.
729# ---------------------------------------------------------------------
730
731_BANNED = re.compile(
732 "|".join([r"\b" + "q" + "9" + r"\b", "ask" + "robots", r"\b" + "wo" + "ld" + r"\b"]),
733 re.IGNORECASE,
734)
735_TOUCHED_FILES = [
736 LIST_PATH,
737 STYLE_PATH,
738 Path(__file__).resolve().parents[1] / "object_server.py",
739 Path(__file__).resolve().parents[1] / "object_schemas.py",
740]
741
742
743def test_no_disallowed_org_names_in_touched_files():
744 for path in _TOUCHED_FILES:
745 text = path.read_text(encoding="utf-8", errors="ignore")
746 assert not _BANNED.search(text), f"disallowed reference found in {path}"
747
748
749def test_this_test_file_has_no_disallowed_org_names():
750 assert not _BANNED.search(Path(__file__).read_text())