Debian Codegraph @

tests/test_generate_rst_docs.py

raw symbols SCIP
1 """Tests for RST documentation generation."""
2
3 from typing import Literal
4
5 from cyclopts import App
6
7
8 def test_generate_rst_docs_simple_app():
9 """Test basic RST documentation generation for a simple app."""
10 app = App(name="myapp", help="A simple CLI application")
11
12 @app.default
13 def main(name: str, verbose: bool = False):
14 """Main command.
15
16 Parameters
17 ----------
18 name : str
19 Your name.
20 verbose : bool
21 Enable verbose output.
22 """
23 pass
24
25 docs = app.generate_docs(output_format="rst")
26
27 assert "=====\nmyapp\n=====" in docs # Level 1 heading with matching markers
28 assert "myapp" in docs
29 assert "A simple CLI application" in docs
30
31 assert "myapp NAME" in docs # Usage without "Usage:" prefix
32 assert "::" in docs # Literal block marker
33 assert "myapp" in docs
34
35 assert "``NAME, --name``" in docs or "name, --name" in docs.lower()
36 assert "Your name" in docs
37 assert "``VERBOSE, --verbose" in docs or "verbose, --verbose" in docs.lower()
38 assert "Enable verbose output" in docs
39
40
41 def test_generate_rst_docs_with_commands():
42 """Test RST documentation generation with subcommands."""
43 app = App(name="myapp", help="CLI with commands")
44
45 @app.command
46 def serve(port: int = 8000):
47 """Start the server.
48
49 Parameters
50 ----------
51 port : int
52 Port number.
53 """
54 pass
55
56 @app.command
57 def build(output: str = "./dist"):
58 """Build the project.
59
60 Parameters
61 ----------
62 output : str
63 Output directory.
64 """
65 pass
66
67 docs = app.generate_docs(output_format="rst")
68
69 # Check main structure - heading markers match title length
70 assert "=====\nmyapp\n=====" in docs # Level 1 heading
71 assert "myapp" in docs
72 assert "CLI with commands" in docs
73
74 # Check commands are documented as sections (not in a list)
75 assert "myapp serve" in docs
76 assert "myapp build" in docs
77 assert "Start the server" in docs
78 assert "Build the project" in docs
79
80
81 def test_generate_rst_docs_recursive():
82 """Test recursive RST documentation generation."""
83 app = App(name="myapp", help="Main app")
84
85 sub = App(name="db", help="Database operations")
86
87 @sub.command
88 def migrate(dry_run: bool = False):
89 """Run database migrations.
90
91 Parameters
92 ----------
93 dry_run : bool
94 Simulate migrations without applying.
95 """
96 pass
97
98 app.command(sub)
99
100 docs = app.generate_docs(output_format="rst", recursive=True)
101
102 # Check main app - heading markers match title length
103 assert "=====\nmyapp\n=====" in docs
104 assert "myapp" in docs
105
106 # Check subcommand is documented as a section
107 assert "myapp db" in docs
108 assert "Database operations" in docs
109
110 # Check nested command
111 assert "migrate" in docs
112 assert "Run database migrations" in docs
113
114
115 def test_generate_rst_docs_with_options():
116 """Test RST documentation with various parameter types."""
117 app = App(name="myapp", help="App with options")
118
119 @app.default
120 def main(
121 name: str,
122 count: int = 1,
123 verbose: bool = False,
124 output: str | None = None,
125 choice: Literal["a", "b", "c"] = "a",
126 ):
127 """Main command with various options.
128
129 Parameters
130 ----------
131 name : str
132 User name.
133 count : int
134 Number of iterations.
135 verbose : bool
136 Enable verbose mode.
137 output : Optional[str]
138 Output file path.
139 choice : str
140 Selection choice.
141 """
142 pass
143
144 docs = app.generate_docs(output_format="rst")
145
146 # Check parameters
147 assert "User name" in docs
148 assert "Number of iterations" in docs
149 assert "Enable verbose mode" in docs
150 assert "Output file path" in docs
151 assert "Selection choice" in docs
152
153 # Check defaults and choices
154 assert "Default:" in docs
155 assert "Choices:" in docs or "choices:" in docs.lower()
156
157
158 def test_generate_rst_docs_heading_levels():
159 """Test RST documentation with different heading levels."""
160 app = App(name="myapp", help="Test app")
161
162 @app.command
163 def cmd():
164 """A command."""
165 pass
166
167 # Test with different heading levels
168 docs1 = app.generate_docs(output_format="rst", heading_level=1)
169 assert "=====\nmyapp\n=====" in docs1 # Level 1 uses = (matching title length)
170
171 docs2 = app.generate_docs(output_format="rst", heading_level=2)
172 assert "myapp\n-----" in docs2 # Level 2 uses - (no overline)
173 assert "=====" not in docs2 # Should not have level 1 markers
174
175 docs3 = app.generate_docs(output_format="rst", heading_level=3)
176 assert "myapp\n^^^^^" in docs3 # Level 3 uses ^
177
178
179 def test_generate_rst_docs_hidden_commands():
180 """Test RST documentation with hidden commands."""
181 app = App(name="myapp", help="App with hidden commands")
182
183 @app.command
184 def visible():
185 """Visible command."""
186 pass
187
188 @app.command(show=False)
189 def hidden():
190 """Hidden command."""
191 pass
192
193 # Without include_hidden
194 docs = app.generate_docs(output_format="rst", include_hidden=False)
195 assert "visible" in docs
196 # Check that the hidden command is not documented (not in Commands section)
197 assert "myapp hidden" not in docs # Hidden command should not appear as a section
198
199 # With include_hidden
200 docs_with_hidden = app.generate_docs(output_format="rst", include_hidden=True)
201 assert "visible" in docs_with_hidden
202 assert "myapp hidden" in docs_with_hidden # Hidden command appears as subcommand section
203 assert "Hidden command." in docs_with_hidden # And its docstring is included
204
205
206 def test_generate_rst_docs_special_characters():
207 """Test RST documentation handles special characters properly."""
208 app = App(name="my-app", help="App with special chars & symbols")
209
210 @app.command
211 def test_cmd(value: str = "default\\value"):
212 """Command with backslash in default.
213
214 Parameters
215 ----------
216 value : str
217 Value with special chars.
218 """
219 pass
220
221 docs = app.generate_docs(output_format="rst")
222
223 # Should handle special characters
224 assert "my-app" in docs
225 assert "special chars" in docs
226 # Backslashes should be escaped in RST
227 assert "default\\\\value" in docs or "default\\value" in docs
228
229
230 def test_generate_rst_docs_flatten_commands():
231 """Test flatten_commands option for RST documentation."""
232 app = App(name="myapp", help="Main app")
233
234 sub1 = App(name="sub1", help="First subcommand")
235
236 @sub1.command
237 def nested1():
238 """Nested command 1."""
239 pass
240
241 @sub1.command
242 def nested2():
243 """Nested command 2."""
244 pass
245
246 sub2 = App(name="sub2", help="Second subcommand")
247
248 @sub2.command
249 def nested3():
250 """Nested command 3."""
251 pass
252
253 app.command(sub1)
254 app.command(sub2)
255
256 # Without flatten_commands - hierarchical headings
257 docs_hierarchical = app.generate_docs(output_format="rst", flatten_commands=False)
258
259 # Main app should be level 1 (=====)
260 assert "=====\nmyapp\n=====" in docs_hierarchical
261 # Subcommands should be level 2 (-----)
262 assert "sub1\n----" in docs_hierarchical
263 assert "sub2\n----" in docs_hierarchical
264 # Nested commands should be level 3 (^^^^^) and show just command name in hierarchical mode
265 assert "nested1\n^^^^^^^" in docs_hierarchical
266 assert "nested2\n^^^^^^^" in docs_hierarchical
267 assert "nested3\n^^^^^^^" in docs_hierarchical
268
269 # With flatten_commands - all at same level
270 docs_flat = app.generate_docs(output_format="rst", flatten_commands=True)
271
272 # Main app should be level 1 (=====)
273 assert "=====\nmyapp\n=====" in docs_flat
274 # All subcommands should also be level 1 (=====) with full path in flattened mode
275 assert "==========\nmyapp sub1\n==========" in docs_flat
276 assert "==========\nmyapp sub2\n==========" in docs_flat
277 # All nested commands should also be level 1 (=====) with full path
278 assert "==================\nmyapp sub1 nested1\n==================" in docs_flat
279 assert "==================\nmyapp sub1 nested2\n==================" in docs_flat
280 assert "==================\nmyapp sub2 nested3\n==================" in docs_flat
281 # Should NOT have level 2 or level 3 markers for commands
282 # (Level 2 uses single underline, level 3 uses ^^^^)
283 # Check that subcommands don't use level 2 markers (----)
284 assert "sub1\n----" not in docs_flat
285 assert "sub2\n----" not in docs_flat
286 # Check that nested commands don't use level 3 markers (^^^^)
287 assert "nested1\n^^^^^^^" not in docs_flat
288
289
290 def test_generate_rst_docs_usage_strings_match_help():
291 """Test that RST usage strings match the actual help output."""
292 app = App(name="myapp", help="Main CLI application")
293
294 @app.command
295 def serve(host: str = "localhost", port: int = 8000):
296 """Start the development server.
297
298 Parameters
299 ----------
300 host : str
301 Host to bind to.
302 port : int
303 Port to listen on.
304 """
305 pass
306
307 @app.command
308 def build(output: str, verbose: bool = False):
309 """Build the project.
310
311 Parameters
312 ----------
313 output : str
314 Output directory.
315 verbose : bool
316 Enable verbose output.
317 """
318 pass
319
320 # Generate RST docs
321 docs = app.generate_docs(output_format="rst", recursive=True)
322
323 # Verify usage strings are present and correctly formatted
324 # The serve command should show: myapp serve [ARGS]
325 assert "myapp serve [ARGS]" in docs
326
327 # The build command should show: myapp build OUTPUT [ARGS]
328 # with OUTPUT as a required argument shown explicitly
329 assert "myapp build OUTPUT [ARGS]" in docs
330
331 # The key thing we're testing is that the usage strings match the actual
332 # help output format, not the old manually-constructed generic patterns
333 # like "myapp serve [ARGS] [OPTIONS]" that were created in the old code
334
335 # Verify that required arguments are shown explicitly by name
336 lines = docs.split("\n")
337 # Look for usage lines in literal blocks (lines that start with myapp after whitespace)
338 usage_lines = [line.strip() for line in lines if line.strip().startswith("myapp")]
339
340 # For the build command with required OUTPUT parameter
341 build_usage = [line for line in usage_lines if "myapp build" in line]
342 assert len(build_usage) > 0, "Should have usage line for build command"
343 # Should show OUTPUT explicitly, not hide it in generic [ARGS]
344 assert "OUTPUT" in build_usage[0]
345
346
347 def test_generate_rst_docs_usage_with_positional_args():
348 """Test RST usage strings correctly show positional arguments."""
349 app = App(name="tool", help="A tool")
350
351 @app.command
352 def process(input_file: str, output_file: str, verbose: bool = False):
353 """Process files.
354
355 Parameters
356 ----------
357 input_file : str
358 Input file path.
359 output_file : str
360 Output file path.
361 verbose : bool
362 Verbose mode.
363 """
364 pass
365
366 docs = app.generate_docs(output_format="rst")
367
368 # Should show the actual parameter names in usage
369 assert "tool process" in docs
370 # Should have INPUT-FILE and OUTPUT-FILE explicitly listed
371 # The key point is that required positional args are shown by name
372 assert "INPUT-FILE OUTPUT-FILE" in docs or "INPUT_FILE OUTPUT_FILE" in docs
373
374
375 def test_generate_rst_docs_usage_with_varargs():
376 """Test RST usage strings correctly show variable arguments."""
377 app = App(name="cmd", help="Command")
378
379 @app.command
380 def run(script: str, *args: str):
381 """Run a script with arguments.
382
383 Parameters
384 ----------
385 script : str
386 Script to run.
387 args : str
388 Additional arguments.
389 """
390 pass
391
392 docs = app.generate_docs(output_format="rst")
393
394 # Should show SCRIPT and [ARGS...] or similar
395 assert "cmd run" in docs
396 assert "SCRIPT" in docs
397 # Variable args are typically shown as [ARGS...] or ARGS...
398 assert "[ARGS" in docs or "ARGS" in docs
399
400
401 def test_generate_rst_docs_usage_name_overrides_root_usage():
402 """usage_name replaces the app name in the root Usage: line (RST)."""
403 app = App(name="cli", help="A CLI")
404
405 @app.default
406 def main(name: str = "world"):
407 """Greet.
408
409 Parameters
410 ----------
411 name : str
412 Name.
413 """
414 pass
415
416 actual = app.generate_docs(output_format="rst", usage_name="uv run cli")
417 assert "uv run cli" in actual
418
419
420 def test_generate_rst_docs_usage_name_overrides_subcommand_usage():
421 """usage_name prefixes every subcommand's Usage: line in RST output."""
422 app = App(name="cli", help="A CLI")
423
424 @app.command
425 def serve(port: int = 8000):
426 """Start server.
427
428 Parameters
429 ----------
430 port : int
431 Port.
432 """
433 pass
434
435 actual = app.generate_docs(output_format="rst", usage_name="uv run cli")
436
437 # Subcommand anchor/ref still uses the plain app name, not the override —
438 # asserted via the explicit RST label rather than a substring match, which
439 # would also be satisfied by the override "uv run cli serve" in the Usage
440 # block.
441 assert ".. _cyclopts-cli-serve:" in actual
442
443 # Usage line for the subcommand shows the override, not the plain app name
444 assert "uv run cli serve" in actual
445
446
447 def test_generate_rst_docs_usage_name_empty_drops_root_in_subcommand_usage():
448 """usage_name='' drops the root token in subcommand Usage lines, with no stray whitespace."""
449 app = App(name="cli", help="A CLI")
450
451 @app.command
452 def serve(port: int = 8000):
453 """Start server.
454
455 Parameters
456 ----------
457 port : int
458 Port.
459 """
460 pass
461
462 actual = app.generate_docs(output_format="rst", usage_name="")
463
464 # Find the Usage literal block for the subcommand. RST emits "::" followed
465 # by a blank line and 4-space-indented content. Check every indented line
466 # inside such blocks.
467 lines = actual.splitlines()
468 literal_contents: list[str] = []
469 i = 0
470 while i < len(lines):
471 if lines[i].rstrip() == "::":
472 i += 1
473 while i < len(lines) and not lines[i].strip():
474 i += 1
475 while i < len(lines) and (lines[i].startswith(" ") or not lines[i].strip()):
476 if lines[i].startswith(" "):
477 literal_contents.append(lines[i][4:])
478 i += 1
479 else:
480 i += 1
481
482 subcommand_lines = [line for line in literal_contents if "serve" in line]
483 assert subcommand_lines, "expected a subcommand Usage literal line"
484 for line in subcommand_lines:
485 assert " " not in line, f"double space in usage line: {line!r}"
486 assert not line.startswith(" "), f"leading space in usage line: {line!r}"
487 assert "cli serve" not in line, f"root name leaked into usage line: {line!r}"
488 assert "serve" in line
489
490
491 def test_generate_rst_docs_usage_name_none_is_default_behavior():
492 """Default (None) preserves existing RST output."""
493 app = App(name="cli", help="A CLI")
494
495 @app.default
496 def main():
497 """Entry."""
498 pass
499
500 assert app.generate_docs(output_format="rst") == app.generate_docs(output_format="rst", usage_name=None)