Debian Codegraph @

tests/test_exceptions_rich.py

raw symbols SCIP
1 """Rich-formatted output tests for cyclopts exceptions."""
2
3 import re
4 from io import StringIO
5 from typing import Literal
6 from unittest.mock import Mock
7
8 import pytest
9 from rich.console import Console
10
11 import cyclopts
12 from cyclopts import (
13 Argument,
14 ArgumentOrderError,
15 CoercionError,
16 MissingArgumentError,
17 MixedArgumentError,
18 Parameter,
19 RepeatArgumentError,
20 RequiresEqualsError,
21 Token,
22 UnknownCommandError,
23 UnknownOptionError,
24 ValidationError,
25 )
26 from cyclopts._convert import convert
27 from cyclopts.panel import CycloptsPanel
28 from cyclopts.utils import default_name_transform
29
30 _ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
31
32
33 def _strip_ansi(s: str) -> str:
34 return _ANSI_RE.sub("", s)
35
36
37 def _provoke_coercion_error(*args, **kwargs) -> CoercionError:
38 """Provoke a CoercionError the way the production code path would, then
39 attach a mocked argument so the exception is fully populated.
40 """
41 mock_argument = Mock()
42 mock_argument.name = "mocked_argument_name"
43 mock_argument.parameter.name_transform = default_name_transform
44 kwargs.setdefault("name_transform", default_name_transform)
45 try:
46 convert(*args, **kwargs)
47 except CoercionError as e:
48 e.argument = mock_argument
49 e.verbose = False # strip the multi-line debug prefix so tests stay focused
50 return e
51 raise AssertionError("convert() did not raise CoercionError")
52
53
54 def _spans(text) -> list[tuple[str, str | None]]:
55 """Extract (text, style) pairs from a rich.text.Text object.
56
57 rich's Text stores styles as Spans that index into a flat plain string;
58 we slice the plain string by each span. Gaps between spans are emitted
59 as (text, None) entries so callers can see un-styled regions in order.
60 """
61 plain = text.plain
62 out: list[tuple[str, str | None]] = []
63 cursor = 0
64 for span in text.spans:
65 if span.start > cursor:
66 out.append((plain[cursor : span.start], None))
67 out.append((plain[span.start : span.end], str(span.style)))
68 cursor = span.end
69 if cursor < len(plain):
70 out.append((plain[cursor:], None))
71 return out
72
73
74 # ---------------------------------------------------------------------------
75 # __str__ unchanged: parity assertions on a few representative cases.
76 # ---------------------------------------------------------------------------
77
78
79 def test_str_parity_literal_with_suggestion():
80 e = _provoke_coercion_error(Literal["pishock", "openshock"], ["pisock"])
81 assert str(e) == (
82 'Invalid value "pisock" for MOCKED_ARGUMENT_NAME. Choose from: "pishock", "openshock". Did you mean "pishock"?'
83 )
84
85
86 def test_str_parity_literal_keyword_non_cli_source():
87 e = _provoke_coercion_error(
88 Literal["foo", "bar", 3],
89 [Token(keyword="--MY-KEYWORD", value="invalid-choice", source="TEST")],
90 )
91 assert str(e) == 'Invalid value "invalid-choice" for --MY-KEYWORD from TEST. Choose from: "foo", "bar", 3.'
92
93
94 def test_str_parity_fallback_int_conversion():
95 e = _provoke_coercion_error(int, ["abc"])
96 assert str(e) == 'Invalid value for MOCKED_ARGUMENT_NAME: unable to convert "abc" into int.'
97
98
99 def test_str_parity_msg_override_no_keyword():
100 e = CoercionError(msg="custom error")
101 assert str(e) == "custom error"
102
103
104 def test_str_parity_msg_override_with_keyword():
105 e = CoercionError(msg="custom error", token=Token(keyword="--flag", value="x"))
106 assert str(e) == "Invalid value for --flag: custom error"
107
108
109 # ---------------------------------------------------------------------------
110 # __rich__ spans: per-branch verification.
111 # ---------------------------------------------------------------------------
112
113
114 def test_rich_literal_branch_styles_value_name_choices_suggestion():
115 e = _provoke_coercion_error(Literal["pishock", "openshock"], ["pisock"])
116 spans = _spans(e.__rich__())
117
118 # Value, name, each choice, and the suggestion are styled.
119 assert ("pisock", "bold red") in spans
120 assert ("MOCKED_ARGUMENT_NAME", "bold") in spans
121 assert ('"pishock"', "cyan") in spans
122 assert ('"openshock"', "cyan") in spans
123 assert ("pishock", "bold green") in spans
124
125
126 def test_rich_literal_branch_no_suggestion_omits_did_you_mean():
127 e = _provoke_coercion_error(Literal["pishock", "openshock"], ["auth"])
128 rich_text = e.__rich__()
129 assert "Did you mean" not in rich_text.plain
130 styles = [str(s.style) for s in rich_text.spans]
131 assert "bold green" not in styles
132
133
134 def test_rich_literal_branch_dims_non_cli_source():
135 e = _provoke_coercion_error(
136 Literal["foo", "bar"],
137 [Token(value="bad", source="CONFIG")],
138 )
139 spans = _spans(e.__rich__())
140 assert (" from CONFIG", "dim") in spans
141
142
143 def test_rich_literal_branch_uses_keyword_as_name_when_present():
144 e = _provoke_coercion_error(
145 Literal["foo", "bar"],
146 [Token(keyword="--my-flag", value="bad")],
147 )
148 spans = _spans(e.__rich__())
149 assert ("--my-flag", "bold") in spans
150 # MOCKED_ARGUMENT_NAME should NOT appear when keyword is present.
151 plain = e.__rich__().plain
152 assert "MOCKED_ARGUMENT_NAME" not in plain
153
154
155 def test_rich_fallback_branch_styles_value_and_name():
156 e = _provoke_coercion_error(int, ["abc"])
157 spans = _spans(e.__rich__())
158 assert ("MOCKED_ARGUMENT_NAME", "bold") in spans
159 assert ("abc", "bold red") in spans
160
161
162 def test_rich_fallback_branch_dims_non_cli_source():
163 e = _provoke_coercion_error(int, [Token(value="abc", source="ENV")])
164 spans = _spans(e.__rich__())
165 assert (" from ENV", "dim") in spans
166 assert ("abc", "bold red") in spans
167
168
169 def test_rich_msg_override_yields_unstyled():
170 e = CoercionError(msg="custom error", token=Token(keyword="--flag", value="x"))
171 rich_text = e.__rich__()
172 assert rich_text.plain == "Invalid value for --flag: custom error"
173 # No styled spans -- override stays plain.
174 assert all(s.style is None or str(s.style) == "" for s in rich_text.spans)
175
176
177 # ---------------------------------------------------------------------------
178 # msg styling: Text instances opt into styling; plain str stays literal (#813).
179 # ---------------------------------------------------------------------------
180
181
182 def test_msg_text_instance_preserved_in_rich():
183 from rich.text import Text
184
185 from cyclopts import CycloptsError
186 from cyclopts.exceptions import STYLE_NAME, STYLE_OFFENDING_VALUE
187
188 t = Text("Invalid value ")
189 t.append("foo", style=STYLE_OFFENDING_VALUE)
190 t.append(" for ")
191 t.append("--name", style=STYLE_NAME)
192 e = CycloptsError(msg=t)
193 rich_text = e.__rich__()
194 assert rich_text.plain == "Invalid value foo for --name"
195 spans = _spans(rich_text)
196 assert ("foo", "bold red") in spans
197 assert ("--name", "bold") in spans
198
199
200 def test_msg_text_from_markup_in_coercion_error_with_keyword():
201 from rich.text import Text
202
203 e = CoercionError(msg=Text.from_markup("[bold red]bad[/]"), token=Token(keyword="--flag", value="x"))
204 rich_text = e.__rich__()
205 assert rich_text.plain == "Invalid value for --flag: bad"
206 spans = _spans(rich_text)
207 assert ("bad", "bold red") in spans
208
209
210 def test_msg_plain_string_with_brackets_renders_literally():
211 """Backwards-compat: strings are never parsed as Rich markup."""
212 from cyclopts import CycloptsError
213
214 e = CycloptsError(msg="error in [section] config")
215 assert str(e) == "error in [section] config"
216 rich_text = e.__rich__()
217 assert rich_text.plain == "error in [section] config"
218
219
220 def test_msg_plain_string_with_no_markup_unchanged():
221 from cyclopts import CycloptsError
222
223 e = CycloptsError(msg="just a plain message")
224 assert str(e) == "just a plain message"
225 rich_text = e.__rich__()
226 assert rich_text.plain == "just a plain message"
227 # No styled spans -- nothing to highlight.
228 assert all(s.style is None or str(s.style) == "" for s in rich_text.spans)
229
230
231 def test_style_constants_match_builtin_palette():
232 """Public style constants should match what the built-in messages emit."""
233 from cyclopts.exceptions import (
234 STYLE_NAME,
235 STYLE_OFFENDING_VALUE,
236 STYLE_SOURCE,
237 STYLE_SUGGESTION,
238 STYLE_VALID_CHOICE,
239 )
240
241 assert STYLE_OFFENDING_VALUE == "bold red"
242 assert STYLE_NAME == "bold"
243 assert STYLE_VALID_CHOICE == "cyan"
244 assert STYLE_SUGGESTION == "bold green"
245 assert STYLE_SOURCE == "dim"
246
247
248 # ---------------------------------------------------------------------------
249 # ANSI smoke test: end-to-end render through CycloptsPanel.
250 # ---------------------------------------------------------------------------
251
252
253 def test_panel_renders_rich_styles_when_color_enabled(rich_console):
254 """End-to-end: CycloptsPanel + truecolor console emits ANSI for styled spans."""
255 e = _provoke_coercion_error(Literal["pishock", "openshock"], ["pisock"])
256 buf = StringIO()
257 rich_console.file = buf
258 rich_console.print(CycloptsPanel(e))
259 output = buf.getvalue()
260
261 # ANSI escapes are present -- the panel didn't flatten styling away.
262 assert "\x1b[" in output
263 # Plain text (with ANSI stripped) is intact end-to-end.
264 plain = _strip_ansi(output)
265 assert 'Invalid value "pisock"' in plain
266 assert 'Did you mean "pishock"?' in plain
267
268
269 def test_panel_renders_plain_when_color_disabled(console):
270 """Existing snapshot-style test: color_system=None strips styles cleanly."""
271 e = _provoke_coercion_error(Literal["pishock", "openshock"], ["pisock"])
272 buf = StringIO()
273 console.file = buf
274 console.print(CycloptsPanel(e))
275 output = buf.getvalue()
276
277 assert "\x1b[" not in output
278 assert 'Invalid value "pisock" for MOCKED_ARGUMENT_NAME' in output
279 assert 'Did you mean "pishock"?' in output
280
281
282 # ---------------------------------------------------------------------------
283 # UnknownCommandError
284 # ---------------------------------------------------------------------------
285
286
287 def _provoke_unknown_command(commands: list[str], typed: str) -> UnknownCommandError:
288 """Build an app, register `commands`, then run with `typed` to provoke the error."""
289 app = cyclopts.App(result_action="return_value")
290 for name in commands:
291 app.command(name=name)(lambda: None)
292 with pytest.raises(UnknownCommandError) as ei:
293 app.parse_args(typed, exit_on_error=False)
294 e = ei.value
295 e.verbose = False
296 return e
297
298
299 def test_unknown_command_str_parity_with_suggestion_and_list():
300 e = _provoke_unknown_command(["mad-command"], "bad-command")
301 assert str(e) == 'Unknown command "bad-command". Did you mean "mad-command"? Available commands: mad-command.'
302
303
304 def test_unknown_command_str_parity_ellipsis():
305 e = _provoke_unknown_command([f"cmd{i}" for i in range(1, 10)], "cmd")
306 assert str(e) == (
307 'Unknown command "cmd". Did you mean "cmd9"? '
308 "Available commands: cmd1, cmd2, cmd3, cmd4, cmd5, cmd6, cmd7, cmd8, ..."
309 )
310
311
312 def test_unknown_command_str_parity_no_suggestion():
313 e = _provoke_unknown_command(["foo"], "zzz")
314 assert str(e) == 'Unknown command "zzz". Available commands: foo.'
315
316
317 def test_unknown_command_rich_styles_token_suggestion_and_commands():
318 e = _provoke_unknown_command(["mad-command", "other-command"], "bad-command")
319 spans = _spans(e.__rich__())
320 assert ("bad-command", "bold red") in spans
321 assert ("mad-command", "bold green") in spans
322 # Both commands are listed and styled.
323 assert ("mad-command", "cyan") in spans
324 assert ("other-command", "cyan") in spans
325
326
327 def test_unknown_command_rich_no_suggestion_omits_did_you_mean():
328 e = _provoke_unknown_command(["foo"], "zzz")
329 rich_text = e.__rich__()
330 assert "Did you mean" not in rich_text.plain
331 styles = [str(s.style) for s in rich_text.spans]
332 assert "bold green" not in styles
333
334
335 def test_unknown_command_rich_ellipsis_truncates_styled_list():
336 e = _provoke_unknown_command([f"cmd{i}" for i in range(1, 10)], "cmd")
337 spans = _spans(e.__rich__())
338 # First 8 commands appear as cyan-styled spans; cmd9 does NOT (truncated).
339 cyan_texts = [text for text, style in spans if style == "cyan"]
340 assert "cmd1" in cyan_texts
341 assert "cmd8" in cyan_texts
342 assert "cmd9" not in cyan_texts
343 # Ellipsis tail is plain.
344 plain = e.__rich__().plain
345 assert plain.endswith(", ...")
346
347
348 # ---------------------------------------------------------------------------
349 # UnknownCommandError synonym suggestions
350 # ---------------------------------------------------------------------------
351
352
353 def _provoke_unknown_with_synonyms(commands: list[tuple[str, list[str]]], typed: str) -> UnknownCommandError:
354 """Build an app where each command optionally declares synonyms, then provoke an unknown-command error.
355
356 `commands` is a list of (name, synonyms) pairs.
357 """
358 app = cyclopts.App(result_action="return_value")
359 for name, synonyms in commands:
360 app.command(name=name, synonym=synonyms)(lambda: None)
361 with pytest.raises(UnknownCommandError) as ei:
362 app.parse_args(typed, exit_on_error=False)
363 e = ei.value
364 e.verbose = False
365 return e
366
367
368 def test_unknown_command_synonym_single_match():
369 """A single declared synonym yields a 'Did you mean...' suggestion for that command."""
370 e = _provoke_unknown_with_synonyms([("uninstall", ["remove", "rm"])], "remove")
371 assert str(e) == 'Unknown command "remove". Did you mean "uninstall"? Available commands: uninstall.'
372
373
374 def test_unknown_command_synonym_rich_styles_suggestion():
375 """The suggested command name is styled as a suggestion (bold green)."""
376 e = _provoke_unknown_with_synonyms([("uninstall", ["remove"])], "remove")
377 spans = _spans(e.__rich__())
378 assert ("remove", "bold red") in spans
379 assert ("uninstall", "bold green") in spans
380
381
382 def test_unknown_command_synonym_two_targets():
383 """When two commands declare the same synonym, both are suggested with 'or'."""
384 e = _provoke_unknown_with_synonyms(
385 [("uninstall", ["remove"]), ("delete", ["remove"])],
386 "remove",
387 )
388 assert str(e) == (
389 'Unknown command "remove". Did you mean "uninstall" or "delete"? Available commands: uninstall, delete.'
390 )
391
392
393 def test_unknown_command_synonym_three_targets_uses_oxford_or():
394 """Three or more matches use comma separation and a final ', or'."""
395 e = _provoke_unknown_with_synonyms(
396 [("uninstall", ["remove"]), ("delete", ["remove"]), ("purge", ["remove"])],
397 "remove",
398 )
399 plain = e.__rich__().plain
400 assert 'Did you mean "uninstall", "delete", or "purge"?' in plain
401
402
403 def test_unknown_command_synonym_falls_back_to_difflib_when_no_match():
404 """When the token does not match any synonym, the existing difflib path still runs."""
405 e = _provoke_unknown_with_synonyms([("mad-command", ["nope"])], "bad-command")
406 # difflib fuzzy match still kicks in because no synonym matched.
407 assert 'Did you mean "mad-command"?' in str(e)
408
409
410 def test_unknown_command_synonym_does_not_register_as_runnable():
411 """A synonym must not make the command runnable under that name."""
412 app = cyclopts.App(result_action="return_value")
413 app.command(name="uninstall", synonym=["remove"])(lambda: None)
414 # The synonym is NOT in the registered commands dict.
415 assert "remove" not in app
416 assert "uninstall" in app
417
418
419 def test_unknown_command_synonym_shadowed_by_real_command():
420 """If a real command shares a name with another command's synonym, the real command wins."""
421 real_called = []
422 synonym_called = []
423
424 app = cyclopts.App(result_action="return_value")
425
426 @app.command(name="remove")
427 def remove_cmd():
428 real_called.append(True)
429
430 @app.command(name="uninstall", synonym=["remove"])
431 def uninstall_cmd():
432 synonym_called.append(True)
433
434 app("remove", exit_on_error=False)
435 assert real_called == [True]
436 assert synonym_called == []
437
438
439 def test_unknown_command_synonym_no_match_no_suggestion():
440 """If neither synonym nor difflib finds anything, no 'Did you mean' is emitted."""
441 e = _provoke_unknown_with_synonyms([("uninstall", ["remove"])], "totally-different-zzz")
442 assert "Did you mean" not in str(e)
443
444
445 def test_unknown_command_synonym_dedupes_across_aliases():
446 """A subapp registered under multiple names (via alias) should only be suggested once."""
447 app = cyclopts.App(result_action="return_value")
448 app.command(name="uninstall", alias=["delete-it", "rm-it"], synonym=["remove"])(lambda: None)
449 with pytest.raises(UnknownCommandError) as ei:
450 app.parse_args("remove", exit_on_error=False)
451 e = ei.value
452 e.verbose = False
453 plain = e.__rich__().plain
454 # Suggestion mentions the primary name once, not all three aliases.
455 assert 'Did you mean "uninstall"?' in plain
456 assert "delete-it" not in plain.split("Available commands:")[0]
457 assert "rm-it" not in plain.split("Available commands:")[0]
458
459
460 def test_synonym_not_in_help_output():
461 """Synonyms should not appear in --help output."""
462 buf = StringIO()
463 console = Console(file=buf, force_terminal=False, width=200)
464 app = cyclopts.App(name="myapp", result_action="return_value", console=console)
465 app.command(name="uninstall", synonym=["remove", "rm"])(lambda: None)
466 app.help_print(console=console)
467 output = _strip_ansi(buf.getvalue())
468 assert "uninstall" in output
469 assert "remove" not in output
470 assert re.search(r"\brm\b", output) is None
471
472
473 # ---------------------------------------------------------------------------
474 # Phase 4: UnknownOptionError
475 # ---------------------------------------------------------------------------
476
477
478 def _provoke_app_exception(exc_cls, app: cyclopts.App, argv: str):
479 """Run app and capture an exception of type `exc_cls`."""
480 with pytest.raises(exc_cls) as ei:
481 app.parse_args(argv, exit_on_error=False)
482 e = ei.value
483 e.verbose = False
484 return e
485
486
487 def _make_unknown_option_app() -> cyclopts.App:
488 """An app where `--no-my-flag` is unknown but `--my-flag` is a close match."""
489 app = cyclopts.App(result_action="return_value", default_parameter=Parameter(negative=""))
490
491 @app.default
492 def main(my_flag: bool = True):
493 pass
494
495 return app
496
497
498 def test_unknown_option_str_parity_cli_with_suggestion():
499 e = _provoke_app_exception(UnknownOptionError, _make_unknown_option_app(), "--no-my-flag")
500 assert str(e) == "Unknown option: --no-my-flag. Did you mean --my-flag?"
501
502
503 def test_unknown_option_rich_styles_token_and_suggestion():
504 e = _provoke_app_exception(UnknownOptionError, _make_unknown_option_app(), "--no-my-flag")
505 spans = _spans(e.__rich__())
506 assert ("--no-my-flag", "bold red") in spans
507 assert ("--my-flag", "bold green") in spans
508
509
510 def test_unknown_option_rich_dims_non_cli_source():
511 e = UnknownOptionError(
512 token=Token(keyword="--bogus", value="x", source="ENV"),
513 argument_collection=Mock(__iter__=lambda self: iter([])),
514 )
515 e.verbose = False
516 spans = _spans(e.__rich__())
517 assert ("--bogus", "bold red") in spans
518 assert (" from ENV", "dim") in spans
519
520
521 # ---------------------------------------------------------------------------
522 # Phase 5: MissingArgumentError + ConsumeMultipleError
523 # ---------------------------------------------------------------------------
524
525
526 def test_missing_argument_str_parity_with_command_chain():
527 app = cyclopts.App(result_action="return_value")
528
529 @app.command
530 def foo(bar: int):
531 pass
532
533 e = _provoke_app_exception(MissingArgumentError, app, "foo")
534 assert str(e) == 'Command "foo" parameter --bar requires an argument.'
535
536
537 def test_missing_argument_rich_styles_command_and_param():
538 app = cyclopts.App(result_action="return_value")
539
540 @app.command
541 def foo(bar: int):
542 pass
543
544 e = _provoke_app_exception(MissingArgumentError, app, "foo")
545 spans = _spans(e.__rich__())
546 assert ("foo", "bold") in spans
547 assert ("--bar", "bold") in spans
548
549
550 def test_missing_argument_rich_styles_did_you_mean_suggestion_and_typo():
551 """`Did you mean --foo instead of --boo?` -- correct is suggestion, typo is value."""
552 app = cyclopts.App(result_action="return_value")
553
554 @app.command
555 def some_command(*, foo: int):
556 pass
557
558 e = _provoke_app_exception(MissingArgumentError, app, "some-command --boo 123")
559 spans = _spans(e.__rich__())
560 # Correct option (suggestion) is bold green; user's typo is bold red.
561 assert ("--foo", "bold green") in spans
562 assert ("--boo", "bold red") in spans
563
564
565 # ---------------------------------------------------------------------------
566 # Phase 6: ValidationError
567 # ---------------------------------------------------------------------------
568
569
570 def test_validation_error_str_parity_with_argument_and_source():
571 """Mirrors test_exceptions_validation_error_non_cli_single_keyword."""
572
573 def positive_validator(type_, value):
574 if value <= 0:
575 raise ValueError("Value must be positive.")
576
577 argument = Argument(
578 hint=int,
579 parameter=Parameter(name=("--bar",), validator=positive_validator),
580 tokens=[Token(value="-2", source="test")],
581 )
582 with pytest.raises(ValidationError) as ei:
583 argument.convert_and_validate()
584 e = ei.value
585 e.verbose = False
586
587 assert str(e) == 'Invalid value "-2" for BAR provided by test. Value must be positive.'
588
589
590 def test_validation_error_rich_styles_value_name_source_and_appended_message():
591 def positive_validator(type_, value):
592 if value <= 0:
593 raise ValueError("Value must be positive.")
594
595 argument = Argument(
596 hint=int,
597 parameter=Parameter(name=("--bar",), validator=positive_validator),
598 tokens=[Token(value="-2", source="test")],
599 )
600 with pytest.raises(ValidationError) as ei:
601 argument.convert_and_validate()
602 e = ei.value
603 e.verbose = False
604 spans = _spans(e.__rich__())
605
606 assert ("-2", "bold red") in spans
607 assert ("BAR", "bold") in spans
608 assert (" provided by test", "dim") in spans
609 # Appended exception_message stays plain.
610 assert "Value must be positive." in e.__rich__().plain
611
612
613 # ---------------------------------------------------------------------------
614 # Phase 7: small one-line classes
615 # ---------------------------------------------------------------------------
616
617
618 def test_repeat_argument_error_rich_styles_keyword():
619 app = cyclopts.App(result_action="return_value")
620
621 @app.default
622 def main(a):
623 pass
624
625 e = _provoke_app_exception(RepeatArgumentError, app, "--a=1 --a=2")
626 assert str(e) == "Parameter --a specified multiple times."
627 spans = _spans(e.__rich__())
628 assert ("--a", "bold") in spans
629
630
631 def test_requires_equals_error_rich_styles_keyword_twice():
632 e = RequiresEqualsError(
633 keyword="--name",
634 argument=Mock(name="--name"),
635 )
636 e.verbose = False
637 assert str(e) == "Parameter --name requires a value assigned with `=`. Use --name=VALUE."
638 spans = _spans(e.__rich__())
639 # The keyword appears twice in the message, both styled bold.
640 bold_names = [text for text, style in spans if style == "bold"]
641 assert bold_names == ["--name", "--name"]
642
643
644 def test_mixed_argument_error_rich_styles_display_name():
645 app = cyclopts.App(result_action="return_value")
646
647 @app.default
648 def foo(bar: int | dict):
649 pass
650
651 e = _provoke_app_exception(MixedArgumentError, app, "--bar 5 --bar.baz fizz")
652 assert str(e) == "Cannot supply keyword & non-keyword arguments to --bar."
653 spans = _spans(e.__rich__())
654 assert ("--bar", "bold") in spans
655
656
657 def test_argument_order_error_singular_str_parity_and_styling():
658 app = cyclopts.App(result_action="return_value")
659
660 @app.command
661 def foo(a, b, c):
662 pass
663
664 e = _provoke_app_exception(ArgumentOrderError, app, "foo --b=5 1 2")
665 assert str(e) == (
666 'Cannot specify token "2" positionally for parameter c due to '
667 "previously specified keyword --b. --b must either be passed positionally, "
668 'or "2" must be passed as a keyword to --c.'
669 )
670 spans = _spans(e.__rich__())
671 # Token appears twice (bold red), display_name once (bold), prior keyword twice (bold),
672 # argument.name once (bold).
673 red_tokens = [text for text, style in spans if style == "bold red"]
674 assert red_tokens == ["2", "2"]
675 bold_names = [text for text, style in spans if style == "bold"]
676 # display_name "c", prior "--b" twice, argument.name "--c"
677 assert bold_names == ["c", "--b", "--b", "--c"]
678
679
680 def test_argument_order_error_plural_styles_list_literal():
681 app = cyclopts.App(result_action="return_value")
682
683 @app.command
684 def foo(a, b, c):
685 pass
686
687 e = _provoke_app_exception(ArgumentOrderError, app, "foo --a=1 --b=5 3")
688 spans = _spans(e.__rich__())
689 # The list literal "['--a', '--b']" appears twice, styled as a single bold span each time.
690 bold_strs = [text for text, style in spans if style == "bold"]
691 assert bold_strs.count("['--a', '--b']") == 2