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_app_views_package.py · 16.6 KB · 413 lines
| 1 | """Structural tests for packages/app-views (dynamic UI: views as records). |
| 2 | |
| 3 | Mirrors the package/schema/permission/renderer testing conventions used for |
| 4 | packages/app-notes and packages/app-settings in tests/test_object_packages.py |
| 5 | and tests/test_app_settings_package.py. |
| 6 | """ |
| 7 | |
| 8 | import json |
| 9 | import re |
| 10 | from pathlib import Path |
| 11 | |
| 12 | import object_execution |
| 13 | import object_packages |
| 14 | import object_permissions |
| 15 | import python_object_runtime |
| 16 | |
| 17 | PACKAGES_ROOT = Path(__file__).resolve().parents[1] / "packages" |
| 18 | APP_VIEWS_DIR = PACKAGES_ROOT / "app-views" |
| 19 | |
| 20 | # The `object` kind is the escape hatch that keeps a generated page from |
| 21 | # being all-or-nothing: one block may be a hand-written object, so a page |
| 22 | # can stay generated everywhere except the part that genuinely needs code. |
| 23 | CLOSED_VOCABULARY = {"list", "form", "detail", "related", "thread", "count", |
| 24 | "aggregate", "markdown", "reader", "object"} |
| 25 | |
| 26 | |
| 27 | def test_get_package_normalizes_app_views_manifest(): |
| 28 | package = object_packages.get_package("app-views", root=PACKAGES_ROOT) |
| 29 | |
| 30 | assert package["id"] == "app-views" |
| 31 | assert package["name"] == "Views" |
| 32 | assert package["objects"] == [ |
| 33 | {"id": "site_view_render", "path": "objects/site/view_render.py"}, |
| 34 | # 0.2.0: /flow -- the workflow viewable, compiled live by |
| 35 | # object_governance from the declarations the server enforces. |
| 36 | {"id": "site_flow", "path": "objects/site/flow.py"}, |
| 37 | # 0.3.0: /urls -- the site map, compiled (convention + routes + |
| 38 | # views + core constants), with shadowing called out. |
| 39 | {"id": "site_urls", "path": "objects/site/urls.py"}, |
| 40 | ] |
| 41 | assert package["schemas"] == [{"collection": "views", "path": "schemas/views.json"}] |
| 42 | assert package["permissions"] == [{"path": "permissions/rules.json"}] |
| 43 | # 0.2.0 seeds the /flow routes. |
| 44 | assert package["seed"] == [ |
| 45 | {"collection": "site_routes", "path": "seed/site_routes.tsv"} |
| 46 | ] |
| 47 | |
| 48 | |
| 49 | def test_dry_run_app_views_package_is_safe(tmp_path): |
| 50 | object_root = tmp_path / "objects" |
| 51 | object_root.mkdir() |
| 52 | |
| 53 | plan = object_packages.dry_run_package( |
| 54 | "app-views", |
| 55 | root=PACKAGES_ROOT, |
| 56 | base_dir=tmp_path / "data", |
| 57 | object_roots=[object_root], |
| 58 | ) |
| 59 | |
| 60 | assert plan["safe_to_install"] is True |
| 61 | assert plan["warnings"] == [] |
| 62 | assert {schema["collection"] for schema in plan["schemas"]} == {"views"} |
| 63 | |
| 64 | |
| 65 | def test_views_schema_matches_spec_fields(): |
| 66 | payload = json.loads((APP_VIEWS_DIR / "schemas" / "views.json").read_text()) |
| 67 | |
| 68 | assert payload["name"] == "views" |
| 69 | field_names = [field["name"] for field in payload["fields"]] |
| 70 | assert field_names == [ |
| 71 | "id", "title", "route", "layout", "blocks", |
| 72 | "owner_id", "is_public", "pinned", "created_at", |
| 73 | ] |
| 74 | |
| 75 | by_name = {field["name"]: field for field in payload["fields"]} |
| 76 | assert by_name["title"]["required"] is True |
| 77 | assert by_name["route"]["type"] == "text" |
| 78 | assert by_name["layout"]["type"] == "enum" |
| 79 | assert by_name["layout"]["enum"] == ["single", "two_column", "grid"] |
| 80 | assert by_name["layout"]["default"] == "single" |
| 81 | assert by_name["blocks"]["type"] == "textarea" |
| 82 | assert by_name["owner_id"]["type"] == "text" |
| 83 | assert by_name["is_public"]["type"] == "boolean" |
| 84 | assert by_name["is_public"]["default"] == "false" |
| 85 | assert by_name["pinned"]["type"] == "boolean" |
| 86 | assert by_name["pinned"]["default"] == "false" |
| 87 | assert by_name["created_at"]["type"] == "datetime" |
| 88 | assert by_name["created_at"]["read_only"] is True |
| 89 | |
| 90 | # forms/views/search keys are present and sensible for a records-list UI. |
| 91 | assert "blocks" in payload["forms"]["default"]["fields"] |
| 92 | assert "title" in payload["forms"]["default"]["fields"] |
| 93 | assert "id" not in payload["forms"]["default"]["fields"] |
| 94 | assert "created_at" not in payload["forms"]["default"]["fields"] |
| 95 | assert payload["views"]["list_mode"] in {"table", "cards"} |
| 96 | assert "title" in payload["views"]["list_fields"] |
| 97 | assert "title" in payload["search"]["fields"] |
| 98 | |
| 99 | |
| 100 | def test_blocks_vocabulary_documented_in_schema_help(): |
| 101 | payload = json.loads((APP_VIEWS_DIR / "schemas" / "views.json").read_text()) |
| 102 | by_name = {field["name"]: field for field in payload["fields"]} |
| 103 | help_text = by_name["blocks"].get("help", "") |
| 104 | |
| 105 | for kind in CLOSED_VOCABULARY: |
| 106 | assert kind in help_text, f"blocks help text must document the {kind!r} kind" |
| 107 | |
| 108 | |
| 109 | def test_install_app_views_package_loads_schema(tmp_path): |
| 110 | data_dir = tmp_path / "data" |
| 111 | object_root = tmp_path / "objects" |
| 112 | object_root.mkdir() |
| 113 | |
| 114 | object_packages.install_package( |
| 115 | "app-views", |
| 116 | root=PACKAGES_ROOT, |
| 117 | base_dir=data_dir, |
| 118 | object_roots=[object_root], |
| 119 | ) |
| 120 | |
| 121 | import object_schemas |
| 122 | |
| 123 | schema = object_schemas.get_schema("views", base_dir=data_dir) |
| 124 | assert schema["name"] == "views" |
| 125 | assert (object_root / "site" / "view_render.py").is_file() |
| 126 | |
| 127 | |
| 128 | def _app_views_policy(): |
| 129 | payload = json.loads((APP_VIEWS_DIR / "permissions" / "rules.json").read_text()) |
| 130 | return object_permissions.policy_from_dict({"access_mode": "role_based", "rules": payload["rules"]}) |
| 131 | |
| 132 | |
| 133 | def test_owner_can_crud_own_views(): |
| 134 | policy = _app_views_policy() |
| 135 | subject = object_permissions.PermissionSubject(user_id="7") |
| 136 | record = {"owner_id": "7", "title": "My Dashboard", "is_public": "false"} |
| 137 | |
| 138 | for action in ( |
| 139 | object_permissions.CREATE, |
| 140 | object_permissions.READ, |
| 141 | object_permissions.UPDATE, |
| 142 | object_permissions.DELETE, |
| 143 | ): |
| 144 | decision = object_permissions.check_permission( |
| 145 | subject, action, policy=policy, collection="views", record=record |
| 146 | ) |
| 147 | assert decision.allowed is True |
| 148 | |
| 149 | |
| 150 | def test_others_cannot_touch_a_private_view(): |
| 151 | policy = _app_views_policy() |
| 152 | subject = object_permissions.PermissionSubject(user_id="8") |
| 153 | record = {"owner_id": "7", "title": "My Dashboard", "is_public": "false"} |
| 154 | |
| 155 | for action in ( |
| 156 | object_permissions.READ, |
| 157 | object_permissions.UPDATE, |
| 158 | object_permissions.DELETE, |
| 159 | ): |
| 160 | decision = object_permissions.check_permission( |
| 161 | subject, action, policy=policy, collection="views", record=record |
| 162 | ) |
| 163 | assert decision.allowed is False |
| 164 | |
| 165 | |
| 166 | def test_public_view_is_readable_by_anonymous_visitors(): |
| 167 | policy = _app_views_policy() |
| 168 | record = {"owner_id": "7", "title": "Public Board", "is_public": "true"} |
| 169 | |
| 170 | decision = object_permissions.check_permission( |
| 171 | None, object_permissions.READ, policy=policy, collection="views", record=record |
| 172 | ) |
| 173 | assert decision.allowed is True |
| 174 | |
| 175 | |
| 176 | def test_private_view_is_not_readable_by_anonymous_visitors(): |
| 177 | policy = _app_views_policy() |
| 178 | record = {"owner_id": "7", "title": "My Dashboard", "is_public": "false"} |
| 179 | |
| 180 | decision = object_permissions.check_permission( |
| 181 | None, object_permissions.READ, policy=policy, collection="views", record=record |
| 182 | ) |
| 183 | assert decision.allowed is False |
| 184 | |
| 185 | |
| 186 | def test_renderer_execute_is_public(): |
| 187 | policy = _app_views_policy() |
| 188 | |
| 189 | decision = object_permissions.check_permission( |
| 190 | None, object_permissions.EXECUTE, policy=policy, object_id="site_view_render" |
| 191 | ) |
| 192 | assert decision.allowed is True |
| 193 | |
| 194 | |
| 195 | def test_renderer_object_serves_scaffolding_for_a_view_id(tmp_path): |
| 196 | data_dir = tmp_path / "data" |
| 197 | object_root = tmp_path / "objects" |
| 198 | object_root.mkdir() |
| 199 | |
| 200 | object_packages.install_package( |
| 201 | "app-views", |
| 202 | root=PACKAGES_ROOT, |
| 203 | base_dir=data_dir, |
| 204 | object_roots=[object_root], |
| 205 | ) |
| 206 | |
| 207 | runtime = python_object_runtime.PythonObjectRuntime(base_dir=data_dir) |
| 208 | view_id = "3fbb7e9e-2222-4d3d-8b8a-9d6b7f000001" |
| 209 | result = object_execution.execute_object( |
| 210 | runtime, |
| 211 | object_execution.ObjectExecutionRequest( |
| 212 | "site_view_render", payload={"view_id": view_id, "_identity": {}} |
| 213 | ), |
| 214 | roots=[object_root], |
| 215 | ) |
| 216 | |
| 217 | assert result.ok is True |
| 218 | body = result.result["body"] |
| 219 | assert result.result["content_type"] == "text/html; charset=utf-8" |
| 220 | assert view_id in body |
| 221 | assert 'id="blocks"' in body |
| 222 | assert 'id="viewtitle"' in body |
| 223 | assert '<script src="/list">' in body |
| 224 | assert '<script src="/form">' in body |
| 225 | assert '<script src="/nav">' in body |
| 226 | |
| 227 | |
| 228 | def test_renderer_returns_404_shape_for_a_missing_view_id(tmp_path): |
| 229 | data_dir = tmp_path / "data" |
| 230 | object_root = tmp_path / "objects" |
| 231 | object_root.mkdir() |
| 232 | |
| 233 | object_packages.install_package( |
| 234 | "app-views", |
| 235 | root=PACKAGES_ROOT, |
| 236 | base_dir=data_dir, |
| 237 | object_roots=[object_root], |
| 238 | ) |
| 239 | |
| 240 | runtime = python_object_runtime.PythonObjectRuntime(base_dir=data_dir) |
| 241 | result = object_execution.execute_object( |
| 242 | runtime, |
| 243 | object_execution.ObjectExecutionRequest("site_view_render", payload={"_identity": {}}), |
| 244 | roots=[object_root], |
| 245 | ) |
| 246 | |
| 247 | assert result.ok is True |
| 248 | assert result.result["status"] == 404 |
| 249 | |
| 250 | |
| 251 | def test_renderer_source_covers_the_closed_block_vocabulary(): |
| 252 | source = (APP_VIEWS_DIR / "objects" / "site" / "view_render.py").read_text() |
| 253 | |
| 254 | assert ('KNOWN_KINDS = ["list", "form", "detail", "related", "thread", ' |
| 255 | '"count", "aggregate", "markdown", "reader", "object"]') in source |
| 256 | for kind in CLOSED_VOCABULARY: |
| 257 | assert f'"{kind}": render' in source or f"render{kind.capitalize()}" in source |
| 258 | assert "unsupported" in source.lower() |
| 259 | assert "Invalid blocks JSON" in source |
| 260 | |
| 261 | |
| 262 | def test_renderer_markdown_block_delegates_to_shared_renderer_and_never_raw_innerhtmls(): |
| 263 | """The markdown block delegates to the ONE shared renderer at |
| 264 | /markdown (window.dbbasicMarkdown, in markdown.py -- escapes ALL html |
| 265 | first, then applies markdown on the already-escaped text) rather than |
| 266 | formatting block.text itself. Assert the delegation directly on the |
| 267 | JS source, and that block.text is never innerHTML'd raw regardless of |
| 268 | whether window.dbbasicMarkdown happens to be loaded. |
| 269 | """ |
| 270 | source = (APP_VIEWS_DIR / "objects" / "site" / "view_render.py").read_text() |
| 271 | |
| 272 | match = re.search( |
| 273 | r"function renderMarkdown\(block, mount\) \{(.*?)\n\}", source, re.S |
| 274 | ) |
| 275 | assert match, "renderMarkdown function not found in view_render.py" |
| 276 | body = match.group(1) |
| 277 | |
| 278 | assert "window.dbbasicMarkdown" in body |
| 279 | assert "window.dbbasicMarkdown(block.text)" in body |
| 280 | # The no-/markdown-loaded fallback still escapes -- never a raw pass-through. |
| 281 | assert "esc(block.text)" in body |
| 282 | assert "innerHTML = block.text" not in source |
| 283 | assert "innerHTML = mount.textContent" not in source |
| 284 | |
| 285 | |
| 286 | def test_renderer_reader_block_fetches_api_read_and_escapes_output(): |
| 287 | """The reader block is client-side like every other block here: it |
| 288 | POSTs to /api/read and renders whatever comes back through esc() -- |
| 289 | title, paragraph text, and link labels must never be innerHTML'd raw, |
| 290 | same discipline as renderMarkdown.""" |
| 291 | source = (APP_VIEWS_DIR / "objects" / "site" / "view_render.py").read_text() |
| 292 | |
| 293 | match = re.search(r"function renderReader\(block, mount\) \{(.*?)\n\}", source, re.S) |
| 294 | assert match, "renderReader function not found in view_render.py" |
| 295 | body = match.group(1) |
| 296 | |
| 297 | assert '"/api/read"' in body |
| 298 | assert "method: \"POST\"" in body |
| 299 | assert "esc(data.title" in body |
| 300 | assert "esc(p)" in body |
| 301 | assert "esc(l.href)" in body |
| 302 | assert "esc(l.label)" in body |
| 303 | assert "unsupportedCard(data.error" in body |
| 304 | |
| 305 | |
| 306 | def test_nav_lists_pinned_views_and_fails_silently(): |
| 307 | source = (PACKAGES_ROOT / "app-theme" / "objects" / "site" / "nav.py").read_text() |
| 308 | |
| 309 | assert "loadPinnedViews" in source |
| 310 | assert "/collections/views/records" in source |
| 311 | assert "v.pinned" in source |
| 312 | # The fetch is wrapped so a missing app-views package cannot break the bar. |
| 313 | assert "catch (e)" in source |
| 314 | |
| 315 | |
| 316 | def test_app_theme_manifest_still_normalizes_after_nav_change(): |
| 317 | package = object_packages.get_package("app-theme", root=PACKAGES_ROOT) |
| 318 | assert package["id"] == "app-theme" |
| 319 | assert {obj["id"] for obj in package["objects"]} >= {"site_nav"} |
| 320 | |
| 321 | |
| 322 | def test_view_render_resolves_capture_less_list_view_by_path(tmp_path): |
| 323 | """view_render can route a capture-LESS index/list view (e.g. /entities, |
| 324 | whose views.route is a plain literal with no {param}) by matching the raw |
| 325 | request path (request["_path"], set by object_server for every routed |
| 326 | object) against the view's `route` -- not just detail views with a route |
| 327 | capture. The views record stays the single source of truth; no second |
| 328 | route table.""" |
| 329 | import types |
| 330 | |
| 331 | src = (APP_VIEWS_DIR / "objects" / "site" / "view_render.py").read_text() |
| 332 | mod = types.ModuleType("view_render_under_test") |
| 333 | exec(compile(src, "view_render.py", "exec"), mod.__dict__) |
| 334 | |
| 335 | data_dir = tmp_path / "data" |
| 336 | (data_dir / "collections" / "views").mkdir(parents=True) |
| 337 | (data_dir / "collections" / "views" / "records.tsv").write_text( |
| 338 | "id\troute\n" |
| 339 | "view_entities_list\t/entities\n" |
| 340 | "view_entities_detail\t/entities/{entity_id}\n" |
| 341 | ) |
| 342 | |
| 343 | uuid = "00000000-0000-4000-8000-000000000000" |
| 344 | # capture-less list route resolves by _path, with no record id |
| 345 | assert mod._resolve_view_and_record({"_path": "/entities"}, data_dir) == ( |
| 346 | "view_entities_list", "", |
| 347 | ) |
| 348 | # detail route still resolves by its single capture (record id present) |
| 349 | assert mod._resolve_view_and_record( |
| 350 | {"entity_id": uuid, "_path": f"/entities/{uuid}"}, data_dir |
| 351 | ) == ("view_entities_detail", uuid) |
| 352 | # an unknown path resolves to nothing (404 upstream), never a wrong view |
| 353 | assert mod._resolve_view_and_record({"_path": "/nope"}, data_dir) == ("", "") |
| 354 | # _path is reserved -- never mistaken for a route capture value |
| 355 | assert "_path" in mod._RESERVED_REQUEST_KEYS |
| 356 | |
| 357 | |
| 358 | def test_view_render_has_an_aggregate_block_for_document_totals(): |
| 359 | """The `aggregate` block sums numeric fields across a related/filtered set |
| 360 | (a journal's debit/credit balance, an invoice's line subtotal) -- the |
| 361 | document-totals shape `related` (lists) and `count` (counts) can't express. |
| 362 | Money `_cents` sums render in whole units; `balance: [a,b]` adds a |
| 363 | Balanced/Not badge. The one new block the Stage-6 retrofit surfaced a real |
| 364 | need for (the journal's client-computed balance summary).""" |
| 365 | source = (APP_VIEWS_DIR / "objects" / "site" / "view_render.py").read_text() |
| 366 | assert '"aggregate"' in source # registered in KNOWN_KINDS |
| 367 | assert "aggregate: renderAggregate" in source # wired into RENDERERS |
| 368 | assert "function renderAggregate(block, mount)" in source |
| 369 | # sums numeric fields, filtered to the parent like `related` |
| 370 | assert "block.sums" in source and "block.fk_field" in source or "const fk = block.fk_field" in source |
| 371 | assert "reduce((a, r) => a + (Number(r[f]) || 0), 0)" in source |
| 372 | # money-aware (cents -> whole units) and the balance badge |
| 373 | assert '/_cents$/.test(String(f)) ? (Number(n) / 100).toFixed(2)' in source |
| 374 | assert "block.balance" in source and "Balanced" in source and "Not balanced" in source |
| 375 | |
| 376 | |
| 377 | def test_a_list_block_can_carry_a_standing_where_instead_of_a_client_side_filter(): |
| 378 | """0.4.0: `where` on a `list` block compiles to the same server-side |
| 379 | narrowing `related` has always used (window.dbbasicList's `where`, one |
| 380 | field=value param applied after the permission row filter), so an index |
| 381 | over ONE SLICE of a shared collection keeps the real generator. |
| 382 | |
| 383 | The distinction matters because the alternative is not merely worse, it |
| 384 | is unusable: `filters` routes the block through renderFilteredList, |
| 385 | which titles every row `title || name || id`, so a collection with |
| 386 | neither a title nor a name (shipments) renders as a column of raw ids |
| 387 | with no table, no filter bar, no search and no row cap. app-returns' |
| 388 | inbound bench is the case that surfaced it. |
| 389 | """ |
| 390 | source = (APP_VIEWS_DIR / "objects" / "site" / "view_render.py").read_text() |
| 391 | |
| 392 | assert "cfg.where = block.where" in source |
| 393 | # It must NOT divert into the client-side fallback: that branch keys off |
| 394 | # `filters`/`limit` only, and `where` has to reach window.dbbasicList. |
| 395 | assert "const hasFilters = block.filters && Object.keys(block.filters).length;" in source |
| 396 | assert "block.where" not in source.split("const hasFilters")[1].split("const cfg =")[0] |
| 397 | # Literals only -- a parent-scoped child list is what `related` is for. |
| 398 | assert "resolveRecordId(block.where" not in source |
| 399 | |
| 400 | |
| 401 | def test_the_where_key_is_documented_where_a_view_author_would_look(): |
| 402 | """A block option nobody can discover is a private API. The module |
| 403 | docstring is the vocabulary reference for this renderer, and it has to |
| 404 | say why `where` exists next to `filters` rather than just that it |
| 405 | does.""" |
| 406 | source = (APP_VIEWS_DIR / "objects" / "site" / "view_render.py").read_text() |
| 407 | docstring = source.split('"""')[1] |
| 408 | |
| 409 | assert "`where`" in docstring |
| 410 | assert "filters" in docstring |
| 411 | manifest = json.loads((APP_VIEWS_DIR / "dbbasic-package.json").read_text()) |
| 412 | assert manifest["version"] == "0.4.0" |
| 413 | assert "`where`" in manifest["description"] |