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_detail_related_spec.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_detail_related_spec.py · 39.6 KB · 942 lines
1"""Tests for plan/vocabulary/59-detail-related-spec.md: detail mode, the
2`related` block, `thread` sugar, $record_id route-capture resolution, and
3route-seeding.
4
5Mirrors the source-assertion + structural-install testing style already
6used by tests/test_app_views_package.py (for packages/app-views) and the
7route-resolution testing style of tests/test_object_site_routes.py (for
8object_site_routes.py / object_server.py's site routing).
9"""
10
11import json
12import re
13import shutil
14import subprocess
15from pathlib import Path
16
17from test_object_server import (
18 auth_headers,
19 enable_admin_token,
20 raw_request,
21 request,
22 save_permission_policy,
23 write_records,
24)
25from test_object_site_routes import enable_site_routes
26
27import object_execution
28import object_packages
29import object_permissions
30import object_server
31import python_object_runtime
32
33PACKAGES_ROOT = Path(__file__).resolve().parents[1] / "packages"
34APP_VIEWS_DIR = PACKAGES_ROOT / "app-views"
35APP_THEME_DIR = PACKAGES_ROOT / "app-theme"
36APP_CONTACTS_DIR = PACKAGES_ROOT / "app-contacts"
37APP_TASKS_DIR = PACKAGES_ROOT / "app-tasks"
38
39
40def _view_render_source():
41 return (APP_VIEWS_DIR / "objects" / "site" / "view_render.py").read_text()
42
43
44def _form_source():
45 return (APP_THEME_DIR / "objects" / "site" / "form.py").read_text()
46
47
48def _detail_source():
49 return (APP_THEME_DIR / "objects" / "site" / "detail.py").read_text()
50
51
52def _list_source():
53 return (APP_THEME_DIR / "objects" / "site" / "list.py").read_text()
54
55
56# ---------------------------------------------------------------------
57# Detail mode reuses /form's field-rendering pipeline (no second renderer)
58# ---------------------------------------------------------------------
59
60
61def test_detail_generator_is_a_public_static_script_like_list_and_form():
62 manifest = json.loads((APP_THEME_DIR / "dbbasic-package.json").read_text())
63 object_ids = {obj["id"] for obj in manifest["objects"]}
64 assert "site_detail" in object_ids
65
66 rules = json.loads((APP_THEME_DIR / "permissions" / "rules.json").read_text())["rules"]
67 detail_rules = [r for r in rules if r.get("object_id") == "site_detail"]
68 assert len(detail_rules) == 1
69 assert detail_rules[0]["effect"] == "allow"
70 assert detail_rules[0]["principal"] == "public"
71 assert detail_rules[0]["actions"] == ["execute"]
72
73
74def test_site_detail_execute_is_public():
75 policy = object_permissions.policy_from_dict(
76 {
77 "access_mode": "role_based",
78 "rules": json.loads((APP_THEME_DIR / "permissions" / "rules.json").read_text())["rules"],
79 }
80 )
81 decision = object_permissions.check_permission(
82 None, object_permissions.EXECUTE, policy=policy, object_id="site_detail",
83 )
84 assert decision.allowed is True
85
86
87def test_detail_object_serves_dbbasicDetail_script():
88 runtime = python_object_runtime.PythonObjectRuntime()
89 result = object_execution.execute_object(
90 runtime,
91 object_execution.ObjectExecutionRequest("site_detail", payload={}),
92 roots=[APP_THEME_DIR / "objects"],
93 )
94 assert result.ok is True
95 assert result.result["content_type"] == "application/javascript; charset=utf-8"
96 assert "window.dbbasicDetail" in result.result["body"]
97 assert "mount:" in result.result["body"]
98
99
100def test_detail_delegates_to_form_read_only_pipeline_not_a_second_renderer():
101 """59's Purpose section: detail mode reuses /form's schema fetch,
102 field order, relation display-field resolution, and type-aware value
103 formatting -- 'a second field-renderer would be a second place to
104 keep that formatting logic correct.' detail.py must not re-implement
105 any of that; it only fetches the record and hands it to
106 window.dbbasicForm.readOnly.
107 """
108 form_source = _form_source()
109 detail_source = _detail_source()
110
111 assert "window.dbbasicForm.readOnly = async function" in form_source
112 assert "window.dbbasicForm.readOnly(" in detail_source
113 # No independent relation/enum/date formatting logic in detail.py --
114 # that stays in form.py's control()/readOnlyText(), used by both modes.
115 for needle in ("f.relation", "f.enum", "readOnlyText", "/api/schema/"):
116 assert needle not in detail_source, f"{needle!r} should live in form.py only, not detail.py"
117
118
119def test_form_read_only_shares_control_with_edit_mode():
120 """One control() function backs both window.dbbasicForm (edit) and
121 window.dbbasicForm.readOnly (detail) -- the same relation-fetch and
122 type-formatting branches, not two copies."""
123 source = _form_source()
124 assert source.count("async function control(f, value, readOnly)") == 1
125 assert "control(f, record[f.name], true)" in source # readOnly mode
126 assert "control(f, record ? record[f.name] : f.default)" in source # edit mode, unchanged
127
128
129def test_form_read_only_field_order_prefers_views_detail_fields():
130 source = _form_source()
131 match = re.search(
132 r"window\.dbbasicForm\.readOnly = async function \(collection, opts\) \{(.*?)\n \};",
133 source, re.S,
134 )
135 assert match, "window.dbbasicForm.readOnly not found"
136 body = match.group(1)
137 assert "schema.views && schema.views.detail_fields" in body
138 # NOT forms.default.fields -- that's edit mode's own convention (59:
139 # "Otherwise, schema field declaration order", not the edit form's).
140 assert "forms.default" not in body
141
142
143def test_form_read_only_skips_fields_absent_from_the_record():
144 """'Visible = readable' falls out of the platform's own field
145 redaction (object_server.py's _apply_record_field_policy deletes
146 denied keys) -- detail mode must not re-implement a permission check,
147 it just skips a field missing from the record."""
148 source = _form_source()
149 assert "if (!(f.name in record)) continue;" in source
150
151
152def test_form_read_only_textarea_delegates_to_shared_markdown_renderer(tmp_path):
153 """Behavioral, not source-text: found while trying to publish a real
154 article -- a textarea field shown read-only went through plain
155 esc(text) inside a <span>, so multi-line content collapsed into one
156 run-together line and literal "**bold**" syntax showed as literal
157 asterisks. The fix delegates to the ONE shared renderer at /markdown
158 (window.dbbasicMarkdown, tested on its own merits in
159 test_markdown_object.py) rather than a second copy of markdown logic
160 living in this file -- this test only needs to prove the delegation
161 and its safe fallback, not re-verify markdown itself.
162 """
163 node = shutil.which("node")
164 if not node:
165 return
166
167 source = _form_source()
168
169 def extract_function(name):
170 start = source.index(f"function {name}(")
171 depth = 0
172 i = source.index("{", start)
173 for j in range(i, len(source)):
174 if source[j] == "{":
175 depth += 1
176 elif source[j] == "}":
177 depth -= 1
178 if depth == 0:
179 return source[start : j + 1]
180 raise AssertionError(f"unbalanced braces extracting {name}()")
181
182 esc_line = re.search(r"const esc = .*?;\n", source, re.S)
183 assert esc_line, "esc() not found in form.py"
184
185 probe = f"""
186{esc_line.group(0)}
187{extract_function("textareaHtml")}
188
189global.window = {{dbbasicMarkdown: (t) => "MARKDOWN:" + t}};
190const delegated = textareaHtml("hello");
191
192global.window = {{}};
193const fallback = textareaHtml("line one\\nline two <script>alert(1)</script>");
194
195console.log(JSON.stringify({{delegated, fallback}}));
196"""
197 probe_path = tmp_path / "textarea_html_probe.js"
198 probe_path.write_text(probe)
199 result = subprocess.run([node, str(probe_path)], capture_output=True, text=True)
200 assert result.returncode == 0, f"node probe failed:\n{result.stderr}"
201 outcome = json.loads(result.stdout)
202
203 # window.dbbasicMarkdown present -> delegate to it, verbatim.
204 assert outcome["delegated"] == "MARKDOWN:hello"
205 # window.dbbasicMarkdown absent (a page loaded /form without /markdown)
206 # -> a safe bare-escape fallback, never raw innerHTML of untrusted text.
207 assert "<script>" not in outcome["fallback"]
208 assert "&lt;script&gt;" in outcome["fallback"]
209 assert "line one<br>line two" in outcome["fallback"]
210
211 # The readOnly branch must route textarea through textareaHtml in a
212 # block element (not the plain-text <span> every other field type
213 # gets, which is exactly what collapsed real article content).
214 assert (
215 "if (t === \"textarea\") {\n"
216 " return v ? '<div class=\"detailvalue textareavalue\">' + textareaHtml(v) + '</div>'"
217 ) in source
218
219
220def test_view_render_page_loads_markdown_script():
221 """The standalone "markdown" block and /form's textarea rendering
222 both delegate to window.dbbasicMarkdown -- the page wrapper this file
223 emits must actually load /markdown, or both call sites silently fall
224 back to a bare escape instead of real markdown."""
225 source = _view_render_source()
226 assert '<script src="/markdown"></script>' in source
227 # Must load before /form -- not strictly required by either renderer
228 # (both check window.dbbasicMarkdown defensively), but loading it
229 # first is the intent and catches a reordering that would make the
230 # timing accidentally matter.
231 markdown_idx = source.index('<script src="/markdown">')
232 form_idx = source.index('<script src="/form">')
233 assert markdown_idx < form_idx
234
235
236def test_view_render_markdown_block_delegates_to_shared_renderer(tmp_path):
237 node = shutil.which("node")
238 if not node:
239 return
240
241 source = _view_render_source()
242
243 def extract_function(name):
244 start = source.index(f"function {name}(")
245 depth = 0
246 i = source.index("{", start)
247 for j in range(i, len(source)):
248 if source[j] == "{":
249 depth += 1
250 elif source[j] == "}":
251 depth -= 1
252 if depth == 0:
253 return source[start : j + 1]
254 raise AssertionError(f"unbalanced braces extracting {name}()")
255
256 esc_line = re.search(r"const esc = .*?;\n", source, re.S)
257 assert esc_line, "esc() not found in view_render.py"
258
259 probe = f"""
260{esc_line.group(0)}
261{extract_function("renderMarkdown")}
262
263let capturedHtml = null;
264const mount = {{set innerHTML(v) {{ capturedHtml = v; }}}};
265
266global.window = {{dbbasicMarkdown: (t) => "MARKDOWN:" + t}};
267renderMarkdown({{text: "hello"}}, mount);
268const delegated = capturedHtml;
269
270global.window = {{}};
271renderMarkdown({{text: "line one\\nline two <script>alert(1)</script>"}}, mount);
272const fallback = capturedHtml;
273
274console.log(JSON.stringify({{delegated, fallback}}));
275"""
276 probe_path = tmp_path / "render_markdown_probe.js"
277 probe_path.write_text(probe)
278 result = subprocess.run([node, str(probe_path)], capture_output=True, text=True)
279 assert result.returncode == 0, f"node probe failed:\n{result.stderr}"
280 outcome = json.loads(result.stdout)
281
282 assert outcome["delegated"] == '<div class="markdownblock">MARKDOWN:hello</div>'
283 assert "<script>" not in outcome["fallback"]
284 assert "&lt;script&gt;" in outcome["fallback"]
285 assert "line one<br>line two" in outcome["fallback"]
286
287
288def test_view_render_detail_block_is_a_thin_mount_wrapper():
289 source = _view_render_source()
290 assert '<script src="/detail">' in source
291 # Detail mounts into a sub-element so a capabilities.comments thread can
292 # sit below it (see maybeMountComments); still a thin mount wrapper.
293 assert "window.dbbasicDetail.mount(detailMount" in source
294 # The old inline schema+record fetch/format is gone from renderDetail's own
295 # body (the schema fetch that gates comments lives in maybeMountComments).
296 detail_fn = re.search(r"function renderDetail\(block, mount\) \{(.*?)\n\}", source, re.S)
297 assert detail_fn, "renderDetail not found"
298 assert "/api/schema/" not in detail_fn.group(1)
299 assert "maybeMountCapabilities" in detail_fn.group(1)
300
301
302def test_detail_auto_mounts_capability_widgets_when_declared():
303 """capabilities wiring: the detail page mounts a widget for a record only
304 when its collection's schema declares the matching capability."""
305 source = _view_render_source()
306 assert '<script src="/thread">' in source
307 assert '<script src="/attachments">' in source
308 assert '<script src="/share">' in source
309 assert "caps.comments && window.dbbasicThread" in source
310 assert "caps.attachments && window.dbbasicAttachments" in source
311 assert "caps.shareable && window.dbbasicShare" in source
312 assert "window.dbbasicThread.mount" in source
313 assert "window.dbbasicAttachments.mount" in source
314 assert "window.dbbasicShare.mount" in source
315
316
317# ---------------------------------------------------------------------
318# Owner-aware edit/delete (Stage 6 extension): the detail block gains
319# editable/deletable affordances, shown only to the record's owner, that
320# REUSE /form's existing edit pipeline -- so per-collection *_view pages
321# collapse into one view record + this renderer.
322# ---------------------------------------------------------------------
323
324
325def test_detail_owner_aware_edit_reuses_form_edit_pipeline_not_a_new_one():
326 source = _detail_source()
327 # Owner gate: compare the record's owner_field to the viewer id, both
328 # supplied by the caller (view_render passes VIEWER_ID) -- never a new
329 # permission path, just whether to render the affordance.
330 assert "opts.viewer_id" in source
331 assert 'opts.owner_field || "owner_id"' in source
332 assert "opts.editable" in source and "opts.deletable" in source
333 # Edit reuses window.dbbasicForm's edit mode (a record present => PUT)
334 # and its onSaved callback -- detail.py must not re-implement editing.
335 assert "window.dbbasicForm(collection, {" in source
336 assert "onSaved:" in source
337 # Still delegates read rendering to the shared read-only pipeline, and
338 # still re-implements no field formatting of its own.
339 assert "window.dbbasicForm.readOnly(" in source
340 for needle in ("f.relation", "f.enum", "readOnlyText"):
341 assert needle not in source, f"{needle!r} should live in form.py only, not detail.py"
342
343
344def test_detail_delete_issues_record_delete_then_redirects():
345 source = _detail_source()
346 assert '"DELETE"' in source
347 assert "opts.delete_redirect" in source
348 assert "window.confirm(" in source # never a silent destructive action
349
350
351def test_detail_edit_state_survives_a_subscribe_reload():
352 """view_render re-mounts the detail block on any collection change; that
353 must not wipe out an edit the owner is mid-way through."""
354 source = _detail_source()
355 assert "_dbbasicEditing" in source
356 assert "if (mount._dbbasicEditing) return;" in source
357
358
359def test_view_render_detail_passes_owner_aware_options_and_viewer_id():
360 source = _view_render_source()
361 detail_fn = re.search(r"function renderDetail\(block, mount\) \{(.*?)\n\}", source, re.S)
362 assert detail_fn, "renderDetail not found"
363 body = detail_fn.group(1)
364 for needle in ("block.editable", "block.deletable", "block.delete_redirect", "VIEWER_ID"):
365 assert needle in body, f"renderDetail should forward {needle!r} to the detail generator"
366
367
368# ---------------------------------------------------------------------
369# related compiles to 58's filtered read, not a bespoke fetch
370# ---------------------------------------------------------------------
371
372
373def test_list_generator_where_option_encodes_58_field_eq_query():
374 source = _list_source()
375 assert "cfg.where" in source
376 assert 'encodeURIComponent(k) + "=" + encodeURIComponent(v)' in source
377 assert "/records?limit=500" in source
378
379
380def test_related_block_compiles_to_dbbasicList_where_not_a_bespoke_fetch():
381 source = _view_render_source()
382 related_fn = re.search(r"function renderRelated\(block, mount\) \{(.*?)\n\}", source, re.S)
383 assert related_fn, "renderRelated not found"
384 body = related_fn.group(1)
385 assert "window.dbbasicList(block.collection, {mount: listMount, where: {[block.fk_field]: match}})" in body
386 # Never the client-side filter fallback `list` sometimes needs.
387 assert "renderFilteredList" not in body
388 assert "fetch(" not in body
389
390
391def test_related_block_resolves_record_id_token():
392 source = _view_render_source()
393 related_fn = re.search(r"function renderRelated\(block, mount\) \{(.*?)\n\}", source, re.S)
394 assert "resolveRecordId(block.match)" in related_fn.group(1)
395
396
397def test_resolve_record_id_helper_handles_literal_and_token():
398 source = _view_render_source()
399 fn = re.search(r"function resolveRecordId\(value\) \{(.*?)\n\}", source, re.S)
400 assert fn, "resolveRecordId not found"
401 body = fn.group(1)
402 assert 'value !== "$record_id"' in body
403 assert "return RECORD_ID" in body
404
405
406def test_known_kinds_include_related_and_thread():
407 source = _view_render_source()
408 assert ('KNOWN_KINDS = ["list", "form", "detail", "related", "thread", '
409 '"count", "aggregate", "markdown", "reader", "object"]') in source
410 assert "related: renderRelated" in source
411 assert "thread: renderThread" in source
412
413
414# ---------------------------------------------------------------------
415# thread: sugar over 22, not reinvented
416# ---------------------------------------------------------------------
417
418
419def test_thread_block_mounts_dbbasicThread_and_degrades_without_it():
420 source = _view_render_source()
421 thread_fn = re.search(r"function renderThread\(block, mount\) \{(.*?)\n\}", source, re.S)
422 assert thread_fn, "renderThread not found"
423 body = thread_fn.group(1)
424 assert "window.dbbasicThread.mount(mount, {parent_collection: block.collection, parent_id: recordId})" in body
425 assert "if (!window.dbbasicThread)" in body
426 # No comment moderation/anon-mode/markdown logic here -- 22 owns it.
427 for needle in ("moderation", "anon", "markdown"):
428 assert needle not in body.lower()
429
430
431# ---------------------------------------------------------------------
432# $record_id route-capture resolution (Route-Seeding)
433# ---------------------------------------------------------------------
434
435
436def _install_app_views(base_dir, object_root):
437 object_root.mkdir(parents=True, exist_ok=True)
438 object_packages.install_package(
439 "app-views", root=PACKAGES_ROOT, base_dir=base_dir, object_roots=[object_root],
440 )
441
442
443def test_record_id_resolves_from_a_routed_detail_capture(tmp_path, monkeypatch):
444 data_dir = tmp_path / "data"
445 object_root = tmp_path / "objects"
446 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
447 _install_app_views(data_dir, object_root)
448
449 write_records(
450 data_dir,
451 "views",
452 "id\ttitle\troute\tlayout\tblocks\towner_id\tis_public\tpinned\tcreated_at\n"
453 "view_contacts_detail\tContact\t/contacts/{contact_id}\tsingle\t[]\t\ttrue\tfalse\t\n",
454 )
455
456 runtime = python_object_runtime.PythonObjectRuntime(base_dir=data_dir)
457 contact_id = "3fbb7e9e-2222-4d3d-8b8a-9d6b7f000099"
458 result = object_execution.execute_object(
459 runtime,
460 object_execution.ObjectExecutionRequest(
461 "site_view_render",
462 payload={"contact_id": contact_id, "_identity": {}},
463 ),
464 roots=[object_root],
465 )
466
467 assert result.ok is True
468 body = result.result["body"]
469 assert "const VIEW_ID = 'view_contacts_detail';" in body
470 assert f"const RECORD_ID = {contact_id!r};" in body
471
472
473def test_record_id_stays_empty_when_route_has_no_capture(tmp_path, monkeypatch):
474 """A plain route (/stuck, no {param}) -- or a view reached directly
475 via /views/{id} with no matching capture -- must not resolve a
476 record id: a block referencing $record_id degrades to its visible
477 error state instead of guessing (Degradation: "$record_id
478 unresolvable ... the view was reached without going through its
479 registered route")."""
480 data_dir = tmp_path / "data"
481 object_root = tmp_path / "objects"
482 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
483 _install_app_views(data_dir, object_root)
484
485 write_records(
486 data_dir,
487 "views",
488 "id\ttitle\troute\tlayout\tblocks\towner_id\tis_public\tpinned\tcreated_at\n"
489 "view_stuck\tStuck\t/stuck\tsingle\t[]\t\ttrue\tfalse\t\n",
490 )
491
492 runtime = python_object_runtime.PythonObjectRuntime(base_dir=data_dir)
493 result = object_execution.execute_object(
494 runtime,
495 object_execution.ObjectExecutionRequest(
496 "site_view_render",
497 payload={"view_id": "view_stuck", "_identity": {}},
498 ),
499 roots=[object_root],
500 )
501
502 assert result.ok is True
503 assert "const RECORD_ID = '';" in result.result["body"]
504
505
506def test_record_id_stays_empty_for_a_two_capture_route(tmp_path, monkeypatch):
507 """Defense-in-depth: 59 pins $record_id to routes with EXACTLY one
508 capture (Open Questions). A route with two captures (a future
509 multi-entity case, 65, not decided here) must not pick one
510 arbitrarily -- it degrades the same as zero captures."""
511 data_dir = tmp_path / "data"
512 object_root = tmp_path / "objects"
513 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
514 _install_app_views(data_dir, object_root)
515
516 write_records(
517 data_dir,
518 "views",
519 "id\ttitle\troute\tlayout\tblocks\towner_id\tis_public\tpinned\tcreated_at\n"
520 "view_two\tTwo\t/entities/{entity_id}/accounts/{account_id}\tsingle\t[]\t\ttrue\tfalse\t\n",
521 )
522
523 runtime = python_object_runtime.PythonObjectRuntime(base_dir=data_dir)
524 result = object_execution.execute_object(
525 runtime,
526 object_execution.ObjectExecutionRequest(
527 "site_view_render",
528 payload={
529 "view_id": "view_two",
530 "entity_id": "e1",
531 "account_id": "a1",
532 "_identity": {},
533 },
534 ),
535 roots=[object_root],
536 )
537
538 assert result.ok is True
539 assert "const RECORD_ID = '';" in result.result["body"]
540
541
542def test_missing_view_id_and_no_matching_capture_is_still_404(tmp_path, monkeypatch):
543 data_dir = tmp_path / "data"
544 object_root = tmp_path / "objects"
545 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
546 _install_app_views(data_dir, object_root)
547
548 runtime = python_object_runtime.PythonObjectRuntime(base_dir=data_dir)
549 result = object_execution.execute_object(
550 runtime,
551 object_execution.ObjectExecutionRequest(
552 "site_view_render", payload={"_identity": {}},
553 ),
554 roots=[object_root],
555 )
556 assert result.ok is True
557 assert result.result["status"] == 404
558
559
560# ---------------------------------------------------------------------
561# Route-seeding: real site routing end to end, using this package's own
562# seeded views + site_routes rows -- closes the audit's "detail routes
563# not seeded into packages" finding.
564# ---------------------------------------------------------------------
565
566
567def test_route_resolution_for_a_seeded_detail_path(tmp_path, monkeypatch):
568 root, data_dir = enable_site_routes(monkeypatch, tmp_path)
569 object_packages.install_package(
570 "app-views", root=PACKAGES_ROOT, base_dir=data_dir, object_roots=[root],
571 )
572 object_packages.install_package(
573 "app-contacts", root=PACKAGES_ROOT, base_dir=data_dir, object_roots=[root],
574 )
575
576 contact_id = "5c2b6b0a-1111-4a3d-8b8a-9d6b7f0000aa"
577 status, headers, body = raw_request(f"/contacts/{contact_id}")
578
579 assert status == 200
580 text = body.decode("utf-8")
581 assert "const VIEW_ID = 'view_contacts_detail';" in text
582 assert f"const RECORD_ID = {contact_id!r};" in text
583 assert '<script src="/detail">' in text
584
585 # The detail route is `{contact_id}` (no :uuid constraint) so ANY id segment
586 # routes to the view -- this is deliberate: records with non-uuid ids (seed
587 # data, friendly ids) must be reachable too, per "everything has a url"
588 # (docs/ui-decisions.md). A record that then doesn't exist is the view's own
589 # not-found state, not a routing 404. (The :uuid constraint still exists for
590 # a route that wants to enforce uuid shape; the app seeds just don't use it.)
591 any_status, _, any_body = raw_request("/contacts/friendly-id-123")
592 assert any_status == 200
593 assert "const VIEW_ID = 'view_contacts_detail';" in any_body.decode("utf-8")
594
595
596def test_route_resolution_for_a_seeded_task_detail_path_with_related_children(tmp_path, monkeypatch):
597 root, data_dir = enable_site_routes(monkeypatch, tmp_path)
598 object_packages.install_package(
599 "app-views", root=PACKAGES_ROOT, base_dir=data_dir, object_roots=[root],
600 )
601 object_packages.install_package(
602 "app-projects", root=PACKAGES_ROOT, base_dir=data_dir, object_roots=[root],
603 )
604 object_packages.install_package(
605 "app-tasks", root=PACKAGES_ROOT, base_dir=data_dir, object_roots=[root],
606 )
607
608 task_id = "9f1a2b3c-2222-4a3d-8b8a-9d6b7f0000bb"
609 status, _, body = raw_request(f"/tasks/{task_id}")
610
611 assert status == 200
612 text = body.decode("utf-8")
613 assert "const VIEW_ID = 'view_tasks_detail';" in text
614 assert f"const RECORD_ID = {task_id!r};" in text
615
616
617def test_contacts_and_tasks_seed_views_and_site_routes(tmp_path):
618 for pkg_id, base_dir_name in (("app-contacts", "c"), ("app-tasks", "t")):
619 base_dir = tmp_path / base_dir_name / "data"
620 object_root = tmp_path / base_dir_name / "objects"
621 object_root.mkdir(parents=True)
622 result = object_packages.install_package(
623 pkg_id, root=PACKAGES_ROOT, base_dir=base_dir, object_roots=[object_root],
624 )
625 assert result["warnings"] == []
626 assert (base_dir / "collections" / "views" / "records.tsv").is_file()
627 assert (base_dir / "collections" / "site_routes" / "records.tsv").is_file()
628
629
630# ---------------------------------------------------------------------
631# Permissions posture: a related block is exactly a 58 filtered read, so
632# it inherits 58's row-filter-first guarantee verbatim -- no leak.
633# ---------------------------------------------------------------------
634
635
636def test_related_query_shape_cannot_leak_a_row_outside_the_row_filter(tmp_path, monkeypatch):
637 """The exact query shape renderRelated compiles to --
638 /collections/{child}/records?{fk_field}={match} -- run against
639 app-contacts' own real, owner-scoped permission rules (interactions
640 has no public/cross-user read rule at all). A related block over
641 another user's interactions must come back empty, never their row,
642 even though the fk_field itself (contact_id) is fully readable."""
643 data_dir = tmp_path / "data"
644 write_records(
645 data_dir,
646 "interactions",
647 "id\tcontact_id\tsummary\towner_id\n"
648 "i1\tc1\tCalled about renewal\towner-a\n"
649 "i2\tc1\tPrivate note from another rep\towner-b\n",
650 )
651 policy = json.loads((APP_CONTACTS_DIR / "permissions" / "rules.json").read_text())
652 save_permission_policy(data_dir, {"access_mode": "role_based", "rules": policy["rules"]})
653 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
654 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
655 monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true")
656 enable_admin_token(monkeypatch)
657
658 # owner-a's own related-interactions read: sees only their own row.
659 owner_status, _, owner_payload = request(
660 "/collections/interactions/records",
661 query_string="contact_id=c1",
662 headers=[("x-dbbasic-user-id", "owner-a"), ("x-dbbasic-roles", "registered")],
663 )
664 # A different signed-in visitor's related-interactions read over the
665 # SAME contact: interactions has no cross-user read rule at all, so
666 # this must be empty, not owner-a's or owner-b's row.
667 other_status, _, other_payload = request(
668 "/collections/interactions/records",
669 query_string="contact_id=c1",
670 headers=[("x-dbbasic-user-id", "owner-c"), ("x-dbbasic-roles", "registered")],
671 )
672 # Anonymous: interactions has no "public" rule at all, so this is a
673 # flat permission denial (403) rather than an empty 200 -- an even
674 # more direct "no leak" than the signed-in-but-out-of-scope case
675 # above, just a different status shape.
676 anon_status, _, anon_payload = request(
677 "/collections/interactions/records", query_string="contact_id=c1",
678 )
679 # Admin really can reach both rows -- proving the row filter, not an
680 # accident, is what hid them above.
681 admin_status, _, admin_payload = request(
682 "/collections/interactions/records",
683 query_string="contact_id=c1",
684 headers=auth_headers(),
685 )
686
687 assert owner_status == 200
688 assert [r["id"] for r in owner_payload["records"]] == ["i1"]
689
690 assert other_status == 200
691 assert other_payload["records"] == []
692
693 assert anon_status == 403
694 assert "i1" not in json.dumps(anon_payload)
695 assert "i2" not in json.dumps(anon_payload)
696
697 assert admin_status == 200
698 assert {r["id"] for r in admin_payload["records"]} == {"i1", "i2"}
699
700
701# ---------------------------------------------------------------------
702# Scope boundary: related is for true children, not document-composition
703# (order/invoice line items) -- 66-line-items-spec.md's territory.
704# ---------------------------------------------------------------------
705
706_LINE_ITEMS_COLLECTIONS = {"order_lines", "invoice_lines", "fin_journal_lines"}
707
708
709def test_scope_boundary_is_stated_in_view_render_docs():
710 source = _view_render_source()
711 assert "Scope boundary" in source
712 assert "line-items" in source
713 assert "66-line-items-spec.md" in source
714
715
716def test_no_seeded_related_block_targets_a_line_items_collection():
717 """Regression guard for the related-vs-embed boundary: scan every
718 schema's views.related for a target collection that is actually a
719 document-composition (line-items) collection. None of the `related`
720 entries this task seeds -- or any other schema in the repo -- may
721 point at one; those compose via a `line-items` block (66) instead,
722 once it exists."""
723 for schema_path in PACKAGES_ROOT.glob("*/schemas/*.json"):
724 try:
725 schema = json.loads(schema_path.read_text())
726 except json.JSONDecodeError:
727 continue
728 related = ((schema.get("views") or {}).get("related")) or []
729 for entry in related:
730 assert entry.get("collection") not in _LINE_ITEMS_COLLECTIONS, (
731 f"{schema_path} declares a related block over a line-items "
732 f"collection ({entry.get('collection')}) -- document-"
733 "composition items embed (66), they are not a related target"
734 )
735
736
737def test_line_items_collections_have_no_fk_field_a_related_block_could_use():
738 """66's own claim (59's Purpose section): once line items embed as a
739 JSON array field, they have structurally nothing for `related`'s
740 collection + fk_field shape to point at. Today (pre-66) these are
741 still real collections -- this test just documents which ones the
742 boundary applies to, so a future related-block author doesn't
743 reach for one by habit."""
744 for name in _LINE_ITEMS_COLLECTIONS:
745 matches = list(PACKAGES_ROOT.glob(f"*/schemas/{name}.json"))
746 assert matches, f"expected a schema for {name}"
747
748
749# ---------------------------------------------------------------------
750# Schema surfacing: views.detail_fields / views.related additive keys
751# ---------------------------------------------------------------------
752
753
754def test_contacts_detail_fields_and_related_interactions():
755 schema = json.loads((APP_CONTACTS_DIR / "schemas" / "contacts.json").read_text())
756 views = schema["views"]
757 assert "detail_fields" in views
758 assert set(views["detail_fields"]) <= {f["name"] for f in schema["fields"]}
759 assert views["related"] == [{"collection": "interactions", "fk_field": "contact_id"}]
760
761
762def test_organizations_related_contacts():
763 schema = json.loads((APP_CONTACTS_DIR / "schemas" / "organizations.json").read_text())
764 assert schema["views"]["related"] == [{"collection": "contacts", "fk_field": "organization_id"}]
765
766
767def test_forum_topics_detail_fields_include_ai_summary():
768 schema = json.loads((PACKAGES_ROOT / "app-forum" / "schemas" / "forum_topics.json").read_text())
769 assert "ai_summary" in schema["views"]["detail_fields"]
770
771
772def test_tasks_related_comments_and_files():
773 schema = json.loads((APP_TASKS_DIR / "schemas" / "tasks.json").read_text())
774 related = {(r["collection"], r["fk_field"]) for r in schema["views"]["related"]}
775 assert ("task_comments", "task_id") in related
776 assert ("files", "task_id") in related
777
778
779def test_files_task_id_is_a_soft_relation_like_template_id():
780 schema = json.loads((PACKAGES_ROOT / "app-files" / "schemas" / "files.json").read_text())
781 by_name = {f["name"]: f for f in schema["fields"]}
782 assert by_name["task_id"]["relation"]["collection"] == "tasks"
783 manifest = json.loads((PACKAGES_ROOT / "app-files" / "dbbasic-package.json").read_text())
784 assert "app-tasks" not in manifest.get("dependencies", [])
785
786
787# ---------------------------------------------------------------------
788# Repo hygiene: no internal org/codename references in anything this
789# task added or touched.
790# ---------------------------------------------------------------------
791
792_BANNED = re.compile(
793 "|".join([r"\b" + "q" + "9" + r"\b", "ask" + "robots", r"\b" + "wo" + "ld" + r"\b"]),
794 re.IGNORECASE,
795)
796_TOUCHED_DIRS = [
797 APP_THEME_DIR,
798 APP_VIEWS_DIR,
799 APP_CONTACTS_DIR,
800 APP_TASKS_DIR,
801 PACKAGES_ROOT / "app-forum",
802 PACKAGES_ROOT / "app-files",
803 PACKAGES_ROOT / "app-worker",
804]
805
806
807def test_no_disallowed_org_names_in_touched_packages():
808 for directory in _TOUCHED_DIRS:
809 for path in directory.rglob("*"):
810 if path.is_dir():
811 continue
812 text = path.read_text(encoding="utf-8", errors="ignore")
813 assert not _BANNED.search(text), f"disallowed reference found in {path}"
814
815
816def test_this_test_file_has_no_disallowed_org_names():
817 assert not _BANNED.search(Path(__file__).read_text())
818
819
820# ---------------------------------------------------------------------
821# WHAT THIS CLOSES: profile regains the social graph, forum renders
822# ai_summary -- both closed as direct 59 mechanism usage on their
823# existing bespoke pages, not through the views/site_routes system (see
824# their own module docstrings for why).
825# ---------------------------------------------------------------------
826
827
828def test_profile_page_composes_followers_and_following_as_related_lists():
829 source = (PACKAGES_ROOT / "app-worker" / "objects" / "site" / "profile.py").read_text()
830 assert '<script src="/list">' in source
831 assert 'where: {following_id: PROFILE_ID}' in source
832 assert 'where: {follower_id: PROFILE_ID}' in source
833 assert "loadFollowGraph();" in source
834
835
836def test_forum_topic_ai_summary_renders_via_visible_when_not_a_bespoke_page():
837 """59's Purpose called out the forum topic page finally rendering its
838 stored-but-orphaned ai_summary. The bespoke page that did that (with
839 hand-written show/hide JS) is gone; the seeded detail view renders every
840 field, and ai_summary shows only when is_ai_summarized via the field's
841 own `visible_when` -- the general primitive, not a per-page renderer."""
842 schema = json.loads(
843 (PACKAGES_ROOT / "app-forum" / "schemas" / "forum_topics.json").read_text()
844 )
845 ai = next(f for f in schema["fields"] if f["name"] == "ai_summary")
846 assert ai["visible_when"] == {"field": "is_ai_summarized", "equals": "true"}
847 assert not (PACKAGES_ROOT / "app-forum" / "objects" / "site" / "forum_topic.py").exists()
848
849
850def test_form_read_only_formats_cents_money_fields_in_whole_units():
851 """Every hand-written *_view page re-implemented cents->whole-units money
852 formatting; it is hoisted into /form's shared read-only renderer, keyed
853 on the universal `_cents` field-name doctrine, so it applies to every
854 detail page with zero schema changes."""
855 source = _form_source()
856 assert "function isMoneyField(f)" in source
857 assert "/_cents$/.test(f.name" in source
858 assert "(n / 100).toFixed(2)" in source
859 # The read-only value branch and the label both go through the money path.
860 assert "isMoneyField(f) ? moneyText(v)" in source
861 assert "isMoneyField(f) ? moneyLabel(f)" in source
862 # Display only -- edit mode still submits the raw integer cents, never a
863 # dollars value that would need round-trip conversion.
864 assert "type=\"number\"" in source
865
866
867def test_form_honors_conditional_field_visibility_visible_when():
868 """A field's `visible_when` = {field, equals|in} hides it unless the
869 record's value matches -- replacing every *_view page's bespoke show/hide
870 CSS+JS with one field-level declaration honored on every generated
871 surface. Fails OPEN (unknown/absent condition => visible)."""
872 source = _form_source()
873 assert "function fieldVisible(f, record)" in source
874 assert "f.visible_when" in source
875 # Applied in read-only (detail) mode AND edit mode (against an existing
876 # record; create shows all).
877 assert "if (!fieldVisible(f, record)) continue;" in source
878 assert "(!record || fieldVisible(f, record))" in source
879 # Supports equals and in, the same tiny vocabulary 58's filter uses.
880 assert '"equals" in cond' in source
881 assert "Array.isArray(cond.in)" in source
882
883
884def test_form_supports_fk_locked_fields_for_child_compose():
885 """A `form` block can lock fields to a context value (opts.fixed) -- the
886 parent->child compose shape (reply.topic_id, line.invoice_id, ...) every
887 hand-written page re-implemented as prefill+hide. A shared capability of
888 the generic form renderer, not a bespoke per-page form: locked fields are
889 excluded from the UI and injected on submit."""
890 form_source = _form_source()
891 # excluded from the rendered/ordered fields...
892 assert "!(f.name in fixed)" in form_source
893 # ...and injected into the record on submit.
894 assert "for (const k in fixed) rec[k] = fixed[k];" in form_source
895 assert "opts.fixed" in form_source
896
897
898def test_view_render_form_block_resolves_fixed_from_record_id():
899 """The form block resolves $record_id in its `fixed` map (same resolution
900 detail/related use) and passes it + the viewer as owner to the generic
901 form renderer -- so [detail, related, form] compose one child-bearing page
902 from generic block renderers, no bespoke code."""
903 source = _view_render_source()
904 form_fn = re.search(r"function renderForm\(block, mount\) \{(.*?)\n\}", source, re.S)
905 assert form_fn, "renderForm not found"
906 body = form_fn.group(1)
907 assert "block.fixed" in body
908 assert "resolveRecordId(block.fixed[k])" in body
909 assert "base.fixed = fixed" in body
910 assert "owner: viewerId" in body
911
912
913def test_form_auto_scopes_new_records_to_the_current_entity():
914 """65 multi-entity: a NEW record in an entity-scoped collection (schema has
915 an entity_id field) is auto-locked to the nav switcher's current entity
916 (window.dbbasicEntity) via the same `fixed` mechanism a caller-supplied FK
917 uses -- only on create, only when an entity is selected. No per-form wiring;
918 every generator create form writes into the current set of books."""
919 source = _form_source()
920 assert 'byName["entity_id"]' in source
921 assert "window.dbbasicEntity" in source
922 assert '!("entity_id" in fixed)' in source
923 # opts.fixed is COPIED, never mutated, so auto-scoping never leaks back to
924 # the caller's object.
925 assert "Object.assign({}, opts.fixed)" in source
926
927
928def test_list_auto_scopes_top_level_browse_to_current_entity():
929 """65 multi-entity: a TOP-LEVEL browse list over an entity-scoped
930 collection (schema has entity_id) auto-filters to the nav switcher's
931 current entity -- but only when there is NO existing cfg.where, so a
932 `related` child list (scoped by its own FK) and explicitly-filtered lists
933 are never wrongly narrowed to a different entity."""
934 source = _list_source()
935 assert "async function scopeToCurrentEntity()" in source
936 assert "window.dbbasicEntity" in source
937 # the never-hide guards: an entity must be selected, and no existing where
938 assert "if (!cur || cfg.where) return;" in source
939 assert '(f) => f.name === "entity_id"' in source
940 assert "cfg.where = {entity_id: cur}" in source
941 # cfg is copied so the caller's config object is never mutated
942 assert "cfg = Object.assign({}, cfg || {})" in source