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