Coverage for tests/test_variant_discovery.py: 100%
193 statements
« prev ^ index » next coverage.py v7.6.1, created at 2026-11-30 00:03 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2026-11-30 00:03 +0000
1from pathlib import Path 1ab
2from xml.etree import ElementTree 1ab
4import markdown 1ab
5import pytest 1ab
7from markdown_include_variants import IncludeVariantsExtension 1ab
10@pytest.fixture(params=["file", "folder", "nested_folder"]) 1ab
11def examples(request, tmp_path, monkeypatch): 1ab
12 monkeypatch.chdir(tmp_path) 1ab
14 def create(*names): 1ab
15 paths = {} 1AsBcEMFGNtguopmdikvCwDeHOIJPxhyqrnfjlz
16 for name in names: 1AsBcEMFGNtguopmdikvCwDeHOIJPxhyqrnfjlz
17 if request.param == "file": 1AsBcEMFGNtguopmdikvCwDeHOIJPxhyqrnfjlz
18 path = Path(f"{name}.py") 1AsBcEMFGNtguopmdikvCwDeHOIJPxhyqrnfjlz
19 elif request.param == "folder": 1AsBcEMFGNtguopmdikvCwDeHOIJPxhyqrnfjlz
20 path = Path(name) / "main.py" 1AsBcEMFGNtguopmdikvCwDeHOIJPxhyqrnfjlz
21 else:
22 path = Path(name) / "routers" / "items.py" 1AsBcEMFGNtguopmdikvCwDeHOIJPxhyqrnfjlz
23 path.parent.mkdir(parents=True, exist_ok=True) 1AsBcEMFGNtguopmdikvCwDeHOIJPxhyqrnfjlz
24 path.write_text( 1AsBcEMFGNtguopmdikvCwDeHOIJPxhyqrnfjlz
25 "".join(f'print("{name}: {line}")\n' for line in range(1, 7))
26 )
27 paths[name] = path 1AsBcEMFGNtguopmdikvCwDeHOIJPxhyqrnfjlz
28 return paths 1AsBcEMFGNtguopmdikvCwDeHOIJPxhyqrnfjlz
30 return create 1ab
33def render(path, config=""): 1ab
34 html = markdown.markdown( 1AsBcEMFGNKtguopmQdikvCwDeHOIJPLxhyqrnRfjlz
35 f"{{* {path} {config} *}}",
36 extensions=[
37 IncludeVariantsExtension(),
38 "mdx_include",
39 "pymdownx.superfences",
40 "pymdownx.highlight",
41 "pymdownx.blocks.tab",
42 "pymdownx.blocks.details",
43 "pymdownx.blocks.admonition",
44 ],
45 extension_configs={"pymdownx.blocks.tab": {"alternate_style": True}},
46 )
47 assert "////" not in html 1AsBcKtguopmQdikvCwDeLxhyqrnRfjlz
48 return ElementTree.fromstring(f"<root>{html}</root>") 1AsBcKtguopmQdikvCwDeLxhyqrnRfjlz
51def labels(root): 1ab
52 return ["".join(label.itertext()) for label in root.iter("label")] 1AsBcKtguopmQdikvCwDeLxhyqrnRfjlz
55def code_blocks(root): 1ab
56 return ["".join(code.itertext()) for code in root.findall(".//pre/code")] 1cKtguopmQdikveLxhyqrnRfjlz
59@pytest.mark.parametrize("name", ["example", "example_an"]) 1ab
60def test_single_unversioned_example(examples, name): 1ab
61 paths = examples(name) 1pr
62 root = render(paths[name]) 1pr
64 assert labels(root) == [] 1pr
65 assert root.findall(".//details") == [] 1pr
66 assert code_blocks(root) == [paths[name].read_text()] 1pr
69@pytest.mark.parametrize("preferred", ["example", "example_an"]) 1ab
70def test_legacy_unversioned_annotated_pair(examples, preferred): 1ab
71 paths = examples("example", "example_an") 1ce
72 root = render(paths[preferred]) 1ce
74 assert labels(root) == ["non-Annotated"] 1ce
75 assert code_blocks(root)[0] == paths[preferred].read_text() 1ce
76 details = root.findall(".//details") 1ce
77 assert len(details) == 1 1ce
78 assert details[0].findtext("summary") == "🤓 Other versions and variants" 1ce
79 assert "Python" not in "".join(root.itertext()) 1ce
80 if preferred == "example_an": 1ce
81 assert root[0].get("class") == "highlight" 1ce
82 assert "Prefer to use the Annotated version" in "".join(details[0].itertext()) 1ce
83 else:
84 assert labels(details[0]) == [] 1ce
85 assert code_blocks(details[0]) == [paths["example_an"].read_text()] 1ce
88@pytest.mark.parametrize("preferred", ["example", "example_non_an"]) 1ab
89def test_unversioned_non_annotated_pair(examples, preferred): 1ab
90 paths = examples("example", "example_non_an") 1df
91 root = render(paths[preferred]) 1df
93 assert labels(root) == ["non-Annotated"] 1df
94 assert code_blocks(root)[0] == paths[preferred].read_text() 1df
95 details = root.findall(".//details") 1df
96 assert len(details) == 1 1df
97 assert details[0].findtext("summary") == "🤓 Other versions and variants" 1df
98 assert "Python" not in "".join(root.itertext()) 1df
99 if preferred == "example": 1df
100 assert root[0].get("class") == "highlight" 1df
101 assert "Prefer to use the Annotated version" in "".join(details[0].itertext()) 1df
102 else:
103 assert labels(details[0]) == [] 1df
104 assert code_blocks(details[0]) == [paths["example"].read_text()] 1df
107def test_single_non_annotated_example_keeps_label(examples): 1ab
108 paths = examples("example_non_an") 1oq
109 root = render(paths["example_non_an"]) 1oq
111 assert labels(root) == ["non-Annotated"] 1oq
112 assert root.findall(".//details") == [] 1oq
113 assert code_blocks(root) == [paths["example_non_an"].read_text()] 1oq
116@pytest.mark.parametrize( 1ab
117 "name, title",
118 [
119 ("example_py312", "Python 3.12+"),
120 ("example_an_py312", "Python 3.12+"),
121 ("example_non_an_py312", "Python 3.12+ - non-Annotated"),
122 ],
123)
124def test_single_explicit_version_keeps_label(examples, name, title): 1ab
125 paths = examples(name) 1uy
126 root = render(paths[name], "ln[2:4] hl[3]") 1uy
128 assert labels(root) == [title, title] 1uy
129 assert code_blocks(root)[1] == paths[name].read_text() 1uy
132def test_version_order_and_preferred_file(examples): 1ab
133 paths = examples("example_py39", "example_py314", "example_py310", "example_py312") 1vz
134 root = render(paths["example_py310"]) 1vz
136 assert labels(root) == [ 1vz
137 "Python 3.10+",
138 "Python 3.14+",
139 "Python 3.12+",
140 "Python 3.9+",
141 ]
142 assert code_blocks(root) == [ 1vz
143 paths[name].read_text()
144 for name in ["example_py310", "example_py314", "example_py312", "example_py39"]
145 ]
148def test_legacy_incomplete_annotated_version_pairs(examples): 1ab
149 paths = examples("example_an_py312", "example_py311", "example_an_py311") 1BD
150 root = render(paths["example_an_py312"]) 1BD
152 assert labels(root) == [ 1BD
153 "Python 3.12+",
154 "Python 3.11+",
155 "Python 3.11+ - non-Annotated",
156 ]
157 assert ( 1BD
158 "".join(root.itertext()).count(
159 "Prefer to use the Annotated version if possible."
160 )
161 == 1
162 )
165def test_legacy_bare_version_without_annotated_counterpart(examples): 1ab
166 paths = examples("example_an_py312", "example_py311") 1sw
167 root = render(paths["example_an_py312"]) 1sw
169 assert labels(root) == ["Python 3.12+", "Python 3.11+"] 1sw
170 assert "non-Annotated" not in "".join(root.itertext()) 1sw
171 assert "Prefer to use" not in "".join(root.itertext()) 1sw
174def test_non_annotated_versions_follow_recommended_versions(examples): 1ab
175 paths = examples( 1tx
176 "example_non_an_py311",
177 "example_non_an_py312",
178 "example_py311",
179 "example_py312",
180 )
181 root = render(paths["example_non_an_py311"]) 1tx
183 assert labels(root) == [ 1tx
184 "Python 3.11+ - non-Annotated",
185 "Python 3.12+",
186 "Python 3.11+",
187 "Python 3.12+ - non-Annotated",
188 ]
189 assert code_blocks(root) == [ 1tx
190 paths[name].read_text()
191 for name in [
192 "example_non_an_py311",
193 "example_py312",
194 "example_py311",
195 "example_non_an_py312",
196 ]
197 ]
200def test_incomplete_non_annotated_version_pairs(examples): 1ab
201 paths = examples("example_py312", "example_non_an_py311") 1AC
202 root = render(paths["example_py312"]) 1AC
204 assert labels(root) == ["Python 3.12+", "Python 3.11+ - non-Annotated"] 1AC
205 assert "Prefer to use the Annotated version" in "".join(root.itertext()) 1AC
208@pytest.mark.parametrize("preferred", ["example", "example_an", "example_non_an"]) 1ab
209def test_mixed_annotation_conventions_are_rejected(examples, preferred): 1ab
210 paths = examples("example", "example_an", "example_non_an") 1FI
212 with pytest.raises(ValueError, match="Cannot mix legacy _an and _non_an") as exc: 1FI
213 render(paths[preferred]) 1FI
214 assert str(paths[preferred]) in str(exc.value) 1FI
215 assert "Migrate the whole example family" in str(exc.value) 1FI
218def test_mixed_annotation_conventions_across_versions_are_rejected(examples): 1ab
219 paths = examples("example_an_py311", "example_non_an_py312") 1MO
221 with pytest.raises(ValueError, match="Cannot mix legacy _an and _non_an"): 1MO
222 render(paths["example_an_py311"]) 1MO
225@pytest.mark.parametrize("preferred", ["example", "example_an_py312"]) 1ab
226def test_mixed_version_markers_are_rejected(examples, preferred): 1ab
227 paths = examples("example", "example_an_py312") 1GJ
229 with pytest.raises(ValueError, match="Cannot mix versioned and unversioned") as exc: 1GJ
230 render(paths[preferred]) 1GJ
231 assert str(paths[preferred]) in str(exc.value) 1GJ
232 assert "Add a Python version suffix to every variant" in str(exc.value) 1GJ
235def test_mixed_version_markers_with_non_annotated_are_rejected(examples): 1ab
236 paths = examples("example", "example_non_an_py312") 1NP
238 with pytest.raises(ValueError, match="Cannot mix versioned and unversioned"): 1NP
239 render(paths["example"]) 1NP
242def test_missing_preferred_file_does_not_select_an_alternative(examples): 1ab
243 paths = examples("example_an_py312") 1EH
244 missing = Path(str(paths["example_an_py312"]).replace("_an_py312", "_py312")) 1EH
246 with pytest.raises(FileNotFoundError, match="Included file does not exist") as exc: 1EH
247 render(missing) 1EH
248 assert str(missing) in str(exc.value) 1EH
251@pytest.mark.parametrize("name", ["example", "example_an"]) 1ab
252def test_unversioned_preview_highlights_and_filename_title(examples, name): 1ab
253 paths = examples(name) 1ij
254 root = render(paths[name], 'ln[2:4] hl[3] title["app/main.py"]') 1ij
256 assert labels(root) == [] 1ij
257 assert len(root.findall(".//details")) == 1 1ij
258 assert code_blocks(root) == [ 1ij
259 "# Code above omitted 👆\n\n"
260 + "".join(f'print("{name}: {line}")\n' for line in range(2, 5))
261 + "\n# Code below omitted 👇\n",
262 paths[name].read_text(),
263 ]
264 highlights = root.findall(".//*[@class='hll']") 1ij
265 assert ["".join(span.itertext()) for span in highlights] == [ 1ij
266 f'print("{name}: 3")\n',
267 f'print("{name}: 3")\n',
268 ]
269 titles = root.findall(".//*[@class='filename']") 1ij
270 assert [title.text for title in titles] == ["app/main.py", "app/main.py"] 1ij
273def test_unversioned_preview_only(examples): 1ab
274 paths = examples("example_an") 1kl
275 root = render(paths["example_an"], 'ln[0] title["main.py"]') 1kl
277 assert labels(root) == [] 1kl
278 assert len(root) == 1 1kl
279 assert root[0].tag == "details" 1kl
280 assert root[0].findtext("summary") == "👀 Full file preview" 1kl
281 assert code_blocks(root) == [paths["example_an"].read_text()] 1kl
284def test_recommended_preview_with_non_annotated_alternative(examples): 1ab
285 paths = examples("example", "example_non_an") 1gh
286 root = render(paths["example"], 'ln[2:4] hl[3] title["main.py"]') 1gh
288 assert labels(root) == ["non-Annotated"] 1gh
289 assert root[0].get("class") == "highlight" 1gh
290 preview, alternatives = root.findall(".//details") 1gh
291 assert labels(preview) == [] 1gh
292 assert code_blocks(preview) == [paths["example"].read_text()] 1gh
293 assert code_blocks(alternatives) == [paths["example_non_an"].read_text()] 1gh
294 highlights = root.findall(".//*[@class='hll']") 1gh
295 assert ["".join(span.itertext()) for span in highlights] == [ 1gh
296 'print("example: 3")\n',
297 'print("example: 3")\n',
298 ]
299 assert [title.text for title in root.findall(".//*[@class='filename']")] == [ 1gh
300 "main.py",
301 "main.py",
302 "main.py",
303 ]
306def test_unrelated_example_can_use_legacy_annotation_convention(examples): 1ab
307 paths = examples("example", "example_non_an", "other", "other_an") 1mn
309 for name in ["example", "other_an"]: 1mn
310 root = render(paths[name]) 1mn
311 assert labels(root) == ["non-Annotated"] 1mn
312 assert code_blocks(root)[0] == paths[name].read_text() 1mn
313 assert len(code_blocks(root)) == 2 1mn
316def test_unrelated_files_and_directories_are_not_variants(tmp_path, monkeypatch): 1ab
317 monkeypatch.chdir(tmp_path) 1QR
318 Path("example.py").write_text("pass\n") 1QR
319 Path("example_extra.py").write_text("raise RuntimeError\n") 1QR
320 Path("example_py312.txt").write_text("not Python\n") 1QR
321 Path("example_py313.py").mkdir() 1QR
323 root = render("example.py") 1QR
325 assert labels(root) == [] 1QR
326 assert code_blocks(root) == ["pass\n"] 1QR
329@pytest.mark.parametrize( 1ab
330 "directories", [("app_py312", "app_non_an_py312"), ("app_an_py312", "app_py312")]
331)
332def test_nested_directory_variants_with_absolute_path(tmp_path, directories): 1ab
333 paths = [] 1KL
334 for directory in directories: 1KL
335 path = tmp_path / directory / "routers" / "items.py" 1KL
336 path.parent.mkdir(parents=True) 1KL
337 path.write_text(f'print("{directory}")\n') 1KL
338 paths.append(path) 1KL
339 # A sibling package without the requested relative file is not an alternative.
340 other = tmp_path / "app_py311" / "routers" / "other.py" 1KL
341 other.parent.mkdir(parents=True) 1KL
342 other.write_text("pass\n") 1KL
344 root = render(paths[0]) 1KL
346 assert labels(root) == [ 1KL
347 "Python 3.12+",
348 "Python 3.12+ - non-Annotated",
349 ]
350 assert code_blocks(root) == [path.read_text() for path in paths] 1KL