Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/tests/test_app_views_package.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

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