Debian Codegraph @

tests/test_help_customization.py

raw symbols SCIP
1 """Test help customization via Group help_formatter."""
2
3 from textwrap import dedent
4 from typing import Annotated, Any
5
6 from rich.box import DOUBLE, SIMPLE, SQUARE
7 from rich.console import Console
8
9 from cyclopts import App, Group, Parameter
10 from cyclopts.annotations import get_hint_name
11 from cyclopts.help import ColumnSpec, DefaultFormatter, HelpEntry, PanelSpec, TableSpec
12 from cyclopts.help.specs import DescriptionColumn, DescriptionRenderer
13
14
15 def _type_renderer(entry: Any) -> str:
16 """Render the type field as a human-readable string."""
17 type_annotation = entry.type
18 if type_annotation is None:
19 return ""
20 return get_hint_name(type_annotation)
21
22
23 def test_group_custom_table_spec(console: Console):
24 """Test that custom table_spec on Group is used."""
25 custom_group = Group(
26 "Custom Options",
27 help="These are custom options.",
28 help_formatter=DefaultFormatter(
29 table_spec=TableSpec(
30 show_header=True,
31 border_style="blue",
32 ),
33 ),
34 )
35
36 app = App()
37
38 @app.default
39 def main(
40 verbose: Annotated[bool, Parameter(group=custom_group)] = False,
41 config: Annotated[str, Parameter(group=custom_group)] = "default.cfg",
42 ):
43 pass
44
45 with console.capture() as capture:
46 app.help_print(console=console)
47
48 actual = capture.get()
49 expected = dedent(
50 """\
51 Usage: test_help_customization [ARGS]
52
53 ╭─ Commands ─────────────────────────────────────────────────────────╮
54 │ --help (-h) Display this message and exit. │
55 │ --version Display application version. │
56 ╰────────────────────────────────────────────────────────────────────╯
57 ╭─ Custom Options ───────────────────────────────────────────────────╮
58 │ These are custom options. │
59 │ │
60 │ Option Description │
61 │ VERBOSE --verbose [default: False] │
62 │ --no-verbose │
63 │ CONFIG --config [default: default.cfg] │
64 ╰────────────────────────────────────────────────────────────────────╯
65 """
66 )
67 assert actual == expected
68
69
70 def test_group_custom_panel_spec(console: Console):
71 """Test that custom panel_spec on Group is used."""
72 custom_group = Group(
73 "Styled Options",
74 help_formatter=DefaultFormatter(
75 panel_spec=PanelSpec(
76 box=DOUBLE,
77 border_style="cyan",
78 padding=(1, 2),
79 ),
80 ),
81 )
82
83 app = App()
84
85 @app.default
86 def main(
87 flag: Annotated[bool, Parameter(group=custom_group)] = False,
88 ):
89 pass
90
91 with console.capture() as capture:
92 app.help_print(console=console)
93
94 actual = capture.get()
95 expected = dedent(
96 """\
97 Usage: test_help_customization [ARGS]
98
99 ╭─ Commands ─────────────────────────────────────────────────────────╮
100 │ --help (-h) Display this message and exit. │
101 │ --version Display application version. │
102 ╰────────────────────────────────────────────────────────────────────╯
103 ╔═ Styled Options ═══════════════════════════════════════════════════╗
104 ║ ║
105 ║ FLAG --flag --no-flag [default: False] ║
106 ║ ║
107 ╚════════════════════════════════════════════════════════════════════╝
108 """
109 )
110 assert actual == expected
111
112
113 def test_group_custom_columns(console: Console):
114 """Test that custom columns can be specified via DefaultFormatter."""
115
116 def names_renderer(entry):
117 """Render names and shorts as a single string."""
118 names_str = " ".join(entry.names) if entry.names else ""
119 shorts_str = " ".join(entry.shorts) if entry.shorts else ""
120 if names_str and shorts_str:
121 return names_str + " " + shorts_str
122 return names_str or shorts_str
123
124 custom_columns = (
125 ColumnSpec(renderer=names_renderer, style="green bold", header="Option"),
126 ColumnSpec(renderer=_type_renderer, style="yellow", header="Type"),
127 DescriptionColumn,
128 )
129
130 custom_group = Group(
131 "Advanced Options",
132 help_formatter=DefaultFormatter(
133 column_specs=custom_columns,
134 table_spec=TableSpec(show_header=True),
135 ),
136 )
137
138 app = App()
139
140 @app.default
141 def main(
142 threads: Annotated[int, Parameter(group=custom_group, help="Number of threads")] = 4,
143 ):
144 pass
145
146 with console.capture() as capture:
147 app.help_print(console=console)
148
149 actual = capture.get()
150 expected = dedent(
151 """\
152 Usage: test_help_customization [ARGS]
153
154 ╭─ Commands ─────────────────────────────────────────────────────────╮
155 │ --help (-h) Display this message and exit. │
156 │ --version Display application version. │
157 ╰────────────────────────────────────────────────────────────────────╯
158 ╭─ Advanced Options ─────────────────────────────────────────────────╮
159 │ Option Type Description │
160 │ THREADS --threads int Number of threads [default: 4] │
161 ╰────────────────────────────────────────────────────────────────────╯
162 """
163 )
164 assert actual == expected
165
166
167 def test_default_group_with_custom_spec(app, console):
168 """Test that default groups can be created and then customized with specs."""
169 # Create a default parameters group and then set its specs
170 custom_params_group = Group.create_default_parameters()
171 custom_params_group = Group(
172 custom_params_group.name,
173 sort_key=custom_params_group.sort_key,
174 help_formatter=DefaultFormatter(
175 table_spec=TableSpec(
176 show_lines=True,
177 box=SQUARE, # Need a box style for lines to appear
178 ),
179 panel_spec=PanelSpec(
180 box=DOUBLE,
181 ),
182 ),
183 )
184
185 app.group_parameters = custom_params_group
186
187 @app.default
188 def main(verbose: bool = False):
189 pass
190
191 with console.capture() as capture:
192 app.help_print(console=console)
193
194 actual = capture.get()
195 expected = dedent(
196 """\
197 Usage: test_help_customization [ARGS]
198
199 ╭─ Commands ─────────────────────────────────────────────────────────╮
200 │ --help (-h) Display this message and exit. │
201 │ --version Display application version. │
202 ╰────────────────────────────────────────────────────────────────────╯
203 ╔═ Parameters ═══════════════════════════════════════════════════════╗
204 ║ ┌───────────────────┬────────────────────────────────────────────┐ ║
205 ║ │VERBOSE --verbose │[default: False] │ ║
206 ║ │ --no-verbose │ │ ║
207 ║ └───────────────────┴────────────────────────────────────────────┘ ║
208 ╚════════════════════════════════════════════════════════════════════╝
209 """
210 )
211 assert actual == expected
212
213
214 def test_command_group_with_custom_spec(console: Console):
215 """Test that command groups can have custom specs."""
216 # Create a default commands group and then customize it
217 custom_commands_group = Group(
218 "Commands",
219 sort_key=Group.create_default_commands().sort_key,
220 help_formatter=DefaultFormatter(
221 table_spec=TableSpec(
222 padding=(0, 1),
223 ),
224 ),
225 )
226
227 app = App(group_commands=custom_commands_group)
228
229 @app.command
230 def foo():
231 """Foo command."""
232 pass
233
234 @app.command
235 def bar():
236 """Bar command."""
237 pass
238
239 with console.capture() as capture:
240 app.help_print(console=console)
241
242 actual = capture.get()
243 expected = dedent(
244 """\
245 Usage: test_help_customization COMMAND
246
247 ╭─ Commands ─────────────────────────────────────────────────────────╮
248 │ bar Bar command. │
249 │ foo Foo command. │
250 │ --help (-h) Display this message and exit. │
251 │ --version Display application version. │
252 ╰────────────────────────────────────────────────────────────────────╯
253 """
254 )
255 assert actual == expected
256
257
258 def test_panel_spec_custom_title(console: Console):
259 """Test that a custom title in panel_spec overrides the group name."""
260 custom_group = Group(
261 "Original Name",
262 help_formatter=DefaultFormatter(
263 panel_spec=PanelSpec(
264 title="Custom Title",
265 border_style="magenta",
266 ),
267 ),
268 )
269
270 app = App()
271
272 @app.default
273 def main(
274 option: Annotated[str, Parameter(group=custom_group)] = "default",
275 ):
276 pass
277
278 with console.capture() as capture:
279 app.help_print(console=console)
280
281 actual = capture.get()
282 expected = dedent(
283 """\
284 Usage: test_help_customization [ARGS]
285
286 ╭─ Commands ─────────────────────────────────────────────────────────╮
287 │ --help (-h) Display this message and exit. │
288 │ --version Display application version. │
289 ╰────────────────────────────────────────────────────────────────────╯
290 ╭─ Custom Title ─────────────────────────────────────────────────────╮
291 │ OPTION --option [default: default] │
292 ╰────────────────────────────────────────────────────────────────────╯
293 """
294 )
295 assert actual == expected
296
297
298 def test_mixed_groups_with_different_specs(console: Console):
299 """Test multiple groups each with their own custom specs."""
300 required_group = Group(
301 "Required",
302 help_formatter=DefaultFormatter(
303 table_spec=TableSpec(
304 border_style="red",
305 ),
306 ),
307 )
308
309 optional_group = Group(
310 "Optional",
311 help_formatter=DefaultFormatter(
312 table_spec=TableSpec(
313 border_style="green",
314 ),
315 ),
316 )
317
318 app = App()
319
320 @app.default
321 def main(
322 name: Annotated[str, Parameter(group=required_group)],
323 verbose: Annotated[bool, Parameter(group=optional_group)] = False,
324 debug: Annotated[bool, Parameter(group=optional_group)] = False,
325 ):
326 pass
327
328 with console.capture() as capture:
329 app.help_print(console=console)
330
331 actual = capture.get()
332 expected = dedent(
333 """\
334 Usage: test_help_customization NAME [ARGS]
335
336 ╭─ Commands ─────────────────────────────────────────────────────────╮
337 │ --help (-h) Display this message and exit. │
338 │ --version Display application version. │
339 ╰────────────────────────────────────────────────────────────────────╯
340 ╭─ Optional ─────────────────────────────────────────────────────────╮
341 │ VERBOSE --verbose [default: False] │
342 │ --no-verbose │
343 │ DEBUG --debug --no-debug [default: False] │
344 ╰────────────────────────────────────────────────────────────────────╯
345 ╭─ Required ─────────────────────────────────────────────────────────╮
346 │ * NAME --name [required] │
347 ╰────────────────────────────────────────────────────────────────────╯
348 """
349 )
350 assert actual == expected
351
352
353 def test_table_show_lines_with_box(console: Console):
354 """Test that lines appear between rows when both show_lines=True and box is set."""
355 custom_group = Group(
356 "Options",
357 help_formatter=DefaultFormatter(
358 table_spec=TableSpec(
359 show_lines=True,
360 box=SIMPLE, # Need a box style for lines to appear
361 border_style="green",
362 ),
363 ),
364 )
365
366 app = App()
367
368 @app.default
369 def main(
370 first: Annotated[str, Parameter(group=custom_group)] = "one",
371 second: Annotated[str, Parameter(group=custom_group)] = "two",
372 ):
373 pass
374
375 with console.capture() as capture:
376 app.help_print(console=console)
377
378 actual = capture.get()
379 expected = dedent(
380 """\
381 Usage: test_help_customization [ARGS]
382
383 ╭─ Commands ─────────────────────────────────────────────────────────╮
384 │ --help (-h) Display this message and exit. │
385 │ --version Display application version. │
386 ╰────────────────────────────────────────────────────────────────────╯
387 ╭─ Options ──────────────────────────────────────────────────────────╮
388 │ │
389 │ FIRST --first [default: one] │
390 │ │
391 │ SECOND --second [default: two] │
392 │ │
393 ╰────────────────────────────────────────────────────────────────────╯
394 """
395 )
396 assert actual == expected
397
398
399 def test_table_headers_with_default_columns(console: Console):
400 """Test that default columns now have headers that show when show_header=True."""
401 custom_group = Group(
402 "Config",
403 help_formatter=DefaultFormatter(
404 table_spec=TableSpec(
405 show_header=True, # Headers should now show with default columns
406 ),
407 ),
408 )
409
410 app = App()
411
412 @app.default
413 def main(
414 param: Annotated[str, Parameter(group=custom_group)] = "value",
415 ):
416 pass
417
418 with console.capture() as capture:
419 app.help_print(console=console)
420
421 actual = capture.get()
422 expected = dedent(
423 """\
424 Usage: test_help_customization [ARGS]
425
426 ╭─ Commands ─────────────────────────────────────────────────────────╮
427 │ --help (-h) Display this message and exit. │
428 │ --version Display application version. │
429 ╰────────────────────────────────────────────────────────────────────╯
430 ╭─ Config ───────────────────────────────────────────────────────────╮
431 │ Option Description │
432 │ PARAM --param [default: value] │
433 ╰────────────────────────────────────────────────────────────────────╯
434 """
435 )
436 assert actual == expected
437
438
439 def test_table_headers_suppressed_when_all_empty(console: Console):
440 """Test that headers are suppressed when all column headers are empty strings."""
441 from cyclopts.help import DescriptionRenderer
442
443 # Create columns with explicitly empty headers
444 custom_columns = (
445 ColumnSpec(renderer=lambda entry: " ".join(entry.names) if entry.names else "", header="", style="cyan"),
446 ColumnSpec(renderer=DescriptionRenderer(), header=""),
447 )
448
449 custom_group = Group(
450 "Settings",
451 help_formatter=DefaultFormatter(
452 column_specs=custom_columns,
453 table_spec=TableSpec(
454 show_header=True, # Even with this True, headers shouldn't show if all are empty
455 ),
456 ),
457 )
458
459 app = App()
460
461 @app.default
462 def main(
463 setting: Annotated[str, Parameter(group=custom_group, help="A configuration setting")] = "default",
464 ):
465 pass
466
467 with console.capture() as capture:
468 app.help_print(console=console)
469
470 actual = capture.get()
471 expected = dedent(
472 """\
473 Usage: test_help_customization [ARGS]
474
475 ╭─ Commands ─────────────────────────────────────────────────────────╮
476 │ --help (-h) Display this message and exit. │
477 │ --version Display application version. │
478 ╰────────────────────────────────────────────────────────────────────╯
479 ╭─ Settings ─────────────────────────────────────────────────────────╮
480 │ SETTING --setting A configuration setting [default: default] │
481 ╰────────────────────────────────────────────────────────────────────╯
482 """
483 )
484 assert actual == expected
485
486
487 def test_table_headers_with_non_empty_headers(console: Console):
488 """Test that headers appear when column headers have text."""
489
490 def names_renderer(entry):
491 """Render names and shorts as a single string."""
492 names_str = " ".join(entry.names) if entry.names else ""
493 shorts_str = " ".join(entry.shorts) if entry.shorts else ""
494 if names_str and shorts_str:
495 return names_str + " " + shorts_str
496 return names_str or shorts_str
497
498 custom_columns = (
499 ColumnSpec(renderer=names_renderer, header="Option", style="cyan"),
500 DescriptionColumn,
501 )
502
503 custom_group = Group(
504 "Settings",
505 help_formatter=DefaultFormatter(
506 column_specs=custom_columns,
507 table_spec=TableSpec(
508 show_header=True,
509 ),
510 ),
511 )
512
513 app = App()
514
515 @app.default
516 def main(
517 setting: Annotated[str, Parameter(group=custom_group, help="A configuration setting")] = "default",
518 ):
519 pass
520
521 with console.capture() as capture:
522 app.help_print(console=console)
523
524 actual = capture.get()
525 expected = dedent(
526 """\
527 Usage: test_help_customization [ARGS]
528
529 ╭─ Commands ─────────────────────────────────────────────────────────╮
530 │ --help (-h) Display this message and exit. │
531 │ --version Display application version. │
532 ╰────────────────────────────────────────────────────────────────────╯
533 ╭─ Settings ─────────────────────────────────────────────────────────╮
534 │ Option Description │
535 │ SETTING --setting A configuration setting [default: default] │
536 ╰────────────────────────────────────────────────────────────────────╯
537 """
538 )
539 assert actual == expected
540
541
542 class SimpleCustomFormatter:
543 """A simple custom formatter that wraps content in ASCII borders."""
544
545 def __call__(self, console, options, panel):
546 from rich.markdown import Markdown
547 from rich.text import Text
548
549 # Create a simple ASCII border around the panel
550 console.print("+" + "-" * 68 + "+")
551 console.print(f"| {panel.title:^66} |")
552 console.print("+" + "-" * 68 + "+")
553
554 # Handle description - convert to plain text if needed
555 if panel.description:
556 desc_text = ""
557 if hasattr(panel.description, "primary_renderable"):
558 pr = panel.description.primary_renderable
559 if isinstance(pr, Text):
560 desc_text = pr.plain
561 elif isinstance(pr, Markdown):
562 desc_text = pr.markup
563 else:
564 desc_text = str(pr)
565 else:
566 desc_text = str(panel.description)
567 if desc_text: # Only print if there's actual text
568 console.print(f"| {desc_text:<66} |")
569
570 for entry in panel.entries:
571 names = " ".join(entry.names) if entry.names else ""
572 shorts = " ".join(entry.shorts) if entry.shorts else ""
573 name_part = f"{names} {shorts}".strip()
574
575 # Handle entry description - convert to plain text if needed
576 desc = ""
577 if entry.description:
578 if hasattr(entry.description, "primary_renderable"):
579 pr = entry.description.primary_renderable
580 if isinstance(pr, Text):
581 desc = pr.plain
582 elif isinstance(pr, Markdown):
583 desc = pr.markup
584 else:
585 desc = str(pr)
586 else:
587 desc = str(entry.description)
588
589 # Add default value if present
590 if entry.default is not None:
591 if desc:
592 desc += f" [default: {entry.default}]"
593 else:
594 desc = f"[default: {entry.default}]"
595
596 # Format line based on panel format
597 if panel.format == "command":
598 # Commands: align with padding for readability
599 if desc:
600 # Pad the name part to a reasonable width for alignment
601 line = f"{name_part:<20} {desc}"
602 else:
603 line = name_part
604 else:
605 # Parameters: similar padding for consistency
606 if desc:
607 line = f"{name_part:<20} {desc}"
608 else:
609 line = name_part
610
611 # Use Text object to prevent wrapping
612 text_line = Text(f"| {line:<66} |", no_wrap=True)
613 console.print(text_line)
614 console.print("+" + "-" * 68 + "+")
615
616
617 def test_custom_help_formatter_basic(console: Console):
618 """Test that a custom HelpFormatter protocol implementation works."""
619 custom_group = Group(
620 "Custom Options",
621 help="These are custom options.",
622 help_formatter=SimpleCustomFormatter(),
623 )
624
625 app = App()
626
627 @app.default
628 def main(
629 verbose: Annotated[bool, Parameter(group=custom_group)] = False,
630 config: Annotated[str, Parameter(group=custom_group)] = "default.cfg",
631 ):
632 pass
633
634 with console.capture() as capture:
635 app.help_print(console=console)
636
637 actual = capture.get()
638 expected = dedent(
639 """\
640 Usage: test_help_customization [ARGS]
641
642 ╭─ Commands ─────────────────────────────────────────────────────────╮
643 │ --help (-h) Display this message and exit. │
644 │ --version Display application version. │
645 ╰────────────────────────────────────────────────────────────────────╯
646 +--------------------------------------------------------------------+
647 | Custom Options |
648 +--------------------------------------------------------------------+
649 | These are custom options. |
650 | VERBOSE --verbose --no-verbose [default: False] |
651 | CONFIG --config [default: default.cfg] |
652 +--------------------------------------------------------------------+
653 """
654 )
655 assert actual == expected
656
657
658 def test_custom_help_formatter_with_optional_methods(console: Console):
659 """Test custom formatter with optional render_usage and render_description methods."""
660
661 class FullCustomFormatter:
662 """Custom formatter with all optional methods."""
663
664 def render_usage(self, console, options, usage):
665 if usage:
666 console.print("[CUSTOM USAGE] ", usage)
667
668 def render_description(self, console, options, description):
669 if description:
670 console.print("[CUSTOM DESC]", description)
671
672 def __call__(self, console, options, panel):
673 from rich.markdown import Markdown
674 from rich.text import Text
675
676 console.print(f"=== {panel.title} ===")
677
678 if panel.description:
679 desc_text = ""
680 if hasattr(panel.description, "primary_renderable"):
681 pr = panel.description.primary_renderable
682 if isinstance(pr, Text):
683 desc_text = pr.plain
684 elif isinstance(pr, Markdown):
685 desc_text = pr.markup
686 else:
687 desc_text = str(pr)
688 else:
689 desc_text = str(panel.description)
690 if desc_text:
691 console.print(f" {desc_text}")
692
693 for entry in panel.entries:
694 names = " ".join(entry.names) if entry.names else ""
695 shorts = " ".join(entry.shorts) if entry.shorts else ""
696 if shorts:
697 names += " " + shorts
698
699 # Handle entry description - convert to plain text if needed
700 desc = ""
701 if entry.description:
702 if hasattr(entry.description, "primary_renderable"):
703 pr = entry.description.primary_renderable
704 if isinstance(pr, Text):
705 desc = pr.plain
706 elif isinstance(pr, Markdown):
707 desc = pr.markup
708 else:
709 desc = str(pr)
710 else:
711 desc = str(entry.description)
712
713 # Add default value if present
714 if entry.default is not None:
715 if desc:
716 desc += " "
717 desc += f"[default: {entry.default}]"
718
719 console.print(f" * {names}: {desc}", markup=False)
720
721 app = App(
722 help="This is a test application.",
723 help_formatter=FullCustomFormatter(),
724 )
725
726 custom_group = Group(
727 "Options",
728 help="Test options group.",
729 )
730
731 @app.default
732 def main(
733 verbose: Annotated[bool, Parameter(group=custom_group)] = False,
734 ):
735 pass
736
737 with console.capture() as capture:
738 app.help_print(console=console)
739
740 actual = capture.get()
741 expected = dedent(
742 """\
743 [CUSTOM USAGE] test_help_customization [ARGS]
744
745 [CUSTOM DESC]
746 This is a test application.
747
748 === Commands ===
749 * --help -h: Display this message and exit.
750 * --version: Display application version.
751 === Options ===
752 Test options group.
753 * VERBOSE --verbose --no-verbose: [default: False]
754 """
755 )
756 assert actual == expected
757
758
759 def test_multiple_groups_different_formatters(console: Console):
760 """Test multiple groups each using different formatter types."""
761 from cyclopts.help.formatters import PlainFormatter
762
763 # Custom formatter for first group
764 class PrefixFormatter:
765 def __call__(self, console, options, panel):
766 from rich.markdown import Markdown
767 from rich.text import Text
768
769 console.print(f">> {panel.title}")
770 for entry in panel.entries:
771 names = " ".join(entry.names) if entry.names else ""
772
773 # Handle entry description - convert to plain text if needed
774 desc = ""
775 if entry.description:
776 if hasattr(entry.description, "primary_renderable"):
777 pr = entry.description.primary_renderable
778 if isinstance(pr, Text):
779 desc = pr.plain
780 elif isinstance(pr, Markdown):
781 desc = pr.markup
782 else:
783 desc = str(pr)
784 else:
785 desc = str(entry.description)
786
787 # Add default value if present
788 if entry.default is not None:
789 if desc:
790 desc += f" [default: {entry.default}]"
791 else:
792 desc = f"[default: {entry.default}]"
793
794 console.print(f" -> {names}: {desc}", markup=False)
795
796 custom_group = Group(
797 "Custom Group",
798 help_formatter=PrefixFormatter(),
799 )
800
801 plain_group = Group(
802 "Plain Group",
803 help_formatter=PlainFormatter(),
804 )
805
806 rich_group = Group(
807 "Rich Group",
808 help_formatter=DefaultFormatter(
809 table_spec=TableSpec(border_style="green"),
810 ),
811 )
812
813 app = App()
814
815 @app.default
816 def main(
817 opt1: Annotated[str, Parameter(group=custom_group)] = "val1",
818 opt2: Annotated[str, Parameter(group=plain_group)] = "val2",
819 opt3: Annotated[str, Parameter(group=rich_group)] = "val3",
820 ):
821 pass
822
823 with console.capture() as capture:
824 app.help_print(console=console)
825
826 actual = capture.get()
827 expected = dedent(
828 """\
829 Usage: test_help_customization [ARGS]
830
831 ╭─ Commands ─────────────────────────────────────────────────────────╮
832 │ --help (-h) Display this message and exit. │
833 │ --version Display application version. │
834 ╰────────────────────────────────────────────────────────────────────╯
835 >> Custom Group
836 -> OPT1 --opt1: [default: val1]
837 Plain Group:
838 OPT2, --opt2: [default: val2]
839
840 ╭─ Rich Group ───────────────────────────────────────────────────────╮
841 │ OPT3 --opt3 [default: val3] │
842 ╰────────────────────────────────────────────────────────────────────╯
843 """
844 )
845 assert actual == expected
846
847
848 def test_custom_formatter_protocol_validation(console: Console):
849 """Test that any callable satisfying HelpFormatter protocol works."""
850
851 # Simple function that satisfies the protocol
852 def minimal_formatter(console, options, panel):
853 console.print(f"[{panel.title}]")
854 for entry in panel.entries:
855 names = " ".join(entry.names) if entry.names else ""
856 console.print(f" {names}")
857
858 custom_group = Group(
859 "Minimal",
860 help_formatter=minimal_formatter,
861 )
862
863 app = App()
864
865 @app.default
866 def main(
867 option: Annotated[str, Parameter(group=custom_group)] = "test",
868 ):
869 pass
870
871 with console.capture() as capture:
872 app.help_print(console=console)
873
874 actual = capture.get()
875 expected = dedent(
876 """\
877 Usage: test_help_customization [ARGS]
878
879 ╭─ Commands ─────────────────────────────────────────────────────────╮
880 │ --help (-h) Display this message and exit. │
881 │ --version Display application version. │
882 ╰────────────────────────────────────────────────────────────────────╯
883 [Minimal]
884 OPTION --option
885 """
886 )
887 assert actual == expected
888
889
890 def test_group_formatter_none_fallback(console: Console):
891 """Test that groups with formatter=None fall back to app's formatter."""
892 app = App(help_formatter=SimpleCustomFormatter())
893
894 # Group with explicit None formatter (should use app.app_formatter -> SimpleCustomFormatter)
895 default_group = Group("Fallback to App.help_formatter Group", help_formatter=None)
896
897 # Group with its own formatter
898 custom_group = Group("Explicitly DefaultFormatter Group", help_formatter="default")
899
900 @app.default
901 def main(
902 opt1: Annotated[str, Parameter(group=default_group)] = "default1",
903 opt2: Annotated[str, Parameter(group=custom_group)] = "custom1",
904 ):
905 pass
906
907 with console.capture() as capture:
908 app.help_print(console=console)
909
910 actual = capture.get()
911 expected = dedent(
912 """\
913 test_help_customization [ARGS]
914
915 +--------------------------------------------------------------------+
916 | Commands |
917 +--------------------------------------------------------------------+
918 | --help -h Display this message and exit. |
919 | --version Display application version. |
920 +--------------------------------------------------------------------+
921 ╭─ Explicitly DefaultFormatter Group ────────────────────────────────╮
922 │ OPT2 --opt2 [default: custom1] │
923 ╰────────────────────────────────────────────────────────────────────╯
924 +--------------------------------------------------------------------+
925 | Fallback to App.help_formatter Group |
926 +--------------------------------------------------------------------+
927 | OPT1 --opt1 [default: default1] |
928 +--------------------------------------------------------------------+
929 """
930 )
931 assert actual == expected
932
933
934 def test_custom_formatter_receives_correct_arguments(console: Console):
935 """Test that custom formatter receives correct console, options, and panel."""
936 captured_args = {}
937
938 class ValidatingFormatter:
939 def __call__(self, console, options, panel):
940 # Capture arguments for validation
941 captured_args["console"] = console
942 captured_args["options"] = options
943 captured_args["panel"] = panel
944
945 # Verify panel structure
946 assert hasattr(panel, "title")
947 assert hasattr(panel, "entries")
948 assert hasattr(panel, "description")
949
950 # Render something to verify it works
951 console.print(f"Panel: {panel.title}")
952 assert len(panel.entries) == 1
953 entry = panel.entries[0]
954 assert "test" in " ".join(entry.names).lower() and "param" in " ".join(entry.names).lower()
955 console.print(f" Entry: {' '.join(entry.names)}")
956
957 custom_group = Group(
958 "Validated Group",
959 help="Group with validation.",
960 help_formatter=ValidatingFormatter(),
961 )
962
963 app = App()
964
965 @app.default
966 def main(
967 test_param: Annotated[str, Parameter(group=custom_group)] = "value",
968 ):
969 pass
970
971 with console.capture() as capture:
972 app.help_print(console=console)
973
974 actual = capture.get()
975
976 # Verify captured arguments
977 assert captured_args["console"] is console
978 assert captured_args["options"] is not None
979 assert captured_args["panel"].title == "Validated Group"
980
981 # Check description - handle InlineText object
982 from rich.markdown import Markdown
983 from rich.text import Text
984
985 panel_desc = captured_args["panel"].description
986 if hasattr(panel_desc, "primary_renderable"):
987 pr = panel_desc.primary_renderable
988 if isinstance(pr, Text):
989 desc_text = pr.plain
990 elif isinstance(pr, Markdown):
991 desc_text = pr.markup
992 else:
993 desc_text = str(pr)
994 else:
995 desc_text = str(panel_desc)
996 assert desc_text == "Group with validation."
997
998 expected = dedent(
999 """\
1000 Usage: test_help_customization [ARGS]
1001
1002 ╭─ Commands ─────────────────────────────────────────────────────────╮
1003 │ --help (-h) Display this message and exit. │
1004 │ --version Display application version. │
1005 ╰────────────────────────────────────────────────────────────────────╯
1006 Panel: Validated Group
1007 Entry: TEST-PARAM --test-param
1008 """
1009 )
1010 assert actual == expected
1011
1012
1013 def test_plain_formatter_with_rich_text(console: Console):
1014 """Test PlainFormatter handling of Rich Text objects with .plain property."""
1015 from cyclopts.help.formatters import PlainFormatter
1016
1017 # Create a group with PlainFormatter
1018 plain_group = Group(
1019 "Plain Options",
1020 help="Test group with rich text",
1021 help_formatter=PlainFormatter(),
1022 )
1023
1024 app = App()
1025
1026 @app.default
1027 def main(
1028 option: Annotated[str, Parameter(group=plain_group, help="Test option")] = "value",
1029 ):
1030 pass
1031
1032 with console.capture() as capture:
1033 app.help_print(console=console)
1034
1035 actual = capture.get()
1036 # Commands group still uses default formatter, only Plain Options uses PlainFormatter
1037 expected = dedent(
1038 """\
1039 Usage: test_help_customization [ARGS]
1040
1041 ╭─ Commands ─────────────────────────────────────────────────────────╮
1042 │ --help (-h) Display this message and exit. │
1043 │ --version Display application version. │
1044 ╰────────────────────────────────────────────────────────────────────╯
1045 Plain Options:
1046 OPTION, --option: Test option [default: value]
1047
1048 """
1049 )
1050 assert actual == expected
1051
1052
1053 def test_plain_formatter_empty_panel(console: Console):
1054 """Test PlainFormatter skips empty panels."""
1055 from cyclopts.help import HelpPanel
1056 from cyclopts.help.formatters import PlainFormatter
1057
1058 formatter = PlainFormatter()
1059
1060 # Create an empty panel
1061 empty_panel = HelpPanel(
1062 title="Empty Panel", description="This panel has no entries", entries=[], format="parameter"
1063 )
1064
1065 # This should not output anything
1066 with console.capture() as capture:
1067 formatter(console, console.options, empty_panel)
1068
1069 assert capture.get() == ""
1070
1071
1072 def test_plain_formatter_no_title(console: Console):
1073 """Test PlainFormatter with panel without title."""
1074 from cyclopts.help import HelpEntry, HelpPanel
1075 from cyclopts.help.formatters import PlainFormatter
1076
1077 formatter = PlainFormatter()
1078
1079 # Create a panel without title
1080 panel = HelpPanel(
1081 title="",
1082 description="",
1083 entries=[
1084 HelpEntry(
1085 positive_names=("--option",),
1086 positive_shorts=(),
1087 description="Test option",
1088 default="value",
1089 )
1090 ],
1091 format="parameter",
1092 )
1093
1094 with console.capture() as capture:
1095 formatter(console, console.options, panel)
1096
1097 actual = capture.get()
1098 # When panel has no title, PlainFormatter still indents entries with 2 spaces
1099 expected = " --option: Test option [default: value]\n\n"
1100 assert actual == expected
1101
1102
1103 def test_plain_formatter_render_methods(console: Console):
1104 """Test PlainFormatter render_usage and render_description methods."""
1105 from cyclopts.help.formatters import PlainFormatter
1106
1107 app = App(
1108 help="Test application with plain formatter.",
1109 help_formatter=PlainFormatter(indent_width=4),
1110 )
1111
1112 @app.default
1113 def main(
1114 verbose: bool = False,
1115 ):
1116 pass
1117
1118 with console.capture() as capture:
1119 app.help_print(console=console)
1120
1121 actual = capture.get()
1122 expected = dedent(
1123 """\
1124 Usage: test_help_customization [ARGS]
1125
1126 Test application with plain formatter.
1127
1128 Commands:
1129 --help, -h: Display this message and exit.
1130 --version: Display application version.
1131
1132 Parameters:
1133 VERBOSE, --verbose, --no-verbose: [default: False]
1134
1135 """
1136 )
1137 assert actual == expected
1138
1139
1140 def test_plain_formatter_parameter_with_metadata(console: Console):
1141 """Test PlainFormatter with parameters having env_var, required."""
1142 from typing import Literal
1143
1144 from cyclopts.help.formatters import PlainFormatter
1145
1146 plain_group = Group(
1147 "Settings",
1148 help_formatter=PlainFormatter(),
1149 )
1150
1151 app = App()
1152
1153 @app.default
1154 def main(
1155 mode: Annotated[
1156 Literal["fast", "slow", "medium"], Parameter(group=plain_group, help="Operation mode", env_var="MODE")
1157 ],
1158 output: Annotated[
1159 str,
1160 Parameter(
1161 group=plain_group,
1162 help="Output file",
1163 required=True,
1164 ),
1165 ],
1166 ):
1167 pass
1168
1169 with console.capture() as capture:
1170 app.help_print(console=console)
1171
1172 actual = capture.get()
1173 # Commands group uses default formatter
1174 expected = dedent(
1175 """\
1176 Usage: test_help_customization MODE OUTPUT
1177
1178 ╭─ Commands ─────────────────────────────────────────────────────────╮
1179 │ --help (-h) Display this message and exit. │
1180 │ --version Display application version. │
1181 ╰────────────────────────────────────────────────────────────────────╯
1182 Settings:
1183 MODE, --mode: Operation mode [choices: fast, slow, medium] [env var:
1184 MODE] [required]
1185 OUTPUT, --output: Output file [required]
1186
1187 """
1188 )
1189 assert actual == expected
1190
1191
1192 def test_plain_formatter_command_multiple_names(console: Console):
1193 """Test PlainFormatter with command having multiple names."""
1194 from cyclopts.help.formatters import PlainFormatter
1195
1196 app = App(help_formatter=PlainFormatter())
1197
1198 @app.command(name=["list", "ls", "show"])
1199 def list_cmd():
1200 """List items."""
1201 pass
1202
1203 with console.capture() as capture:
1204 app.help_print(console=console)
1205
1206 actual = capture.get()
1207 expected = dedent(
1208 """\
1209 Usage: test_help_customization COMMAND
1210
1211 Commands:
1212 list: List items.
1213 ls
1214 show
1215 --help, -h: Display this message and exit.
1216 --version: Display application version.
1217
1218 """
1219 )
1220 assert actual == expected
1221
1222
1223 def test_plain_formatter_command_only_shorts(console: Console):
1224 """Test PlainFormatter with entries having only short names."""
1225 from cyclopts.help import HelpEntry, HelpPanel
1226 from cyclopts.help.formatters import PlainFormatter
1227
1228 formatter = PlainFormatter()
1229
1230 panel = HelpPanel(
1231 title="Options",
1232 description="",
1233 entries=[
1234 HelpEntry(
1235 positive_names=(),
1236 positive_shorts=("-v", "-vv"),
1237 description="Verbose output",
1238 )
1239 ],
1240 format="command",
1241 )
1242
1243 with console.capture() as capture:
1244 formatter(console, console.options, panel)
1245
1246 actual = capture.get()
1247 expected = dedent(
1248 """\
1249 Options:
1250 -v -vv: Verbose output
1251
1252 """
1253 )
1254 assert actual == expected
1255
1256
1257 def test_plain_formatter_rich_renderable(console: Console):
1258 """Test PlainFormatter with Rich renderable objects."""
1259 from rich.table import Table
1260
1261 from cyclopts.help import HelpEntry, HelpPanel
1262 from cyclopts.help.formatters import PlainFormatter
1263
1264 formatter = PlainFormatter()
1265
1266 # Create a Rich table as description
1267 table = Table(title="Test Table")
1268 table.add_column("Name")
1269 table.add_column("Value")
1270 table.add_row("test", "123")
1271
1272 panel = HelpPanel(
1273 title="Rich Content",
1274 description=table,
1275 entries=[
1276 HelpEntry(
1277 positive_names=("--option",),
1278 positive_shorts=(),
1279 description="Test",
1280 )
1281 ],
1282 format="parameter",
1283 )
1284
1285 # Note: PlainFormatter doesn't print panel description, only entries
1286 with console.capture() as capture:
1287 formatter(console, console.options, panel)
1288
1289 actual = capture.get()
1290 expected = dedent(
1291 """\
1292 Rich Content:
1293 --option: Test
1294
1295 """
1296 )
1297 assert actual == expected
1298
1299
1300 def test_plain_formatter_none_values(console: Console):
1301 """Test PlainFormatter handles None values gracefully."""
1302 from cyclopts.help import HelpEntry, HelpPanel
1303 from cyclopts.help.formatters import PlainFormatter
1304
1305 formatter = PlainFormatter()
1306
1307 panel = HelpPanel(
1308 title="Test",
1309 description=None,
1310 entries=[
1311 HelpEntry(
1312 positive_names=("--test",),
1313 positive_shorts=(),
1314 description=None, # No description
1315 default=None, # No default
1316 )
1317 ],
1318 format="parameter",
1319 )
1320
1321 with console.capture() as capture:
1322 formatter(console, console.options, panel)
1323
1324 actual = capture.get()
1325 expected = dedent(
1326 """\
1327 Test:
1328 --test
1329
1330 """
1331 )
1332 assert actual == expected
1333
1334
1335 def test_plain_formatter_fallback_str_conversion(console: Console):
1336 """Test PlainFormatter fallback to str() for unknown objects."""
1337 from cyclopts.help import HelpEntry, HelpPanel
1338 from cyclopts.help.formatters import PlainFormatter
1339
1340 class CustomObject:
1341 def __str__(self):
1342 return "Custom description"
1343
1344 formatter = PlainFormatter()
1345
1346 panel = HelpPanel(
1347 title="Custom",
1348 description=CustomObject(), # Object without __rich_console__ or .plain
1349 entries=[
1350 HelpEntry(
1351 positive_names=("--custom",),
1352 positive_shorts=(),
1353 description=CustomObject(),
1354 )
1355 ],
1356 format="parameter",
1357 )
1358
1359 with console.capture() as capture:
1360 formatter(console, console.options, panel)
1361
1362 actual = capture.get()
1363 expected = dedent(
1364 """\
1365 Custom:
1366 --custom: Custom description
1367
1368 """
1369 )
1370 assert actual == expected
1371
1372
1373 def test_description_renderer_newline_metadata():
1374 """Test DescriptionRenderer with newline_metadata=True."""
1375 from rich.console import Console
1376
1377 # Create a test entry with metadata
1378 entry = HelpEntry(
1379 positive_names=("verbose",),
1380 positive_shorts=("--verbose",),
1381 description="Enable verbose output",
1382 env_var=("VERBOSE", "VERB"),
1383 default="False",
1384 choices=("true", "false"),
1385 required=False,
1386 )
1387
1388 # Test with newline_metadata=True
1389 renderer = DescriptionRenderer(newline_metadata=True)
1390 result = renderer(entry)
1391
1392 # Render to string for testing
1393 console = Console(width=80, force_terminal=False, legacy_windows=False)
1394 with console.capture() as capture:
1395 console.print(result, end="")
1396
1397 output = capture.get()
1398
1399 # Check that metadata is on separate lines
1400 lines = output.strip().split("\n")
1401 assert len(lines) == 4, f"Expected 4 lines, got {len(lines)}: {lines}"
1402
1403 assert lines[0] == "Enable verbose output"
1404 assert lines[1] == "[choices: true, false]"
1405 assert lines[2] == "[env var: VERBOSE, VERB]"
1406 assert lines[3] == "[default: False]"
1407
1408
1409 def test_description_renderer_inline_metadata():
1410 """Test DescriptionRenderer with newline_metadata=False (default)."""
1411 from rich.console import Console
1412
1413 # Create a test entry with metadata
1414 entry = HelpEntry(
1415 positive_names=("verbose",),
1416 positive_shorts=("--verbose",),
1417 description="Enable verbose output",
1418 env_var=("VERBOSE",),
1419 default="False",
1420 required=False,
1421 )
1422
1423 # Test with newline_metadata=False (default)
1424 renderer = DescriptionRenderer(newline_metadata=False)
1425 result = renderer(entry)
1426
1427 # Render to string for testing
1428 console = Console(width=80, force_terminal=False, legacy_windows=False)
1429 with console.capture() as capture:
1430 console.print(result, end="")
1431
1432 output = capture.get()
1433
1434 # Check that metadata is inline (all on one line)
1435 lines = output.strip().split("\n")
1436 assert len(lines) == 1, f"Expected 1 line, got {len(lines)}: {lines}"
1437 assert "Enable verbose output [env var: VERBOSE] [default: False]" in output
1438
1439
1440 def test_with_newline_metadata_classmethod(console: Console):
1441 """Test DefaultFormatter.with_newline_metadata() classmethod."""
1442 app = App(help_formatter=DefaultFormatter.with_newline_metadata())
1443
1444 @app.default
1445 def main(
1446 verbose: Annotated[bool, Parameter(help="Enable verbose output", env_var="VERBOSE")] = False,
1447 config: Annotated[str, Parameter(help="Config file path", env_var=["CONFIG", "CFG"])] = "config.yaml",
1448 output: Annotated[str | None, Parameter(help="Output file")] = None,
1449 ):
1450 """Test application with newline metadata."""
1451 pass
1452
1453 with console.capture() as capture:
1454 app.help_print(console=console)
1455
1456 actual = capture.get()
1457
1458 # Check that metadata appears on separate lines
1459 assert "[env var: VERBOSE]" in actual
1460 assert "[default: False]" in actual
1461 assert "[env var: CONFIG, CFG]" in actual
1462 assert "[default: config.yaml]" in actual
1463
1464 # Check structure - metadata should be on its own line
1465 lines = actual.split("\n")
1466 for i, line in enumerate(lines):
1467 if "Enable verbose output" in line:
1468 # Next lines should contain the metadata
1469 assert "[env var: VERBOSE]" not in line, "Metadata should not be inline"
1470 # Find the env var line (should be within next few lines)
1471 found_env = False
1472 found_default = False
1473 for j in range(i + 1, min(i + 4, len(lines))):
1474 if "[env var: VERBOSE]" in lines[j]:
1475 found_env = True
1476 if "[default: False]" in lines[j]:
1477 found_default = True
1478 assert found_env, "Should find env var on separate line"
1479 assert found_default, "Should find default on separate line"
1480 break
1481
1482
1483 def test_default_formatter_regular_inline(console: Console):
1484 """Test that regular DefaultFormatter still shows metadata inline."""
1485 app = App(help_formatter=DefaultFormatter())
1486
1487 @app.default
1488 def main(
1489 verbose: Annotated[bool, Parameter(help="Enable verbose output", env_var="VERBOSE")] = False,
1490 ):
1491 """Test application with inline metadata."""
1492 pass
1493
1494 with console.capture() as capture:
1495 app.help_print(console=console)
1496
1497 actual = capture.get()
1498
1499 # Check that metadata is inline with description
1500 # Due to line wrapping in narrow console, we just check they're not on separate lines
1501 lines = actual.split("\n")
1502
1503 # Find the line with "Enable verbose output"
1504 for i, line in enumerate(lines):
1505 if "Enable verbose output" in line:
1506 # Check that env var is on same or immediately continued line (not indented on new line)
1507 if "[env var: VERBOSE]" in line:
1508 # It's inline on the same line
1509 pass
1510 elif i + 1 < len(lines) and "[env var: VERBOSE]" in lines[i + 1]:
1511 # It wrapped to next line - check it's not indented like newline mode
1512 next_line = lines[i + 1]
1513 # In newline mode it would start directly with bracket
1514 # In inline mode it continues at the column position
1515 assert not next_line.lstrip().startswith("[env var"), "Should not be on its own line like newline mode"
1516 break
1517 else:
1518 assert False, "Should find description in output"
1519
1520
1521 def test_description_renderer_no_extra_whitespace():
1522 """Test that DescriptionRenderer with newline_metadata doesn't add extra spaces."""
1523 from rich.console import Console
1524
1525 entry = HelpEntry(
1526 positive_names=("test",),
1527 description="Test description",
1528 env_var=("TEST_VAR",),
1529 default="value",
1530 )
1531
1532 renderer = DescriptionRenderer(newline_metadata=True)
1533 result = renderer(entry)
1534
1535 console = Console(width=80, force_terminal=False, legacy_windows=False)
1536 with console.capture() as capture:
1537 console.print(result, end="")
1538
1539 output = capture.get()
1540 lines = output.strip().split("\n")
1541
1542 # Check that metadata lines start with bracket (no indentation)
1543 for line in lines[1:]: # Skip the description line
1544 if line.strip(): # Skip empty lines
1545 # The line should start with "[metadata...]" with no indentation
1546 assert line.startswith("["), f"Line should not be indented: {repr(line)}"