1from pathlib import Path
2
3from markdown_it.token import Token
4from nixos_render_docs.manual import HTMLConverter, HTMLParameters
5from nixos_render_docs.md import Converter
6
7auto_id_prefix="TEST_PREFIX"
8def set_prefix(token: Token, ident: str) -> None:
9 token.attrs["id"] = f"{auto_id_prefix}-{ident}"
10
11
12def test_auto_id_prefix_simple() -> None:
13 md = HTMLConverter("1.0.0", HTMLParameters("", [], [], 2, 2, 2, Path("")), {})
14
15 src = f"""
16# title
17
18## subtitle
19 """
20 tokens = Converter()._parse(src)
21 md._handle_headings(tokens, on_heading=set_prefix)
22
23 assert [
24 {**token.attrs, "tag": token.tag}
25 for token in tokens
26 if token.type == "heading_open"
27 ] == [
28 {"id": "TEST_PREFIX-1", "tag": "h1"},
29 {"id": "TEST_PREFIX-1.1", "tag": "h2"}
30 ]
31
32
33def test_auto_id_prefix_repeated() -> None:
34 md = HTMLConverter("1.0.0", HTMLParameters("", [], [], 2, 2, 2, Path("")), {})
35
36 src = f"""
37# title
38
39## subtitle
40
41# title2
42
43## subtitle2
44 """
45 tokens = Converter()._parse(src)
46 md._handle_headings(tokens, on_heading=set_prefix)
47
48 assert [
49 {**token.attrs, "tag": token.tag}
50 for token in tokens
51 if token.type == "heading_open"
52 ] == [
53 {"id": "TEST_PREFIX-1", "tag": "h1"},
54 {"id": "TEST_PREFIX-1.1", "tag": "h2"},
55 {"id": "TEST_PREFIX-2", "tag": "h1"},
56 {"id": "TEST_PREFIX-2.1", "tag": "h2"},
57 ]
58
59def test_auto_id_prefix_maximum_nested() -> None:
60 md = HTMLConverter("1.0.0", HTMLParameters("", [], [], 2, 2, 2, Path("")), {})
61
62 src = f"""
63# h1
64
65## h2
66
67### h3
68
69#### h4
70
71##### h5
72
73###### h6
74
75## h2.2
76 """
77 tokens = Converter()._parse(src)
78 md._handle_headings(tokens, on_heading=set_prefix)
79
80 assert [
81 {**token.attrs, "tag": token.tag}
82 for token in tokens
83 if token.type == "heading_open"
84 ] == [
85 {"id": "TEST_PREFIX-1", "tag": "h1"},
86 {"id": "TEST_PREFIX-1.1", "tag": "h2"},
87 {"id": "TEST_PREFIX-1.1.1", "tag": "h3"},
88 {"id": "TEST_PREFIX-1.1.1.1", "tag": "h4"},
89 {"id": "TEST_PREFIX-1.1.1.1.1", "tag": "h5"},
90 {"id": "TEST_PREFIX-1.1.1.1.1.1", "tag": "h6"},
91 {"id": "TEST_PREFIX-1.2", "tag": "h2"},
92 ]