Debian Codegraph @

tests/test_generate_docs.py

raw symbols SCIP
1 """Tests for App.generate_docs() method."""
2
3 import tempfile
4 from pathlib import Path
5 from textwrap import dedent
6 from typing import Annotated
7
8 import pytest
9
10 from cyclopts import App, Parameter
11
12
13 def test_generate_docs_simple_app():
14 """Test basic documentation generation for a simple app."""
15 app = App(name="myapp", help="A simple CLI application")
16
17 @app.default
18 def main(name: str, verbose: bool = False):
19 """Main command.
20
21 Parameters
22 ----------
23 name : str
24 Your name.
25 verbose : bool
26 Enable verbose output.
27 """
28 pass
29
30 actual = app.generate_docs()
31
32 expected = dedent(
33 """\
34 # myapp
35
36 ```console
37 myapp NAME [ARGS]
38 ```
39
40 A simple CLI application
41
42 **Parameters**:
43
44 * `NAME, --name`: Your name. **[required]**
45 * `VERBOSE, --verbose, --no-verbose`: Enable verbose output. *[default: False]*
46 """
47 )
48
49 assert actual == expected
50
51
52 def test_generate_docs_with_commands():
53 """Test documentation generation with subcommands."""
54 app = App(name="myapp", help="CLI with commands")
55
56 @app.command
57 def serve(port: int = 8000):
58 """Start the server.
59
60 Parameters
61 ----------
62 port : int
63 Port number.
64 """
65 pass
66
67 @app.command
68 def build(output: str = "./dist"):
69 """Build the project.
70
71 Parameters
72 ----------
73 output : str
74 Output directory.
75 """
76 pass
77
78 actual = app.generate_docs()
79
80 # Check structure without being too specific about Usage lines that vary by context
81 assert "# myapp" in actual
82 assert "CLI with commands" in actual
83
84 # Main usage section
85 assert "myapp COMMAND" in actual
86
87 # Commands list with hyperlinks
88 assert "**Commands**:" in actual
89 assert "* [`build`](#myapp-build): Build the project." in actual
90 assert "* [`serve`](#myapp-serve): Start the server." in actual
91
92 # Serve command details (now shows full path)
93 assert "## myapp serve" in actual
94 assert "Start the server." in actual
95 assert "**Parameters**:" in actual
96 assert "* `PORT, --port`: Port number. *[default: 8000]*" in actual
97
98 # Build command details (now shows full path)
99 assert "## myapp build" in actual
100 assert "Build the project." in actual
101 assert "* `OUTPUT, --output`: Output directory. *[default: ./dist]*" in actual
102
103
104 def test_generate_docs_recursive():
105 """Test recursive documentation generation."""
106 app = App(name="myapp", help="Main app")
107
108 subapp = App(name="db", help="Database commands")
109
110 @subapp.command
111 def migrate():
112 """Run database migrations."""
113 pass
114
115 @subapp.command
116 def backup(output: str):
117 """Backup the database.
118
119 Parameters
120 ----------
121 output : str
122 Backup file path.
123 """
124 pass
125
126 app.command(subapp)
127
128 actual = app.generate_docs(recursive=True)
129
130 # Verify structure of recursive documentation
131 assert "# myapp" in actual
132 assert "Main app" in actual
133 assert "## myapp db" in actual
134 assert "Database commands" in actual
135 assert "migrate" in actual
136 assert "backup" in actual
137 assert "Run database migrations" in actual
138 assert "Backup the database" in actual
139
140
141 def test_generate_docs_non_recursive():
142 """Test non-recursive documentation generation."""
143 app = App(name="myapp", help="Main app")
144
145 subapp = App(name="db", help="Database commands")
146
147 @subapp.command
148 def migrate():
149 """Run database migrations."""
150 pass
151
152 app.command(subapp)
153
154 actual = app.generate_docs(recursive=False)
155
156 # Note: In non-recursive mode, subcommands like 'migrate' don't get headings,
157 # so they appear in the ToC but the link is broken. This is a known limitation.
158 # The current implementation always collects ToC entries recursively.
159 # Note: The 'db' subcommand doesn't show usage because it has no default_command.
160 expected = dedent(
161 """\
162 # myapp
163
164 ```console
165 myapp COMMAND
166 ```
167
168 Main app
169
170 ## Table of Contents
171
172 - [`db`](#myapp-db)
173 - [`migrate`](#myapp-db-migrate)
174
175 **Commands**:
176
177 * [`db`](#myapp-db): Database commands
178
179 ## myapp db
180
181 Database commands
182 """
183 )
184
185 assert actual == expected
186
187
188 def test_generate_docs_with_hidden_commands(mocker):
189 """Test documentation with hidden commands."""
190 # Mock sys.argv[0] for consistent output
191 mocker.patch("sys.argv", ["myapp"])
192
193 app = App(name="myapp", help="App with hidden commands")
194
195 @app.command
196 def visible():
197 """Visible command."""
198 pass
199
200 @app.command(show=False)
201 def hidden():
202 """Hidden command."""
203 pass
204
205 # Test WITHOUT include_hidden
206 actual_without_hidden = app.generate_docs(include_hidden=False)
207
208 expected_without_hidden = dedent(
209 """\
210 # myapp
211
212 ```console
213 myapp COMMAND
214 ```
215
216 App with hidden commands
217
218 ## Table of Contents
219
220 - [`visible`](#myapp-visible)
221
222 **Commands**:
223
224 * [`visible`](#myapp-visible): Visible command.
225
226 ## myapp visible
227
228 ```console
229 myapp visible
230 ```
231
232 Visible command.
233 """
234 )
235
236 assert actual_without_hidden == expected_without_hidden
237
238 # Test WITH include_hidden
239 actual_with_hidden = app.generate_docs(include_hidden=True)
240
241 # Verify the hidden command is present when include_hidden=True
242 assert "## myapp hidden" in actual_with_hidden
243 assert "Hidden command." in actual_with_hidden
244 # Note: --help and --version are builtin flags, not commands, so they
245 # should not appear in the Commands section even with include_hidden=True
246
247
248 def test_generate_docs_with_required_parameters():
249 """Test documentation with required parameters."""
250 app = App(name="myapp")
251
252 @app.default
253 def main(
254 required: Annotated[str, Parameter(help="Required parameter")],
255 optional: str = "default",
256 ):
257 """Main command."""
258 pass
259
260 actual = app.generate_docs()
261
262 expected = dedent(
263 """\
264 # myapp
265
266 ```console
267 myapp REQUIRED [ARGS]
268 ```
269
270 Main command.
271
272 **Parameters**:
273
274 * `REQUIRED, --required`: Required parameter **[required]**
275 * `OPTIONAL, --optional`: *[default: default]*
276 """
277 )
278
279 assert actual == expected
280
281
282 def test_generate_docs_with_choices():
283 """Test documentation with parameter choices."""
284 from enum import Enum
285
286 app = App(name="myapp")
287
288 class Color(Enum):
289 RED = "red"
290 GREEN = "green"
291 BLUE = "blue"
292
293 @app.default
294 def main(color: Color = Color.RED):
295 """Choose a color."""
296 pass
297
298 actual = app.generate_docs()
299
300 # Should show available choices in the documentation
301 assert "red" in actual
302 assert "green" in actual
303 assert "blue" in actual
304 assert "choices:" in actual
305
306
307 def test_generate_docs_with_custom_usage():
308 """Test documentation with custom usage string."""
309 app = App(name="myapp", usage="myapp [OPTIONS] <input> <output>")
310
311 @app.default
312 def main():
313 """Main command."""
314 pass
315
316 actual = app.generate_docs()
317
318 expected = dedent(
319 """\
320 # myapp
321
322 ```console
323 myapp [OPTIONS] <input> <output>
324 ```
325
326 Main command.
327 """
328 )
329
330 assert actual == expected
331
332
333 def test_generate_docs_no_usage():
334 """Test documentation with suppressed usage."""
335 app = App(name="myapp", usage="") # Empty string suppresses usage
336
337 @app.default
338 def main():
339 """Main command."""
340 pass
341
342 actual = app.generate_docs()
343
344 expected = dedent(
345 """\
346 # myapp
347
348 Main command.
349 """
350 )
351
352 assert actual == expected
353
354
355 def test_generate_docs_write_to_file():
356 """Test writing documentation to a file."""
357 app = App(name="myapp", help="Test app")
358
359 @app.default
360 def main():
361 """Main command."""
362 pass
363
364 with tempfile.TemporaryDirectory() as tmpdir:
365 output_path = Path(tmpdir) / "docs" / "cli.md"
366
367 # Generate docs
368 actual = app.generate_docs()
369
370 expected = dedent(
371 """\
372 # myapp
373
374 ```console
375 myapp
376 ```
377
378 Test app
379 """
380 )
381
382 # Write to file manually
383 output_path.parent.mkdir(parents=True, exist_ok=True)
384 output_path.write_text(actual)
385
386 # Check file was created and contains expected content
387 assert output_path.exists()
388 content = output_path.read_text()
389 assert content == expected
390
391 # Should return the expected content
392 assert actual == expected
393
394
395 def test_generate_docs_output_format_explicit():
396 """Test explicitly specifying output format."""
397 app = App(name="myapp", help="Test app")
398
399 @app.default
400 def main():
401 """Main command."""
402 pass
403
404 # Explicitly specify markdown format
405 actual = app.generate_docs(output_format="markdown")
406
407 expected = dedent(
408 """\
409 # myapp
410
411 ```console
412 myapp
413 ```
414
415 Test app
416 """
417 )
418
419 assert actual == expected
420
421
422 def test_generate_docs_output_format_markdown():
423 """Test generating markdown format documentation."""
424 app = App(name="myapp", help="Test app")
425
426 @app.default
427 def main():
428 """Main command."""
429 pass
430
431 # Test markdown format (default)
432 docs_md = app.generate_docs()
433 assert "# myapp" in docs_md
434
435 # Test explicitly specifying markdown
436 docs_explicit = app.generate_docs(output_format="markdown")
437 assert "# myapp" in docs_explicit
438 assert docs_md == docs_explicit
439
440
441 def test_generate_docs_invalid_format():
442 """Test that invalid output format raises ValueError."""
443 app = App(name="myapp", help="Test app")
444
445 with pytest.raises(ValueError, match='Unsupported format "pdf"'):
446 app.generate_docs(output_format="pdf") # type: ignore[arg-type]
447
448 with pytest.raises(ValueError, match='Unsupported format "invalid"'):
449 app.generate_docs(output_format="invalid") # type: ignore[arg-type]
450
451
452 def test_generate_docs_with_heading_levels():
453 """Test custom heading levels."""
454 app = App(name="myapp", help="Main app")
455
456 @app.command
457 def cmd():
458 """A command."""
459 pass
460
461 actual = app.generate_docs(heading_level=2)
462
463 # Check the heading levels
464 assert "## myapp" in actual
465 assert "Main app" in actual
466 assert "**Commands**:" in actual
467 assert "### myapp cmd" in actual
468
469
470 def test_generate_docs_complex_nested_app():
471 """Test complex nested application documentation."""
472 app = App(name="cli", help="Complex CLI tool")
473
474 # Add top-level command
475 @app.command
476 def version():
477 """Show version information."""
478 pass
479
480 # Create nested subapp
481 git = App(name="git", help="Git operations")
482
483 @git.command
484 def clone(
485 url: Annotated[str, Parameter(help="Repository URL")],
486 depth: int = 1,
487 ):
488 """Clone a repository.
489
490 Parameters
491 ----------
492 url : str
493 The repository URL to clone.
494 depth : int
495 Clone depth.
496 """
497 pass
498
499 @git.command
500 def push(force: bool = False):
501 """Push changes.
502
503 Parameters
504 ----------
505 force : bool
506 Force push.
507 """
508 pass
509
510 app.command(git)
511
512 docs = app.generate_docs(recursive=True)
513
514 # Check structure
515 assert "# cli" in docs
516 assert "Complex CLI tool" in docs
517 assert "version" in docs
518 assert "Show version information" in docs
519 assert "## cli git" in docs
520 assert "Git operations" in docs
521 assert "clone" in docs
522 assert "push" in docs
523 assert "Clone a repository" in docs
524 assert "Push changes" in docs
525 assert "Repository URL" in docs
526 assert "Force push" in docs
527
528
529 def test_generate_docs_with_aliases():
530 """Test documentation with command aliases."""
531 app = App(name="myapp")
532
533 @app.command(alias=["s", "srv"])
534 def serve():
535 """Start the server."""
536 pass
537
538 docs = app.generate_docs()
539
540 assert "serve" in docs
541 assert "Start the server" in docs
542 # Note: Aliases might not be shown in current implementation
543 # This is acceptable as the main command name is shown
544
545
546 def test_generate_docs_with_meta_app():
547 """Test documentation generation with meta app."""
548 from typing import Annotated
549
550 app = App(name="myapp", help="Main application")
551
552 @app.default
553 def main(input_file: str):
554 """Process a file.
555
556 Parameters
557 ----------
558 input_file : str
559 Input file path.
560 """
561 pass
562
563 @app.meta.default
564 def meta(
565 verbose: bool = False,
566 config: Annotated[str | None, Parameter(help="Config file")] = None,
567 ):
568 """Meta app for global options.
569
570 Parameters
571 ----------
572 verbose : bool
573 Enable verbose output.
574 config : str
575 Configuration file path.
576 """
577 pass
578
579 actual = app.generate_docs()
580
581 expected = dedent(
582 """\
583 # myapp
584
585 ```console
586 myapp INPUT-FILE [ARGS]
587 ```
588
589 Main application
590
591 **Parameters**:
592
593 * `INPUT-FILE, --input-file`: Input file path. **[required]**
594 * `VERBOSE, --verbose, --no-verbose`: Enable verbose output. *[default: False]*
595 * `CONFIG, --config`: Config file
596 """
597 )
598
599 assert actual == expected
600
601
602 def test_generate_docs_meta_app_with_commands():
603 """Test documentation with meta app and subcommands."""
604 app = App(name="myapp", help="Main app with meta")
605
606 @app.meta.default
607 def meta(
608 debug: bool = False,
609 ):
610 """Global meta options.
611
612 Parameters
613 ----------
614 debug : bool
615 Enable debug mode.
616 """
617 pass
618
619 @app.command
620 def serve(port: int = 8000):
621 """Start the server.
622
623 Parameters
624 ----------
625 port : int
626 Port number.
627 """
628 pass
629
630 @app.command
631 def build():
632 """Build the project."""
633 pass
634
635 actual = app.generate_docs()
636
637 # Meta parameters should appear with the main app
638 assert "debug" in actual.lower() or "DEBUG" in actual
639 assert "Enable debug mode" in actual
640
641 # Commands should still appear
642 assert "serve" in actual
643 assert "build" in actual
644 assert "Start the server" in actual
645 assert "Build the project" in actual
646
647
648 def test_generate_docs_nested_meta_apps():
649 """Test documentation with nested apps that have their own meta apps."""
650 # Create a subapp with its own meta
651 db_app = App(name="db", help="Database commands")
652
653 @db_app.meta.default
654 def db_meta(
655 connection: str = "sqlite:///:memory:",
656 ):
657 """Database meta options.
658
659 Parameters
660 ----------
661 connection : str
662 Database connection string.
663 """
664 pass
665
666 @db_app.command
667 def migrate():
668 """Run database migrations."""
669 pass
670
671 # Main app with its own meta
672 app = App(name="myapp", help="Main application")
673
674 @app.meta.default
675 def main_meta(
676 verbose: bool = False,
677 ):
678 """Global options.
679
680 Parameters
681 ----------
682 verbose : bool
683 Verbose output.
684 """
685 pass
686
687 # Register the db app with its meta
688 app.command(db_app.meta, name="db")
689
690 docs = app.generate_docs(recursive=True)
691
692 # Check main app meta parameters appear
693 assert "verbose" in docs.lower() or "VERBOSE" in docs
694 assert "Verbose output" in docs
695
696 # Check db subcommand appears
697 assert "## myapp db" in docs
698 # When registering db_app.meta, it uses the meta's docstring
699 assert "Database meta options" in docs
700
701 # Check nested db commands appear when recursive
702 assert "migrate" in docs
703 assert "Run database migrations" in docs
704
705 # Check db meta parameters appear with db command
706 assert "connection" in docs.lower() or "CONNECTION" in docs
707 assert "Database connection string" in docs
708
709
710 def test_generate_docs_flatten_commands():
711 """Test flatten_commands option for markdown documentation."""
712 app = App(name="myapp", help="Main app")
713
714 sub1 = App(name="sub1", help="First subcommand")
715
716 @sub1.command
717 def nested1():
718 """Nested command 1."""
719 pass
720
721 @sub1.command
722 def nested2():
723 """Nested command 2."""
724 pass
725
726 sub2 = App(name="sub2", help="Second subcommand")
727
728 @sub2.command
729 def nested3():
730 """Nested command 3."""
731 pass
732
733 app.command(sub1)
734 app.command(sub2)
735
736 # Without flatten_commands - hierarchical headings (but full paths to avoid collisions)
737 docs_hierarchical = app.generate_docs(flatten_commands=False)
738
739 # Main app should be h1
740 assert "# myapp" in docs_hierarchical
741 # Subcommands should be h2 with full paths
742 assert "## myapp sub1" in docs_hierarchical
743 assert "## myapp sub2" in docs_hierarchical
744 # Nested commands should be h3 (properly nested under their parent) with full paths
745 assert "### myapp sub1 nested1" in docs_hierarchical
746 assert "### myapp sub1 nested2" in docs_hierarchical
747 assert "### myapp sub2 nested3" in docs_hierarchical
748
749 # With flatten_commands - all at same level
750 docs_flat = app.generate_docs(flatten_commands=True)
751
752 # Main app should be h1
753 assert "# myapp" in docs_flat
754 # All subcommands should also be h1 (flattened) with full paths
755 assert "# myapp sub1" in docs_flat
756 assert "# myapp sub2" in docs_flat
757 # All nested commands should also be h1 (flattened) with full paths
758 assert "# myapp sub1 nested1" in docs_flat
759 assert "# myapp sub1 nested2" in docs_flat
760 assert "# myapp sub2 nested3" in docs_flat
761 # Should NOT have h2 command headings when flattened
762 assert "## myapp sub" not in docs_flat
763
764
765 def test_generate_docs_toc_anchors_flattened():
766 """Test that TOC anchors match actual heading anchors in flattened mode."""
767 app = App(name="myapp", help="My app")
768
769 sub1 = App(name="sub1", help="First subcommand")
770
771 @sub1.command
772 def nested1():
773 """Nested command 1."""
774 pass
775
776 @sub1.command
777 def nested2():
778 """Nested command 2."""
779 pass
780
781 sub2 = App(name="sub2", help="Second subcommand")
782
783 @sub2.command
784 def nested3():
785 """Nested command 3."""
786 pass
787
788 app.command(sub1)
789 app.command(sub2)
790
791 docs = app.generate_docs(flatten_commands=True)
792
793 # In flattened mode, TOC anchors should include full path with app name
794 assert "- [`sub1`](#myapp-sub1)" in docs
795 assert "- [`nested1`](#myapp-sub1-nested1)" in docs
796 assert "- [`nested2`](#myapp-sub1-nested2)" in docs
797 assert "- [`sub2`](#myapp-sub2)" in docs
798 assert "- [`nested3`](#myapp-sub2-nested3)" in docs
799
800 # Verify headings exist that will generate these anchors (all show full paths)
801 assert "# myapp sub1" in docs
802 assert "# myapp sub1 nested1" in docs
803 assert "# myapp sub1 nested2" in docs
804 assert "# myapp sub2" in docs
805 assert "# myapp sub2 nested3" in docs
806
807
808 def test_generate_docs_toc_anchors_hierarchical():
809 """Test that TOC anchors match actual heading anchors in hierarchical mode."""
810 app = App(name="myapp", help="My app")
811
812 sub1 = App(name="sub1", help="First subcommand")
813
814 @sub1.command
815 def nested1():
816 """Nested command 1."""
817 pass
818
819 @sub1.command
820 def nested2():
821 """Nested command 2."""
822 pass
823
824 sub2 = App(name="sub2", help="Second subcommand")
825
826 @sub2.command
827 def nested3():
828 """Nested command 3."""
829 pass
830
831 app.command(sub1)
832 app.command(sub2)
833
834 docs = app.generate_docs(flatten_commands=False)
835
836 # TOC anchors use full paths with app name to avoid collisions (e.g., files.cp vs other.cp)
837 assert "- [`sub1`](#myapp-sub1)" in docs
838 assert "- [`nested1`](#myapp-sub1-nested1)" in docs
839 assert "- [`nested2`](#myapp-sub1-nested2)" in docs
840 assert "- [`sub2`](#myapp-sub2)" in docs
841 assert "- [`nested3`](#myapp-sub2-nested3)" in docs
842
843 # Verify headings exist that will generate these anchors (now showing full paths)
844 assert "## myapp sub1" in docs
845 assert "### myapp sub1 nested1" in docs
846 assert "### myapp sub1 nested2" in docs
847 assert "## myapp sub2" in docs
848 assert "### myapp sub2 nested3" in docs
849
850
851 def test_generate_docs_toc_anchor_collisions():
852 """Test that headings with same command name don't collide (full paths prevent this)."""
853 app = App(name="myapp", help="My app")
854
855 sub1 = App(name="sub1", help="First subcommand")
856
857 @sub1.command(name="create")
858 def create1():
859 """Create via sub1."""
860 pass
861
862 @sub1.command(name="delete")
863 def delete1():
864 """Delete via sub1."""
865 pass
866
867 sub2 = App(name="sub2", help="Second subcommand")
868
869 @sub2.command(name="create")
870 def create2():
871 """Create via sub2."""
872 pass
873
874 @sub2.command(name="delete")
875 def delete2():
876 """Delete via sub2."""
877 pass
878
879 app.command(sub1)
880 app.command(sub2)
881
882 docs = app.generate_docs(flatten_commands=False)
883
884 # Headings now use full paths with app name, so no collisions occur
885 assert "- [`sub1`](#myapp-sub1)" in docs
886 assert " - [`create`](#myapp-sub1-create)" in docs
887 assert " - [`delete`](#myapp-sub1-delete)" in docs
888
889 assert "- [`sub2`](#myapp-sub2)" in docs
890 assert " - [`create`](#myapp-sub2-create)" in docs
891 assert " - [`delete`](#myapp-sub2-delete)" in docs
892
893 # Verify the actual headings use full paths
894 assert "### myapp sub1 create" in docs
895 assert "### myapp sub1 delete" in docs
896 assert "### myapp sub2 create" in docs
897 assert "### myapp sub2 delete" in docs
898
899
900 def test_generate_docs_nested_command_list_hyperlinks():
901 """Test that command list hyperlinks in nested apps use full command path.
902
903 This tests that when a deeply nested command (e.g., app -> parent -> child -> grandchild)
904 lists its subcommands in the **Commands**: section, the hyperlinks use the full path
905 (e.g., #app-parent-child-grandchild) not just the app name and command
906 (e.g., #child-grandchild).
907 """
908 app = App(name="darts", help="Main app")
909
910 training = App(name="training", help="Training commands")
911
912 create_dataset = App(name="create-dataset", help="Dataset creation")
913
914 @create_dataset.command
915 def planet():
916 """Preprocess Planet data for training."""
917 pass
918
919 @create_dataset.command
920 def sentinel2():
921 """Preprocess Sentinel-2 data for training."""
922 pass
923
924 training.command(create_dataset)
925 app.command(training)
926
927 docs = app.generate_docs()
928
929 # The command list in create-dataset should have hyperlinks with the FULL path
930 # NOT just #create-dataset-planet (wrong) but #darts-training-create-dataset-planet (correct)
931 assert "* [`planet`](#darts-training-create-dataset-planet):" in docs
932 assert "* [`sentinel2`](#darts-training-create-dataset-sentinel2):" in docs
933
934 # Verify the headings exist with matching anchors
935 assert "### darts training create-dataset" in docs
936 assert "#### darts training create-dataset planet" in docs
937 assert "#### darts training create-dataset sentinel2" in docs
938
939 # Also verify the root-level command list (darts listing training)
940 assert "* [`training`](#darts-training):" in docs
941
942
943 def test_generate_docs_usage_name_overrides_root_usage():
944 """usage_name replaces the app name in the root Usage: line."""
945 app = App(name="cli", help="A CLI")
946
947 @app.default
948 def main(name: str = "world"):
949 """Greet.
950
951 Parameters
952 ----------
953 name : str
954 Name.
955 """
956 pass
957
958 actual = app.generate_docs(usage_name="uv run cli")
959 assert "# cli" in actual # heading unchanged
960 usage_block = actual.split("```console")[1].split("```")[0].strip()
961 first_line = next(line for line in usage_block.splitlines() if line.strip())
962 assert first_line.startswith("uv run cli"), f"usage line: {first_line!r}"
963
964
965 def test_generate_docs_usage_name_overrides_subcommand_usage():
966 """usage_name prefixes every subcommand's Usage: line too."""
967 app = App(name="cli", help="A CLI")
968
969 @app.command
970 def serve(port: int = 8000):
971 """Start the server.
972
973 Parameters
974 ----------
975 port : int
976 Port.
977 """
978 pass
979
980 actual = app.generate_docs(usage_name="uv run cli")
981 # Subcommand heading still uses plain app name
982 assert "## cli serve" in actual
983 # TOC anchor unchanged
984 assert "](#cli-serve)" in actual
985 # Every console block begins with "uv run cli"
986 for block in actual.split("```console")[1:]:
987 body = block.split("```")[0].strip()
988 first_line = next(line for line in body.splitlines() if line.strip())
989 assert first_line.startswith("uv run cli"), f"usage line should start with 'uv run cli': {first_line!r}"
990
991
992 def test_generate_docs_usage_name_none_is_default_behavior():
993 """Passing usage_name=None (default) produces identical output to omitting it."""
994 app = App(name="cli", help="A CLI")
995
996 @app.default
997 def main():
998 """Entry."""
999 pass
1000
1001 assert app.generate_docs() == app.generate_docs(usage_name=None)
1002
1003
1004 @pytest.mark.parametrize("fmt", ["markdown", "rst", "html"])
1005 def test_generate_docs_usage_name_applies_across_formats(fmt):
1006 """usage_name is accepted by every output format and affects its Usage: output."""
1007 app = App(name="cli", help="A CLI")
1008
1009 @app.default
1010 def main():
1011 """Entry."""
1012 pass
1013
1014 output = app.generate_docs(output_format=fmt, usage_name="uv run cli")
1015 assert "uv run cli" in output
1016
1017
1018 def test_generate_docs_usage_name_empty_string_is_inserted_verbatim():
1019 """Empty usage_name is inserted verbatim; the bare "cli" prefix is dropped."""
1020 app = App(name="cli", help="A CLI")
1021
1022 @app.command
1023 def serve(port: int = 8000):
1024 """Start the server.
1025
1026 Parameters
1027 ----------
1028 port : int
1029 Port.
1030 """
1031 pass
1032
1033 actual = app.generate_docs(usage_name="")
1034 # Heading untouched
1035 assert "## cli serve" in actual
1036 # Subcommand usage line no longer starts with "cli " — the root token has been replaced by "".
1037 subcommand_usage = actual.split("## cli serve")[1].split("```console")[1].split("```")[0].strip()
1038 first_line = next(line for line in subcommand_usage.splitlines() if line.strip())
1039 assert not first_line.startswith("cli ")
1040 assert first_line.startswith("serve")