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