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_markdown_object.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_markdown_object.py · 7.2 KB · 184 lines
1"""Tests for the shared markdown renderer (packages/app-theme/objects/site/markdown.py),
2served at /markdown as window.dbbasicMarkdown -- the one place markdown
3rendering lives, per that file's own docstring. Behavioral: executes the
4real function under node against realistic input, not a source-text match.
5"""
6
7import ast
8import json
9import shutil
10import subprocess
11from pathlib import Path
12
13import pytest
14
15pytestmark = pytest.mark.node # needs the `node` binary; `pytest -m node` selects these (scripts/release_gate.sh node)
16
17MARKDOWN_PATH = (
18 Path(__file__).resolve().parents[1]
19 / "packages" / "app-theme" / "objects" / "site" / "markdown.py"
20)
21
22
23def _markdown_js():
24 tree = ast.parse(MARKDOWN_PATH.read_text())
25 for node in ast.walk(tree):
26 if isinstance(node, ast.Assign) and any(
27 getattr(t, "id", None) == "_JS" for t in node.targets
28 ):
29 return ast.literal_eval(node.value)
30 raise AssertionError("_JS not found in markdown.py")
31
32
33def _render(*texts, tmp_path):
34 node = shutil.which("node")
35 if not node:
36 pytest.skip("node not available")
37 probe = (
38 "global.window = {};\n"
39 + _markdown_js()
40 + "\nconsole.log(JSON.stringify("
41 + json.dumps([{"text": t} for t in texts])
42 + ".map(o => window.dbbasicMarkdown(o.text))));\n"
43 )
44 probe_path = tmp_path / "markdown_probe.js"
45 probe_path.write_text(probe)
46 result = subprocess.run([node, str(probe_path)], capture_output=True, text=True)
47 assert result.returncode == 0, f"node probe failed:\n{result.stderr}"
48 return json.loads(result.stdout)
49
50
51def test_headings_render_as_real_heading_tags(tmp_path):
52 [html] = _render("# Title\n\n## Sub", tmp_path=tmp_path)
53 assert html == "<h1>Title</h1><h2>Sub</h2>"
54
55
56def test_inline_bold_italic_code_and_autolink(tmp_path):
57 [html] = _render(
58 "Some **bold** and *italic* and `code` and https://example.com/page here.",
59 tmp_path=tmp_path,
60 )
61 assert "<strong>bold</strong>" in html
62 assert "<em>italic</em>" in html
63 assert "<code>code</code>" in html
64 assert '<a href="https://example.com/page" target="_blank" rel="noopener">https://example.com/page</a>' in html
65
66
67def test_unordered_and_ordered_lists(tmp_path):
68 [ul] = _render("- one\n- two\n- three", tmp_path=tmp_path)
69 assert ul == "<ul><li>one</li><li>two</li><li>three</li></ul>"
70 [ol] = _render("1. first\n2. second", tmp_path=tmp_path)
71 assert ol == "<ol><li>first</li><li>second</li></ol>"
72
73
74def test_fenced_code_block_preserves_language_and_does_not_apply_inline_markdown(tmp_path):
75 [html] = _render("```js\nconst x = **not bold**;\n```", tmp_path=tmp_path)
76 assert html == '<pre><code class="language-js">const x = **not bold**;</code></pre>'
77
78
79def test_blockquote_joins_lines(tmp_path):
80 [html] = _render("> line one\n> line two", tmp_path=tmp_path)
81 assert html == "<blockquote>line one line two</blockquote>"
82
83
84def test_horizontal_rule(tmp_path):
85 [html] = _render("above\n\n---\n\nbelow", tmp_path=tmp_path)
86 assert "<hr>" in html
87 assert "<p>above</p>" in html
88 assert "<p>below</p>" in html
89
90
91def test_gfm_table(tmp_path):
92 [html] = _render("| A | B |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |", tmp_path=tmp_path)
93 assert html == (
94 "<table><thead><tr><th>A</th><th>B</th></tr></thead>"
95 "<tbody><tr><td>1</td><td>2</td></tr><tr><td>3</td><td>4</td></tr></tbody></table>"
96 )
97 # Never a doubled close tag -- a real bug caught while writing this.
98 assert html.count("</table>") == 1
99
100
101def test_paragraphs_separated_by_blank_lines(tmp_path):
102 [html] = _render("First paragraph.\n\nSecond paragraph.", tmp_path=tmp_path)
103 assert html == "<p>First paragraph.</p><p>Second paragraph.</p>"
104
105
106def test_raw_html_is_escaped_before_any_markdown_parsing(tmp_path):
107 """The whole point: untrusted text (an AI reply, a user note, a
108 published article) must never inject a live tag, no matter how it's
109 combined with real markdown syntax on adjacent lines."""
110 [html] = _render("<script>alert(1)</script>\n\n# **bold** header", tmp_path=tmp_path)
111 assert "<script>" not in html
112 assert "&lt;script&gt;alert(1)&lt;/script&gt;" in html
113 assert "<h1><strong>bold</strong> header</h1>" in html
114
115
116def test_empty_and_none_input_does_not_throw(tmp_path):
117 results = _render("", tmp_path=tmp_path)
118 assert results == [""]
119
120 node = shutil.which("node")
121 if not node:
122 pytest.skip("node not available")
123 probe = (
124 "global.window = {};\n" + _markdown_js()
125 + "\nconsole.log(JSON.stringify([window.dbbasicMarkdown(null), window.dbbasicMarkdown(undefined)]));\n"
126 )
127 probe_path = tmp_path / "markdown_null_probe.js"
128 probe_path.write_text(probe)
129 result = subprocess.run([node, str(probe_path)], capture_output=True, text=True)
130 assert result.returncode == 0, f"node probe failed:\n{result.stderr}"
131 assert json.loads(result.stdout) == ["", ""]
132
133
134def test_bracket_links_render_with_href_allowlist(tmp_path):
135 [internal, external, anchor, mail, hostile] = _render(
136 "See the [deployment guide](/docs/single-vm-deployment) for more.",
137 "Read [the spec](https://example.com/spec).",
138 "Jump to [setup](#setup).",
139 "Mail [us](mailto:hi@example.com).",
140 "Click [here](javascript:alert(1)) now.",
141 tmp_path=tmp_path,
142 )
143 # Relative links stay in-tab; external links open in a new one.
144 assert '<a href="/docs/single-vm-deployment">deployment guide</a>' in internal
145 assert "target" not in internal
146 assert '<a href="https://example.com/spec" target="_blank" rel="noopener">the spec</a>' in external
147 assert '<a href="#setup">setup</a>' in anchor
148 assert '<a href="mailto:hi@example.com">us</a>' in mail
149 # A javascript: href never becomes a link -- the literal text survives,
150 # escaped, exactly as written.
151 assert "<a" not in hostile
152 assert "[here](javascript:alert(1))" in hostile
153
154
155def test_bracket_link_href_is_not_double_linked_by_the_autolink_pass(tmp_path):
156 [html] = _render("A [labeled link](https://example.com/x) in prose.", tmp_path=tmp_path)
157 # Exactly one anchor: the bare-URL pass must not wrap the href that the
158 # bracket-link pass already put inside href="...".
159 assert html.count("<a ") == 1
160 assert html.count("</a>") == 1
161 assert ">labeled link</a>" in html
162
163
164def test_hard_wrapped_list_items_rejoin_their_bullet(tmp_path):
165 [html] = _render(
166 "- A small VM (a $5 droplet is plenty) running Debian 12 or Ubuntu\n"
167 " 22.04+, with root or `sudo`.\n"
168 "- Second bullet.",
169 tmp_path=tmp_path,
170 )
171 # One list, two items -- the wrapped line rejoined the first bullet
172 # instead of escaping into a stray paragraph.
173 assert html.count("<li>") == 2
174 assert "<p>" not in html
175 assert "Ubuntu 22.04+, with root or <code>sudo</code>." in html
176
177
178def test_indented_nested_bullet_stays_a_bullet_not_a_continuation(tmp_path):
179 [html] = _render("- parent\n - nested\n- sibling", tmp_path=tmp_path)
180 # The documented wrong-but-lossless behavior: a nested marker becomes
181 # its own top-level bullet; it must never be glued into the parent as
182 # literal "- nested" text.
183 assert html.count("<li>") == 3
184 assert "parent -" not in html