Debian Codegraph @

tests/test_bind_basic.py

raw symbols SCIP
1 from functools import partial
2 from typing import Annotated, Any
3
4 import pytest
5
6 from cyclopts import Parameter
7 from cyclopts.exceptions import (
8 ArgumentOrderError,
9 CoercionError,
10 MissingArgumentError,
11 RepeatArgumentError,
12 UnknownCommandError,
13 UnknownOptionError,
14 UnusedCliTokensError,
15 )
16 from cyclopts.group import Group
17
18
19 def test_parse_known_args(app):
20 @app.command
21 def foo(a: int, b: int):
22 pass
23
24 command, _, unused_tokens, ignored = app.parse_known_args("foo 1 2 --bar 100")
25 assert ignored == {}
26 assert command == foo
27 assert unused_tokens == ["--bar", "100"]
28
29
30 @pytest.mark.parametrize(
31 "cmd_str",
32 [
33 "foo 1 2 3",
34 "foo 1 2 --c=3",
35 "foo --a 1 --b 2 --c 3",
36 "foo --c 3 --b=2 --a 1",
37 ],
38 )
39 def test_basic_1(app, cmd_str, assert_parse_args):
40 @app.command
41 def foo(a: int, b: int, c: int):
42 pass
43
44 assert_parse_args(foo, cmd_str, 1, 2, 3)
45
46
47 @pytest.mark.parametrize(
48 "cmd_str",
49 [
50 "foo 1 2 3 --d 10 --some-flag",
51 "foo --some-flag 1 --b=2 --c 3 --d 10",
52 "foo 1 2 --some-flag 3 --d 10",
53 ],
54 )
55 def test_basic_2(app, cmd_str, assert_parse_args):
56 @app.command
57 def foo(a: int, b: int, c: int, d: int = 5, *, some_flag: bool = False):
58 pass
59
60 assert_parse_args(foo, cmd_str, 1, 2, 3, d=10, some_flag=True)
61
62
63 def test_functools_partial_default(app, assert_parse_args):
64 def foo(a: int, b: int, c: int):
65 pass
66
67 foo_partial = partial(foo, c=3)
68 app.default(foo_partial)
69
70 assert_parse_args(foo_partial, "1 2", a=1, b=2)
71
72
73 def test_functools_partial_command(app, assert_parse_args):
74 def foo(a: int, b: int, c: int):
75 pass
76
77 foo_partial = partial(foo, c=3)
78 app.command(foo_partial)
79
80 assert_parse_args(foo_partial, "foo 1 2", a=1, b=2)
81
82
83 def test_basic_allow_hyphen_or_underscore(app, assert_parse_args):
84 @app.default
85 def default(foo_bar):
86 pass
87
88 assert_parse_args(default, "--foo-bar=bazz", "bazz")
89 assert_parse_args(default, "--foo_bar=bazz", "bazz")
90
91
92 def test_out_of_order_mixed_positional_or_keyword(app, assert_parse_args):
93 @app.command
94 def foo(a, b, c):
95 pass
96
97 with pytest.raises(ArgumentOrderError):
98 app.parse_args("foo --b=5 1 2", print_error=False, exit_on_error=False)
99
100
101 def test_command_rename(app, assert_parse_args):
102 @app.command(name="bar")
103 def foo():
104 pass
105
106 assert_parse_args(foo, "bar")
107
108
109 def test_command_delete(app, assert_parse_args):
110 @app.command
111 def foo():
112 pass
113
114 del app["foo"]
115
116 with pytest.raises(UnknownCommandError):
117 assert_parse_args(foo, "foo")
118
119
120 def test_command_multiple_alias(app, assert_parse_args):
121 @app.command(name=["bar", "baz"])
122 def foo():
123 pass
124
125 assert_parse_args(foo, "bar")
126 assert_parse_args(foo, "baz")
127
128
129 @pytest.mark.parametrize(
130 "cmd_str",
131 [
132 "foo --age 10",
133 "foo --duration 10",
134 "foo -a 10",
135 ],
136 )
137 def test_multiple_names(app, cmd_str, assert_parse_args):
138 @app.command
139 def foo(age: Annotated[int, Parameter(name=["--age", "--duration", "-a"])]):
140 pass
141
142 assert_parse_args(foo, cmd_str, age=10)
143
144
145 @pytest.mark.parametrize(
146 "cmd_str",
147 [
148 "foo --age 10",
149 "foo --duration 10",
150 "foo -a 10",
151 ],
152 )
153 def test_alias(app, cmd_str, assert_parse_args):
154 @app.command
155 def foo(age: Annotated[int, Parameter(alias=["--duration", "-a"])]):
156 pass
157
158 assert_parse_args(foo, cmd_str, age=10)
159
160
161 @pytest.mark.parametrize(
162 "cmd_str",
163 [
164 "foo --age 10",
165 "foo --duration 10",
166 "foo -a 10",
167 ],
168 )
169 def test_name_and_alias(app, cmd_str, assert_parse_args):
170 """Weird use-case, but should be handled."""
171
172 @app.command
173 def foo(age: Annotated[int, Parameter(name="--age", alias=["--duration", "-a"])]):
174 pass
175
176 assert_parse_args(foo, cmd_str, age=10)
177
178
179 @pytest.mark.parametrize(
180 "cmd_str",
181 [
182 "--job-name foo",
183 "-j foo",
184 ],
185 )
186 def test_short_name_j(app, cmd_str, assert_parse_args):
187 """
188 "-j" previously didn't work as a short-name because it's a valid complex value.
189
190 https://github.com/BrianPugh/cyclopts/issues/328
191 """
192
193 @app.default
194 def main(
195 *,
196 job_name: Annotated[str, Parameter(name=["--job-name", "-j"], negative=False)],
197 ):
198 pass
199
200 assert_parse_args(main, cmd_str, job_name="foo")
201
202
203 def test_short_flag_combining(app, assert_parse_args):
204 @app.default
205 def main(
206 foo: Annotated[bool, Parameter(name=("--foo", "-f"))] = False,
207 bar: Annotated[bool, Parameter(name=("--bar", "-b"))] = False,
208 my_list: Annotated[list | None, Parameter(negative=("--empty-my-list", "-e"))] = None,
209 ):
210 pass
211
212 # Note: ``my_list`` is explicitly getting an empty list.
213 assert_parse_args(main, "-bfe", foo=True, bar=True, my_list=[])
214
215
216 def test_short_flag_combining_unknown_flag(app, assert_parse_args):
217 @app.default
218 def main(
219 foo: Annotated[bool, Parameter(name=("--foo", "-f"))] = False,
220 bar: Annotated[bool, Parameter(name=("--bar", "-b"))] = False,
221 ):
222 pass
223
224 with pytest.raises(UnknownOptionError):
225 # The flag "-e" is unknown
226 app("-be", exit_on_error=False)
227
228
229 def test_short_flag_combining_with_short_option(app, assert_parse_args):
230 @app.default
231 def main(
232 *,
233 foo: Annotated[bool, Parameter(name=("--foo", "-f"))] = False,
234 bar: Annotated[str, Parameter(name=("--bar", "-b"))],
235 ):
236 pass
237
238 # With GNU-style support, -fb is now valid: -f (flag) + -b (needs value from next token)
239 # Since no next token exists, should raise MissingArgumentError
240 with pytest.raises(MissingArgumentError):
241 app("-fb", exit_on_error=False)
242
243 # But -fb with a value should work
244 assert_parse_args(main, "-fb value", foo=True, bar="value")
245
246
247 def test_short_integer_flag(app, assert_parse_args):
248 @app.default
249 def main(
250 foo: Annotated[int, Parameter(name=("--foo", "-f"))],
251 *,
252 bar: Annotated[bool, Parameter(name=("--bar", "-1"))],
253 ):
254 pass
255
256 assert_parse_args(main, "-1 -2", -2, bar=True)
257
258
259 @pytest.mark.parametrize(
260 "cmd_str,expected",
261 [
262 ("-9", -9),
263 ("-10", -10), # Multi-digit negatives should NOT be treated as combined short flags
264 ("-100", -100),
265 ("-3.14", -3.14),
266 ("-1e5", -1e5),
267 ("-1.5e-3", -1.5e-3),
268 ],
269 )
270 def test_negative_number_not_combined_short_flags(app, cmd_str, expected, assert_parse_args):
271 """Negative numbers should be parsed as values, not as combined short flags.
272
273 Regression test for issue where -10 was incorrectly interpreted as combined
274 short flags -1 and -0, while -9 worked because len("-9") == 2 doesn't trigger
275 combined flag parsing (which requires len > 2).
276 """
277
278 @app.default
279 def main(value: float):
280 pass
281
282 assert_parse_args(main, cmd_str, expected)
283
284
285 @pytest.mark.parametrize(
286 "cmd_str",
287 [
288 "foo --age 10",
289 "foo --duration 10",
290 "foo -a 10",
291 ],
292 )
293 def test_multiple_names_no_hyphen(app, cmd_str, assert_parse_args):
294 @app.command
295 def foo(age: Annotated[int, Parameter(name=["age", "duration", "-a"])]):
296 pass
297
298 assert_parse_args(foo, cmd_str, age=10)
299
300
301 @pytest.mark.parametrize(
302 "cmd_str",
303 [
304 "foo 1",
305 "foo --a=1",
306 "foo --a 1",
307 ],
308 )
309 @pytest.mark.parametrize("annotated", [False, True])
310 def test_optional_nonrequired_implicit_coercion(app, cmd_str, annotated, assert_parse_args):
311 """
312 For a union without an explicit coercion, the first non-None type annotation
313 should be used. In this case, it's ``int``.
314 """
315 if annotated:
316
317 @app.command
318 def foo(a: Annotated[int | None, Parameter(help="help for a")] = None):
319 pass
320
321 else:
322
323 @app.command
324 def foo(a: int | None = None):
325 pass
326
327 assert_parse_args(foo, cmd_str, 1)
328
329
330 @pytest.mark.parametrize(
331 "cmd_str",
332 [
333 "foo 1",
334 "foo --a=1",
335 "foo --a 1",
336 ],
337 )
338 @pytest.mark.parametrize("annotated", [False, True])
339 def test_optional_nonrequired_implicit_coercion_python310_syntax(app, cmd_str, annotated, assert_parse_args):
340 """
341 For a union without an explicit coercion, the first non-None type annotation
342 should be used. In this case, it's ``int``.
343 """
344 if annotated:
345
346 @app.command
347 def foo(a: Annotated[int | None, Parameter(help="help for a")] = None): # pyright: ignore
348 pass
349
350 else:
351
352 @app.command
353 def foo(a: int | None = None): # pyright: ignore
354 pass
355
356 assert_parse_args(foo, cmd_str, 1)
357
358
359 @pytest.mark.parametrize(
360 "cmd_str",
361 [
362 "--foo val1 --foo val2",
363 ],
364 )
365 def test_exception_repeat_argument(app, cmd_str):
366 @app.default
367 def default(foo: str):
368 pass
369
370 with pytest.raises(RepeatArgumentError):
371 app.parse_args(cmd_str, print_error=False, exit_on_error=False)
372
373
374 @pytest.mark.parametrize(
375 "cmd_str",
376 [
377 "--foo val1 --foo val2",
378 ],
379 )
380 def test_exception_repeat_argument_kwargs(app, cmd_str):
381 @app.default
382 def default(**kwargs: str):
383 pass
384
385 with pytest.raises(RepeatArgumentError):
386 app.parse_args(cmd_str, print_error=False, exit_on_error=False)
387
388
389 @pytest.mark.parametrize("type_hint", [list[str], str])
390 def test_allow_repeating_false(app, type_hint):
391 @app.default
392 def default(foo: Annotated[type_hint, Parameter(allow_repeating=False)]): # pyright: ignore[reportInvalidTypeForm]
393 pass
394
395 with pytest.raises(RepeatArgumentError):
396 app.parse_args("--foo a --foo b", print_error=False, exit_on_error=False)
397
398
399 def test_allow_repeating_false_consume_multiple(app, assert_parse_args):
400 @app.default
401 def default(foo: Annotated[list[str], Parameter(allow_repeating=False, consume_multiple=True)]):
402 pass
403
404 assert_parse_args(default, "--foo a b c", foo=["a", "b", "c"])
405
406
407 def test_allow_repeating_false_consume_multiple_repeated(app):
408 @app.default
409 def default(foo: Annotated[list[str], Parameter(allow_repeating=False, consume_multiple=True)]):
410 pass
411
412 with pytest.raises(RepeatArgumentError):
413 app.parse_args("--foo a --foo b", print_error=False, exit_on_error=False)
414
415
416 @pytest.mark.parametrize(
417 "consume_multiple,cmd_str,expected",
418 [
419 (False, "--foo a --foo b", ["a", "b"]),
420 (True, "--foo a --foo b", ["a", "b"]),
421 (True, "--foo a b --foo c d", ["a", "b", "c", "d"]),
422 ],
423 )
424 def test_allow_repeating_true_list(app, assert_parse_args, consume_multiple, cmd_str, expected):
425 @app.default
426 def default(foo: Annotated[list[str], Parameter(allow_repeating=True, consume_multiple=consume_multiple)]):
427 pass
428
429 assert_parse_args(default, cmd_str, foo=expected)
430
431
432 @pytest.mark.parametrize(
433 "cmd_str,expected",
434 [
435 ("--foo a --foo b", "b"),
436 ("--foo a --foo b --foo c", "c"),
437 ],
438 )
439 def test_allow_repeating_true_scalar(app, assert_parse_args, cmd_str, expected):
440 @app.default
441 def default(foo: Annotated[str, Parameter(allow_repeating=True)]):
442 pass
443
444 assert_parse_args(default, cmd_str, foo=expected)
445
446
447 def test_exception_unused_token(app):
448 @app.default
449 def default(foo: str):
450 pass
451
452 with pytest.raises(UnusedCliTokensError):
453 app.parse_args("foo bar", print_error=False, exit_on_error=False)
454
455
456 @pytest.mark.parametrize(
457 "cmd_str",
458 [
459 "foo 1",
460 "foo --a=1",
461 "foo --a 1",
462 ],
463 )
464 @pytest.mark.parametrize("annotated", [False, True])
465 def test_bind_no_hint_no_default(app, cmd_str, annotated, assert_parse_args):
466 """Parameter with no type hint & no default should be treated as a ``str``."""
467 if annotated:
468
469 @app.command
470 def foo(a: Annotated[Any, Parameter(help="help for a")]): # pyright: ignore[reportRedeclaration]
471 pass
472
473 else:
474
475 @app.command
476 def foo(a): # pyright: ignore[reportRedeclaration]
477 pass
478
479 assert_parse_args(foo, cmd_str, "1")
480
481
482 @pytest.mark.parametrize(
483 "cmd_str",
484 [
485 "foo 1",
486 "foo --a=1",
487 "foo --a 1",
488 ],
489 )
490 @pytest.mark.parametrize("annotated", [False, True])
491 def test_bind_no_hint_none_default(app, cmd_str, annotated, assert_parse_args):
492 """Parameter with no type hint & ``None`` default should be treated as a ``str``."""
493 if annotated:
494
495 @app.command
496 def foo(a: Annotated[Any, Parameter(help="help for a")] = None): # pyright: ignore[reportRedeclaration]
497 pass
498
499 else:
500
501 @app.command
502 def foo(a=None): # pyright: ignore[reportRedeclaration]
503 pass
504
505 assert_parse_args(foo, cmd_str, "1")
506
507
508 @pytest.mark.parametrize(
509 "cmd_str",
510 [
511 "foo 1",
512 "foo --a=1",
513 "foo --a 1",
514 ],
515 )
516 @pytest.mark.parametrize("annotated", [False, True])
517 def test_bind_no_hint_typed_default(app, cmd_str, annotated, assert_parse_args):
518 """Parameter with no type hint & typed default should be treated as a ``type(default)``."""
519 if annotated:
520
521 @app.command
522 def foo(a: Annotated[Any, Parameter(help="help for a")] = 5): # pyright: ignore[reportRedeclaration]
523 pass
524
525 else:
526
527 @app.command
528 def foo(a=5): # pyright: ignore[reportRedeclaration]
529 pass
530
531 assert_parse_args(foo, cmd_str, 1)
532
533
534 @pytest.mark.parametrize(
535 "cmd_str",
536 [
537 "foo 1",
538 "foo --a=1",
539 "foo --a 1",
540 ],
541 )
542 @pytest.mark.parametrize("annotated", [False, True])
543 def test_bind_any_hint(app, cmd_str, annotated, assert_parse_args):
544 """The ``Any`` type hint should be treated as a ``str``."""
545 if annotated:
546
547 @app.command
548 def foo(a: Annotated[Any, Parameter(help="help for a")] = None):
549 pass
550
551 else:
552
553 @app.command
554 def foo(a: Any = None):
555 pass
556
557 assert_parse_args(foo, cmd_str, "1")
558
559
560 @pytest.mark.parametrize(
561 "cmd_str",
562 [
563 "1",
564 "0b1",
565 "0x01",
566 "1.0",
567 "0.9",
568 ],
569 )
570 def test_bind_int_advanced(app, cmd_str, assert_parse_args):
571 @app.default
572 def foo(a: int):
573 pass
574
575 assert_parse_args(foo, cmd_str, 1)
576
577
578 def test_bind_int_advanced_coercion_error(app):
579 @app.default
580 def foo(a: int):
581 pass
582
583 with pytest.raises(CoercionError):
584 app.parse_args("foo", exit_on_error=False)
585
586
587 @pytest.mark.parametrize(
588 "value",
589 [
590 "10000000000000001",
591 "10000000000000011",
592 "100000000000000111234",
593 ],
594 )
595 def test_bind_large_int(app, assert_parse_args, value):
596 """Test that large integers are parsed correctly without precision loss.
597
598 Reproduces bug: https://github.com/BrianPugh/cyclopts/issues/581
599 """
600
601 @app.default
602 def foo(a: int):
603 pass
604
605 assert_parse_args(foo, value, int(value))
606
607
608 def test_bind_override_app_groups(app):
609 g_commands = Group("Custom Commands")
610 g_arguments = Group("Custom Arguments")
611 g_parameters = Group("Custom Parameters")
612
613 @app.command(group_commands=g_commands, group_arguments=g_arguments, group_parameters=g_parameters)
614 def foo():
615 pass
616
617 assert app["foo"].group_commands == g_commands
618 assert app["foo"].group_arguments == g_arguments
619 assert app["foo"].group_parameters == g_parameters
620
621
622 def test_bind_version(app, capsys):
623 app.version = "1.2.3"
624 actual_command, actual_bind, ignored = app.parse_args("--version")
625 assert ignored == {}
626 assert actual_command == app.version_print
627
628 actual_command(*actual_bind.args, **actual_bind.kwargs)
629 captured = capsys.readouterr()
630 assert captured.out == "1.2.3\n"
631
632
633 def test_bind_version_factory(app, capsys):
634 app.version = lambda: "1.2.3"
635 actual_command, actual_bind, ignored = app.parse_args("--version")
636 assert ignored == {}
637 assert actual_command == app.version_print
638
639 actual_command(*actual_bind.args, **actual_bind.kwargs)
640 captured = capsys.readouterr()
641 assert captured.out == "1.2.3\n"
642
643
644 @pytest.mark.parametrize(
645 "cmd_str_e",
646 [
647 ("foo 1 2 3", MissingArgumentError),
648 ("foo 1 2", MissingArgumentError),
649 ],
650 )
651 def test_missing_keyword_argument(app, cmd_str_e):
652 cmd_str, e = cmd_str_e
653
654 @app.command
655 def foo(a: int, b: int, c: int, *, d: int):
656 pass
657
658 with pytest.raises(e):
659 app.parse_args(cmd_str, print_error=False, exit_on_error=False)
660
661
662 @pytest.mark.parametrize(
663 "cmd_str",
664 [
665 "1 -- --2 3 4",
666 "-- 1 --2 3 4",
667 "--c=3 4 -- 1 --2",
668 "--c 3 4 -- 1 --2",
669 ],
670 )
671 def test_default_double_hyphen_end_of_options_delimiter(app, cmd_str, assert_parse_args):
672 @app.default
673 def foo(a: int, b: str, c: tuple[int, int]):
674 pass
675
676 assert_parse_args(foo, cmd_str, 1, "--2", (3, 4))
677
678
679 def test_disabled_double_hyphen_end_of_options_delimiter_from_app(app, assert_parse_args):
680 app.end_of_options_delimiter = ""
681
682 @app.default
683 def foo(a: int, b: Annotated[str, Parameter(allow_leading_hyphen=True)], c: tuple[int, int]):
684 pass
685
686 assert_parse_args(foo, "1 -- 3 4", 1, "--", (3, 4))
687
688
689 def test_disabled_double_hyphen_end_of_options_delimiter_from_parse_args(app, assert_parse_args_config):
690 @app.default
691 def foo(a: int, b: Annotated[str, Parameter(allow_leading_hyphen=True)], c: tuple[int, int]):
692 pass
693
694 assert_parse_args_config({"end_of_options_delimiter": ""}, foo, "1 -- 3 4", 1, "--", (3, 4))
695
696
697 def test_end_of_options_delimiter_from_parse_args(app, assert_parse_args):
698 app.end_of_options_delimiter = "AND"
699
700 @app.default
701 def foo(a: int, b: str, c: tuple[int, int]):
702 pass
703
704 assert_parse_args(foo, "1 AND --2 3 4", 1, "--2", (3, 4))
705
706
707 def test_end_of_options_delimiter_override(app, assert_parse_args_config):
708 app.end_of_options_delimiter = "AND" # This gets overridden
709
710 @app.default
711 def foo(a: int, b: str, c: tuple[int, int]):
712 pass
713
714 assert_parse_args_config({"end_of_options_delimiter": "DELIMIT"}, foo, "1 DELIMIT --2 3 4", 1, "--2", (3, 4))
715
716
717 # ============================================================================
718 # GNU-style combined short options tests
719 # Tests for the feature where short options can be combined with their values
720 # in a single token, similar to GNU getopt behavior.
721 #
722 # Examples:
723 # -o9 → -o with value "9"
724 # -iuroot → -i (flag), -u with value "root"
725 # -fvbfile → -f (flag), -v (flag), -b with value "file"
726 # ============================================================================
727
728
729 def test_single_short_option_with_attached_value(app, assert_parse_args):
730 """Test that -o9 is equivalent to -o 9."""
731
732 @app.default
733 def main(output: Annotated[str, Parameter(name=("-o", "--output"))]):
734 pass
735
736 # Traditional syntax should still work
737 assert_parse_args(main, "-o 9", output="9")
738 assert_parse_args(main, "-o=9", output="9")
739
740 # NEW: Attached value should work
741 assert_parse_args(main, "-o9", output="9")
742
743
744 def test_single_short_option_with_attached_string_value(app, assert_parse_args):
745 """Test that -ofile.txt works for string values."""
746
747 @app.default
748 def main(output: Annotated[str, Parameter(name=("-o", "--output"))]):
749 pass
750
751 # Traditional syntax
752 assert_parse_args(main, "-o file.txt", output="file.txt")
753
754 # NEW: Attached string value
755 assert_parse_args(main, "-ofile.txt", output="file.txt")
756 assert_parse_args(main, "-oroot", output="root")
757
758
759 def test_combined_flags_before_option_with_value(app, assert_parse_args):
760 """Test sudo -iuroot style: flags followed by option with attached value."""
761
762 @app.default
763 def main(
764 user: Annotated[str, Parameter(name=("-u", "--user"))],
765 interactive: Annotated[bool, Parameter(name=("-i", "--interactive"))] = False,
766 ):
767 pass
768
769 # Traditional syntax
770 assert_parse_args(main, "-i -u root", interactive=True, user="root")
771
772 # NEW: GNU-style combined
773 assert_parse_args(main, "-iuroot", interactive=True, user="root")
774
775
776 def test_multiple_flags_before_option_with_value(app, assert_parse_args):
777 """Test multiple flags combined with an option that takes a value."""
778
779 @app.default
780 def main(
781 output: Annotated[str, Parameter(name=("-o", "--output"))],
782 force: Annotated[bool, Parameter(name=("-f", "--force"))] = False,
783 verbose: Annotated[bool, Parameter(name=("-v", "--verbose"))] = False,
784 ):
785 pass
786
787 # Traditional syntax
788 assert_parse_args(main, "-f -v -o file.txt", force=True, verbose=True, output="file.txt")
789
790 # NEW: GNU-style combined
791 assert_parse_args(main, "-fvofile.txt", force=True, verbose=True, output="file.txt")
792 assert_parse_args(main, "-vfofile.txt", verbose=True, force=True, output="file.txt")
793
794
795 def test_option_with_value_at_end_consumes_next_token(app, assert_parse_args):
796 """Test that -fu (without attached value) consumes next token."""
797
798 @app.default
799 def main(
800 user: Annotated[str, Parameter(name=("-u", "--user"))],
801 force: Annotated[bool, Parameter(name=("-f", "--force"))] = False,
802 ):
803 pass
804
805 # When -u is at the end without attached value, next token is the value
806 assert_parse_args(main, "-fu root", force=True, user="root")
807
808
809 def test_option_with_value_in_middle_stops_processing(app, assert_parse_args):
810 """Test that once we hit an option with a value, rest is consumed as the value."""
811
812 @app.default
813 def main(
814 user: Annotated[str, Parameter(name=("-u", "--user"))],
815 force: Annotated[bool, Parameter(name=("-f", "--force"))] = False,
816 verbose: Annotated[bool, Parameter(name=("-v", "--verbose"))] = False,
817 ):
818 pass
819
820 # -fuvroot should be: -f (flag), -u with value "vroot"
821 # The 'v' is NOT treated as a flag, it's part of the value
822 assert_parse_args(main, "-fuvroot", force=True, user="vroot")
823
824
825 def test_combined_short_options_numeric_value(app, assert_parse_args):
826 """Test numeric values attached to short options."""
827
828 @app.default
829 def main(
830 port: Annotated[int, Parameter(name=("-p", "--port"))],
831 verbose: Annotated[bool, Parameter(name=("-v", "--verbose"))] = False,
832 ):
833 pass
834
835 # Traditional syntax
836 assert_parse_args(main, "-v -p 8080", verbose=True, port=8080)
837
838 # NEW: Attached numeric value
839 assert_parse_args(main, "-vp8080", verbose=True, port=8080)
840 assert_parse_args(main, "-p8080", port=8080)
841
842
843 def test_gnu_backward_compatibility_all_flags(app, assert_parse_args):
844 """Test that combining only flags still works (no regression)."""
845
846 @app.default
847 def main(
848 force: Annotated[bool, Parameter(name=("-f", "--force"))] = False,
849 verbose: Annotated[bool, Parameter(name=("-v", "--verbose"))] = False,
850 quiet: Annotated[bool, Parameter(name=("-q", "--quiet"))] = False,
851 ):
852 pass
853
854 # This should continue to work as before
855 assert_parse_args(main, "-fvq", force=True, verbose=True, quiet=True)
856 assert_parse_args(main, "-qvf", quiet=True, verbose=True, force=True)
857
858
859 def test_gnu_backward_compatibility_space_separated(app, assert_parse_args):
860 """Ensure traditional space-separated syntax still works."""
861
862 @app.default
863 def main(
864 output: Annotated[str, Parameter(name=("-o", "--output"))],
865 user: Annotated[str, Parameter(name=("-u", "--user"))],
866 ):
867 pass
868
869 # Traditional syntax must still work
870 assert_parse_args(main, "-o file.txt -u root", output="file.txt", user="root")
871
872
873 def test_gnu_backward_compatibility_equals_syntax(app, assert_parse_args):
874 """Ensure equals syntax still works."""
875
876 @app.default
877 def main(
878 output: Annotated[str, Parameter(name=("-o", "--output"))],
879 ):
880 pass
881
882 # Equals syntax must still work
883 assert_parse_args(main, "-o=file.txt", output="file.txt")
884 assert_parse_args(main, "--output=file.txt", output="file.txt")
885
886
887 def test_empty_string_value_attached(app, assert_parse_args):
888 """Test edge case: can we have an empty attached value?"""
889
890 @app.default
891 def main(
892 user: Annotated[str, Parameter(name=("-u", "--user"))],
893 force: Annotated[bool, Parameter(name=("-f", "--force"))] = False,
894 ):
895 pass
896
897 # -fu with no characters after should consume next token
898 # This is actually the same as test_option_with_value_at_end_consumes_next_token
899 assert_parse_args(main, "-fu root", force=True, user="root")
900
901
902 def test_counting_parameter_combined(app, assert_parse_args):
903 """Test that counting parameters work in combinations."""
904
905 @app.default
906 def main(
907 output: Annotated[str, Parameter(name=("-o", "--output"))],
908 verbose: Annotated[int, Parameter(name=("-v", "--verbose"), count=True)] = 0,
909 ):
910 pass
911
912 # Multiple v's for verbosity levels, then option with value
913 assert_parse_args(main, "-vvvofile.txt", verbose=3, output="file.txt")
914 assert_parse_args(main, "-vvofile.txt", verbose=2, output="file.txt")
915
916
917 def test_only_option_no_flags(app, assert_parse_args):
918 """Test single option with attached value (simplest case)."""
919
920 @app.default
921 def main(
922 user: Annotated[str, Parameter(name=("-u", "--user"))],
923 ):
924 pass
925
926 assert_parse_args(main, "-uroot", user="root")
927 assert_parse_args(main, "-u root", user="root")
928
929
930 def test_long_option_should_not_be_split(app, assert_parse_args):
931 """Test that long options (--) are NOT affected by this feature."""
932
933 @app.default
934 def main(
935 output: Annotated[str, Parameter(name=("--output",))],
936 ):
937 pass
938
939 # Long options should still require space or equals
940 assert_parse_args(main, "--output file.txt", output="file.txt")
941 assert_parse_args(main, "--output=file.txt", output="file.txt")
942
943 # --outputfile.txt should NOT be split into --output with value file.txt
944 # It should be treated as an unknown option "--outputfile.txt"
945 # (This maintains current behavior)
946
947
948 def test_hyphenated_value_attached(app, assert_parse_args):
949 """Test that hyphenated values work when attached."""
950
951 @app.default
952 def main(
953 output: Annotated[str, Parameter(name=("-o", "--output"))],
954 ):
955 pass
956
957 # Value containing hyphens
958 assert_parse_args(main, "-omy-file.txt", output="my-file.txt")
959 assert_parse_args(main, "-o--weird-value", output="--weird-value")
960
961
962 def test_special_characters_in_attached_value(app, assert_parse_args):
963 """Test special characters in attached values."""
964
965 @app.default
966 def main(
967 pattern: Annotated[str, Parameter(name=("-p", "--pattern"))],
968 ):
969 pass
970
971 # Special characters should be preserved
972 assert_parse_args(main, "-p*.txt", pattern="*.txt")
973 assert_parse_args(main, "-p[a-z]+", pattern="[a-z]+")
974 # Note: For short options with GNU-style attachment, = is part of the value
975 # Use -p "file=value" or --pattern=file for splitting on =
976 assert_parse_args(main, "-pfile=value", pattern="file=value")
977
978
979 def test_multiple_options_only_first_gets_attached_value(app, assert_parse_args):
980 """Test behavior when multiple value-taking options are combined.
981
982 Only the first option can have an attached value. Once we hit a value-taking
983 option, everything after is the value.
984 """
985
986 @app.default
987 def main(
988 user: Annotated[str, Parameter(name=("-u", "--user"))],
989 password: Annotated[str | None, Parameter(name=("-p", "--password"))] = None,
990 ):
991 pass
992
993 # -uprootpass should be: -u with value "prootpass"
994 # The 'p' is NOT treated as another option, it's part of the value
995 assert_parse_args(main, "-uprootpass", user="prootpass")
996
997 # To set both, use separate options or space
998 assert_parse_args(main, "-uroot -ppass", user="root", password="pass")
999
1000
1001 @pytest.mark.parametrize(
1002 "cmd,expected_output",
1003 [
1004 ("-o9", "9"),
1005 ("-o99", "99"),
1006 ("-o123abc", "123abc"),
1007 ("-oabc123", "abc123"),
1008 ],
1009 )
1010 def test_various_attached_values(app, assert_parse_args, cmd, expected_output):
1011 """Parametrized test for various value formats."""
1012
1013 @app.default
1014 def main(output: Annotated[str, Parameter(name=("-o", "--output"))]):
1015 pass
1016
1017 assert_parse_args(main, cmd, output=expected_output)
1018
1019
1020 def test_single_char_option_with_negative_value(app, assert_parse_args):
1021 """Test that -o-5 treats -5 as the value for -o."""
1022
1023 @app.default
1024 def main(
1025 offset: Annotated[int, Parameter(name=("-o", "--offset"))],
1026 ):
1027 pass
1028
1029 # -o-5 should be: -o with value "-5"
1030 # This tests that the "-5" part is treated as a value, not as a separate option
1031 assert_parse_args(main, "-o-5", offset=-5)
1032
1033
1034 def test_positional_only_list_interleaved_with_keywords_error(app):
1035 """Positional tokens after keyword args should not be consumed by a positional-only list.
1036
1037 Regression test for issue #763.
1038 """
1039
1040 @app.default
1041 def main(foo: list[str] | None = None, /, *, bar: int = 0, baz: int = 0):
1042 pass
1043
1044 with pytest.raises(UnusedCliTokensError):
1045 app.parse_args("a b c --bar 8 --baz 10 d", print_error=False, exit_on_error=False)
1046
1047
1048 def test_positional_only_list_then_keywords(app):
1049 """Positional tokens before keywords should work fine.
1050
1051 Regression test for issue #763.
1052 """
1053
1054 @app.default
1055 def main(foo: list[str] | None = None, /, *, bar: int = 0, baz: int = 0):
1056 pass
1057
1058 _, actual_bind, _ = app.parse_args("a b c d --bar 8 --baz 10", print_error=False, exit_on_error=False)
1059 assert actual_bind.args == (["a", "b", "c", "d"],)
1060 assert actual_bind.kwargs == {"bar": 8, "baz": 10}
1061
1062
1063 def test_positional_only_list_keywords_first(app):
1064 """Keywords before positional tokens should work fine.
1065
1066 Regression test for issue #763.
1067 """
1068
1069 @app.default
1070 def main(foo: list[str] | None = None, /, *, bar: int = 0, baz: int = 0):
1071 pass
1072
1073 _, actual_bind, _ = app.parse_args("--bar 8 --baz 10 a b c d", print_error=False, exit_on_error=False)
1074 assert actual_bind.args == (["a", "b", "c", "d"],)
1075 assert actual_bind.kwargs == {"bar": 8, "baz": 10}
1076
1077
1078 def test_positional_only_list_interleaved_with_delimiter(app):
1079 """Tokens after -- should still be consumed even with interleaving before the delimiter.
1080
1081 Regression test for issue #763.
1082 """
1083
1084 @app.default
1085 def main(foo: list[str] | None = None, /, *, bar: int = 0):
1086 pass
1087
1088 _, actual_bind, _ = app.parse_args("a b --bar 8 -- d e", print_error=False, exit_on_error=False)
1089 assert actual_bind.args == (["a", "b", "d", "e"],)
1090 assert actual_bind.kwargs == {"bar": 8}
1091
1092
1093 def test_positional_only_list_and_scalar_interleaved_error(app):
1094 """Multiple positional-only params (list + scalar) should also reject interleaving.
1095
1096 Regression test for issue #763.
1097 """
1098 from pathlib import Path
1099
1100 @app.default
1101 def main(inputs: list[str], output: Path, /, *, verbose: bool = False):
1102 pass
1103
1104 # Non-interleaved: should work
1105 _, actual_bind, _ = app.parse_args("a b c out.csv --verbose", print_error=False, exit_on_error=False)
1106 assert actual_bind.args == (["a", "b", "c"], Path("out.csv"))
1107 assert actual_bind.kwargs == {"verbose": True}
1108
1109 # Interleaved: should error
1110 with pytest.raises(UnusedCliTokensError):
1111 app.parse_args("a b --verbose c out.csv", print_error=False, exit_on_error=False)