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

0 downloads

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

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

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