Debian Codegraph @

tests/test_generate_html_docs.py

raw symbols SCIP
1 """Tests for HTML documentation generation."""
2
3 import tempfile
4 from pathlib import Path
5 from typing import Annotated
6
7 from cyclopts import App, Parameter
8
9
10 def test_generate_html_docs_simple_app():
11 """Test basic HTML documentation generation for a simple app."""
12 app = App(name="myapp", help="A simple CLI application")
13
14 @app.default
15 def main(name: str, verbose: bool = False):
16 """Main command.
17
18 Parameters
19 ----------
20 name : str
21 Your name.
22 verbose : bool
23 Enable verbose output.
24 """
25 pass
26
27 docs = app.generate_docs(output_format="html")
28
29 # Check HTML structure
30 assert "<!DOCTYPE html>" in docs
31 assert "<html" in docs
32 assert "<head>" in docs
33 assert "<title>myapp - CLI Documentation</title>" in docs
34 assert "<style>" in docs # CSS should be embedded
35 assert '<body id="top">' in docs
36
37 # Check content is present
38 assert "myapp" in docs
39 assert "A simple CLI application" in docs
40 assert "Usage" in docs
41
42 # Check parameters are documented
43 assert "Your name" in docs
44 assert "Enable verbose output" in docs
45
46
47 def test_generate_html_docs_with_commands():
48 """Test HTML documentation generation with subcommands."""
49 app = App(name="myapp", help="CLI with commands")
50
51 @app.command
52 def serve(port: int = 8000):
53 """Start the server.
54
55 Parameters
56 ----------
57 port : int
58 Port number.
59 """
60 pass
61
62 @app.command
63 def build(output: str = "./dist"):
64 """Build the project.
65
66 Parameters
67 ----------
68 output : str
69 Output directory.
70 """
71 pass
72
73 docs = app.generate_docs(output_format="html")
74
75 # Check main content
76 assert "myapp" in docs
77 assert "CLI with commands" in docs
78
79 # Check commands are documented
80 assert "serve" in docs
81 assert "build" in docs
82 assert "Start the server" in docs
83 assert "Build the project" in docs
84 assert "Port number" in docs
85 assert "Output directory" in docs
86
87
88 def test_generate_html_docs_with_choices():
89 """Test HTML documentation with parameter choices."""
90 from enum import Enum
91
92 app = App(name="myapp")
93
94 class Color(Enum):
95 RED = "red"
96 GREEN = "green"
97 BLUE = "blue"
98
99 @app.default
100 def main(color: Color = Color.RED):
101 """Choose a color."""
102 pass
103
104 docs = app.generate_docs(output_format="html")
105
106 # Should show available choices in HTML
107 assert "choices:" in docs
108 assert "<code>red</code>" in docs
109 assert "<code>green</code>" in docs
110 assert "<code>blue</code>" in docs
111
112
113 def test_generate_html_docs_write_to_file():
114 """Test writing HTML documentation to a file."""
115 app = App(name="myapp", help="Test app")
116
117 @app.default
118 def main():
119 """Main command."""
120 pass
121
122 with tempfile.TemporaryDirectory() as tmpdir:
123 output_path = Path(tmpdir) / "docs" / "cli.html"
124
125 # Generate HTML docs
126 docs = app.generate_docs(output_format="html")
127
128 # Write to file manually
129 output_path.parent.mkdir(parents=True, exist_ok=True)
130 output_path.write_text(docs)
131
132 # Check file was created
133 assert output_path.exists()
134 content = output_path.read_text()
135
136 # Should be complete HTML document
137 assert "<!DOCTYPE html>" in content
138 assert "<html" in content
139 assert '<h1 class="app-title">myapp</h1>' in content
140
141 # Content should match what we wrote
142 assert docs == content
143
144
145 def test_generate_html_docs_format_explicit():
146 """Test explicitly generating HTML format."""
147 app = App(name="myapp", help="Test app")
148
149 # Test explicitly specifying HTML format
150 docs_html = app.generate_docs(output_format="html")
151 assert "<!DOCTYPE html>" in docs_html
152 assert "<html" in docs_html
153 assert '<h1 class="app-title">myapp</h1>' in docs_html
154
155
156 def test_generate_html_docs_with_meta_app():
157 """Test HTML documentation generation with meta app."""
158 app = App(name="myapp", help="Main application")
159
160 @app.default
161 def main(input_file: str):
162 """Process a file.
163
164 Parameters
165 ----------
166 input_file : str
167 Input file path.
168 """
169 pass
170
171 @app.meta.default
172 def meta(
173 verbose: bool = False,
174 config: Annotated[str | None, Parameter(help="Config file")] = None,
175 ):
176 """Meta app for global options.
177
178 Parameters
179 ----------
180 verbose : bool
181 Enable verbose output.
182 config : str
183 Configuration file path.
184 """
185 pass
186
187 docs = app.generate_docs(output_format="html")
188
189 # Check parameters are included
190 assert "input" in docs.lower()
191 assert "Input file path" in docs
192 assert "verbose" in docs.lower()
193 assert "Enable verbose output" in docs
194 assert "config" in docs.lower()
195 assert "Config file" in docs
196
197
198 def test_generate_html_docs_html_escaping():
199 """Test that special characters are properly escaped in HTML."""
200 app = App(name="myapp", help='Test <script> & "quotes"')
201
202 @app.command
203 def test():
204 """Command with <b>HTML</b> & special chars."""
205 pass
206
207 docs = app.generate_docs(output_format="html")
208
209 # Check that special characters are escaped
210 assert "&lt;script&gt;" in docs
211 assert "&amp;" in docs
212 assert "&quot;quotes&quot;" in docs
213 assert "&lt;b&gt;HTML&lt;/b&gt;" in docs
214
215 # Should not contain unescaped HTML
216 assert "<script>" not in docs
217 assert "<b>HTML</b>" not in docs
218
219
220 def test_generate_html_docs_css_included():
221 """Test that CSS styles are included in the HTML output."""
222 app = App(name="myapp", help="Test app")
223
224 docs = app.generate_docs(output_format="html")
225
226 # Check that CSS is included
227 assert "<style>" in docs
228 assert "body {" in docs # Basic CSS present
229
230 # Check for responsive design
231 assert "@media" in docs
232
233 # Check for dark mode support
234 assert "prefers-color-scheme: dark" in docs
235
236
237 def test_generate_html_docs_standalone_false():
238 """Test generating non-standalone HTML (no <html> wrapper)."""
239 from cyclopts.docs.html import generate_html_docs
240
241 app = App(name="myapp", help="Test app")
242
243 @app.default
244 def main():
245 """Main command."""
246 pass
247
248 # Generate non-standalone HTML
249 docs = generate_html_docs(app, standalone=False)
250
251 # Should not have HTML document wrapper
252 assert "<!DOCTYPE html>" not in docs
253 assert "<html" not in docs
254 assert "<head>" not in docs
255 assert "<body>" not in docs
256
257 # Should still have content
258 assert '<div class="cli-documentation">' in docs
259 assert '<h1 class="app-title">myapp</h1>' in docs
260
261
262 def test_generate_html_docs_invalid_format():
263 """Test that invalid output format raises ValueError."""
264 import pytest
265
266 app = App(name="myapp", help="Test app")
267
268 with pytest.raises(ValueError, match='Unsupported format "pdf"'):
269 app.generate_docs(output_format="pdf") # type: ignore[arg-type]
270
271 with pytest.raises(ValueError, match='Unsupported format "latex"'):
272 app.generate_docs(output_format="latex") # type: ignore[arg-type]
273
274
275 def test_generate_html_docs_flatten_commands():
276 """Test flatten_commands option for HTML documentation."""
277 app = App(name="myapp", help="Main app")
278
279 sub1 = App(name="sub1", help="First subcommand")
280
281 @sub1.command
282 def nested1():
283 """Nested command 1."""
284 pass
285
286 @sub1.command
287 def nested2():
288 """Nested command 2."""
289 pass
290
291 sub2 = App(name="sub2", help="Second subcommand")
292
293 @sub2.command
294 def nested3():
295 """Nested command 3."""
296 pass
297
298 app.command(sub1)
299 app.command(sub2)
300
301 # Without flatten_commands - hierarchical headings
302 docs_hierarchical = app.generate_docs(output_format="html", flatten_commands=False)
303
304 # Main app should be h1
305 assert '<h1 class="app-title">myapp</h1>' in docs_hierarchical
306 # Subcommands should be h2
307 assert '<h2 id="myapp-sub1" class="command-title">' in docs_hierarchical
308 assert '<h2 id="myapp-sub2" class="command-title">' in docs_hierarchical
309 # Nested commands should be h3
310 assert '<h3 id="myapp-sub1-nested1" class="command-title">' in docs_hierarchical
311 assert '<h3 id="myapp-sub1-nested2" class="command-title">' in docs_hierarchical
312 assert '<h3 id="myapp-sub2-nested3" class="command-title">' in docs_hierarchical
313
314 # With flatten_commands - all at same level
315 docs_flat = app.generate_docs(output_format="html", flatten_commands=True)
316
317 # Main app should be h1
318 assert '<h1 class="app-title">myapp</h1>' in docs_flat
319 # Subcommands should be h1 (flattened)
320 assert '<h1 id="myapp-sub1" class="command-title">' in docs_flat
321 assert '<h1 id="myapp-sub2" class="command-title">' in docs_flat
322 # Nested commands should also be h1 (flattened)
323 assert '<h1 id="myapp-sub1-nested1" class="command-title">' in docs_flat
324 assert '<h1 id="myapp-sub1-nested2" class="command-title">' in docs_flat
325 assert '<h1 id="myapp-sub2-nested3" class="command-title">' in docs_flat
326 # Should NOT have h2 or h3 command headings
327 assert '<h2 id="myapp-sub' not in docs_flat
328 assert '<h3 id="myapp-sub' not in docs_flat
329
330
331 def test_generate_html_docs_usage_name_overrides_root_usage():
332 """usage_name replaces the app name in the root Usage: line (HTML)."""
333 app = App(name="cli", help="A CLI")
334
335 @app.default
336 def main(name: str = "world"):
337 """Greet.
338
339 Parameters
340 ----------
341 name : str
342 Name.
343 """
344 pass
345
346 actual = app.generate_docs(output_format="html", usage_name="uv run cli")
347 assert "uv run cli" in actual
348
349
350 def test_generate_html_docs_usage_name_overrides_subcommand_usage():
351 """usage_name prefixes every subcommand's Usage: line in HTML output."""
352 app = App(name="cli", help="A CLI")
353
354 @app.command
355 def serve(port: int = 8000):
356 """Start server.
357
358 Parameters
359 ----------
360 port : int
361 Port.
362 """
363 pass
364
365 actual = app.generate_docs(output_format="html", usage_name="uv run cli")
366 import re
367
368 usage_blocks = re.findall(r'<pre class="usage">([^<]+)</pre>', actual)
369 assert usage_blocks, "expected at least one <pre class='usage'> block"
370 for block in usage_blocks:
371 assert block.strip().startswith("$ uv run cli"), f"usage block: {block!r}"
372
373 # Section anchors still use the plain app name
374 assert 'id="cli-serve"' in actual
375
376
377 def test_generate_html_docs_usage_name_empty_drops_root_in_subcommand_usage():
378 """usage_name='' drops the root token in subcommand Usage lines, with no stray whitespace."""
379 app = App(name="cli", help="A CLI")
380
381 @app.command
382 def serve(port: int = 8000):
383 """Start server.
384
385 Parameters
386 ----------
387 port : int
388 Port.
389 """
390 pass
391
392 actual = app.generate_docs(output_format="html", usage_name="")
393 import re
394
395 usage_blocks = re.findall(r'<pre class="usage">([^<]+)</pre>', actual)
396 assert usage_blocks, "expected at least one <pre class='usage'> block"
397 subcommand_blocks = [b for b in usage_blocks if "serve" in b]
398 assert subcommand_blocks, "expected a subcommand Usage block"
399 for block in subcommand_blocks:
400 assert " " not in block, f"double space in usage block: {block!r}"
401 assert not block.startswith(" "), f"leading space in usage block: {block!r}"
402 assert "cli serve" not in block, f"root name leaked into usage block: {block!r}"
403 assert "serve" in block
404
405
406 def test_generate_html_docs_usage_name_none_is_default_behavior():
407 """Default (None) preserves existing HTML output."""
408 app = App(name="cli", help="A CLI")
409
410 @app.default
411 def main():
412 """Entry."""
413 pass
414
415 assert app.generate_docs(output_format="html") == app.generate_docs(output_format="html", usage_name=None)