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_docs_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_docs_package.py · 14.0 KB · 338 lines
1"""Tests for packages/app-docs: the public documentation site at /docs and
2/docs/{slug}. A Rails-Guides-shaped guide site -- sidebar grouped by
3category, client-side search, per-page table of contents, prev/next paging
4-- built as bespoke page objects (not the view_render block system) on top
5of the shared /style theme and the ONE shared markdown renderer at
6/markdown. Content is seeded doc_pages records adapted from the internal
7docs/ tree; the whole surface is public and unauthenticated.
8
9Behavioral JS tests follow the repo's node-execution pattern (see
10tests/test_markdown_object.py): extract the real function source from the
11Python-embedded script string, run it under node with stubbed globals,
12assert on real output -- not just source-text greps.
13"""
14
15import csv
16import json
17import re
18import shutil
19import subprocess
20from pathlib import Path
21
22import pytest
23
24import object_packages
25
26pytestmark = pytest.mark.node # needs the `node` binary; `pytest -m node` selects these (scripts/release_gate.sh node)
27
28PACKAGES_ROOT = Path(__file__).resolve().parents[1] / "packages"
29APP_DOCS_DIR = PACKAGES_ROOT / "app-docs"
30
31NAV_SOURCE = (APP_DOCS_DIR / "objects" / "site" / "docs_nav.py").read_text()
32INDEX_SOURCE = (APP_DOCS_DIR / "objects" / "site" / "docs_index.py").read_text()
33DETAIL_SOURCE = (APP_DOCS_DIR / "objects" / "site" / "docs_detail.py").read_text()
34
35
36def _seed_rows(name):
37 with open(APP_DOCS_DIR / "seed" / f"{name}.tsv", newline="") as fh:
38 return list(csv.DictReader(fh, delimiter="\t"))
39
40
41def _node():
42 node = shutil.which("node")
43 if node is None:
44 pytest.skip("node not available")
45 return node
46
47
48# --- package shape -----------------------------------------------------------
49
50
51def test_manifest_ships_three_objects_schema_permissions_and_both_seeds():
52 package = object_packages.get_package("app-docs", root=PACKAGES_ROOT)
53 assert {o["id"] for o in package["objects"]} >= {
54 "site_docs_nav", "site_docs_index", "site_docs_detail",
55 }
56 assert {s["collection"] for s in package["schemas"]} >= {"doc_pages"}
57 assert {entry["collection"] for entry in package["seed"]} >= {
58 "site_routes", "doc_pages",
59 }
60
61
62def test_routes_seed_detail_and_index_with_articles_style_priorities():
63 rows = _seed_rows("site_routes")
64 by_id = {r["id"]: r for r in rows}
65 detail = by_id["route_docs_detail"]
66 index = by_id["route_docs_index"]
67 assert detail["pattern"] == "/docs/{slug}"
68 assert detail["object_id"] == "site_docs_detail"
69 assert index["pattern"] == "/docs"
70 assert index["object_id"] == "site_docs_index"
71 # Same convention as app-articles: the more specific pattern gets the
72 # lower (higher-precedence) priority number.
73 assert int(detail["priority"]) < int(index["priority"])
74
75
76def test_routes_seed_pins_the_script_objects_for_prefixed_hosts():
77 """/docs/{slug} matches on every host as a route record, but the two
78 scripts the page loads (/docs-nav, /markdown) were convention-only, so on
79 a site_hosts domain with its own prefix they resolved to {prefix}_docs_nav
80 and {prefix}_markdown, 404ed, and the page sat on "Loading..." forever.
81 Route rows make them resolve wherever the docs page itself does."""
82 by_id = {r["id"]: r for r in _seed_rows("site_routes")}
83 assert by_id["route_docs_nav"]["pattern"] == "/docs-nav"
84 assert by_id["route_docs_nav"]["object_id"] == "site_docs_nav"
85 assert by_id["route_docs_markdown"]["pattern"] == "/markdown"
86 assert by_id["route_docs_markdown"]["object_id"] == "site_markdown"
87
88
89def test_permissions_make_every_surface_public():
90 payload = json.loads((APP_DOCS_DIR / "permissions" / "rules.json").read_text())
91 rules = payload["rules"]
92 assert all(rule["principal"] == "public" for rule in rules)
93 read_rules = [r for r in rules if "read" in r["actions"]]
94 assert any(r.get("collection") == "doc_pages" for r in read_rules)
95 # A doc page is public unconditionally -- no row_filter gate like
96 # articles' is_public, because nothing non-public is ever seeded.
97 assert all("row_filter" not in r for r in read_rules)
98 executable = {r.get("object_id") for r in rules if "execute" in r["actions"]}
99 # All three page objects, including the shared nav script -- without
100 # site_docs_nav here the sidebar 403s for anonymous visitors and the
101 # whole site is broken for exactly the audience it exists for.
102 assert executable == {"site_docs_nav", "site_docs_index", "site_docs_detail"}
103
104
105def test_doc_pages_seed_is_nonempty_and_every_row_is_complete():
106 rows = _seed_rows("doc_pages")
107 assert len(rows) >= 30
108 slug_re = re.compile(r"^[a-z0-9][a-z0-9-]*$")
109 seen = set()
110 for row in rows:
111 assert slug_re.fullmatch(row["id"]), row["id"]
112 assert row["id"] not in seen
113 seen.add(row["id"])
114 assert row["title"].strip()
115 assert row["category"].strip()
116 assert int(row["nav_order"]) > 0
117 assert row["summary"].strip()
118 assert len(row["content"]) > 500, f"{row['id']} content suspiciously short"
119 # The page template renders the title itself -- content starting
120 # with an H1 would double the title on every page.
121 assert not row["content"].lstrip().startswith("# ")
122
123
124def test_seeded_cross_links_resolve_to_seeded_slugs_only():
125 rows = _seed_rows("doc_pages")
126 slugs = {row["id"] for row in rows}
127 link_re = re.compile(r"\]\(/docs/([A-Za-z0-9_-]+)")
128 for row in rows:
129 for slug in link_re.findall(row["content"]):
130 assert slug in slugs, f"{row['id']} links to unseeded /docs/{slug}"
131 # No internal-tree .md links should survive the seed build.
132 assert ".md)" not in row["content"], f"{row['id']} kept a raw .md link"
133
134
135def test_no_disallowed_org_names_leak_into_the_package():
136 banned = re.compile(r"\bq9\b|askrobots|\bwold\b", re.IGNORECASE)
137 for path in sorted(APP_DOCS_DIR.rglob("*")):
138 if "__pycache__" in path.parts:
139 continue # compiled bytes can match a name by chance
140 if path.is_file():
141 hits = banned.findall(path.read_text(errors="replace"))
142 assert not hits, f"{path} contains banned names: {hits}"
143
144
145def test_dry_run_is_safe(tmp_path):
146 object_root = tmp_path / "objects"
147 object_root.mkdir()
148 plan = object_packages.dry_run_package(
149 "app-docs",
150 root=PACKAGES_ROOT,
151 base_dir=tmp_path / "data",
152 object_roots=[object_root],
153 )
154 assert plan["safe_to_install"] is True
155 assert plan["warnings"] == []
156
157
158# --- page structure ----------------------------------------------------------
159
160
161def test_pages_are_public_chrome_not_the_signed_in_apps():
162 for source in (INDEX_SOURCE, DETAIL_SOURCE):
163 # The shared building blocks every themed page uses...
164 assert '<link rel="stylesheet" href="/style">' in source
165 assert '<script src="/markdown"></script>' in source
166 assert '<script src="/docs-nav"></script>' in source
167 # ...but never the internal signed-in shell's nav or a login nudge.
168 assert 'src="/nav"' not in source
169 assert "/login" not in source
170
171
172def test_detail_gates_the_slug_before_interpolating_into_script():
173 # `slug` is URL-derived and lands inside a <script> block via {slug!r};
174 # repr-escaping alone cannot stop a "</script>" payload from closing
175 # the tag, so the same regex gate view_render.py uses must run first.
176 assert "_SLUG_RE" in DETAIL_SOURCE
177 gate = DETAIL_SOURCE.index("_SLUG_RE.fullmatch(slug)")
178 interpolate = DETAIL_SOURCE.index("{slug!r}")
179 assert gate < interpolate
180 pattern = re.search(r'_SLUG_RE = re\.compile\(r"([^"]+)"\)', DETAIL_SOURCE)
181 compiled = re.compile(pattern.group(1))
182 assert not compiled.fullmatch("</script><script>alert(1)</script>")
183 assert not compiled.fullmatch("")
184 assert compiled.fullmatch("single-vm-deployment")
185
186
187def test_nav_manifest_fetch_is_cached_per_tab_not_per_navigation():
188 # Every /docs/{slug} click is a full page load; the manifest (all page
189 # bodies included) is a few hundred KB -- so it must come from
190 # sessionStorage after the first load, not refetch each navigation.
191 assert "sessionStorage.getItem" in NAV_SOURCE
192 assert "sessionStorage.setItem" in NAV_SOURCE
193 assert NAV_SOURCE.count("/collections/doc_pages/records") == 1
194
195
196# --- real JS behavior (node-executed) ---------------------------------------
197
198
199def _extract_js(source, marker):
200 """Extract a top-level `function name(...) {...}` from the embedded JS
201 by brace counting, starting at `marker`."""
202 start = source.index(marker)
203 depth = 0
204 for i in range(start, len(source)):
205 if source[i] == "{":
206 depth += 1
207 elif source[i] == "}":
208 depth -= 1
209 if depth == 0:
210 return source[start:i + 1]
211 raise AssertionError(f"unbalanced braces after {marker}")
212
213
214def test_sidebar_sorts_by_nav_order_and_groups_by_first_appearance(tmp_path):
215 node = _node()
216 sort_fn = _extract_js(NAV_SOURCE, "function sortManifest(")
217 group_fn = _extract_js(NAV_SOURCE, "function groupByCategory(")
218 probe = tmp_path / "probe.js"
219 probe.write_text(
220 sort_fn + "\n" + group_fn + "\n" + """
221const records = [
222 {id: "c", title: "C", category: "Two", nav_order: "300"},
223 {id: "a", title: "A", category: "One", nav_order: "100"},
224 {id: "d", title: "D", category: "One", nav_order: "110"},
225 {id: "b", title: "B", category: "Two", nav_order: "250"},
226 {id: "x", title: "X", category: "", nav_order: "junk"},
227];
228const sorted = sortManifest(records);
229const groups = groupByCategory(sorted);
230console.log(JSON.stringify({
231 order: sorted.map((r) => r.id),
232 groups: groups.map((g) => [g.category, g.items.map((i) => i.id)]),
233}));
234""")
235 out = subprocess.run([node, str(probe)], capture_output=True, text=True)
236 assert out.returncode == 0, out.stderr
237 result = json.loads(out.stdout)
238 # Numeric sort (not string sort -- "300" > "1000" as strings), with the
239 # unparseable nav_order sinking to the end.
240 assert result["order"] == ["a", "d", "b", "c", "x"]
241 # Groups keep first-appearance order over the sorted list; a blank
242 # category lands in "General".
243 assert result["groups"] == [
244 ["One", ["a", "d"]],
245 ["Two", ["b", "c"]],
246 ["General", ["x"]],
247 ]
248
249
250def test_toc_builder_assigns_ids_dedupes_and_indents_h3(tmp_path):
251 node = _node()
252 slug_fn = _extract_js(DETAIL_SOURCE, "function slugify(")
253 toc_fn = _extract_js(DETAIL_SOURCE, "function buildToc(")
254 probe = tmp_path / "probe.js"
255 probe.write_text("""
256const esc = (s) => String(s == null ? "" : s).replace(/[&<>"']/g,
257 (c) => ({"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"}[c]));
258""" + slug_fn + "\n" + toc_fn + "\n" + """
259global.document = {getElementById: () => null};
260function head(tag, text) {
261 return {tagName: tag.toUpperCase(), textContent: text, id: ""};
262}
263const heads = [head("h2", "Setup"), head("h3", "Setup"), head("h2", "Run & verify")];
264const container = {querySelectorAll: () => heads};
265const html = buildToc(container);
266console.log(JSON.stringify({ids: heads.map((h) => h.id), html: html}));
267""")
268 out = subprocess.run([node, str(probe)], capture_output=True, text=True)
269 assert out.returncode == 0, out.stderr
270 result = json.loads(out.stdout)
271 # Duplicate heading text gets a deduped id, punctuation slugifies away.
272 assert result["ids"] == ["setup", "setup-2", "run-verify"]
273 assert '#setup"' in result["html"]
274 assert '#setup-2"' in result["html"]
275 assert "doctocsub" in result["html"] # the h3 is indented
276
277
278def test_search_filter_hides_nonmatching_items_and_empty_groups(tmp_path):
279 node = _node()
280 wire_fn = _extract_js(NAV_SOURCE, "function wireSearch(")
281 probe = tmp_path / "probe.js"
282 probe.write_text(wire_fn + "\n" + """
283function item(haystack) {
284 return {
285 style: {display: ""},
286 getAttribute: (name) => (name === "data-search" ? haystack : null),
287 };
288}
289const one = item("quickstart from a fresh vm start here");
290const two = item("permissions model security");
291const groupOne = {style: {display: ""}, querySelectorAll: () => [one]};
292const groupTwo = {style: {display: ""}, querySelectorAll: () => [two]};
293let handler = null;
294const inputEl = {
295 value: "",
296 addEventListener: (evt, fn) => { handler = fn; },
297};
298const listEl = {
299 querySelectorAll: (sel) =>
300 (sel === ".navitem" ? [one, two] : [groupOne, groupTwo]),
301};
302wireSearch(inputEl, listEl);
303inputEl.value = "PERMISS";
304handler();
305const filtered = [one.style.display, two.style.display, groupOne.style.display, groupTwo.style.display];
306inputEl.value = "";
307handler();
308const restored = [one.style.display, two.style.display, groupOne.style.display, groupTwo.style.display];
309console.log(JSON.stringify({filtered, restored}));
310""")
311 out = subprocess.run([node, str(probe)], capture_output=True, text=True)
312 assert out.returncode == 0, out.stderr
313 result = json.loads(out.stdout)
314 # Case-insensitive match keeps only the permissions item and its group.
315 assert result["filtered"] == ["none", "", "none", ""]
316 # Clearing the box restores everything.
317 assert result["restored"] == ["", "", "", ""]
318
319
320def test_prev_next_pager_walks_the_manifest_sequence(tmp_path):
321 node = _node()
322 pager_fn = _extract_js(DETAIL_SOURCE, "function pagerHtml(")
323 probe = tmp_path / "probe.js"
324 probe.write_text("""
325const esc = (s) => String(s == null ? "" : s).replace(/[&<>"']/g,
326 (c) => ({"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"}[c]));
327""" + pager_fn + "\n" + """
328const middle = pagerHtml({id: "why", title: "Why"}, {id: "quickstart", title: "Quickstart"});
329const first = pagerHtml(null, {id: "quickstart", title: "Quickstart"});
330const last = pagerHtml({id: "why", title: "Why"}, null);
331console.log(JSON.stringify({middle, first, last}));
332""")
333 out = subprocess.run([node, str(probe)], capture_output=True, text=True)
334 assert out.returncode == 0, out.stderr
335 result = json.loads(out.stdout)
336 assert '/docs/why' in result["middle"] and '/docs/quickstart' in result["middle"]
337 assert '/docs/why' not in result["first"] and '/docs/quickstart' in result["first"]
338 assert '/docs/quickstart' not in result["last"] and '/docs/why' in result["last"]