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_nav_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_nav_package.py · 19.9 KB · 458 lines
1"""Structural + behavioral tests for packages/app-nav.
2
3Follows the package/schema/permission conventions of
4tests/test_app_activity_package.py and the direct-execution pattern it
5uses for a site object. The platform half of the nav registry (manifest
6validation, install idempotency, the operator_hidden rule, the
7shipped-package sweep) lives in tests/test_package_nav.py; this file is
8about what the two surfaces actually render.
9"""
10
11import json
12from pathlib import Path
13
14import pytest
15
16import object_execution
17import object_packages
18import object_permissions
19import object_records
20import python_object_runtime
21from package_pins import assert_includes_in_order
22
23PACKAGES_ROOT = Path(__file__).resolve().parents[1] / "packages"
24APP_NAV_DIR = PACKAGES_ROOT / "app-nav"
25
26
27def _app_nav_policy():
28 payload = json.loads((APP_NAV_DIR / "permissions" / "rules.json").read_text())
29 return object_permissions.policy_from_dict(
30 {"access_mode": "role_based", "rules": payload["rules"]})
31
32
33@pytest.fixture
34def installed(tmp_path, monkeypatch):
35 """app-nav installed into empty roots, with the environment pointed at
36 them: site_home calls action_nav_entries in-process, which resolves
37 through the same roots the server would use."""
38 data_dir = tmp_path / "data"
39 object_root = tmp_path / "objects"
40 object_root.mkdir()
41 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
42 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(object_root))
43
44 object_packages.install_package(
45 "app-nav", root=PACKAGES_ROOT, base_dir=data_dir, object_roots=[object_root])
46 return {"data": data_dir, "objects": object_root}
47
48
49def add_entry(installed, nav_id, **fields):
50 row = {"id": nav_id, "package": "app-test", "label": nav_id.title(),
51 "path": f"/{nav_id}", "blurb": "", "group": "Work",
52 "surface": "member", "order": "10", "operator_hidden": "false"}
53 row.update(fields)
54 object_records.create_collection_record(
55 "nav_entries", row, base_dir=installed["data"], actor="test")
56
57
58def run(installed, object_id, identity, method="POST"):
59 runtime = python_object_runtime.PythonObjectRuntime(base_dir=installed["data"])
60 return object_execution.execute_object(
61 runtime,
62 object_execution.ObjectExecutionRequest(
63 object_id, method=method, payload={"_identity": identity}),
64 roots=[installed["objects"]])
65
66
67def page(installed, identity):
68 """site_home is a GET page; the action it folds over answers either."""
69 result = run(installed, "site_home", identity, method="GET")
70 assert result.ok, result.error
71 return result.result["body"]
72
73
74def labels(result):
75 return [entry["label"] for entry in result.result["entries"]]
76
77
78# --- the package ------------------------------------------------------------
79
80def test_get_package_normalizes_the_app_nav_manifest():
81 package = object_packages.get_package("app-nav", root=PACKAGES_ROOT)
82
83 assert package["id"] == "app-nav"
84 assert_includes_in_order([entry["id"] for entry in package["objects"]], [
85 "action_nav_entries", "site_home"])
86 assert_includes_in_order(package["schemas"], [
87 {"collection": "nav_entries", "path": "schemas/nav_entries.json"},
88 {"collection": "attention_sources", "path": "schemas/attention_sources.json"},
89 {"collection": "attention_counts", "path": "schemas/attention_counts.json"}])
90 assert package["nav"][0]["path"] == "/"
91
92
93def test_dry_run_app_nav_package_is_safe(tmp_path):
94 object_root = tmp_path / "objects"
95 object_root.mkdir()
96 plan = object_packages.dry_run_package(
97 "app-nav", root=PACKAGES_ROOT, base_dir=tmp_path / "data",
98 object_roots=[object_root])
99
100 assert plan["safe_to_install"] is True
101 assert plan["warnings"] == []
102
103
104def test_the_seed_is_header_only():
105 """The registry's rows come from other packages' manifests, not from
106 a seed file that would be a fourth hand-maintained list."""
107 lines = (APP_NAV_DIR / "seed" / "nav_entries.tsv").read_text().splitlines()
108 assert len(lines) == 1
109 schema = json.loads((APP_NAV_DIR / "schemas" / "nav_entries.json").read_text())
110 assert lines[0].split("\t") == [field["name"] for field in schema["fields"]]
111
112
113def test_reading_the_menu_is_public_and_so_is_the_front_door():
114 policy = _app_nav_policy()
115 for object_id in ("action_nav_entries", "site_home"):
116 decision = object_permissions.check_permission(
117 None, object_permissions.EXECUTE, policy=policy, object_id=object_id)
118 assert decision.allowed is True, object_id
119
120
121def test_the_registry_itself_is_not_public_and_only_a_manager_may_edit_it():
122 """A visitor reads the menu through the object that filters it, never
123 the raw collection -- otherwise `surface` would leak every operator
124 door to anyone who asked for the records."""
125 policy = _app_nav_policy()
126
127 anonymous = object_permissions.check_permission(
128 None, object_permissions.READ, policy=policy, collection="nav_entries")
129 assert anonymous.allowed is False
130
131 member = object_permissions.PermissionSubject(user_id="alice", roles=("user",))
132 assert object_permissions.check_permission(
133 member, object_permissions.READ, policy=policy, collection="nav_entries").allowed is True
134 assert object_permissions.check_permission(
135 member, object_permissions.UPDATE, policy=policy, collection="nav_entries").allowed is False
136
137 manager = object_permissions.PermissionSubject(user_id="mo", roles=("manager",))
138 assert object_permissions.check_permission(
139 manager, object_permissions.UPDATE, policy=policy, collection="nav_entries").allowed is True
140
141
142# --- action_nav_entries: the visibility tiers ---------------------------------
143
144def test_a_visitor_sees_only_the_public_tier(installed):
145 add_entry(installed, "shop", surface="public")
146 add_entry(installed, "notes", surface="member")
147 add_entry(installed, "scheduler", surface="operator")
148
149 assert labels(run(installed, "action_nav_entries", {})) == ["Home", "Shop"]
150
151
152def test_a_signed_in_user_also_sees_the_member_tier(installed):
153 add_entry(installed, "shop", surface="public")
154 add_entry(installed, "notes", surface="member")
155 add_entry(installed, "scheduler", surface="operator")
156
157 result = run(installed, "action_nav_entries", {"user_id": "alice"})
158 assert labels(result) == ["Home", "Notes", "Shop"]
159
160
161def test_only_an_admin_sees_the_operator_tier(installed):
162 """The same admin test system_scheduler makes before it will draw the
163 task board -- one answer on this server to 'is this an operator?'."""
164 add_entry(installed, "scheduler", surface="operator")
165
166 assert "Scheduler" not in labels(run(installed, "action_nav_entries",
167 {"user_id": "alice", "roles": ["user"]}))
168 assert "Scheduler" in labels(run(installed, "action_nav_entries",
169 {"user_id": "root", "roles": ["admin"]}))
170
171
172def test_hidden_surfaces_and_operator_hidden_rows_are_never_returned(installed):
173 """Two columns because they answer two different questions: the
174 package registered a door it does not want rendered, and the operator
175 took a door off this deployment's menu."""
176 add_entry(installed, "internal", surface="hidden")
177 add_entry(installed, "removed", surface="member", operator_hidden="true")
178 add_entry(installed, "removed_public", surface="public", operator_hidden="true")
179
180 for identity in ({}, {"user_id": "alice"}, {"user_id": "root", "roles": ["admin"]}):
181 shown = labels(run(installed, "action_nav_entries", identity))
182 assert "Internal" not in shown
183 assert "Removed" not in shown
184 assert "Removed_Public" not in shown
185
186
187def test_entries_are_grouped_and_a_group_sorts_where_its_first_entry_does(installed):
188 """Group order falls out of the same `order` the entries carry, so
189 there is no seventh list holding the reading order of the groups."""
190 add_entry(installed, "dashboard", group="System", order="600")
191 add_entry(installed, "invoices", group="Money", order="300")
192 add_entry(installed, "notes", group="Work", order="30")
193
194 result = run(installed, "action_nav_entries", {"user_id": "alice"})
195 assert [group["group"] for group in result.result["groups"]] == [
196 "Work", "Money", "System"]
197 assert [entry["label"] for entry in result.result["groups"][0]["entries"]] == [
198 "Home", "Notes"]
199
200
201def test_a_hand_edited_order_that_will_not_parse_does_not_break_the_menu(installed):
202 """The schema refuses a non-integer `order` on the write path, so this
203 can only arrive by somebody editing the TSV -- which is exactly when a
204 menu that raised instead of degrading would be least welcome."""
205 records = installed["data"] / "collections" / "nav_entries" / "records.tsv"
206 records.write_text(records.read_text()
207 + "typo\tapp-test\tTypo\t/typo\t\tWork\tmember\tsoon\tfalse\t\t\n")
208
209 result = run(installed, "action_nav_entries", {"user_id": "alice"})
210 assert result.ok is True
211 assert "Typo" in labels(result)
212
213
214def test_an_empty_registry_is_an_empty_menu_not_an_error(tmp_path, monkeypatch):
215 """The nav app installed before anything else has registered: a real
216 answer, which is what lets both surfaces fall back on their own."""
217 data_dir = tmp_path / "data"
218 object_root = tmp_path / "objects"
219 object_root.mkdir()
220 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
221 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(object_root))
222 object_packages.install_package(
223 "app-nav", root=PACKAGES_ROOT, base_dir=data_dir, object_roots=[object_root])
224 object_records.delete_collection_record(
225 "nav_entries", "home", base_dir=data_dir, actor="test")
226
227 result = run({"data": data_dir, "objects": object_root},
228 "action_nav_entries", {"user_id": "alice"})
229 assert result.ok is True
230 assert result.result == {"ok": True, "groups": [], "entries": [],
231 "attention": [], "count": 0}
232
233
234# --- site_home: the fold ------------------------------------------------------
235
236def test_the_home_page_renders_the_registry_grouped_under_headings(installed):
237 add_entry(installed, "notes", group="Work", order="30", blurb="Quick capture")
238 add_entry(installed, "invoices", group="Money", order="300")
239
240 body = page(installed, {"user_id": "alice"})
241
242 assert "<h2>Work</h2>" in body
243 assert "<h2>Money</h2>" in body
244 assert body.index("<h2>Work</h2>") < body.index("<h2>Money</h2>")
245 assert '<a class="tile" href="/notes">' in body
246 assert "Quick capture" in body
247 assert '<script src="/nav">' in body # the shared design system
248 assert "<style" not in body # no inline CSS: /style owns it
249
250
251def test_the_home_page_shows_a_visitor_only_public_doors(installed):
252 add_entry(installed, "notes", surface="member")
253
254 body = page(installed, {})
255 assert '<a href="/login">sign in</a>' in body
256 assert "/notes" not in body
257 assert '<a class="tile" href="/">' in body # the public Home entry
258
259
260def test_the_home_page_falls_back_rather_than_showing_a_blank_front_door(installed):
261 """A fresh install renders this page before anything has registered,
262 and a blank switchboard is a worse first impression than a stale one."""
263 object_records.delete_collection_record(
264 "nav_entries", "home", base_dir=installed["data"], actor="test")
265
266 body = page(installed, {"user_id": "alice"})
267 assert "<h2>Work</h2>" in body
268 assert 'href="/shell"' in body
269 assert 'href="/dashboard"' in body
270
271
272def test_the_home_page_escapes_what_the_registry_hands_it(installed):
273 add_entry(installed, "xss", label='<script>alert(1)</script>', blurb='" onmouseover=x')
274
275 body = page(installed, {"user_id": "alice"})
276 assert "<script>alert(1)</script>" not in body
277 assert "&lt;script&gt;alert(1)&lt;/script&gt;" in body
278
279
280# --- attention: the counts on the doors, and the band above them ----------------
281
282# A stored count is a code provider's number over everybody's rows, and with
283# no source row naming what it reads it reaches only an admin
284# (object_attention.provider_shown_to); the presentation tests below look as
285# one. What a member is shown is tested where the gate is
286# (tests/test_attention_declared.py) and here, once.
287OPERATOR = {"user_id": "root", "roles": ["admin"]}
288
289
290def add_count(installed, count_id, **fields):
291 row = {"id": count_id, "source_id": count_id, "label": count_id.title(),
292 "path": f"/{count_id}", "nav_id": "", "group": "Work",
293 "severity": "normal", "count": "1", "detail": "", "computed_at": "",
294 "error": ""}
295 row.update(fields)
296 object_records.create_collection_record(
297 "attention_counts", row, base_dir=installed["data"], actor="test")
298
299
300def test_a_door_with_a_queue_comes_back_carrying_its_number(installed):
301 """Half the value of a dashboard for none of the cost: the app list
302 people already open says how much is waiting behind each door."""
303 add_entry(installed, "invoices", group="Money", order="300")
304 add_count(installed, "invoices_overdue", label="Invoices past due",
305 nav_id="invoices", count="5", detail="oldest 45 days late",
306 severity="warning")
307
308 entries = {entry["id"]: entry for entry in
309 run(installed, "action_nav_entries", OPERATOR).result["entries"]}
310 assert entries["invoices"]["count"] == 5
311 assert entries["invoices"]["detail"] == "oldest 45 days late"
312 assert entries["invoices"]["severity"] == "warning"
313 assert "count" not in entries["home"] # a quiet door carries nothing
314
315
316def test_two_queues_on_one_door_are_summed_into_its_badge(installed):
317 """Found by a usability trial: a user with one owned and one assigned
318 item (two attention sources, one nav_id) saw a badge of 1, because the
319 louder queue won and the other was dropped. The door's number is the
320 total waiting behind it; the severity is the loudest; both rows stay in
321 the band."""
322 add_entry(installed, "tasks", group="Work", order="10")
323 add_count(installed, "tasks_owned", nav_id="tasks", count="1",
324 detail="1 owned", severity="normal")
325 add_count(installed, "tasks_assigned", nav_id="tasks", count="2",
326 detail="2 assigned", severity="warning")
327
328 result = run(installed, "action_nav_entries", OPERATOR).result
329 entry = {e["id"]: e for e in result["entries"]}["tasks"]
330 assert entry["count"] == 3
331 assert entry["severity"] == "warning"
332 assert entry["detail"] == "2 assigned; 1 owned"
333 assert sorted(row["count"] for row in result["attention"]) == [1, 2]
334
335
336def test_a_global_number_nobody_vouched_for_does_not_reach_a_member(installed):
337 """Until 2026-11 every signed-in user was shown every stored count. A
338 count whose source does not say what it reads is everybody's rows, and
339 a member may not read everybody's rows."""
340 add_entry(installed, "invoices", group="Money", order="300")
341 add_count(installed, "invoices_overdue", nav_id="invoices", count="5")
342
343 member = run(installed, "action_nav_entries", {"user_id": "alice"}).result
344 assert member["attention"] == []
345 assert all("count" not in entry for entry in member["entries"])
346
347
348def test_an_empty_queue_contributes_nothing_at_all(installed):
349 """Not a zero on the entry, not a row in the band: absent. A surface
350 handed zeros will eventually render them."""
351 add_entry(installed, "invoices", group="Money", order="300")
352 add_count(installed, "invoices_overdue", nav_id="invoices", count="0")
353
354 result = run(installed, "action_nav_entries", {"user_id": "alice"})
355 assert result.result["attention"] == []
356 assert all("count" not in entry for entry in result.result["entries"])
357
358
359def test_the_band_is_sorted_loudest_first(installed):
360 add_count(installed, "scheduler_failures", count="1", severity="urgent")
361 add_count(installed, "invoices_overdue", count="2", severity="warning")
362 add_count(installed, "scans_to_confirm", count="9", severity="normal")
363 add_count(installed, "time_to_approve", count="30", severity="normal")
364
365 result = run(installed, "action_nav_entries", OPERATOR)
366 assert [row["id"] for row in result.result["attention"]] == [
367 "scheduler_failures", "invoices_overdue", "time_to_approve",
368 "scans_to_confirm"]
369
370
371def test_a_visitor_is_never_told_what_needs_a_human(installed):
372 """These are internal work queues. How many receipts are unconfirmed
373 is a fact about how a business is running, not part of the public
374 web."""
375 add_count(installed, "scans_to_confirm", count="4")
376 assert run(installed, "action_nav_entries", {}).result["attention"] == []
377
378
379def test_a_count_on_an_operator_door_does_not_leak_to_a_member(installed):
380 add_entry(installed, "scheduler", surface="operator")
381 add_count(installed, "scheduler_failures", nav_id="scheduler", count="3",
382 severity="urgent")
383
384 member = run(installed, "action_nav_entries", {"user_id": "alice", "roles": ["user"]})
385 admin = run(installed, "action_nav_entries", {"user_id": "root", "roles": ["admin"]})
386 assert member.result["attention"] == []
387 assert [row["id"] for row in admin.result["attention"]] == ["scheduler_failures"]
388
389
390def test_a_queue_whose_package_ships_no_door_still_reaches_the_band(installed):
391 """app-intake is the real case: no page of its own, and the most
392 valuable queue on the box."""
393 add_count(installed, "scans_to_confirm", label="Receipts to confirm",
394 path="/scans?status=extracted", count="3", group="Money")
395
396 result = run(installed, "action_nav_entries", OPERATOR)
397 assert [row["label"] for row in result.result["attention"]] == [
398 "Receipts to confirm"]
399
400
401def test_a_hand_edited_count_that_will_not_parse_does_not_break_the_menu(installed):
402 records = installed["data"] / "collections" / "attention_counts" / "records.tsv"
403 records.write_text(
404 records.read_text()
405 + "typo\ttypo\tTypo\t/typo\t\tWork\tnormal\tloads\t\t\t\t\t\n")
406
407 result = run(installed, "action_nav_entries", {"user_id": "alice"})
408 assert result.ok is True
409 assert result.result["attention"] == []
410
411
412def test_the_home_page_shows_the_band_above_the_grid(installed):
413 add_entry(installed, "invoices", group="Money", order="300")
414 add_count(installed, "invoices_overdue", label="Invoices past due",
415 path="/invoices", nav_id="invoices", count="5",
416 detail="oldest 45 days late", severity="warning")
417
418 body = page(installed, OPERATOR)
419 assert "<h2>Needs you" in body
420 assert body.index("Needs you") < body.index("<h2>Money</h2>")
421 assert "Invoices past due" in body
422 assert "oldest 45 days late" in body
423 assert '<a class="tile" href="/invoices">' in body
424 assert 'class="badge warning">5<' in body # and again on the tile
425
426
427def test_the_home_page_has_no_band_at_all_when_nothing_needs_you(installed):
428 """Not '0 pending', not an empty panel with a heading: absent. A board
429 that says zero every day trains people to stop reading it."""
430 add_entry(installed, "invoices", group="Money", order="300")
431 add_count(installed, "invoices_overdue", nav_id="invoices", count="0")
432
433 body = page(installed, {"user_id": "alice"})
434 assert "Needs you" not in body
435 assert "<h2>Money</h2>" in body # the rest of the page is fine
436 assert "badge" not in body
437
438
439def test_the_home_page_escapes_what_the_rollup_hands_it(installed):
440 add_count(installed, "xss", label='<script>alert(1)</script>',
441 detail='" onmouseover=x', count="1")
442
443 body = page(installed, OPERATOR)
444 assert "<script>alert(1)</script>" not in body
445 assert "&lt;script&gt;alert(1)&lt;/script&gt;" in body
446
447
448def test_the_nav_script_folds_the_switcher_over_the_registry():
449 """site_nav's hardcoded APPS array is now a fallback for a failed
450 fetch, not the list -- and HIT_URL is deliberately still hand-kept,
451 because a search hit needs a permalink for a RECORD, which the
452 registry does not model."""
453 source = (PACKAGES_ROOT / "app-theme" / "objects" / "site" / "nav.py").read_text()
454
455 assert "/objects/action_nav_entries" in source
456 assert "const APPS" in source
457 assert "Fallback only" in source
458 assert "const HIT_URL" in source