Debian Codegraph @

tests/test_annotated.py

raw symbols SCIP
1 """Unit tests for cmd2.annotated -- verify build_parser_from_function produces correct actions.
2
3 The focus is on testing that type annotations are correctly translated into
4 argparse action attributes (option_strings, type, nargs, choices, action, default, etc.).
5 We do NOT re-test argparse parsing logic or cmd2 integration here.
6 """
7
8 import argparse
9 import datetime
10 import decimal
11 import enum
12 import functools
13 import inspect
14 import types
15 import uuid
16 from dataclasses import (
17 InitVar,
18 dataclass,
19 field,
20 )
21 from pathlib import Path
22 from typing import (
23 Annotated,
24 Any,
25 ClassVar,
26 Literal,
27 Optional,
28 )
29
30 import pytest
31
32 import cmd2
33 from cmd2 import (
34 CompletionItem,
35 constants,
36 )
37 from cmd2.annotated import (
38 Argument,
39 ArgumentBlock,
40 Group,
41 Option,
42 _apply_mutex_group_targets,
43 _ArgparseArgument,
44 _BlockSpec,
45 _build_argument_group_targets,
46 _CollectionCastingAction,
47 _invoke_command_func,
48 _make_enum_type,
49 _make_literal_type,
50 _normalize_annotation,
51 _parse_bool,
52 _reconstruct_dataclass_blocks,
53 _validate_group_specs,
54 build_parser_from_function,
55 with_annotated,
56 )
57 from cmd2.argparse_utils import register_argparse_argument_parameter
58
59 from .conftest import run_cmd
60
61
62 def _resolve_annotation(annotation: Any, *, has_default: bool = False, default: Any = None) -> _ArgparseArgument:
63 """Build and validate a single argument from a bare annotation (test helper).
64
65 The library builds a whole parameter list in ``_resolve_parameters``; these unit tests exercise one
66 annotation in isolation, mirroring that step: peel the annotation, populate the builder, run the
67 validity table. A lone argument has no following positional or group membership, so the
68 cross-argument/cross-config rows in ``_CONSTRAINTS`` are naturally inert.
69 """
70 inner_type, metadata, is_optional = _normalize_annotation(annotation)
71 arg = _ArgparseArgument(
72 name="arg",
73 func_qualname="<function>",
74 has_default=has_default,
75 param_default=default,
76 is_kw_only=False,
77 is_variadic=False,
78 inner_type=inner_type,
79 metadata=metadata,
80 is_optional=is_optional,
81 kind=inspect.Parameter.POSITIONAL_OR_KEYWORD,
82 is_base_command=False,
83 )
84 arg._check_constraints()
85 return arg
86
87
88 # ---------------------------------------------------------------------------
89 # Test enums
90 # ---------------------------------------------------------------------------
91
92
93 class _Color(enum.StrEnum):
94 red = "red"
95 green = "green"
96 blue = "blue"
97
98
99 class _IntColor(enum.IntEnum):
100 red = 1
101 green = 2
102 blue = 3
103
104
105 class _PlainColor(enum.Enum):
106 RED = "red"
107 GREEN = "green"
108 BLUE = "blue"
109
110
111 _COLOR_CHOICE_ITEMS = [
112 CompletionItem(_Color.red, text="red", display_meta="red"),
113 CompletionItem(_Color.green, text="green", display_meta="green"),
114 CompletionItem(_Color.blue, text="blue", display_meta="blue"),
115 ]
116
117 _INT_COLOR_CHOICE_ITEMS = [
118 CompletionItem(_IntColor.red, text="1", display_meta="red"),
119 CompletionItem(_IntColor.green, text="2", display_meta="green"),
120 CompletionItem(_IntColor.blue, text="3", display_meta="blue"),
121 ]
122
123 _PLAIN_COLOR_CHOICE_ITEMS = [
124 CompletionItem(_PlainColor.RED, text="red", display_meta="RED"),
125 CompletionItem(_PlainColor.GREEN, text="green", display_meta="GREEN"),
126 CompletionItem(_PlainColor.BLUE, text="blue", display_meta="BLUE"),
127 ]
128
129
130 class _Port(int):
131 """Subclass of ``int`` used to verify subclass fallback in type resolution."""
132
133
134 # ---------------------------------------------------------------------------
135 # Single-parameter test functions for build_parser_from_function.
136 # Each has exactly one param (besides self) so dest is auto-derived.
137 # ---------------------------------------------------------------------------
138
139
140 def _func_empty(self) -> None: ...
141 def _func_var_keyword(self, name: str, **kwargs: str) -> None: ...
142 def _func_multi(self, a: str, b: int, c: int = 1) -> None: ...
143 def _func_grouped(
144 self,
145 *,
146 local: str | None = None,
147 remote: str | None = None,
148 force: bool = False,
149 dry_run: bool = False,
150 ) -> None: ...
151
152
153 def _func_positional_only(self, name: str, /) -> None: ...
154 def _func_positional_only_xy(self, x: str, /, y: int) -> None: ...
155 def _func_positional_only_mixed(self, x: str, /, y: int, *, z: int = 0) -> None: ...
156
157
158 # Forward references with no matching name in this module's globals, so they are unresolvable at
159 # runtime. They exercise type-hint resolution: hints on parameters that never become arguments
160 # (``self``/``cls`` and the injected, skipped ``cmd2_statement``/``cmd2_subcommand_func``) must be tolerated,
161 # while hints on real arguments must still raise. ``noqa: F821`` marks the intentionally-undefined names.
162 def _func_unresolvable_self(self: "UnimportableCmd", name: str, count: int = 1) -> None: ... # noqa: F821
163 def _func_unresolvable_cmd2_statement(self, cmd2_statement: "UnimportableStatement", name: str, count: int = 1) -> None: ... # noqa: F821
164 def _func_unresolvable_cmd2_subcommand_func(
165 self,
166 cmd2_subcommand_func: "UnimportableHandler", # noqa: F821
167 verbose: bool = False,
168 ) -> None: ...
169 def _func_unresolvable_return(self, name: str) -> "UnimportableReturn": ... # noqa: F821
170 def _func_unresolvable_argument(self, name: "NonExistentType") -> None: ... # noqa: F821
171 def _func_unresolvable_argument_base(self, cmd2_subcommand_func, name: "NonExistentType") -> None: ... # noqa: F821
172
173
174 def _arg_names_via_parser(func: Any) -> set[str]:
175 """Resolve argument names through the public ``build_parser_from_function`` entry point."""
176 parser = build_parser_from_function(func)
177 return {action.dest for action in parser._actions if action.dest != "help"}
178
179
180 def _arg_names_via_base_command(func: Any) -> set[str]:
181 """Resolve a base command's argument names (``base_command`` is not exposed on the public builder)."""
182 from cmd2.annotated import _resolve_parameters
183
184 resolved, _base_args_types = _resolve_parameters(func, base_command=True)
185 return {arg.name for arg in resolved}
186
187
188 def _wrap_in_foreign_module(func: Any) -> Any:
189 """Wrap *func* as a ``functools.wraps`` decorator would, but give the wrapper a ``__globals__``
190 that lacks this module's names. This mimics a user decorator defined in *another* module and
191 stacked under ``@with_annotated``: ``functools.wraps`` copies ``__annotations__`` but not
192 ``__globals__``, so a forward reference can only be resolved via ``__wrapped__`` (the original
193 function's module), not the wrapper's. Rebinding the wrapper's globals is the single-module way
194 to recreate that cross-module split.
195 """
196
197 def wrapper(*args: Any, **kwargs: Any) -> Any:
198 return func(*args, **kwargs)
199
200 foreign = types.FunctionType(
201 wrapper.__code__, {"__builtins__": __builtins__}, func.__name__, wrapper.__defaults__, wrapper.__closure__
202 )
203 functools.update_wrapper(foreign, func) # copies __annotations__ etc. and sets __wrapped__ = func
204 return foreign
205
206
207 def _provider(cmd: cmd2.Cmd):
208 return []
209
210
211 # ---------------------------------------------------------------------------
212 # Helper
213 # ---------------------------------------------------------------------------
214
215
216 def _get_param_action(func: object) -> argparse.Action:
217 """Build parser from a single-param function and return its action."""
218 sig = inspect.signature(func) # type: ignore[arg-type]
219 param_names = [n for n in sig.parameters if n != "self"]
220 assert len(param_names) == 1, f"Expected 1 param besides self, got {param_names}"
221 parser = build_parser_from_function(func) # type: ignore[arg-type]
222 for action in parser._actions:
223 if action.dest == param_names[0]:
224 return action
225 raise ValueError(f"No action with dest={param_names[0]!r}")
226
227
228 # Templates used by ``_make_func``: one per parameter kind. ``code.replace`` swaps
229 # the literal name ``value`` for whatever ``name=`` the caller asks for, so the
230 # resulting signature carries the right dest without resorting to ``exec``.
231 def _stub_pos(self, value): ... # type: ignore[no-untyped-def]
232 def _stub_kw(self, *, value): ... # type: ignore[no-untyped-def]
233 def _stub_var(self, *value): ... # type: ignore[no-untyped-def]
234
235
236 _STUB_TEMPLATES = {"pos": _stub_pos, "kw": _stub_kw, "var": _stub_var}
237 _MISSING: Any = object()
238
239
240 def _make_func(
241 annotation: Any,
242 *,
243 name: str = "value",
244 default: Any = _MISSING,
245 kind: str = "pos",
246 ) -> Any:
247 """Construct a one-parameter ``self``-method carrying just an annotation.
248
249 ``kind`` is ``"pos"`` (positional-or-keyword), ``"kw"`` (keyword-only), or
250 ``"var"`` (``*args``). Used by tests as a stand-in for the throwaway
251 ``def do_x(self, value: T): ...`` stubs that only exist to be fed to
252 ``build_parser_from_function``.
253 """
254 template = _STUB_TEMPLATES[kind]
255 code = template.__code__
256 new_varnames = tuple(n if n != "value" else name for n in code.co_varnames)
257 new_code = code.replace(co_varnames=new_varnames)
258 f = types.FunctionType(new_code, template.__globals__, name=f"_stub_{name}")
259 # ``_MISSING`` for ``annotation`` produces an unannotated parameter (still ``-> None``).
260 f.__annotations__ = {"return": type(None)} if annotation is _MISSING else {name: annotation, "return": type(None)}
261 if default is not _MISSING:
262 if kind == "pos":
263 f.__defaults__ = (default,)
264 elif kind == "kw":
265 f.__kwdefaults__ = {name: default}
266 else:
267 raise ValueError(f"default not supported for kind={kind!r}")
268 return f
269
270
271 def _action_for(annotation: Any, **kwargs: Any) -> argparse.Action:
272 """Build a one-param function with the given annotation and return its action."""
273 return _get_param_action(_make_func(annotation, **kwargs))
274
275
276 def _assert_build_error(annotation: Any, *, match: str | None = None, **kwargs: Any) -> None:
277 """Assert ``build_parser_from_function`` rejects a one-param function with this annotation."""
278 with pytest.raises(TypeError, match=match):
279 build_parser_from_function(_make_func(annotation, **kwargs))
280
281
282 def _complete_cmd(app: cmd2.Cmd, line: str, text: str) -> list[str]:
283 begidx = len(line) - len(text)
284 endidx = len(line)
285 completions = app.complete(text, line, begidx, endidx)
286 return list(completions.to_strings())
287
288
289 # Register a custom add_argument parameter so we can verify that Argument()/Option()
290 # forward arbitrary registered parameters (parity with hand-built parsers).
291 register_argparse_argument_parameter("annotated_custom_attr")
292
293
294 # ---------------------------------------------------------------------------
295 # Core: build_parser_from_function produces correct action attributes
296 # ---------------------------------------------------------------------------
297
298
299 class TestBuildParser:
300 """Verify action attributes produced by build_parser_from_function."""
301
302 @pytest.mark.parametrize(
303 ("func", "expected"),
304 [
305 # --- Positionals ---
306 pytest.param(_make_func(str, name="name"), {"option_strings": [], "type": None}, id="str_positional"),
307 pytest.param(_make_func(Path, name="file"), {"option_strings": [], "type": Path}, id="path_positional"),
308 pytest.param(
309 _make_func(decimal.Decimal, name="amount"),
310 {"option_strings": [], "type": decimal.Decimal},
311 id="decimal_positional",
312 ),
313 pytest.param(_make_func(bool, name="flag"), {"option_strings": [], "type": _parse_bool}, id="bool_positional"),
314 pytest.param(
315 _make_func(_Color, name="color"), {"option_strings": [], "choices": _COLOR_CHOICE_ITEMS}, id="enum_positional"
316 ),
317 pytest.param(
318 _make_func(Literal["fast", "slow"], name="mode"),
319 {"option_strings": [], "choices": ["fast", "slow"]},
320 id="literal_positional",
321 ),
322 pytest.param(
323 _make_func(Literal[1, 2, 3], name="level"),
324 {"option_strings": [], "choices": [1, 2, 3]},
325 id="literal_int_positional",
326 ),
327 pytest.param(
328 _make_func(_IntColor, name="color"),
329 {"option_strings": [], "choices": _INT_COLOR_CHOICE_ITEMS},
330 id="int_enum_positional",
331 ),
332 pytest.param(
333 _make_func(_PlainColor, name="color"),
334 {"option_strings": [], "choices": _PLAIN_COLOR_CHOICE_ITEMS},
335 id="plain_enum_positional",
336 ),
337 pytest.param(_make_func(list[int], name="nums"), {"option_strings": [], "nargs": "+", "type": int}, id="list_int"),
338 pytest.param(_make_func(set[int], name="nums"), {"option_strings": [], "nargs": "+", "type": int}, id="set_int"),
339 pytest.param(
340 _make_func(frozenset[int], name="nums"),
341 {"option_strings": [], "nargs": "+", "type": int},
342 id="frozenset_int",
343 ),
344 pytest.param(
345 _make_func(tuple[int, int, int], name="triple"),
346 {"option_strings": [], "nargs": 3, "type": int},
347 id="tuple_fixed_triple",
348 ),
349 pytest.param(_make_func(list[str], name="files"), {"option_strings": [], "nargs": "+"}, id="list_positional"),
350 pytest.param(_make_func(set[str], name="tags"), {"option_strings": [], "nargs": "+"}, id="set_positional"),
351 pytest.param(
352 _make_func(frozenset[str], name="tags"), {"option_strings": [], "nargs": "+"}, id="frozenset_positional"
353 ),
354 pytest.param(
355 _make_func(tuple[int, ...], name="values"),
356 {"option_strings": [], "nargs": "+", "type": int},
357 id="tuple_ellipsis",
358 ),
359 pytest.param(
360 _make_func(tuple[int, int], name="pair"), {"option_strings": [], "nargs": 2, "type": int}, id="tuple_fixed"
361 ),
362 pytest.param(_make_func(list, name="items"), {"option_strings": [], "nargs": "+"}, id="bare_list"),
363 pytest.param(_make_func(frozenset, name="items"), {"option_strings": [], "nargs": "+"}, id="bare_frozenset"),
364 pytest.param(_make_func(tuple, name="items"), {"option_strings": [], "nargs": "+"}, id="bare_tuple"),
365 pytest.param(
366 _make_func(Annotated[int | None, Argument()], name="val"),
367 {"option_strings": [], "nargs": "?", "type": int},
368 id="optional_positional",
369 ),
370 pytest.param(
371 _make_func(Annotated[str, Argument()], name="arg", default="foo"),
372 {"option_strings": [], "nargs": "?", "default": "foo"},
373 id="positional_with_default",
374 ),
375 pytest.param(
376 _make_func(int | None, name="val"), {"option_strings": [], "nargs": "?", "type": int}, id="optional_plain"
377 ),
378 pytest.param(
379 _make_func(list[int] | None, name="vals"),
380 {"option_strings": [], "nargs": "*", "type": int},
381 id="optional_list",
382 ),
383 pytest.param(
384 _make_func(tuple[int, ...] | None, name="vals"),
385 {"option_strings": [], "nargs": "*", "type": int},
386 id="optional_tuple_ellipsis",
387 ),
388 # --- Options ---
389 pytest.param(
390 _make_func(int, name="count", default=1),
391 {"option_strings": ["--count"], "type": int, "default": 1},
392 id="int_option",
393 ),
394 pytest.param(
395 _make_func(float, name="rate", default=1.0),
396 {"option_strings": ["--rate"], "type": float, "default": 1.0},
397 id="float_option",
398 ),
399 pytest.param(
400 _make_func(bool, name="verbose", default=False),
401 {"option_strings": ["--verbose", "--no-verbose"], "default": False},
402 id="bool_optional_action",
403 ),
404 pytest.param(
405 _make_func(bool, name="debug", default=True),
406 {"option_strings": ["--debug", "--no-debug"], "default": True},
407 id="bool_optional_action_true",
408 ),
409 pytest.param(
410 _make_func(Path, name="file", default=Path(".")),
411 {"option_strings": ["--file"], "type": Path},
412 id="path_option",
413 ),
414 pytest.param(
415 _make_func(_Color, name="color", default=_Color.blue),
416 {"option_strings": ["--color"], "choices": _COLOR_CHOICE_ITEMS, "default": _Color.blue},
417 id="enum_option",
418 ),
419 pytest.param(
420 _make_func(Literal["fast", "slow"], name="mode", default="fast"),
421 {"option_strings": ["--mode"], "choices": ["fast", "slow"]},
422 id="literal_option",
423 ),
424 pytest.param(
425 _make_func(str | None, name="name", default=None),
426 {"option_strings": ["--name"], "default": None},
427 id="optional_str",
428 ),
429 pytest.param(
430 _make_func(list[str] | None, name="items", default=None),
431 {"option_strings": ["--items"], "nargs": "*"},
432 id="list_with_default",
433 ),
434 # --- Annotated metadata ---
435 pytest.param(
436 _make_func(Annotated[str, Argument(help_text="Your name")], name="name"),
437 {"option_strings": [], "help": "Your name"},
438 id="annotated_help",
439 ),
440 pytest.param(
441 _make_func(Annotated[str, Option("--color", "-c", help_text="Pick")], name="color", default="blue"),
442 {"option_strings": ["--color", "-c"], "help": "Pick"},
443 id="annotated_custom_flags",
444 ),
445 pytest.param(
446 _make_func(Annotated[str, Argument(metavar="NAME")], name="name"),
447 {"option_strings": [], "metavar": "NAME"},
448 id="annotated_metavar",
449 ),
450 pytest.param(
451 # argparse accepts a tuple metavar to label each value of a multi-value argument.
452 _make_func(Annotated[tuple[int, int], Argument(metavar=("LO", "HI"))], name="span"),
453 {"option_strings": [], "metavar": ("LO", "HI")},
454 id="annotated_tuple_metavar",
455 ),
456 pytest.param(
457 _make_func(Annotated[tuple[str, ...], Argument(nargs=2)], name="names"),
458 {"option_strings": [], "nargs": 2},
459 id="annotated_nargs",
460 ),
461 pytest.param(
462 _make_func(Annotated[str, Option("--name", required=True)], name="name"),
463 {"option_strings": ["--name"], "required": True},
464 id="annotated_required",
465 ),
466 pytest.param(
467 _make_func(Annotated[str, Option(required=True)], name="name"),
468 {"option_strings": ["--name"], "required": True},
469 id="annotated_required_auto_flag",
470 ),
471 # A value option with no default and no ``| None`` must be required (else omitting it
472 # would pass None, violating the non-Optional type hint).
473 pytest.param(
474 _make_func(Annotated[str, Option("-c")], name="color"),
475 {"option_strings": ["-c"], "required": True},
476 id="option_no_default_required",
477 ),
478 # A bool option is a flag, not a value: absence means ``False``, so it defaults to False
479 # and is NOT required (a required bool flag would be unsatisfiable for a short-only flag).
480 pytest.param(
481 _make_func(Annotated[bool, Option("-f")], name="flag"),
482 {"option_strings": ["-f"], "required": False, "default": False},
483 id="bool_option_no_default_defaults_false",
484 ),
485 # ``| None`` opts out of required: None is a valid value when omitted.
486 pytest.param(
487 _make_func(Annotated[str | None, Option("-c")], name="color"),
488 {"option_strings": ["-c"], "required": False, "default": None},
489 id="option_optional_no_default_not_required",
490 ),
491 pytest.param(
492 _make_func(str | None, name="name", kind="kw"),
493 {"option_strings": ["--name"], "required": False, "default": None},
494 id="kw_only_optional_not_required",
495 ),
496 pytest.param(
497 _make_func(Annotated[str, Argument(choices=["a", "b"])], name="food"),
498 {"option_strings": [], "choices": ["a", "b"]},
499 id="annotated_choices",
500 ),
501 pytest.param(
502 _make_func(str, name="args", kind="var"), {"option_strings": [], "type": None, "nargs": "*"}, id="star_args"
503 ),
504 pytest.param(
505 _make_func(int, name="args", kind="var"), {"option_strings": [], "type": int, "nargs": "*"}, id="star_args_int"
506 ),
507 # --- Keyword-only ---
508 pytest.param(
509 _make_func(str, name="name", kind="kw"),
510 {"option_strings": ["--name"], "required": True},
511 id="kw_only_required",
512 ),
513 pytest.param(
514 _make_func(str, name="name", default="world", kind="kw"),
515 {"option_strings": ["--name"], "default": "world"},
516 id="kw_only_default",
517 ),
518 # --- Underscore in flag names ---
519 pytest.param(
520 _make_func(str, name="my_param", default="x"),
521 {"option_strings": ["--my-param"], "default": "x"},
522 id="underscore_flag",
523 ),
524 # --- Default type preservation ---
525 pytest.param(
526 _make_func(int, name="count", default="1"),
527 {"option_strings": ["--count"], "default": "1"},
528 id="default_not_coerced",
529 ),
530 pytest.param(
531 _make_func(Path, name="file", default=Path("/tmp")),
532 {"option_strings": ["--file"], "default": Path("/tmp")},
533 id="path_default",
534 ),
535 # --- Optional + Annotated (union inside) ---
536 pytest.param(
537 _make_func(Annotated[str | None, Option("--name")], name="name", default=None),
538 {"option_strings": ["--name"], "default": None},
539 id="optional_annotated_inside",
540 ),
541 # --- Collections of complex element types ---
542 pytest.param(
543 _make_func(list[bool], name="flags"), {"option_strings": [], "nargs": "+", "type": _parse_bool}, id="list_bool"
544 ),
545 pytest.param(
546 _make_func(set[bool], name="flags"), {"option_strings": [], "nargs": "+", "type": _parse_bool}, id="set_bool"
547 ),
548 pytest.param(
549 _make_func(list[Path], name="files"), {"option_strings": [], "nargs": "+", "type": Path}, id="list_path"
550 ),
551 pytest.param(
552 _make_func(list[Literal["fast", "slow"]], name="modes"),
553 {"option_strings": [], "nargs": "+", "choices": ["fast", "slow"]},
554 id="list_literal",
555 ),
556 pytest.param(
557 _make_func(list[_Color], name="colors"),
558 {"option_strings": [], "nargs": "+", "choices": _COLOR_CHOICE_ITEMS},
559 id="list_enum",
560 ),
561 pytest.param(
562 _make_func(tuple[Path, Path], name="src_dst"),
563 {"option_strings": [], "nargs": 2, "type": Path},
564 id="tuple_paths",
565 ),
566 pytest.param(
567 _make_func(tuple[_Color, _Color], name="pair"),
568 {"option_strings": [], "nargs": 2, "choices": _COLOR_CHOICE_ITEMS},
569 id="tuple_enums",
570 ),
571 # --- Subclass fallback (Port(int) uses int converter) ---
572 pytest.param(_make_func(_Port, name="port"), {"option_strings": [], "type": int}, id="int_subclass"),
573 # --- Optional with non-None default ---
574 pytest.param(
575 _make_func(str | None, name="name", default="world"),
576 {"option_strings": ["--name"], "default": "world"},
577 id="optional_str_nondefault",
578 ),
579 # --- typing.Optional[T] (vs T | None) end-to-end ---
580 pytest.param(
581 _make_func(Optional[int], name="count", default=None), # noqa: UP045
582 {"option_strings": ["--count"], "type": int, "default": None},
583 id="typing_optional",
584 ),
585 ],
586 )
587 def test_action_attributes(self, func, expected) -> None:
588 action = _get_param_action(func)
589 for key, value in expected.items():
590 assert getattr(action, key) == value, f"{key}: expected {value!r}, got {getattr(action, key)!r}"
591
592 def test_annotated_action_count(self) -> None:
593 action = _get_param_action(
594 _make_func(Annotated[int, Option("--verbose", "-v", action="count")], name="verbose", default=0)
595 )
596 assert isinstance(action, argparse._CountAction)
597
598 def test_annotated_action_count_non_bool(self) -> None:
599 action = _get_param_action(_make_func(Annotated[int, Option("--count", action="count")], name="count", default=0))
600 assert isinstance(action, argparse._CountAction)
601 assert action.default == 0
602
603 def test_annotated_action_store_true(self) -> None:
604 """``action='store_true'`` strips the inferred bool converter."""
605 action = _get_param_action(
606 _make_func(Annotated[bool, Option("--verbose", action="store_true")], name="verbose", default=False)
607 )
608 assert isinstance(action, argparse._StoreTrueAction)
609 assert action.type is None
610 assert action.default is False
611
612 def test_annotated_action_store_false(self) -> None:
613 """``action='store_false'`` strips the inferred bool converter."""
614 action = _get_param_action(
615 _make_func(Annotated[bool, Option("--quiet", action="store_false")], name="quiet", default=True)
616 )
617 assert isinstance(action, argparse._StoreFalseAction)
618 assert action.type is None
619 assert action.default is True
620
621 def test_annotated_action_append(self) -> None:
622 """``action='append'`` collects repeated flag values into a list."""
623 action = _get_param_action(_make_func(Annotated[list[str], Option("--tag", action="append")], name="tag"))
624 assert isinstance(action, argparse._AppendAction)
625 assert action.option_strings == ["--tag"]
626
627 def test_positional_with_default_is_optional(self) -> None:
628 """A positional with a default takes 0-or-1 tokens and falls back to the default when absent."""
629 parser = build_parser_from_function(_make_func(Annotated[str, Argument()], name="arg", default="foo"))
630 assert parser.parse_args([]).arg == "foo"
631 assert parser.parse_args(["bar"]).arg == "bar"
632
633 def test_str_default_on_int_option_coerced_at_parse(self) -> None:
634 """The decorator stores the default literally ('1', see ``default_not_coerced``); at parse
635 time argparse applies ``type=int`` to the string default, so an absent ``--count`` yields int 1.
636 """
637 parser = build_parser_from_function(_make_func(int, name="count", default="1"))
638 assert parser.parse_args([]).count == 1
639 assert parser.parse_args(["--count", "5"]).count == 5
640
641 def test_typing_optional_parses_end_to_end(self) -> None:
642 """typing.Optional[int] yields None when absent and coerces to int when provided."""
643 parser = build_parser_from_function(_make_func(Optional[int], name="count", default=None)) # noqa: UP045
644 assert parser.parse_args([]).count is None
645 parsed = parser.parse_args(["--count", "5"]).count
646 assert parsed == 5
647 assert isinstance(parsed, int)
648
649 @pytest.mark.parametrize(
650 "func",
651 [
652 pytest.param(_make_func(set[str], name="tags"), id="set"),
653 pytest.param(_make_func(tuple[int, ...], name="values"), id="tuple"),
654 pytest.param(_make_func(str, name="args", kind="var"), id="star_args"),
655 ],
656 )
657 def test_collection_uses_casting_action(self, func) -> None:
658 action = _get_param_action(func)
659 assert isinstance(action, _CollectionCastingAction)
660
661 def test_star_args_bare_defaults_to_str(self) -> None:
662 """A bare ``*args`` (no element annotation) is treated as ``*args: str``."""
663 action = _get_param_action(_make_func(_MISSING, name="args", kind="var"))
664 assert action.option_strings == []
665 assert action.nargs == "*"
666 assert action.type is None
667
668 def test_star_args_parses_to_tuple(self) -> None:
669 """``*args: int`` accepts zero or more values, coerced and collected into a tuple."""
670 parser = build_parser_from_function(_make_func(int, name="args", kind="var"))
671 assert parser.parse_args([]).args == ()
672 parsed = parser.parse_args(["1", "2", "3"]).args
673 assert parsed == (1, 2, 3)
674 assert isinstance(parsed, tuple)
675
676 def test_self_skipped(self) -> None:
677 parser = build_parser_from_function(_make_func(str, name="name"))
678 dests = {a.dest for a in parser._actions}
679 assert "self" not in dests
680
681 def test_no_params_produces_empty_parser(self) -> None:
682 """A function with zero parameters (not even self) produces a parser with no actions."""
683
684 def bare() -> None: ...
685
686 parser = build_parser_from_function(bare)
687 dests = {a.dest for a in parser._actions if a.dest != "help"}
688 assert dests == set()
689
690 def test_self_only_method_produces_empty_parser(self) -> None:
691 """A method whose only parameter is ``self`` produces a parser with no actions."""
692 parser = build_parser_from_function(_func_empty)
693 dests = {a.dest for a in parser._actions if a.dest != "help"}
694 assert dests == set()
695 assert parser.parse_args([]) == argparse.Namespace()
696
697 @pytest.mark.parametrize(
698 ("func", "resolve_arg_names", "expected_args"),
699 [
700 pytest.param(_func_unresolvable_self, _arg_names_via_parser, {"name", "count"}, id="self"),
701 pytest.param(_func_unresolvable_cmd2_statement, _arg_names_via_parser, {"name", "count"}, id="cmd2_statement"),
702 pytest.param(
703 _func_unresolvable_cmd2_subcommand_func, _arg_names_via_base_command, {"verbose"}, id="cmd2_subcommand_func"
704 ),
705 pytest.param(_func_unresolvable_return, _arg_names_via_parser, {"name"}, id="return"),
706 ],
707 )
708 def test_unresolvable_hint_on_ignored_param_is_tolerated(self, func, resolve_arg_names, expected_args) -> None:
709 """An unresolvable forward reference on an annotation that never becomes an argument must not
710 abort parser generation -- the bound ``self``/``cls``, the injected, skipped
711 ``cmd2_statement``/``cmd2_subcommand_func`` parameters, and the function's ``return`` annotation. This
712 is the common case of annotating with a type only importable under ``TYPE_CHECKING``. Only
713 hints for parameters that actually become arguments are resolved; without that filtering each
714 case raises "Failed to resolve type hints".
715 """
716 assert resolve_arg_names(func) == expected_args
717
718 @pytest.mark.parametrize(
719 ("func", "resolve_arg_names"),
720 [
721 pytest.param(_func_unresolvable_argument, _arg_names_via_parser, id="non_base"),
722 pytest.param(_func_unresolvable_argument_base, _arg_names_via_base_command, id="base_command"),
723 ],
724 )
725 def test_unresolvable_hint_on_real_argument_raises(self, func, resolve_arg_names) -> None:
726 """An unresolvable forward reference on a parameter that *does* become an argument must abort
727 with a clear, actionable error rather than being silently swallowed -- for both plain commands
728 and base commands.
729 """
730 with pytest.raises(TypeError, match="Failed to resolve type hints"):
731 resolve_arg_names(func)
732
733 def test_forward_ref_resolves_through_functools_wraps_wrapper(self) -> None:
734 """A forward reference must resolve against the *original* function's module even when the
735 function reaching the parser builder is a ``functools.wraps`` wrapper defined in another
736 module (e.g. a user decorator stacked under ``@with_annotated``). ``functools.wraps`` copies
737 ``__annotations__`` but not ``__globals__``, so resolution must follow ``__wrapped__`` --
738 mirroring what ``typing.get_type_hints`` does for a bare function.
739 """
740
741 def do_path(self, target: "Path", count: int = 1):
742 pass
743
744 # The wrapper carries a foreign global namespace lacking ``Path``; resolution must use the
745 # unwrapped function's globals (this module) instead, or it raises "Failed to resolve".
746 wrapped = _wrap_in_foreign_module(do_path)
747 parser = build_parser_from_function(wrapped)
748 dests = {action.dest for action in parser._actions if action.dest != "help"}
749 assert dests == {"target", "count"}
750
751 def test_dest_param_raises(self) -> None:
752 with pytest.raises(ValueError, match="dest"):
753 build_parser_from_function(_make_func(str, name="dest"))
754
755 def test_subcommand_param_raises(self) -> None:
756 def func(self, subcommand: str) -> None: ...
757
758 with pytest.raises(ValueError, match="subcommand"):
759 build_parser_from_function(func)
760
761 def test_with_annotated_positional_only_param_raises(self) -> None:
762 with pytest.raises(TypeError, match="positional-only"):
763 build_parser_from_function(_func_positional_only)
764
765 def test_with_annotated_positional_only_two_params_raises(self) -> None:
766 with pytest.raises(TypeError, match="positional-only"):
767 build_parser_from_function(_func_positional_only_xy)
768
769 def test_with_annotated_positional_only_mixed_params_raises(self) -> None:
770 with pytest.raises(TypeError, match="positional-only"):
771 build_parser_from_function(_func_positional_only_mixed)
772
773 def test_var_keyword_raises(self) -> None:
774 """``**kwargs`` cannot be mapped to command-line arguments and is rejected."""
775 with pytest.raises(TypeError, match=r"variadic keyword"):
776 build_parser_from_function(_func_var_keyword)
777
778 @pytest.mark.parametrize(
779 "func",
780 [
781 pytest.param(_make_func(tuple[str, ...], name="files", kind="var"), id="tuple[str, ...]"),
782 pytest.param(_make_func(list[str], name="xs", kind="var"), id="list[str]"),
783 pytest.param(_make_func(list, name="xs", kind="var"), id="bare_list"),
784 ],
785 )
786 def test_star_args_collection_element_raises(self, func) -> None:
787 """``*args`` annotated with a collection element is rejected with a targeted hint.
788
789 The annotation on ``*args`` is each value's type, so a collection element (e.g.
790 ``*files: tuple[str, ...]``) would mean a tuple-of-collections. The error must steer
791 the user toward annotating the element type.
792 """
793 with pytest.raises(TypeError, match=r"the type of each value"):
794 build_parser_from_function(func)
795
796 def test_star_args_honors_argument_metadata(self) -> None:
797 """``Annotated[T, Argument(...)]`` on ``*args`` applies help/metavar to the variadic positional."""
798 action = _get_param_action(
799 _make_func(Annotated[str, Argument(help_text="a file", metavar="FILE")], name="files", kind="var")
800 )
801 assert action.option_strings == []
802 assert action.nargs == "*"
803 assert action.help == "a file"
804 assert action.metavar == "FILE"
805
806 def test_star_args_honors_argument_choices(self) -> None:
807 """``Argument(choices=...)`` on ``*args`` restricts every value to the choices."""
808 parser = build_parser_from_function(_make_func(Annotated[str, Argument(choices=["a", "b"])], name="modes", kind="var"))
809 assert parser.parse_args(["a", "b", "a"]).modes == ("a", "b", "a")
810 with pytest.raises(SystemExit):
811 parser.parse_args(["a", "nope"])
812
813 def test_star_args_option_metadata_raises(self) -> None:
814 """``Option()`` on ``*args`` is rejected; *args is always positional."""
815 with pytest.raises(TypeError, match=r"\*args is always a positional"):
816 build_parser_from_function(_make_func(Annotated[str, Option("--files")], name="files", kind="var"))
817
818 def test_star_args_nargs_metadata_raises(self) -> None:
819 """An explicit ``nargs`` on ``*args`` is rejected; its arity is fixed to ``'*'``."""
820 with pytest.raises(TypeError, match=r"arity cannot be overridden"):
821 build_parser_from_function(_make_func(Annotated[str, Argument(nargs=2)], name="files", kind="var"))
822
823 @pytest.mark.parametrize(
824 "func",
825 [
826 pytest.param(_make_func(Annotated[str, Argument()], name="name", kind="kw"), id="no_default"),
827 pytest.param(_make_func(Annotated[str, Argument()], name="name", default="x", kind="kw"), id="with_default"),
828 ],
829 )
830 def test_kw_only_with_argument_metadata_raises(self, func) -> None:
831 """A keyword-only parameter cannot use ``Argument()`` (which marks a positional)."""
832 with pytest.raises(TypeError, match=r"keyword-only but uses Argument\(\)"):
833 build_parser_from_function(func)
834
835 def test_option_no_default_is_enforced_at_parse_time(self) -> None:
836 """Omitting a no-default, non-Optional option errors instead of silently passing None."""
837 parser = build_parser_from_function(_make_func(Annotated[str, Option("-c")], name="color"))
838 with pytest.raises(SystemExit):
839 parser.parse_args([])
840 assert parser.parse_args(["-c", "red"]).color == "red"
841
842 def test_optional_option_no_default_yields_none_when_omitted(self) -> None:
843 """``| None`` opts out of required: omitting it yields None, a valid value for the hint."""
844 parser = build_parser_from_function(_make_func(Annotated[str | None, Option("-c")], name="color"))
845 assert parser.parse_args([]).color is None
846 assert parser.parse_args(["-c", "red"]).color == "red"
847
848 def test_generator_choices_are_materialized(self) -> None:
849 """A single-use iterable (generator) as choices must survive repeated argparse iteration."""
850 parser = build_parser_from_function(
851 _make_func(Annotated[str, Argument(choices=(c for c in ["a", "b"]))]),
852 )
853 assert parser.parse_args(["a"]).value == "a"
854 assert parser.parse_args(["b"]).value == "b"
855 with pytest.raises(SystemExit):
856 parser.parse_args(["c"])
857
858 @pytest.mark.parametrize(
859 ("func", "dest", "default"),
860 [
861 pytest.param(
862 _make_func(Annotated[bool, Option("-v", action="store_true")], name="verbose"),
863 "verbose",
864 False,
865 id="store_true",
866 ),
867 pytest.param(_make_func(Annotated[int, Option("-l", action="count")], name="level"), "level", 0, id="count"),
868 ],
869 )
870 def test_flag_action_no_default_not_required(self, func, dest, default) -> None:
871 """Flag-style actions carry their own implicit default, so a missing default does not force required."""
872 parser = build_parser_from_function(func)
873 action = _get_param_action(func)
874 assert action.required is False
875 assert getattr(parser.parse_args([]), dest) == default
876
877 def test_bool_option_no_default_is_usable_flag(self) -> None:
878 """A bool option is a flag (absence -> False), not a required value.
879
880 Marking it required would make a short-only flag unsatisfiable: ``-f`` can only set True
881 and there is no negation form, so a required ``-f`` could never be False.
882 """
883 parser = build_parser_from_function(_make_func(Annotated[bool, Option("-f")], name="flag"))
884 action = _get_param_action(_make_func(Annotated[bool, Option("-f")], name="flag"))
885 assert action.required is False
886 assert parser.parse_args([]).flag is False
887 assert parser.parse_args(["-f"]).flag is True
888
889 def test_optional_annotated_outside_raises(self) -> None:
890 with pytest.raises(TypeError, match="Annotated"):
891 build_parser_from_function(_make_func(Annotated[str, Option("--name")] | None, name="name", default=None))
892
893 def test_annotated_ambiguous_union_raises(self) -> None:
894 """Annotated[str | int, meta] must raise -- ambiguous inner union."""
895 with pytest.raises(TypeError, match="ambiguous"):
896 _resolve_annotation(Annotated[str | int, Option("--name")])
897
898 def test_multi_param_order_and_presence(self) -> None:
899 """Positional order preserved, options generated correctly."""
900 parser = build_parser_from_function(_func_multi)
901 positionals = [a.dest for a in parser._actions if not a.option_strings and a.dest != "help"]
902 assert positionals == ["a", "b"]
903 dests = {a.dest for a in parser._actions}
904 assert "c" in dests
905
906
907 class TestTypeInferenceBuildParser:
908 """Type-inference behavior and override precedence when building parser actions."""
909
910 def test_choices_provider_overrides_inferred_enum_choices(self) -> None:
911 action = _get_param_action(_make_func(Annotated[_Color, Argument(choices_provider=_provider)], name="color"))
912 assert action.choices is None
913 assert action.get_choices_provider() is _provider # type: ignore[attr-defined]
914 assert action.get_completer() is None # type: ignore[attr-defined]
915
916 def test_choices_provider_keeps_enum_coercion(self) -> None:
917 """A choices_provider on an Enum keeps the converter so values still coerce to the member."""
918 action = _get_param_action(_make_func(Annotated[_Color, Argument(choices_provider=_provider)], name="color"))
919 assert action.type is not None
920 assert action.type("red") is _Color.red
921
922 def test_choices_provider_keeps_literal_coercion(self) -> None:
923 """A choices_provider on a Literal keeps the converter (coercion) but drops the static choices."""
924
925 def func(
926 self,
927 level: Annotated[Literal[1, 2], Argument(choices_provider=_provider)],
928 ) -> None: ...
929
930 action = _get_param_action(func)
931 assert action.choices is None
932 assert action.type is not None
933 assert action.type("1") == 1
934
935 def test_choices_provider_enum_coerces_at_parse(self) -> None:
936 """End-to-end: an Enum with a choices_provider still parses to the enum member, not a str."""
937 parser = build_parser_from_function(_make_func(Annotated[_Color, Argument(choices_provider=_provider)], name="color"))
938 assert parser.parse_args(["red"]).color is _Color.red
939
940 def test_choices_provider_literal_int_coerces_at_parse(self) -> None:
941 """End-to-end: a Literal[int] with a choices_provider parses to int, not a str."""
942
943 def func(
944 self,
945 level: Annotated[Literal[1, 2], Argument(choices_provider=_provider)],
946 ) -> None: ...
947
948 parser = build_parser_from_function(func)
949 parsed = parser.parse_args(["1"]).level
950 assert parsed == 1
951 assert isinstance(parsed, int)
952
953 def test_bare_enum_literal_coerce_at_parse(self) -> None:
954 """Bare Enum/Literal positionals and options coerce to the declared type at parse time.
955
956 Uses identity / isinstance (not ``==``) so a stripped converter returning a raw ``str``
957 cannot hide behind StrEnum/IntEnum equality.
958 """
959 assert build_parser_from_function(_make_func(Literal["fast", "slow"], name="mode")).parse_args(["fast"]).mode == "fast"
960 assert (
961 build_parser_from_function(_make_func(Literal["fast", "slow"], name="mode", default="fast"))
962 .parse_args(["--mode", "slow"])
963 .mode
964 == "slow"
965 )
966
967 level = build_parser_from_function(_make_func(Literal[1, 2, 3], name="level")).parse_args(["2"]).level
968 assert level == 2
969 assert isinstance(level, int)
970
971 assert build_parser_from_function(_make_func(_Color, name="color")).parse_args(["red"]).color is _Color.red
972 assert (
973 build_parser_from_function(_make_func(_Color, name="color", default=_Color.blue))
974 .parse_args(["--color", "red"])
975 .color
976 is _Color.red
977 )
978 # Non-StrEnum cases: identity defeats the StrEnum/IntEnum ``==`` masking property.
979 assert build_parser_from_function(_make_func(_IntColor, name="color")).parse_args(["1"]).color is _IntColor.red
980 assert build_parser_from_function(_make_func(_PlainColor, name="color")).parse_args(["red"]).color is _PlainColor.RED
981
982 def test_completer_keeps_path_converter(self) -> None:
983 """User-supplied completer on Path preserves the (non-restrictive) Path converter."""
984 action = _get_param_action(_make_func(Annotated[Path, Argument(completer=cmd2.Cmd.path_complete)], name="file"))
985 assert action.type is Path
986
987 def test_completer_overrides_inferred_path_completion(self) -> None:
988 action = _get_param_action(_make_func(Annotated[Path, Argument(completer=cmd2.Cmd.path_complete)], name="file"))
989 assert action.get_choices_provider() is None # type: ignore[attr-defined]
990 assert action.get_completer() is cmd2.Cmd.path_complete # type: ignore[attr-defined]
991
992 def test_inferred_enum_choices_match_type_converter(self) -> None:
993 """Enum choices must be convertible by the type converter."""
994 action = _get_param_action(_make_func(_Color, name="color"))
995 converter = action.type
996 for choice in action.choices:
997 assert isinstance(converter(str(choice)), _Color)
998
999 @pytest.mark.parametrize(
1000 "func",
1001 [
1002 pytest.param(_make_func(Path, name="file"), id="path_positional"),
1003 pytest.param(_make_func(Path, name="file", default=Path(".")), id="path_option"),
1004 pytest.param(_make_func(list[Path], name="files"), id="list_path"),
1005 pytest.param(_make_func(tuple[Path, Path], name="src_dst"), id="tuple_paths"),
1006 ],
1007 )
1008 def test_path_annotation_wires_path_completer(self, func) -> None:
1009 """A bare ``Path`` annotation (no user metadata) auto-wires ``Cmd.path_complete``."""
1010 action = _get_param_action(func)
1011 assert action.get_completer() is cmd2.Cmd.path_complete # type: ignore[attr-defined]
1012
1013
1014 # ---------------------------------------------------------------------------
1015 # Argument groups and mutually exclusive groups
1016 # ---------------------------------------------------------------------------
1017
1018
1019 class TestArgumentGroups:
1020 def test_groups_and_mutex_applied(self) -> None:
1021 parser = build_parser_from_function(
1022 _func_grouped,
1023 groups=(Group("local", "remote"), Group("force", "dry_run")),
1024 mutually_exclusive_groups=(Group("local", "remote"), Group("force", "dry_run")),
1025 )
1026
1027 nonempty_groups = [group for group in parser._action_groups if group._group_actions]
1028 grouped_dests = [{action.dest for action in group._group_actions} for group in nonempty_groups]
1029 assert {"local", "remote"} in grouped_dests
1030 assert {"force", "dry_run"} in grouped_dests
1031
1032 mutex_groups = [{action.dest for action in group._group_actions} for group in parser._mutually_exclusive_groups]
1033 assert {"local", "remote"} in mutex_groups
1034 assert {"force", "dry_run"} in mutex_groups
1035
1036 def test_group_nonexistent_param_raises(self) -> None:
1037 with pytest.raises(ValueError, match="'missing', which is not a command-line argument"):
1038 build_parser_from_function(_func_grouped, groups=(Group("missing"),))
1039
1040 def test_param_in_multiple_groups_raises(self) -> None:
1041 with pytest.raises(ValueError, match="cannot be assigned to both argument group"):
1042 build_parser_from_function(_func_grouped, groups=(Group("local"), Group("local", "remote")))
1043
1044 @pytest.mark.filterwarnings("error::DeprecationWarning")
1045 def test_mutex_group_nests_inside_argument_group(self) -> None:
1046 """A mutex group whose members all sit in one Group(...) is created inside that argument group.
1047
1048 This is the one nesting direction argparse supports: ``group.add_mutually_exclusive_group()``.
1049 The Python 3.11 deprecations cover the other three directions (group-in-group, group-in-mutex,
1050 mutex-in-mutex) -- group-in-group is a hard ``ValueError`` on current Python. The
1051 ``filterwarnings`` marker turns any future argparse deprecation of this direction into a
1052 test failure.
1053 """
1054 parser = build_parser_from_function(
1055 _func_grouped,
1056 groups=(Group("local", "remote", "force", title="Location"),),
1057 mutually_exclusive_groups=(Group("local", "remote"),),
1058 )
1059 assert len(parser._mutually_exclusive_groups) == 1
1060 mutex = parser._mutually_exclusive_groups[0]
1061 location = next(g for g in parser._action_groups if g.title == "Location")
1062 # The mutex group's container is the titled argument group, so its members render under it.
1063 assert mutex._container is location
1064 mutex_dests = {action.dest for action in mutex._group_actions}
1065 assert mutex_dests == {"local", "remote"}
1066 # The non-mutex member still lands in the argument group.
1067 assert {action.dest for action in location._group_actions} == {"local", "remote", "force"}
1068 assert "Location" in parser.format_help()
1069 # Exclusivity is enforced.
1070 with pytest.raises(SystemExit):
1071 parser.parse_args(["--local", "a", "--remote", "b"])
1072
1073 def test_mutex_group_spanning_different_argument_groups_raises(self) -> None:
1074 with pytest.raises(ValueError, match="spans parameters in different argument groups"):
1075 build_parser_from_function(
1076 _func_grouped,
1077 groups=(Group("local"), Group("remote")),
1078 mutually_exclusive_groups=(Group("local", "remote"),),
1079 )
1080
1081 def test_mutex_group_partially_in_argument_group_raises(self) -> None:
1082 # ``local`` is in the titled group, ``remote`` is not: nesting the whole mutex inside the group
1083 # would silently pull ``remote`` into its section, so all-or-none membership is required.
1084 with pytest.raises(ValueError, match="mixes members in a titled argument group"):
1085 build_parser_from_function(
1086 _func_grouped,
1087 groups=(Group("local", title="Location"),),
1088 mutually_exclusive_groups=(Group("local", "remote"),),
1089 )
1090
1091 def test_mutex_group_title_creates_titled_section(self) -> None:
1092 # title/description on the mutex itself build the titled section and nest the mutex inside it,
1093 # so no paired groups= entry is needed.
1094 parser = build_parser_from_function(
1095 _func_grouped,
1096 mutually_exclusive_groups=(Group("local", "remote", title="Location", description="where"),),
1097 )
1098 section = next(g for g in parser._action_groups if g.title == "Location")
1099 assert section.description == "where"
1100 assert len(parser._mutually_exclusive_groups) == 1
1101 mutex = parser._mutually_exclusive_groups[0]
1102 assert mutex._container is section
1103 assert {action.dest for action in mutex._group_actions} == {"local", "remote"}
1104 with pytest.raises(SystemExit):
1105 parser.parse_args(["--local", "a", "--remote", "b"])
1106
1107 def test_mutex_group_title_with_members_in_argument_group_raises(self) -> None:
1108 # Declaring the titled section in both places (groups= and the mutex) is ambiguous.
1109 with pytest.raises(ValueError, match="declare the titled section in one place only"):
1110 build_parser_from_function(
1111 _func_grouped,
1112 groups=(Group("local", "remote", title="A"),),
1113 mutually_exclusive_groups=(Group("local", "remote", title="B"),),
1114 )
1115
1116 def test_mutually_exclusive_group(self) -> None:
1117 """Mutually exclusive params cannot be used together."""
1118
1119 def func(self, verbose: bool = False, quiet: bool = False) -> None: ...
1120
1121 parser = build_parser_from_function(func, mutually_exclusive_groups=(Group("verbose", "quiet"),))
1122 assert len(parser._mutually_exclusive_groups) == 1
1123 group_dests = {a.dest for a in parser._mutually_exclusive_groups[0]._group_actions}
1124 assert group_dests == {"verbose", "quiet"}
1125 with pytest.raises(SystemExit):
1126 parser.parse_args(["--verbose", "--quiet"])
1127
1128 def test_multiple_mutually_exclusive_groups(self) -> None:
1129 """Multiple mutually exclusive groups."""
1130
1131 def func(self, verbose: bool = False, quiet: bool = False, json: bool = False, csv: bool = False) -> None: ...
1132
1133 parser = build_parser_from_function(func, mutually_exclusive_groups=(Group("verbose", "quiet"), Group("json", "csv")))
1134 assert len(parser._mutually_exclusive_groups) == 2
1135
1136 def test_required_member_in_mutex_group_raises(self) -> None:
1137 """A required (no default, non-Optional) option in a mutex group is rejected with a clear error.
1138
1139 argparse forbids required members in a mutex group, and it would be type-unsafe: only one
1140 member is supplied, so the others arrive as None. The message must steer toward making it optional.
1141 """
1142
1143 def func(self, local: Annotated[str, Option("--local")], remote: str | None = None) -> None: ...
1144
1145 with pytest.raises(ValueError, match=r"mutually exclusive group members must be optional"):
1146 build_parser_from_function(func, mutually_exclusive_groups=(Group("local", "remote"),))
1147
1148 def test_required_positional_member_in_mutex_group_raises(self) -> None:
1149 """A required *positional* mutex member is rejected with the same clear, type-safety message.
1150
1151 Positionals never carry argparse's ``required=`` flag, so the check keys on the parameter
1152 being non-omittable, not on ``required`` (which is always False for a positional).
1153 """
1154
1155 def func(self, a: int, b: Annotated[int, Option("--b")] = 0) -> None: ...
1156
1157 with pytest.raises(ValueError, match=r"mutually exclusive group members must be optional"):
1158 build_parser_from_function(func, mutually_exclusive_groups=(Group("a", "b"),))
1159
1160 def test_optional_members_in_mutex_group_build(self) -> None:
1161 """Mutex members that are Optional or have defaults build fine (the regression guard)."""
1162
1163 def func(self, local: Annotated[str | None, Option("--local")] = None, remote: str = "x") -> None: ...
1164
1165 parser = build_parser_from_function(func, mutually_exclusive_groups=(Group("local", "remote"),))
1166 assert len(parser._mutually_exclusive_groups) == 1
1167
1168 def test_bool_flag_members_in_mutex_group_build(self) -> None:
1169 """Plain bool flags (no default) are not required, so they belong in a mutex group."""
1170
1171 def func(self, verbose: Annotated[bool, Option("--verbose")], quiet: Annotated[bool, Option("--quiet")]) -> None: ...
1172
1173 parser = build_parser_from_function(func, mutually_exclusive_groups=(Group("verbose", "quiet"),))
1174 assert len(parser._mutually_exclusive_groups) == 1
1175
1176 def test_nonexistent_member_reported_over_required_member(self) -> None:
1177 """A typo'd member name surfaces as 'nonexistent', not masked by the required-member check."""
1178
1179 def func(self, local: Annotated[str, Option("--local")], remote: str | None = None) -> None: ...
1180
1181 with pytest.raises(ValueError, match=r"'ghost', which is not a command-line argument"):
1182 build_parser_from_function(func, mutually_exclusive_groups=(Group("local", "ghost"),))
1183
1184 def test_argument_group(self) -> None:
1185 """Arguments in a group appear under a shared heading in help."""
1186
1187 def func(self, src: str, dst: str, recursive: bool = False, verbose: bool = False) -> None: ...
1188
1189 parser = build_parser_from_function(func, groups=(Group("src", "dst"),))
1190 default_titles = {"Positional Arguments", "options"}
1191 custom_groups = [g for g in parser._action_groups if g.title not in default_titles]
1192 assert len(custom_groups) >= 1
1193 all_custom_dests = {a.dest for g in custom_groups for a in g._group_actions}
1194 assert {"src", "dst"} <= all_custom_dests
1195
1196 def test_mutually_exclusive_via_decorator(self) -> None:
1197 """@with_annotated(mutually_exclusive_groups=...) works end-to-end."""
1198
1199 class App(cmd2.Cmd):
1200 @with_annotated(mutually_exclusive_groups=(Group("verbose", "quiet"),))
1201 def do_run(self, verbose: bool = False, quiet: bool = False) -> None:
1202 if verbose:
1203 self.poutput("verbose")
1204 elif quiet:
1205 self.poutput("quiet")
1206 else:
1207 self.poutput("normal")
1208
1209 app = App()
1210 out, _err = run_cmd(app, "run --verbose")
1211 assert out == ["verbose"]
1212
1213 _out, err = run_cmd(app, "run --verbose --quiet")
1214 assert any("not allowed" in line.lower() for line in err)
1215
1216 def test_group_and_mutex_can_overlap(self) -> None:
1217 def func(self, json: bool = False, csv: bool = False, plain: bool = False) -> None: ...
1218
1219 parser = build_parser_from_function(
1220 func,
1221 groups=(Group("json", "csv"),),
1222 mutually_exclusive_groups=(Group("json", "csv"),),
1223 )
1224 custom_groups = [g for g in parser._action_groups if g.title not in {"Positional Arguments", "options"}]
1225 all_custom_dests = {a.dest for g in custom_groups for a in g._group_actions}
1226 assert {"json", "csv"} <= all_custom_dests
1227 with pytest.raises(SystemExit):
1228 parser.parse_args(["--json", "--csv"])
1229
1230
1231 class TestParserCustomization:
1232 """description / epilog / formatter_class / parser_class and titled Group."""
1233
1234 def test_titled_group(self) -> None:
1235 """Group(title=..., description=...) renders a titled help section."""
1236
1237 def func(self, host: str, port: int = 22, verbose: bool = False) -> None: ...
1238
1239 parser = build_parser_from_function(
1240 func,
1241 groups=(Group("host", "port", title="connection", description="where to connect"),),
1242 )
1243 titled = [g for g in parser._action_groups if g.title == "connection"]
1244 assert len(titled) == 1
1245 assert titled[0].description == "where to connect"
1246 assert {a.dest for a in titled[0]._group_actions} == {"host", "port"}
1247
1248 def test_group_requires_members(self) -> None:
1249 with pytest.raises(ValueError, match="at least one member"):
1250 Group(title="empty")
1251
1252 def test_description_and_epilog(self) -> None:
1253 parser = build_parser_from_function(_make_func(str), description="my description", epilog="my epilog")
1254 assert parser.description == "my description"
1255 assert parser.epilog == "my epilog"
1256
1257 def test_custom_formatter_class(self) -> None:
1258 from cmd2.rich_utils import Cmd2HelpFormatter
1259
1260 class MyFormatter(Cmd2HelpFormatter):
1261 pass
1262
1263 parser = build_parser_from_function(_make_func(str), formatter_class=MyFormatter)
1264 assert parser.formatter_class is MyFormatter
1265
1266 def test_custom_parser_class(self) -> None:
1267 class MyParser(cmd2.Cmd2ArgumentParser):
1268 pass
1269
1270 parser = build_parser_from_function(_make_func(str), parser_class=MyParser)
1271 assert isinstance(parser, MyParser)
1272
1273 def test_default_parser_class(self) -> None:
1274 """With no parser_class, the parser is an instance of the configured default."""
1275 from cmd2 import argparse_utils
1276
1277 parser = build_parser_from_function(_make_func(str))
1278 assert type(parser) is argparse_utils.DEFAULT_ARGUMENT_PARSER
1279
1280 def test_default_parser_class_follows_current_default(self, monkeypatch) -> None:
1281 """The default is resolved at call time, never a copy captured at import.
1282
1283 ``set_default_argument_parser`` rebinds ``argparse_utils.DEFAULT_ARGUMENT_PARSER`` at runtime;
1284 a build issued afterwards must honor the new value.
1285 """
1286 from cmd2 import argparse_utils
1287
1288 class MyDefaultParser(cmd2.Cmd2ArgumentParser):
1289 pass
1290
1291 monkeypatch.setattr(argparse_utils, "DEFAULT_ARGUMENT_PARSER", MyDefaultParser)
1292 parser = build_parser_from_function(_make_func(str))
1293 assert type(parser) is MyDefaultParser
1294
1295 def test_completer_class(self) -> None:
1296 from cmd2.argparse_completer import ArgparseCompleter
1297
1298 class MyCompleter(ArgparseCompleter):
1299 pass
1300
1301 parser = build_parser_from_function(_make_func(str), completer_class=MyCompleter)
1302 assert parser.completer_class is MyCompleter
1303
1304 def test_default_completer_class(self) -> None:
1305 from cmd2 import argparse_completer
1306
1307 assert build_parser_from_function(_make_func(str)).completer_class is argparse_completer.DEFAULT_ARGPARSE_COMPLETER
1308
1309 def test_completer_class_via_decorator(self) -> None:
1310 from cmd2.argparse_completer import ArgparseCompleter
1311
1312 class MyCompleter(ArgparseCompleter):
1313 pass
1314
1315 @with_annotated(completer_class=MyCompleter)
1316 def do_run(self, name: str) -> None: ...
1317
1318 builder = getattr(do_run, constants.ARGPARSE_COMMAND_ATTR_SPEC).parser_source
1319 assert builder().completer_class is MyCompleter
1320
1321 def test_completer_class_threads_to_subcommand(self) -> None:
1322 from cmd2.argparse_completer import ArgparseCompleter
1323
1324 class MyCompleter(ArgparseCompleter):
1325 pass
1326
1327 @with_annotated(subcommand_to="team", completer_class=MyCompleter)
1328 def team_create(self, name: str) -> None: ...
1329
1330 spec = getattr(team_create, constants.SUBCOMMAND_ATTR_SPEC)
1331 assert spec.parser_source().completer_class is MyCompleter
1332
1333 def test_customization_via_decorator(self) -> None:
1334 """description/epilog/titled Group flow through @with_annotated end-to-end."""
1335
1336 class App(cmd2.Cmd):
1337 @with_annotated(
1338 description="run the thing",
1339 epilog="see docs for more",
1340 groups=(Group("name", title="inputs"),),
1341 )
1342 def do_run(self, name: str) -> None:
1343 self.poutput(f"ran {name}")
1344
1345 app = App()
1346 out, _err = run_cmd(app, "run alice")
1347 assert out == ["ran alice"]
1348
1349 help_out, _ = run_cmd(app, "help run")
1350 joined = "\n".join(help_out).lower()
1351 assert "run the thing" in joined
1352 assert "see docs for more" in joined
1353 assert "inputs" in joined
1354
1355 def test_customization_via_subcommand(self) -> None:
1356 """description/epilog flow through subcommand parsers."""
1357
1358 class App(cmd2.Cmd):
1359 @with_annotated(base_command=True)
1360 def do_team(self, *, cmd2_subcommand_func=None) -> None:
1361 if cmd2_subcommand_func:
1362 cmd2_subcommand_func()
1363
1364 @with_annotated(subcommand_to="team", help="add a member", description="add desc", epilog="add epilog")
1365 def team_add(self, name: str) -> None:
1366 self.poutput(f"added {name}")
1367
1368 app = App()
1369 out, _err = run_cmd(app, "team add bob")
1370 assert out == ["added bob"]
1371
1372 spec = getattr(App.team_add, constants.SUBCOMMAND_ATTR_SPEC)
1373 subparser = spec.parser_source()
1374 assert subparser.description == "add desc"
1375 assert subparser.epilog == "add epilog"
1376
1377
1378 class TestGroupHelpers:
1379 def test_build_argument_group_targets(self) -> None:
1380 parser = argparse.ArgumentParser()
1381 target_for, argument_group_for = _build_argument_group_targets(parser, groups=(Group("src", "dst"),))
1382 assert set(target_for) == {"src", "dst"}
1383 assert set(argument_group_for) == {"src", "dst"}
1384 assert target_for["src"] is argument_group_for["src"]
1385 assert target_for["dst"] is argument_group_for["dst"]
1386
1387 def test_duplicate_argument_group_assignment_raises(self) -> None:
1388 # Double-assignment is enforced by _validate_group_specs, which the build path runs first.
1389 def func(self, *, verbose: bool = False) -> None: ...
1390
1391 with pytest.raises(ValueError, match="argument group 1 and argument group 2"):
1392 build_parser_from_function(func, groups=(Group("verbose"), Group("verbose")))
1393
1394 def test_apply_mutex_group_targets(self) -> None:
1395 parser = argparse.ArgumentParser()
1396 target_for, argument_group_for = _build_argument_group_targets(parser, groups=(Group("json", "csv"),))
1397
1398 _apply_mutex_group_targets(
1399 parser,
1400 target_for=target_for,
1401 argument_group_for=argument_group_for,
1402 mutually_exclusive_groups=(Group("json", "csv"),),
1403 )
1404
1405 assert target_for["json"] is target_for["csv"]
1406 assert isinstance(target_for["json"], argparse._MutuallyExclusiveGroup)
1407
1408 def test_duplicate_mutex_group_assignment_raises(self) -> None:
1409 # Double-assignment is enforced by _validate_group_specs, which the build path runs first.
1410 def func(self, *, verbose: bool = False) -> None: ...
1411
1412 with pytest.raises(ValueError, match="multiple mutually exclusive groups"):
1413 build_parser_from_function(func, mutually_exclusive_groups=(Group("verbose"), Group("verbose")))
1414
1415 def test_repeated_member_in_one_argument_group_raises(self) -> None:
1416 # A name listed twice in a single Group is a distinct mistake from cross-group assignment
1417 # and gets its own message (not the misleading "both group 1 and group 1").
1418 def func(self, *, verbose: bool = False) -> None: ...
1419
1420 with pytest.raises(ValueError, match="listed more than once in argument group 1"):
1421 build_parser_from_function(func, groups=(Group("verbose", "verbose"),))
1422
1423 def test_repeated_member_in_one_mutex_group_raises(self) -> None:
1424 def func(self, *, verbose: bool = False) -> None: ...
1425
1426 with pytest.raises(ValueError, match="listed more than once in mutually exclusive group 1"):
1427 build_parser_from_function(func, mutually_exclusive_groups=(Group("verbose", "verbose"),))
1428
1429 def test_validate_group_specs_rejects_cross_group_members(self) -> None:
1430 # The spec validator owns the group-shaped rules; construction trusts it.
1431 def func(self, src: str = "a", dst: str = "b") -> None: ...
1432
1433 with pytest.raises(ValueError, match="different argument groups"):
1434 _validate_group_specs(
1435 groups=(Group("src"), Group("dst")),
1436 mutually_exclusive_groups=(Group("src", "dst"),),
1437 )
1438
1439
1440 class TestBuildTimeMemberValidation:
1441 """A Group member names an argument, and that is checked once the arguments are built.
1442
1443 It cannot be checked at decoration time: an ArgumentBlock expands into one argument per field, and the
1444 field names live inside the dataclass, reachable only by resolving the block's type hint -- which the
1445 decoration-time checks never do, so forward references keep working.
1446 """
1447
1448 def test_block_fields_can_be_named_in_an_argument_group(self) -> None:
1449 """The #1714 case: a block's arguments are its fields, so its fields are what a group names."""
1450
1451 @dataclass
1452 class Conn(ArgumentBlock):
1453 host: Annotated[str, Option("--host")] = "localhost"
1454 port: Annotated[int, Option("--port")] = 8080
1455
1456 def func(self, conn: Conn, verbose: bool = False) -> None: ...
1457
1458 parser = build_parser_from_function(func, groups=(Group("host", "port", title="Connection"),))
1459 section = next(g for g in parser._action_groups if g.title == "Connection")
1460 assert {a.dest for a in section._group_actions} == {"host", "port"}
1461
1462 def test_block_fields_can_be_named_in_a_mutex_group(self) -> None:
1463 """Fields that are genuinely alternatives are named individually, so the meaning is explicit."""
1464
1465 @dataclass
1466 class Format(ArgumentBlock):
1467 json: Annotated[bool, Option("--json")] = False
1468 csv: Annotated[bool, Option("--csv")] = False
1469
1470 def func(self, fmt: Format, verbose: bool = False) -> None: ...
1471
1472 parser = build_parser_from_function(func, mutually_exclusive_groups=(Group("json", "csv"),))
1473 assert {a.dest for a in parser._mutually_exclusive_groups[0]._group_actions} == {"json", "csv"}
1474 with pytest.raises(SystemExit):
1475 parser.parse_args(["--json", "--csv"])
1476
1477 def test_a_group_can_mix_block_fields_and_plain_parameters(self) -> None:
1478 """Members name arguments, so where an argument came from stops mattering once it is built.
1479
1480 The block's own `port` is left out to pin down that a group takes the fields it names rather
1481 than the whole block that one of them happens to belong to.
1482 """
1483
1484 @dataclass
1485 class Conn(ArgumentBlock):
1486 host: Annotated[str, Option("--host")] = "localhost"
1487 port: Annotated[int, Option("--port")] = 8080
1488
1489 def func(self, conn: Conn, verbose: bool = False) -> None: ...
1490
1491 parser = build_parser_from_function(func, groups=(Group("host", "verbose", title="Mixed"),))
1492 section = next(g for g in parser._action_groups if g.title == "Mixed")
1493 assert {a.dest for a in section._group_actions} == {"host", "verbose"}
1494 ns = parser.parse_args(["--host", "h", "--verbose"])
1495 assert (ns.host, ns.verbose) == ("h", True)
1496
1497 def test_a_mutex_can_mix_a_block_field_and_a_plain_parameter(self) -> None:
1498 """A block field and a plain parameter can be genuine alternatives to each other."""
1499
1500 @dataclass
1501 class Conn(ArgumentBlock):
1502 host: Annotated[str, Option("--host")] = "localhost"
1503
1504 def func(self, conn: Conn, verbose: bool = False) -> None: ...
1505
1506 parser = build_parser_from_function(func, mutually_exclusive_groups=(Group("host", "verbose"),))
1507 assert {a.dest for a in parser._mutually_exclusive_groups[0]._group_actions} == {"host", "verbose"}
1508 assert parser.parse_args(["--host", "h"]).host == "h"
1509 assert parser.parse_args(["--verbose"]).verbose is True
1510 with pytest.raises(SystemExit):
1511 parser.parse_args(["--host", "h", "--verbose"])
1512
1513 def test_naming_the_block_parameter_is_rejected(self) -> None:
1514 """The block parameter is expanded away and has no argument, so it cannot be a member."""
1515
1516 @dataclass
1517 class Conn(ArgumentBlock):
1518 host: Annotated[str, Option("--host")] = "localhost"
1519
1520 def func(self, conn: Conn, verbose: bool = False) -> None: ...
1521
1522 with pytest.raises(ValueError, match="'conn', which is an ArgumentBlock parameter"):
1523 build_parser_from_function(func, groups=(Group("conn", title="Connection"),))
1524
1525 def test_naming_the_block_parameter_in_a_mutex_is_rejected_too(self) -> None:
1526 """Same rule in both spec kinds -- there is no groups=/mutex asymmetry to remember."""
1527
1528 @dataclass
1529 class Conn(ArgumentBlock):
1530 host: Annotated[str, Option("--host")] = "localhost"
1531
1532 def func(self, conn: Conn, verbose: bool = False) -> None: ...
1533
1534 with pytest.raises(ValueError, match="'conn', which is an ArgumentBlock parameter"):
1535 build_parser_from_function(func, mutually_exclusive_groups=(Group("conn", "verbose"),))
1536
1537 def test_naming_the_block_class_is_rejected(self) -> None:
1538 """The class name is not a parameter or an argument; only fields are."""
1539
1540 @dataclass
1541 class Conn(ArgumentBlock):
1542 host: Annotated[str, Option("--host")] = "localhost"
1543
1544 def func(self, conn: Conn, verbose: bool = False) -> None: ...
1545
1546 with pytest.raises(ValueError, match="'Conn', which is not a command-line argument"):
1547 build_parser_from_function(func, groups=(Group("Conn", title="Connection"),))
1548
1549 def test_parent_args_block_parameter_is_rejected(self) -> None:
1550 """cmd2_parent_args declares no arguments of its own; its fields come from the parent."""
1551
1552 @dataclass
1553 class Base(ArgumentBlock):
1554 dry: Annotated[bool, Option("--dry")] = False
1555
1556 def func(self, cmd2_parent_args: Base, verbose: bool = False) -> None: ...
1557
1558 with pytest.raises(ValueError, match="'cmd2_parent_args', which is an ArgumentBlock parameter"):
1559 build_parser_from_function(func, groups=(Group("cmd2_parent_args", title="Inherited"),))
1560
1561 def test_member_typo_fails_at_build(self) -> None:
1562 """A typo still hard-fails -- at the parser build rather than at decoration."""
1563
1564 def do_x(self, a: str = "v") -> None: ...
1565
1566 with_annotated(groups=(Group("typo"),))(do_x) # decorates: existence is not knowable yet
1567 with pytest.raises(ValueError, match="'typo', which is not a command-line argument"):
1568 build_parser_from_function(do_x, groups=(Group("typo"),))
1569
1570
1571 class TestEagerGroupSpecValidation:
1572 """Spec-*shape* rules hard-fail at decoration time (class definition), not on first command use.
1573
1574 The decorator runs the spec-shape checks before deferring the parser build, so a misshapen group
1575 raises while the class body executes instead of surfacing as a swallowed runtime error the first
1576 time the command runs. These checks read the ``Group`` specs only -- never the signature and never
1577 the type hints -- so forward-referenced annotations still decorate.
1578
1579 Whether a member *exists* is deliberately not among them: an ArgumentBlock's arguments are its
1580 dataclass fields, which only resolving its hint would reveal, so that check runs at parser build
1581 (see :class:`TestBuildTimeMemberValidation`).
1582 """
1583
1584 def test_param_in_two_argument_groups_fails_at_decoration(self) -> None:
1585 def do_x(self, a: str = "v") -> None: ...
1586
1587 with pytest.raises(ValueError, match="argument group 1 and argument group 2"):
1588 with_annotated(groups=(Group("a"), Group("a")))(do_x)
1589
1590 def test_param_in_two_mutex_groups_fails_at_decoration(self) -> None:
1591 def do_x(self, a: str = "v", b: str = "w") -> None: ...
1592
1593 with pytest.raises(ValueError, match="multiple mutually exclusive groups"):
1594 with_annotated(mutually_exclusive_groups=(Group("a", "b"), Group("a")))(do_x)
1595
1596 def test_required_on_plain_group_fails_at_decoration(self) -> None:
1597 def do_x(self, a: str = "v") -> None: ...
1598
1599 with pytest.raises(ValueError, match="only valid in mutually_exclusive_groups"):
1600 with_annotated(groups=(Group("a", required=True),))(do_x)
1601
1602 def test_mutex_spanning_argument_groups_fails_at_decoration(self) -> None:
1603 def do_x(self, a: str = "v", b: str = "w") -> None: ...
1604
1605 with pytest.raises(ValueError, match="spans parameters in different argument groups"):
1606 with_annotated(groups=(Group("a"), Group("b")), mutually_exclusive_groups=(Group("a", "b"),))(do_x)
1607
1608 def test_mutex_partially_in_argument_group_fails_at_decoration(self) -> None:
1609 def do_x(self, a: str = "v", b: str = "w") -> None: ...
1610
1611 with pytest.raises(ValueError, match="mixes members in a titled argument group"):
1612 with_annotated(groups=(Group("a", title="T"),), mutually_exclusive_groups=(Group("a", "b"),))(do_x)
1613
1614 def test_titled_section_declared_twice_fails_at_decoration(self) -> None:
1615 def do_x(self, a: str = "v", b: str = "w") -> None: ...
1616
1617 with pytest.raises(ValueError, match="declare the titled section in one place only"):
1618 with_annotated(
1619 groups=(Group("a", "b", title="T"),),
1620 mutually_exclusive_groups=(Group("a", "b", title="U"),),
1621 )(do_x)
1622
1623 def test_eager_validation_does_not_resolve_type_hints(self) -> None:
1624 # The shape error fires even though the annotation can never resolve: the checks read the
1625 # Group specs only, so the unresolvable hint is not touched.
1626 def do_x(self, a: "NoSuchType" = None) -> None: ... # noqa: F821
1627
1628 with pytest.raises(ValueError, match="only valid in mutually_exclusive_groups"):
1629 with_annotated(groups=(Group("a", required=True),))(do_x)
1630
1631 def test_unresolvable_hints_with_valid_groups_decorate(self) -> None:
1632 # Valid specs + an unresolvable annotation must decorate without raising; type resolution
1633 # stays deferred to the parser build, preserving forward-reference support.
1634 def do_x(self, a: "NoSuchType" = None) -> None: ... # noqa: F821
1635
1636 with_annotated(groups=(Group("a", title="T"),))(do_x)
1637
1638 def test_valid_nested_config_decorates_cleanly(self) -> None:
1639 def do_x(
1640 self,
1641 a: Annotated[bool, Option(action="store_true")] = False,
1642 b: Annotated[bool, Option(action="store_true")] = False,
1643 c: Annotated[bool, Option(action="store_true")] = False,
1644 d: Annotated[bool, Option(action="store_true")] = False,
1645 ) -> None: ...
1646
1647 # A nested mutex plus a separately titled mutex must decorate without raising.
1648 with_annotated(
1649 groups=(Group("a", "b", title="T"),),
1650 mutually_exclusive_groups=(Group("a", "b"), Group("c", "d", title="U")),
1651 )(do_x)
1652
1653
1654 # ---------------------------------------------------------------------------
1655 # _resolve_annotation: positional vs option classification
1656 # ---------------------------------------------------------------------------
1657
1658 _ARG_META = Argument(help_text="Name")
1659 _OPT_META = Option("--color", "-c", help_text="Pick")
1660
1661
1662 class TestResolveAnnotation:
1663 @pytest.mark.parametrize(
1664 ("annotation", "has_default", "expected_positional"),
1665 [
1666 pytest.param(str, False, True, id="plain_str"),
1667 pytest.param(str | None, False, True, id="optional_str_positional"),
1668 pytest.param(str | None, True, False, id="optional_str_with_default"),
1669 pytest.param(Annotated[str, _ARG_META], False, True, id="annotated_argument"),
1670 pytest.param(Annotated[str, _OPT_META], False, False, id="annotated_option"),
1671 pytest.param(Annotated[str, "some doc"], False, True, id="annotated_no_meta"),
1672 pytest.param(str, True, False, id="has_default"),
1673 pytest.param(bool, True, False, id="bool_flag"),
1674 ],
1675 )
1676 def test_classification(self, annotation, has_default, expected_positional) -> None:
1677 # A non-None default is supplied when has_default (default=None on a non-Optional type
1678 # is itself rejected); classification depends only on whether a default exists, not its value.
1679 extra = {"default": 0} if has_default else {}
1680 arg = _resolve_annotation(annotation, has_default=has_default, **extra)
1681 assert arg.is_positional is expected_positional
1682
1683 def test_optional_wrapping_annotated_with_none_inside(self) -> None:
1684 """Optional[Annotated[T | None, meta]] is allowed (inner type contains None)."""
1685 ann = Annotated[str | None, _OPT_META] | None
1686 arg = _resolve_annotation(ann)
1687 assert arg.metadata is _OPT_META
1688 assert arg.is_positional is False
1689
1690 def test_typing_union_optional(self) -> None:
1691 ns: dict = {}
1692 exec("import typing; t = typing.Union[str, None]", ns)
1693 assert _resolve_annotation(ns["t"]).is_positional is True
1694
1695 def test_typing_union_optional_with_default(self) -> None:
1696 ns: dict = {}
1697 exec("import typing; t = typing.Union[str, None]", ns)
1698 assert _resolve_annotation(ns["t"], has_default=True, default=None).is_positional is False
1699
1700 def test_annotated_multiple_metadata_picks_first(self) -> None:
1701 meta1 = Argument(help_text="first")
1702 meta2 = Option("--x", help_text="second")
1703 arg = _resolve_annotation(Annotated[str, meta1, meta2])
1704 assert arg.metadata is meta1
1705 assert arg.extras.get("help") == "first"
1706
1707
1708 # ---------------------------------------------------------------------------
1709 # Error paths
1710 # ---------------------------------------------------------------------------
1711
1712
1713 class TestUnsupportedPatterns:
1714 def test_union_raises_with_diagnostic_message(self) -> None:
1715 with pytest.raises(TypeError, match=r"str.*int") as exc_info:
1716 _resolve_annotation(str | int)
1717 assert "Union" in str(exc_info.value)
1718
1719 def test_tuple_mixed_raises(self) -> None:
1720 with pytest.raises(TypeError, match="mixed element types"):
1721 _resolve_annotation(tuple[int, str, float])
1722
1723 @pytest.mark.parametrize(
1724 "annotation",
1725 [
1726 pytest.param(Annotated[str, Argument(nargs=2)], id="str_nargs_2"),
1727 pytest.param(Annotated[int | None, Argument(nargs="+")], id="optional_int_nargs_plus"),
1728 pytest.param(Annotated[int, Argument(nargs="*")], id="int_nargs_star"),
1729 pytest.param(Annotated[str, Argument(nargs=1)], id="str_nargs_1"),
1730 ],
1731 )
1732 def test_multi_nargs_on_scalar_raises(self, annotation) -> None:
1733 with pytest.raises(TypeError, match=r"nargs=.* not a collection type"):
1734 _resolve_annotation(annotation)
1735
1736 @pytest.mark.parametrize(
1737 "annotation",
1738 [
1739 pytest.param(Annotated[tuple[str, str], Argument(nargs=1)], id="tuple2_nargs_1"),
1740 pytest.param(Annotated[tuple[str, str], Argument(nargs=3)], id="tuple2_nargs_3"),
1741 pytest.param(Annotated[tuple[int, int, int], Argument(nargs="+")], id="tuple3_nargs_plus"),
1742 pytest.param(Annotated[tuple[str, str], Argument(nargs="?")], id="tuple2_nargs_optional"),
1743 ],
1744 )
1745 def test_nargs_overrides_fixed_arity_raises(self, annotation) -> None:
1746 with pytest.raises(TypeError, match=r"conflicts with the fixed arity"):
1747 _resolve_annotation(annotation)
1748
1749 @pytest.mark.parametrize(
1750 ("annotation", "resolve_kwargs"),
1751 [
1752 pytest.param(
1753 Annotated[tuple[int, int], Argument()],
1754 {"has_default": True, "default": (1, 2)},
1755 id="fixed_tuple_with_default",
1756 ),
1757 pytest.param(Annotated[tuple[int, int] | None, Argument()], {}, id="fixed_tuple_optional"),
1758 pytest.param(
1759 Annotated[tuple[int, ...], Argument(nargs=2)],
1760 {"has_default": True, "default": (1, 2)},
1761 id="explicit_nargs_with_default",
1762 ),
1763 pytest.param(Annotated[tuple[int, ...] | None, Argument(nargs=2)], {}, id="explicit_nargs_optional"),
1764 ],
1765 )
1766 def test_optional_fixed_arity_positional_raises(self, annotation, resolve_kwargs) -> None:
1767 """argparse cannot make a fixed-arity positional optional, so the combination is rejected."""
1768 with pytest.raises(TypeError, match=r"fixed-arity positional"):
1769 _resolve_annotation(annotation, **resolve_kwargs)
1770
1771 @pytest.mark.parametrize(
1772 "annotation",
1773 [
1774 pytest.param(list[set[int]], id="list_of_set"),
1775 pytest.param(set[list[str]], id="set_of_list"),
1776 pytest.param(tuple[list[int], ...], id="tuple_of_list"),
1777 pytest.param(frozenset[list[int]], id="frozenset_of_list"),
1778 pytest.param(list[frozenset[int]], id="list_of_frozenset"),
1779 ],
1780 )
1781 def test_nested_collection_raises(self, annotation) -> None:
1782 with pytest.raises(TypeError, match="Nested collections are not supported"):
1783 _resolve_annotation(annotation)
1784
1785 @pytest.mark.parametrize(
1786 "annotation",
1787 [
1788 pytest.param(dict[str, int], id="dict"),
1789 ],
1790 )
1791 def test_unsupported_subscripted_generic_raises(self, annotation) -> None:
1792 """An unsupported subscripted generic must raise, not silently arrive as a plain str."""
1793 with pytest.raises(TypeError, match=r"Unsupported parameter type"):
1794 _resolve_annotation(annotation)
1795
1796 @pytest.mark.parametrize(
1797 "annotation",
1798 [
1799 pytest.param(Annotated[list[int] | None, Argument(nargs="?")], id="list_q"),
1800 pytest.param(Annotated[list[int] | None, Argument(nargs=(0, 1))], id="list_0_1"),
1801 pytest.param(Annotated[set[str] | None, Argument(nargs="?")], id="set_q"),
1802 ],
1803 )
1804 def test_optional_single_nargs_on_collection_raises(self, annotation) -> None:
1805 """nargs='?'/(0,1) on a collection yields a single value the casting action cannot wrap."""
1806 with pytest.raises(TypeError, match=r"single value"):
1807 _resolve_annotation(annotation)
1808
1809 @pytest.mark.parametrize(
1810 "annotation",
1811 [
1812 pytest.param(datetime.datetime, id="datetime"),
1813 pytest.param(datetime.date, id="date"),
1814 pytest.param(uuid.UUID, id="uuid"),
1815 pytest.param(bytes, id="bytes"),
1816 pytest.param(complex, id="complex"),
1817 ],
1818 )
1819 def test_unsupported_scalar_type_raises(self, annotation) -> None:
1820 """A type with no converter must not silently arrive as a plain string."""
1821 with pytest.raises(TypeError, match="Unsupported parameter type"):
1822 _resolve_annotation(annotation)
1823
1824 def test_unsupported_custom_class_raises(self) -> None:
1825 class Money:
1826 def __init__(self, raw: str) -> None:
1827 self.raw = raw
1828
1829 with pytest.raises(TypeError, match="Unsupported parameter type"):
1830 _resolve_annotation(Money)
1831
1832 @pytest.mark.parametrize(
1833 "annotation",
1834 [
1835 pytest.param(str, id="str"),
1836 pytest.param(Any, id="any"),
1837 pytest.param(object, id="object"),
1838 ],
1839 )
1840 def test_passthrough_scalar_types_keep_no_converter(self, annotation) -> None:
1841 """str / Any / object are stored as the raw string (type stays None)."""
1842 _flags, kwargs = _resolve_annotation(annotation)._emit()
1843 assert "type" not in kwargs
1844
1845 @pytest.mark.parametrize(
1846 "annotation",
1847 [
1848 pytest.param(list[int, str], id="list_multi_args"),
1849 pytest.param(set[int, str], id="set_multi_args"),
1850 ],
1851 )
1852 def test_collection_multiple_type_args_raises(self, annotation) -> None:
1853 with pytest.raises(TypeError, match="type arguments is not supported"):
1854 _resolve_annotation(annotation)
1855
1856 def test_tuple_ellipsis_wrong_position_raises(self) -> None:
1857 with pytest.raises(TypeError, match="Ellipsis in an unexpected position"):
1858 _resolve_annotation(tuple[..., int])
1859
1860 def test_single_element_union_without_none_raises(self) -> None:
1861 """Union with one non-None type and no None should raise."""
1862 from typing import Union
1863 from unittest.mock import patch
1864
1865 from cmd2.annotated import _unwrap_optional
1866
1867 # Python normalizes Union[str] to str, so we can't construct this
1868 # through normal typing. Patch get_origin/get_args to simulate it.
1869 sentinel = object()
1870 with (
1871 patch("cmd2.annotated.get_origin", return_value=Union),
1872 patch("cmd2.annotated.get_args", return_value=(str,)),
1873 pytest.raises(TypeError, match="single-element Union"),
1874 ):
1875 _unwrap_optional(sentinel)
1876
1877
1878 # ---------------------------------------------------------------------------
1879 # Converters
1880 # ---------------------------------------------------------------------------
1881
1882
1883 class TestParseBool:
1884 @pytest.mark.parametrize("value", ["1", "true", "True", "t", "yes", "y", "on"])
1885 def test_true(self, value) -> None:
1886 assert _parse_bool(value) is True
1887
1888 @pytest.mark.parametrize("value", ["0", "false", "False", "f", "no", "n", "off"])
1889 def test_false(self, value) -> None:
1890 assert _parse_bool(value) is False
1891
1892 def test_invalid(self) -> None:
1893 with pytest.raises(argparse.ArgumentTypeError, match="invalid boolean"):
1894 _parse_bool("maybe")
1895
1896
1897 class TestEnumConverter:
1898 @pytest.mark.parametrize(
1899 ("enum_cls", "input_val", "expected"),
1900 [
1901 pytest.param(_Color, "red", _Color.red, id="str_by_value"),
1902 pytest.param(_IntColor, "1", _IntColor.red, id="int_by_value"),
1903 pytest.param(_IntColor, "red", _IntColor.red, id="int_by_name"),
1904 pytest.param(_PlainColor, "red", _PlainColor.RED, id="plain_by_value"),
1905 pytest.param(_PlainColor, "BLUE", _PlainColor.BLUE, id="plain_by_name"),
1906 ],
1907 )
1908 def test_convert(self, enum_cls, input_val, expected) -> None:
1909 assert _make_enum_type(enum_cls)(input_val) is expected
1910
1911 def test_invalid(self) -> None:
1912 with pytest.raises(argparse.ArgumentTypeError, match="invalid choice"):
1913 _make_enum_type(_Color)("purple")
1914
1915 def test_preserves_class(self) -> None:
1916 assert _make_enum_type(_Color)._cmd2_enum_class is _Color
1917
1918
1919 class TestLiteralConverter:
1920 @pytest.mark.parametrize(
1921 ("values", "input_val", "expected"),
1922 [
1923 pytest.param(["fast", "slow"], "fast", "fast", id="str_match"),
1924 pytest.param([1, 2, 3], "2", 2, id="int_match"),
1925 pytest.param([True, False], "yes", True, id="bool_true_coercion"),
1926 pytest.param([True, False], "0", False, id="bool_false_coercion"),
1927 ],
1928 )
1929 def test_convert(self, values, input_val, expected) -> None:
1930 assert _make_literal_type(values)(input_val) == expected
1931
1932 @pytest.mark.parametrize(
1933 ("values", "input_val"),
1934 [
1935 pytest.param(["fast", "slow"], "medium", id="non_bool_string"),
1936 # bool-like input ("yes"/"on") must still be rejected when the Literal has no bool member
1937 pytest.param(["fast", "slow"], "yes", id="bool_like_no_bool_member"),
1938 pytest.param([1, 2], "on", id="bool_like_int_literal"),
1939 ],
1940 )
1941 def test_invalid(self, values, input_val) -> None:
1942 with pytest.raises(argparse.ArgumentTypeError, match="invalid choice"):
1943 _make_literal_type(values)(input_val)
1944
1945 def test_direct_match_before_bool_coercion(self) -> None:
1946 assert _make_literal_type(["yes", "no"])("yes") == "yes"
1947
1948 def test_colliding_str_representations_raises(self) -> None:
1949 with pytest.raises(TypeError, match="same string representation"):
1950 _make_literal_type(["1", 1])
1951
1952
1953 # ---------------------------------------------------------------------------
1954 # Metadata classes
1955 # ---------------------------------------------------------------------------
1956
1957
1958 class TestMetadata:
1959 @pytest.mark.parametrize(
1960 ("meta_kwargs", "expected"),
1961 [
1962 pytest.param({}, {}, id="empty"),
1963 pytest.param({"help_text": "Name"}, {"help": "Name"}, id="help_text"),
1964 pytest.param({"metavar": "NAME"}, {"metavar": "NAME"}, id="metavar"),
1965 pytest.param({"choices": ["a", "b"]}, {"choices": ["a", "b"]}, id="choices"),
1966 pytest.param({"table_columns": ("Name", "Age")}, {"table_columns": ("Name", "Age")}, id="table_columns"),
1967 pytest.param({"suppress_tab_hint": True}, {"suppress_tab_hint": True}, id="suppress_tab_hint"),
1968 ],
1969 )
1970 def test_to_kwargs(self, meta_kwargs, expected) -> None:
1971 assert Argument(**meta_kwargs).to_kwargs() == expected
1972
1973 def test_to_kwargs_preserves_empty_string(self) -> None:
1974 """Explicit empty string help_text should not be silently dropped."""
1975 assert Argument(help_text="").to_kwargs() == {"help": ""}
1976
1977 def test_to_kwargs_preserves_empty_choices(self) -> None:
1978 """Explicit empty choices list should not be silently dropped."""
1979 assert Argument(choices=[]).to_kwargs() == {"choices": []}
1980
1981 def test_option_to_kwargs_includes_action_and_required(self) -> None:
1982 opt = Option("--color", "-c", action="count", required=True, help_text="Pick")
1983 kwargs = opt.to_kwargs()
1984 assert "names" not in kwargs
1985 assert "flags" not in kwargs
1986 assert kwargs["action"] == "count"
1987 assert kwargs["required"] is True
1988 assert kwargs["help"] == "Pick"
1989
1990 def test_choices_provider_in_kwargs(self) -> None:
1991 def provider(cmd):
1992 return []
1993
1994 assert Argument(choices_provider=provider).to_kwargs()["choices_provider"] is provider
1995
1996 def test_completer_in_kwargs(self) -> None:
1997 assert Argument(completer=cmd2.Cmd.path_complete).to_kwargs()["completer"] is cmd2.Cmd.path_complete
1998
1999 def test_extra_kwarg_forwarded_in_to_kwargs(self) -> None:
2000 """A registered custom add_argument parameter is forwarded via **kwargs."""
2001 assert Argument(annotated_custom_attr="v").to_kwargs()["annotated_custom_attr"] == "v"
2002 assert Option("--x", annotated_custom_attr="v").to_kwargs()["annotated_custom_attr"] == "v"
2003
2004 def test_registered_custom_param_set_on_action(self) -> None:
2005 """A registered custom parameter reaches the resulting argparse Action."""
2006 action = _action_for(Annotated[str, Argument(annotated_custom_attr="v")])
2007 assert action.get_annotated_custom_attr() == "v" # type: ignore[attr-defined]
2008
2009 def test_unregistered_kwarg_raises_at_build(self) -> None:
2010 """An unknown (unregistered) keyword is rejected when the parser is built."""
2011 _assert_build_error(Annotated[str, Argument(definitely_not_registered="v")])
2012
2013
2014 # ---------------------------------------------------------------------------
2015 # _CollectionCastingAction
2016 # ---------------------------------------------------------------------------
2017
2018
2019 class TestCollectionCastingAction:
2020 def test_casts_list_to_container(self) -> None:
2021 action = _CollectionCastingAction(
2022 option_strings=[],
2023 dest="items",
2024 nargs="+",
2025 container_factory=set,
2026 )
2027 ns = argparse.Namespace()
2028 action(argparse.ArgumentParser(), ns, ["a", "b", "a"])
2029 assert ns.items == {"a", "b"}
2030
2031 def test_non_list_passthrough(self) -> None:
2032 action = _CollectionCastingAction(
2033 option_strings=[],
2034 dest="items",
2035 nargs="?",
2036 container_factory=set,
2037 )
2038 ns = argparse.Namespace()
2039 action(argparse.ArgumentParser(), ns, "single_value")
2040 assert ns.items == "single_value"
2041
2042
2043 class TestCollectionRuntimeCast:
2044 """End-to-end verify ``parse_args`` returns the declared container type, not a plain list."""
2045
2046 @pytest.mark.parametrize(
2047 ("annotation", "name", "args", "container", "expected"),
2048 [
2049 pytest.param(frozenset[int], "nums", ["1", "2", "2", "3"], frozenset, frozenset({1, 2, 3}), id="frozenset_int"),
2050 pytest.param(set[int], "nums", ["1", "2", "2", "3"], set, {1, 2, 3}, id="set_int"),
2051 pytest.param(tuple[int, ...], "values", ["1", "2", "3"], tuple, (1, 2, 3), id="tuple_ellipsis"),
2052 pytest.param(tuple[int, int], "pair", ["5", "10"], tuple, (5, 10), id="tuple_fixed"),
2053 pytest.param(list[bool], "flags", ["true", "no", "on"], list, [True, False, True], id="list_bool"),
2054 pytest.param(
2055 tuple[Path, Path],
2056 "src_dst",
2057 ["/tmp/a", "/tmp/b"],
2058 tuple,
2059 (Path("/tmp/a"), Path("/tmp/b")),
2060 id="tuple_paths",
2061 ),
2062 ],
2063 )
2064 def test_returns_declared_container(self, annotation, name, args, container, expected) -> None:
2065 parser = build_parser_from_function(_make_func(annotation, name=name))
2066 value = getattr(parser.parse_args(args), name)
2067 assert isinstance(value, container)
2068 assert value == expected
2069
2070 def test_append_action_collects_values(self) -> None:
2071 parser = build_parser_from_function(_make_func(Annotated[list[str], Option("--tag", action="append")], name="tag"))
2072 ns = parser.parse_args(["--tag", "a", "--tag", "b"])
2073 assert ns.tag == ["a", "b"]
2074
2075 def test_int_subclass_uses_int_converter(self) -> None:
2076 """``Port(int)`` falls back to ``int`` converter; argparse returns ``int``, not ``Port``."""
2077 parser = build_parser_from_function(_make_func(_Port, name="port"))
2078 ns = parser.parse_args(["8080"])
2079 assert ns.port == 8080
2080
2081
2082 # ---------------------------------------------------------------------------
2083 # _filtered_namespace_kwargs edge cases
2084 # ---------------------------------------------------------------------------
2085
2086
2087 class TestFilteredNamespaceKwargs:
2088 def test_excludes_subcommand_key(self) -> None:
2089 from cmd2.annotated import _filtered_namespace_kwargs
2090
2091 ns = argparse.Namespace(subcommand="add", name="Alice")
2092 result = _filtered_namespace_kwargs(ns, exclude_subcommand=True)
2093 assert "subcommand" not in result
2094 assert result == {"name": "Alice"}
2095
2096
2097 # ---------------------------------------------------------------------------
2098 # _parse_positionals edge case
2099 # ---------------------------------------------------------------------------
2100
2101
2102 class TestParsePositionals:
2103 def test_skips_non_statement_next_arg(self) -> None:
2104 """When next_arg after Cmd is not Statement/str, loop continues."""
2105 from cmd2.decorators import _parse_positionals
2106
2107 app = cmd2.Cmd()
2108 # Two Cmd-like objects: first has non-str next, second has str next
2109 result_cmd, result_stmt = _parse_positionals((app, 42, app, "hello"))
2110 assert result_cmd is app
2111 assert result_stmt == "hello"
2112
2113 def test_matches_statement_type(self) -> None:
2114 """When next_arg is a Statement, it is accepted."""
2115 from cmd2.decorators import _parse_positionals
2116 from cmd2.parsing import Statement
2117
2118 app = cmd2.Cmd()
2119 stmt = Statement("hello")
2120 result_cmd, result_stmt = _parse_positionals((app, stmt))
2121 assert result_cmd is app
2122 assert result_stmt is stmt
2123
2124
2125 # ---------------------------------------------------------------------------
2126 # Runtime coverage
2127 # ---------------------------------------------------------------------------
2128
2129
2130 class _Sport(enum.StrEnum):
2131 football = "football"
2132 basketball = "basketball"
2133 tennis = "tennis"
2134
2135
2136 class _RuntimeAnnotatedApp(cmd2.Cmd):
2137 def __init__(self) -> None:
2138 super().__init__()
2139 self._items = ["apple", "banana", "cherry"]
2140
2141 def item_choices(self) -> list[cmd2.CompletionItem]:
2142 return [cmd2.CompletionItem(item) for item in self._items]
2143
2144 @with_annotated
2145 def do_greet(self, name: str, count: int = 1) -> None:
2146 for _ in range(count):
2147 self.poutput(f"Hello {name}")
2148
2149 @with_annotated
2150 def do_add(self, a: int, b: int = 0) -> None:
2151 self.poutput(str(a + b))
2152
2153 @with_annotated
2154 def do_paint(
2155 self,
2156 item: str,
2157 color: Annotated[_Color, Option("--color", "-c", help_text="Color to use")] = _Color.blue,
2158 verbose: bool = False,
2159 ) -> None:
2160 msg = f"Painting {item} {color.value}"
2161 if verbose:
2162 msg += " (verbose)"
2163 self.poutput(msg)
2164
2165 @with_annotated
2166 def do_pick(self, item: Annotated[str, Argument(choices_provider=item_choices)]) -> None:
2167 self.poutput(f"Picked: {item}")
2168
2169 @with_annotated
2170 def do_open(self, path: Path) -> None:
2171 self.poutput(f"Opening: {path}")
2172
2173 @with_annotated
2174 def do_sport(self, sport: _Sport) -> None:
2175 self.poutput(f"Playing: {sport.value}")
2176
2177 @with_annotated
2178 def do_toggle(self, enabled: bool) -> None:
2179 self.poutput(f"Enabled: {enabled}")
2180
2181 @with_annotated(preserve_quotes=True)
2182 def do_raw(self, text: str) -> None:
2183 self.poutput(f"raw: {text}")
2184
2185 @with_annotated
2186 def do_echo_all(self, *words: str) -> None:
2187 self.poutput(f"words={list(words)}")
2188
2189 @with_annotated
2190 def do_total(self, label: str, *nums: int) -> None:
2191 self.poutput(f"{label}={sum(nums)}")
2192
2193 @with_annotated
2194 def do_cat(self, *files: str, upper: bool = False) -> None:
2195 joined = " ".join(files)
2196 self.poutput(joined.upper() if upper else joined)
2197
2198 @with_annotated
2199 def do_ping(self) -> None:
2200 self.poutput("pong")
2201
2202
2203 @pytest.fixture
2204 def runtime_app() -> _RuntimeAnnotatedApp:
2205 app = _RuntimeAnnotatedApp()
2206 app.stdout = cmd2.utils.StdSim(app.stdout)
2207 return app
2208
2209
2210 class TestRuntimeExecution:
2211 @pytest.mark.parametrize(
2212 ("command", "expected"),
2213 [
2214 pytest.param("greet Alice", ["Hello Alice"], id="greet_basic"),
2215 pytest.param("greet Alice --count 3", ["Hello Alice", "Hello Alice", "Hello Alice"], id="greet_count"),
2216 pytest.param("add 2 --b 3", ["5"], id="add"),
2217 pytest.param("add 10", ["10"], id="add_default"),
2218 pytest.param("paint wall", ["Painting wall blue"], id="paint_default_color"),
2219 pytest.param("paint wall --color red", ["Painting wall red"], id="paint_color"),
2220 pytest.param("paint wall --verbose", ["Painting wall blue (verbose)"], id="paint_verbose"),
2221 pytest.param("sport football", ["Playing: football"], id="sport_enum"),
2222 pytest.param("echo_all a b c", ["words=['a', 'b', 'c']"], id="star_args_values"),
2223 pytest.param("echo_all", ["words=[]"], id="star_args_empty"),
2224 pytest.param("total score 1 2 3", ["score=6"], id="leading_plus_star_args"),
2225 pytest.param("total score", ["score=0"], id="leading_plus_empty_star_args"),
2226 pytest.param("cat a b c", ["a b c"], id="star_args_with_kwonly_opt"),
2227 pytest.param("cat a b c --upper", ["A B C"], id="star_args_with_kwonly_opt_set"),
2228 pytest.param("ping", ["pong"], id="no_args_command"),
2229 ],
2230 )
2231 def test_command_execution(self, runtime_app, command, expected) -> None:
2232 out, _err = run_cmd(runtime_app, command)
2233 assert out == expected
2234
2235 def test_no_args_command_rejects_extra_args(self, runtime_app) -> None:
2236 """A no-parameter command accepts no positionals and errors on extras."""
2237 _out, err = run_cmd(runtime_app, "ping extra")
2238 assert any("unrecognized" in line.lower() or "error" in line.lower() for line in err)
2239
2240 def test_help_shows_arguments(self, runtime_app) -> None:
2241 out, _ = run_cmd(runtime_app, "help greet")
2242 assert "name" in "\n".join(out).lower()
2243
2244 def test_help_shows_option_help(self, runtime_app) -> None:
2245 out, _ = run_cmd(runtime_app, "help paint")
2246 help_text = "\n".join(out)
2247 assert "Color to use" in help_text
2248
2249
2250 class TestRuntimeCompletion:
2251 def test_enum_completion(self, runtime_app) -> None:
2252 assert sorted(_complete_cmd(runtime_app, "paint wall --color ", "")) == ["blue", "green", "red"]
2253
2254 def test_enum_completion_partial(self, runtime_app) -> None:
2255 assert _complete_cmd(runtime_app, "paint wall --color r", "r") == ["red"]
2256
2257 def test_choices_provider_completion(self, runtime_app) -> None:
2258 assert sorted(_complete_cmd(runtime_app, "pick ", "")) == ["apple", "banana", "cherry"]
2259
2260 def test_positional_enum_completion(self, runtime_app) -> None:
2261 assert _complete_cmd(runtime_app, "sport foot", "foot") == ["football"]
2262
2263 def test_path_completion_from_annotation(self, runtime_app, tmp_path) -> None:
2264 test_file = tmp_path / "annotated-path.txt"
2265 test_file.touch()
2266 text = str(tmp_path) + "/"
2267 result_strings = _complete_cmd(runtime_app, f"open {text}", text)
2268 assert any("annotated-path.txt" in item for item in result_strings)
2269
2270 def test_positional_bool_completion_from_annotation(self, runtime_app) -> None:
2271 completions = set(_complete_cmd(runtime_app, "toggle ", ""))
2272 assert {"true", "false", "yes", "no", "on", "off", "1", "0"}.issubset(completions)
2273
2274
2275 class _AnnotatedCommandSet(cmd2.CommandSet):
2276 def __init__(self) -> None:
2277 super().__init__()
2278 self._sports = ["football", "baseball"]
2279
2280 def sport_choices(self) -> list[cmd2.CompletionItem]:
2281 return [cmd2.CompletionItem(sport) for sport in self._sports]
2282
2283 @with_annotated
2284 def do_play(self, sport: Annotated[str, Argument(choices_provider=sport_choices)]) -> None:
2285 self._cmd.poutput(f"Playing {sport}")
2286
2287
2288 @pytest.fixture
2289 def cmdset_app() -> cmd2.Cmd:
2290 cmdset = _AnnotatedCommandSet()
2291 app = cmd2.Cmd(command_sets=[cmdset])
2292 app.stdout = cmd2.utils.StdSim(app.stdout)
2293 return app
2294
2295
2296 class TestCommandSet:
2297 def test_command_set_execution(self, cmdset_app) -> None:
2298 out, _err = run_cmd(cmdset_app, "play football")
2299 assert out == ["Playing football"]
2300
2301 def test_command_set_completion(self, cmdset_app) -> None:
2302 assert sorted(_complete_cmd(cmdset_app, "play ", "")) == ["baseball", "football"]
2303
2304
2305 # ---------------------------------------------------------------------------
2306 # Integration: with_annotated decorator runs commands through cmd2
2307 # ---------------------------------------------------------------------------
2308
2309
2310 class _IntegrationApp(cmd2.Cmd):
2311 def __init__(self) -> None:
2312 super().__init__()
2313 self.ns_calls = 0
2314
2315 def namespace_provider(self) -> argparse.Namespace:
2316 self.ns_calls += 1
2317 ns = argparse.Namespace()
2318 ns.custom_stuff = "custom"
2319 return ns
2320
2321 @with_annotated
2322 def do_greet(self, name: str, count: int = 1, loud: bool = False, *, keyword_arg: str | None = None) -> None:
2323 """Greet someone."""
2324 for _ in range(count):
2325 msg = f"Hello {name}"
2326 self.poutput(msg.upper() if loud else msg)
2327 if keyword_arg is not None:
2328 self.poutput(keyword_arg)
2329
2330 @with_annotated(with_unknown_args=True)
2331 def do_flex(self, name: str, _unknown: list[str] | None = None) -> None:
2332 self.poutput(f"name={name}")
2333 if _unknown:
2334 self.poutput(f"unknown={_unknown}")
2335
2336 @with_annotated(preserve_quotes=True)
2337 def do_raw(self, text: str) -> None:
2338 self.poutput(f"raw: {text}")
2339
2340 @with_annotated(ns_provider=namespace_provider)
2341 def do_ns_test(self, cmd2_statement=None) -> None:
2342 self.poutput("ok")
2343
2344 @with_annotated
2345 def do_prefixed(self, cmd2_mode: int = 1) -> None:
2346 self.poutput(f"cmd2_mode={cmd2_mode}")
2347
2348
2349 class _GroupedParserApp(cmd2.Cmd):
2350 @with_annotated(
2351 groups=(Group("local", "remote"), Group("force", "dry_run")),
2352 mutually_exclusive_groups=(Group("local", "remote"), Group("force", "dry_run")),
2353 )
2354 def do_transfer(
2355 self,
2356 *,
2357 local: str | None = None,
2358 remote: str | None = None,
2359 force: bool = False,
2360 dry_run: bool = False,
2361 ) -> None:
2362 target = local if local is not None else remote
2363 mode = "force" if force else "dry-run" if dry_run else "normal"
2364 self.poutput(f"Transfer {target} in {mode} mode")
2365
2366
2367 @pytest.fixture
2368 def app() -> _IntegrationApp:
2369 app = _IntegrationApp()
2370 app.stdout = cmd2.utils.StdSim(app.stdout)
2371 return app
2372
2373
2374 @pytest.fixture
2375 def grouped_app() -> _GroupedParserApp:
2376 return _GroupedParserApp()
2377
2378
2379 class TestWithAnnotatedIntegration:
2380 """Integration tests covering the decorator's cmd_wrapper runtime paths."""
2381
2382 @pytest.mark.parametrize(
2383 ("command", "expected"),
2384 [
2385 pytest.param("greet Alice", ["Hello Alice"], id="basic"),
2386 pytest.param("greet Alice --count 2 --loud", ["HELLO ALICE", "HELLO ALICE"], id="options"),
2387 pytest.param("greet Alice --no-loud", ["Hello Alice"], id="bool_no_flag"),
2388 pytest.param("greet Alice --loud", ["HELLO ALICE"], id="bool_flag"),
2389 pytest.param("flex Alice", ["name=Alice"], id="unknown_args_empty"),
2390 ],
2391 )
2392 def test_command_execution(self, app, command, expected) -> None:
2393 out, _err = run_cmd(app, command)
2394 assert out == expected
2395
2396 def test_with_unknown_args(self, app) -> None:
2397 out, _err = run_cmd(app, "flex Alice --extra stuff")
2398 assert out[0] == "name=Alice"
2399 assert "unknown=" in out[1]
2400
2401 def test_preserve_quotes(self, app) -> None:
2402 out, _err = run_cmd(app, 'raw "hello world"')
2403 assert out == ['raw: "hello world"']
2404
2405 def test_error_produces_stderr(self, app) -> None:
2406 _out, err = run_cmd(app, "greet")
2407 assert any("error" in line.lower() or "usage" in line.lower() for line in err)
2408
2409 def test_no_args_raises_type_error(self, app) -> None:
2410 with pytest.raises(TypeError, match="Expected arguments"):
2411 app.do_greet()
2412
2413 def test_with_unknown_args_requires_param(self) -> None:
2414 with pytest.raises(TypeError, match="_unknown"):
2415
2416 @with_annotated(with_unknown_args=True)
2417 def do_broken(self, name: str) -> None:
2418 pass
2419
2420 def test_positional_only_unknown_rejected(self) -> None:
2421 with pytest.raises(TypeError, match="keyword-compatible"):
2422
2423 @with_annotated(with_unknown_args=True)
2424 def do_broken(self, _unknown: list[str], /) -> None:
2425 pass
2426
2427 def test_ns_provider(self, app) -> None:
2428 out, _err = run_cmd(app, "ns_test")
2429 assert out == ["ok"]
2430 assert app.ns_calls == 1
2431
2432 def test_cmd2_prefixed_param_is_preserved(self, app) -> None:
2433 out, _err = run_cmd(app, "prefixed --cmd2-mode 5")
2434 assert out == ["cmd2_mode=5"]
2435
2436 def test_kwargs_passthrough(self, app) -> None:
2437 app.do_greet("Alice", keyword_arg="kwarg_value")
2438
2439 def test_direct_call_with_positional_only(self, app) -> None:
2440 """Calling do_* directly with a single statement string parses normally."""
2441 app.do_greet("Alice")
2442 assert app.stdout.getvalue().splitlines()[-1] == "Hello Alice"
2443
2444 def test_direct_call_with_options(self, app) -> None:
2445 """Direct call with a full statement string including options."""
2446 app.do_greet("Alice --count 2 --loud")
2447 out = app.stdout.getvalue().splitlines()
2448 assert out[-2:] == ["HELLO ALICE", "HELLO ALICE"]
2449
2450 def test_direct_call_kwargs_override_parsed(self, app) -> None:
2451 """Explicit kwargs on a direct call override parsed values."""
2452 app.do_greet("Alice", count=3)
2453 out = app.stdout.getvalue().splitlines()
2454 assert out[-3:] == ["Hello Alice", "Hello Alice", "Hello Alice"]
2455
2456 def test_direct_call_no_arg_command(self) -> None:
2457 """A no-parameter command parses an (empty) statement string on a direct call."""
2458
2459 class App(cmd2.Cmd):
2460 @with_annotated
2461 def do_ping(self) -> None:
2462 self.poutput("pong")
2463
2464 app = App()
2465 app.stdout = cmd2.utils.StdSim(app.stdout)
2466 app.do_ping("")
2467 assert app.stdout.getvalue().splitlines()[-1] == "pong"
2468
2469 def test_direct_call_star_args_command(self) -> None:
2470 """A *args command parses a statement string positionally on a direct call."""
2471
2472 class App(cmd2.Cmd):
2473 @with_annotated
2474 def do_cat(self, *files: str, upper: bool = False) -> None:
2475 joined = "|".join(files)
2476 self.poutput(joined.upper() if upper else joined)
2477
2478 app = App()
2479 app.stdout = cmd2.utils.StdSim(app.stdout)
2480 app.do_cat("a b c")
2481 assert app.stdout.getvalue().splitlines()[-1] == "a|b|c"
2482 app.do_cat("a b --upper")
2483 assert app.stdout.getvalue().splitlines()[-1] == "A|B"
2484
2485 def test_invoke_missing_leading_positional_raises(self) -> None:
2486 """A leading positional missing from func_kwargs fails loud instead of shifting *args.
2487
2488 ``*positional`` is unpacked by index, so silently skipping a missing leading
2489 name would slide ``*var_values`` into the wrong parameter. Fail with KeyError.
2490 """
2491
2492 def fn(self, first: str, *rest: str) -> None: ...
2493
2494 with pytest.raises(KeyError, match="first"):
2495 _invoke_command_func(
2496 fn,
2497 None,
2498 {"rest": ("x", "y")},
2499 leading_names=["first"],
2500 var_positional_name="rest",
2501 )
2502
2503 def test_invoke_missing_var_positional_raises(self) -> None:
2504 """A *args name missing from func_kwargs fails loud instead of defaulting to empty.
2505
2506 argparse always populates the ``*args`` attribute (an empty list when nothing is
2507 given), so a missing key signals a bug and must not be silently swallowed.
2508 """
2509
2510 def fn(self, *rest: str) -> None: ...
2511
2512 with pytest.raises(KeyError, match="rest"):
2513 _invoke_command_func(fn, None, {}, leading_names=[], var_positional_name="rest")
2514
2515 def test_bare_call_decorator(self) -> None:
2516 """@with_annotated() with empty parens works same as @with_annotated."""
2517
2518 class App(cmd2.Cmd):
2519 @with_annotated()
2520 def do_echo(self, text: str) -> None:
2521 self.poutput(text)
2522
2523 out, _err = run_cmd(App(), "echo hi")
2524 assert out == ["hi"]
2525
2526 def test_missing_parser_raises(self, app) -> None:
2527 from unittest.mock import patch
2528
2529 with (
2530 patch.object(app.command_parsers, "get", return_value=None),
2531 pytest.raises(ValueError, match="No argument parser found"),
2532 ):
2533 app.do_greet("Alice")
2534
2535
2536 class TestGroupedParserIntegration:
2537 def test_grouped_command_executes(self, grouped_app) -> None:
2538 out, _err = run_cmd(grouped_app, "transfer --local build.tar.gz --dry-run")
2539 assert out == ["Transfer build.tar.gz in dry-run mode"]
2540
2541 def test_grouped_command_mutex_error(self, grouped_app) -> None:
2542 _out, err = run_cmd(grouped_app, "transfer --local a --remote b")
2543 assert any("not allowed with argument" in line.lower() for line in err)
2544
2545 def test_grouped_command_help_lists_flags(self, grouped_app) -> None:
2546 out, _err = run_cmd(grouped_app, "help transfer")
2547 help_text = "\n".join(out)
2548 assert "--local" in help_text
2549 assert "--remote" in help_text
2550 assert "--force" in help_text
2551 assert "--dry-run" in help_text
2552
2553
2554 # ---------------------------------------------------------------------------
2555 # Subcommands: @with_annotated(base_command=True) + @with_annotated(subcommand_to=...)
2556 # ---------------------------------------------------------------------------
2557
2558
2559 class _SubcommandApp(cmd2.Cmd):
2560 # Level 1: base command
2561 @with_annotated(base_command=True)
2562 def do_manage(self, cmd2_subcommand_func, verbose: bool = False) -> None:
2563 """Management command with subcommands."""
2564 if verbose:
2565 self.poutput("verbose mode")
2566 if cmd2_subcommand_func:
2567 cmd2_subcommand_func()
2568
2569 # Level 2: leaf subcommands
2570 @with_annotated(subcommand_to="manage", help="add something")
2571 def manage_add(self, value: str) -> None:
2572 self.poutput(f"added: {value}")
2573
2574 @with_annotated(subcommand_to="manage", help="sum values")
2575 def manage_sum(self, *nums: int) -> None:
2576 self.poutput(f"sum: {sum(nums)}")
2577
2578 @with_annotated(subcommand_to="manage", help="list things", aliases=["ls"])
2579 def manage_list(self) -> None:
2580 self.poutput("listing all")
2581
2582 # Level 2: intermediate subcommand (also a base for level 3)
2583 @with_annotated(subcommand_to="manage", base_command=True, help="manage members")
2584 def manage_member(self, cmd2_subcommand_func) -> None:
2585 if cmd2_subcommand_func:
2586 cmd2_subcommand_func()
2587
2588 # Level 3: nested subcommand
2589 @with_annotated(subcommand_to="manage member", help="add a member")
2590 def manage_member_add(self, name: str) -> None:
2591 self.poutput(f"member added: {name}")
2592
2593
2594 @pytest.fixture
2595 def subcmd_app() -> _SubcommandApp:
2596 return _SubcommandApp()
2597
2598
2599 class TestSubcommands:
2600 @pytest.mark.parametrize(
2601 ("command", "expected"),
2602 [
2603 pytest.param("manage add hello", ["added: hello"], id="add"),
2604 pytest.param("manage list", ["listing all"], id="list"),
2605 pytest.param("manage ls", ["listing all"], id="list_alias"),
2606 pytest.param("manage member add Alice", ["member added: Alice"], id="nested_3_levels"),
2607 pytest.param("manage sum 1 2 3", ["sum: 6"], id="subcommand_star_args"),
2608 pytest.param("manage sum", ["sum: 0"], id="subcommand_star_args_empty"),
2609 ],
2610 )
2611 def test_subcommand_executes(self, subcmd_app, command, expected) -> None:
2612 out, _err = run_cmd(subcmd_app, command)
2613 assert out == expected
2614
2615 @pytest.mark.parametrize(
2616 ("command", "expected_error"),
2617 [
2618 pytest.param("manage", "the following arguments are required: SUBCOMMAND", id="missing_subcmd"),
2619 pytest.param("manage delete", "invalid choice: 'delete'", id="invalid_subcmd"),
2620 pytest.param("manage member", "the following arguments are required: SUBCOMMAND", id="missing_nested_subcmd"),
2621 ],
2622 )
2623 def test_subcommand_errors(self, subcmd_app, command, expected_error) -> None:
2624 _out, err = run_cmd(subcmd_app, command)
2625 assert any(expected_error in line for line in err), f"expected {expected_error!r} in {err}"
2626
2627 def test_subcommand_help(self, subcmd_app) -> None:
2628 out, _err = run_cmd(subcmd_app, "help manage")
2629 help_text = "\n".join(out)
2630 assert "add" in help_text
2631 assert "list" in help_text
2632 assert "member" in help_text
2633
2634
2635 class _OptionalIntermediateApp(cmd2.Cmd):
2636 """An intermediate subcommand that is itself a base command with an *optional* subcommand."""
2637
2638 @with_annotated(base_command=True)
2639 def do_opt(self, cmd2_subcommand_func) -> None:
2640 if cmd2_subcommand_func:
2641 cmd2_subcommand_func()
2642
2643 @with_annotated(subcommand_to="opt", base_command=True, subcommand_required=False, help="optional middle")
2644 def opt_mid(self, cmd2_subcommand_func) -> None:
2645 # The guard must blank out the self-referential handler so this runs exactly once.
2646 self.poutput("mid:none" if cmd2_subcommand_func is None else "mid:recurse")
2647 if cmd2_subcommand_func:
2648 cmd2_subcommand_func()
2649
2650 @with_annotated(subcommand_to="opt mid", help="leaf")
2651 def opt_mid_leaf(self, name: str) -> None:
2652 self.poutput(f"leaf:{name}")
2653
2654
2655 @pytest.fixture
2656 def opt_app() -> _OptionalIntermediateApp:
2657 return _OptionalIntermediateApp()
2658
2659
2660 class TestOptionalIntermediateSubcommand:
2661 def test_intermediate_without_deeper_subcommand_runs_once(self, opt_app) -> None:
2662 """The recursion guard blanks the self-referential handler: the body runs once with None."""
2663 out, _err = run_cmd(opt_app, "opt mid")
2664 assert out == ["mid:none"]
2665
2666 def test_deeper_subcommand_still_dispatches(self, opt_app) -> None:
2667 """Blanking the self-reference must not break dispatch to a genuine deeper subcommand."""
2668 out, _err = run_cmd(opt_app, "opt mid leaf Bob")
2669 assert out == ["leaf:Bob"]
2670
2671 def test_guard_blanks_only_subcommand_func(self) -> None:
2672 """The guard must null *only* cmd2_subcommand_func, leaving the intermediate's own args intact."""
2673
2674 class App(cmd2.Cmd):
2675 @with_annotated(base_command=True)
2676 def do_opt(self, cmd2_subcommand_func) -> None:
2677 if cmd2_subcommand_func:
2678 cmd2_subcommand_func()
2679
2680 @with_annotated(subcommand_to="opt", base_command=True, subcommand_required=False)
2681 def opt_mid(self, cmd2_subcommand_func, verbose: bool = False) -> None:
2682 self.poutput(f"none={cmd2_subcommand_func is None}:verbose={verbose}")
2683 if cmd2_subcommand_func:
2684 cmd2_subcommand_func()
2685
2686 out, _err = run_cmd(App(), "opt mid --verbose")
2687 assert out == ["none=True:verbose=True"]
2688
2689 def test_guard_fires_at_deeper_nesting_level(self) -> None:
2690 """The guard must work past two levels: the deepest *selected* optional base runs once."""
2691
2692 class App(cmd2.Cmd):
2693 @with_annotated(base_command=True)
2694 def do_a(self, cmd2_subcommand_func) -> None:
2695 if cmd2_subcommand_func:
2696 cmd2_subcommand_func()
2697
2698 @with_annotated(subcommand_to="a", base_command=True, subcommand_required=False)
2699 def a_b(self, cmd2_subcommand_func) -> None:
2700 if cmd2_subcommand_func:
2701 cmd2_subcommand_func()
2702
2703 @with_annotated(subcommand_to="a b", base_command=True, subcommand_required=False)
2704 def a_b_c(self, cmd2_subcommand_func) -> None:
2705 self.poutput(f"c:none={cmd2_subcommand_func is None}")
2706 if cmd2_subcommand_func:
2707 cmd2_subcommand_func()
2708
2709 @with_annotated(subcommand_to="a b c", help="leaf")
2710 def a_b_c_leaf(self, name: str) -> None:
2711 self.poutput(f"leaf:{name}")
2712
2713 app = App()
2714 assert run_cmd(app, "a b c")[0] == ["c:none=True"]
2715 assert run_cmd(app, "a b c leaf Z")[0] == ["leaf:Z"]
2716
2717 def test_guard_works_for_commandset_subcommand(self) -> None:
2718 """The handler is a CommandSet-bound method here; unwrapping to __func__ must still match."""
2719
2720 class _Grp(cmd2.CommandSet):
2721 @cmd2.with_category("grp")
2722 @with_annotated(base_command=True)
2723 def do_grp(self, cmd2_subcommand_func) -> None:
2724 if cmd2_subcommand_func:
2725 cmd2_subcommand_func()
2726
2727 @with_annotated(subcommand_to="grp", base_command=True, subcommand_required=False)
2728 def grp_mid(self, cmd2_subcommand_func) -> None:
2729 self._cmd.poutput(f"mid:none={cmd2_subcommand_func is None}")
2730 if cmd2_subcommand_func:
2731 cmd2_subcommand_func()
2732
2733 @with_annotated(subcommand_to="grp mid", help="leaf")
2734 def grp_mid_leaf(self, name: str) -> None:
2735 self._cmd.poutput(f"leaf:{name}")
2736
2737 app = cmd2.Cmd(auto_load_commands=False)
2738 app.register_command_set(_Grp())
2739 assert run_cmd(app, "grp mid")[0] == ["mid:none=True"]
2740 assert run_cmd(app, "grp mid leaf Q")[0] == ["leaf:Q"]
2741
2742
2743 class TestSubcommandValidation:
2744 def test_subcommand_aliases_none_raises(self) -> None:
2745 """aliases=None is off-spec (it must be a Sequence[str]); reject it with a clear message."""
2746 with pytest.raises(TypeError, match=r"aliases must be a sequence"):
2747 with_annotated(subcommand_to="team", aliases=None)
2748
2749 def test_base_command_positional_str_raises(self) -> None:
2750 """Positional str param conflicts with subcommand name."""
2751 with pytest.raises(TypeError, match="positional"):
2752
2753 @with_annotated(base_command=True)
2754 def do_bad(self, name: str, cmd2_subcommand_func) -> None:
2755 pass
2756
2757 def test_base_command_positional_annotated_raises(self) -> None:
2758 """Explicit Argument() metadata forces positional -- conflict."""
2759 with pytest.raises(TypeError, match="positional"):
2760
2761 @with_annotated(base_command=True)
2762 def do_bad(self, a: Annotated[str, Argument(help_text="x")], cmd2_subcommand_func) -> None:
2763 pass
2764
2765 def test_base_command_missing_subcommand_func_raises(self) -> None:
2766 with pytest.raises(TypeError, match=constants.NS_ATTR_SUBCOMMAND_FUNC):
2767
2768 @with_annotated(base_command=True)
2769 def do_bad(self, verbose: bool = False) -> None:
2770 pass
2771
2772 def test_base_command_missing_subcommand_func_raises_with_no_parameters(self) -> None:
2773 """A zero-parameter base command with no cmd2_subcommand_func must still raise.
2774
2775 Guards the function-level ``cmd2_subcommand_func`` check (a plain ``if`` in ``_resolve_parameters``,
2776 not a :data:`_CONSTRAINTS` row): the per-argument :data:`_CONSTRAINTS` loop never runs when
2777 no arguments exist, so this case is the sole reason the missing-handler check lives at
2778 function scope.
2779 """
2780 with pytest.raises(TypeError, match=constants.NS_ATTR_SUBCOMMAND_FUNC):
2781
2782 @with_annotated(base_command=True)
2783 def do_bad(self) -> None:
2784 pass
2785
2786 def test_cmd2_subcommand_func_without_base_command_raises(self) -> None:
2787 """A 'cmd2_subcommand_func' parameter is only valid when base_command=True."""
2788 with pytest.raises(TypeError, match="base_command=True"):
2789
2790 @with_annotated
2791 def do_bad(self, cmd2_subcommand_func, name: str = "") -> None:
2792 pass
2793
2794 @pytest.mark.parametrize(
2795 "kwargs",
2796 [
2797 pytest.param({"help": "not allowed"}, id="help_only"),
2798 pytest.param({"aliases": ["x"]}, id="aliases_only"),
2799 pytest.param({"deprecated": True}, id="deprecated_only"),
2800 ],
2801 )
2802 def test_subcmd_only_params_without_subcommand_to_raises(self, kwargs) -> None:
2803 with pytest.raises(TypeError, match="subcommand_to"):
2804
2805 @with_annotated(**kwargs)
2806 def do_bad(self, name: str) -> None:
2807 pass
2808
2809 @pytest.mark.parametrize(
2810 ("kwargs", "pattern"),
2811 [
2812 pytest.param({"with_unknown_args": True}, "with_unknown_args", id="with_unknown_args"),
2813 pytest.param({"preserve_quotes": True}, "preserve_quotes", id="preserve_quotes"),
2814 pytest.param({"ns_provider": lambda self: argparse.Namespace()}, "ns_provider", id="ns_provider"),
2815 ],
2816 )
2817 def test_subcommand_rejects_unsupported_runtime_options(self, kwargs, pattern) -> None:
2818 with pytest.raises(TypeError, match=pattern):
2819
2820 @with_annotated(subcommand_to="team", **kwargs)
2821 def team_add(self, name: str, _unknown: list[str] | None = None) -> None:
2822 pass
2823
2824 def test_subcommand_with_mutually_exclusive_groups(self) -> None:
2825 """mutually_exclusive_groups should work on subcommands."""
2826
2827 class App(cmd2.Cmd):
2828 @with_annotated(base_command=True)
2829 def do_fmt(self, cmd2_subcommand_func) -> None:
2830 if cmd2_subcommand_func:
2831 cmd2_subcommand_func()
2832
2833 @with_annotated(subcommand_to="fmt", help="output", mutually_exclusive_groups=(Group("json", "csv"),))
2834 def fmt_out(self, msg: str, json: bool = False, csv: bool = False) -> None:
2835 self.poutput(f"json={json} csv={csv} {msg}")
2836
2837 app = App()
2838 out, _err = run_cmd(app, "fmt out hello --json")
2839 assert out == ["json=True csv=False hello"]
2840 _out, err = run_cmd(app, "fmt out hello --json --csv")
2841 assert any("not allowed" in line.lower() for line in err)
2842
2843 def test_intermediate_base_command_positional_raises(self) -> None:
2844 with pytest.raises(TypeError, match="positional"):
2845
2846 @with_annotated(subcommand_to="team", base_command=True)
2847 def team_member(self, name: str, cmd2_subcommand_func) -> None:
2848 pass
2849
2850 def test_intermediate_base_command_missing_subcommand_func_raises(self) -> None:
2851 with pytest.raises(TypeError, match=constants.NS_ATTR_SUBCOMMAND_FUNC):
2852
2853 @with_annotated(subcommand_to="team", base_command=True)
2854 def team_member(self) -> None:
2855 pass
2856
2857 @pytest.mark.parametrize(
2858 ("subcommand_to", "func_name"),
2859 [
2860 pytest.param("team", "wrong_name", id="wrong_prefix"),
2861 pytest.param("team member", "team_wrong", id="wrong_nested_prefix"),
2862 ],
2863 )
2864 def test_subcommand_naming_enforced(self, subcommand_to, func_name) -> None:
2865 ns: dict = {}
2866 exec(f"def {func_name}(self, x: str) -> None: ...", ns)
2867 with pytest.raises(TypeError, match="must be named"):
2868 with_annotated(subcommand_to=subcommand_to)(ns[func_name])
2869
2870 @pytest.mark.parametrize(
2871 ("decorator_kwargs", "expected_help", "expected_aliases"),
2872 [
2873 pytest.param({"help": "create", "aliases": ["c"]}, "create", ("c",), id="with_help_and_aliases"),
2874 pytest.param({}, None, (), id="without_help_or_aliases"),
2875 ],
2876 )
2877 def test_subcommand_spec_attributes(self, decorator_kwargs, expected_help, expected_aliases) -> None:
2878 @with_annotated(subcommand_to="team", **decorator_kwargs)
2879 def team_create(self, name: str = "") -> None: ...
2880
2881 spec = getattr(team_create, constants.SUBCOMMAND_ATTR_SPEC)
2882 assert spec.command == "team"
2883 assert spec.name == "create"
2884 assert spec.help == expected_help
2885 assert spec.aliases == expected_aliases
2886 assert isinstance(spec.parser_source(), argparse.ArgumentParser)
2887
2888 @pytest.mark.parametrize("deprecated", [True, False])
2889 def test_subcommand_deprecated_flows_to_spec(self, deprecated) -> None:
2890 @with_annotated(subcommand_to="team", deprecated=deprecated)
2891 def team_create(self, name: str = "") -> None: ...
2892
2893 spec = getattr(team_create, constants.SUBCOMMAND_ATTR_SPEC)
2894 assert spec.deprecated is deprecated
2895
2896
2897 # ---------------------------------------------------------------------------
2898 # A non-Optional type with a None default is rejected (None would violate the hint)
2899 # ---------------------------------------------------------------------------
2900
2901
2902 class TestNoneDefaultRejection:
2903 @pytest.mark.parametrize(
2904 ("annotation", "kind"),
2905 [
2906 pytest.param(str, "pos", id="str"),
2907 pytest.param(int, "pos", id="int"),
2908 pytest.param(list[str], "pos", id="list"),
2909 pytest.param(Annotated[str, Option("-n")], "pos", id="option"),
2910 pytest.param(Annotated[str, Argument()], "pos", id="argument"),
2911 pytest.param(str, "kw", id="kw_only"),
2912 ],
2913 )
2914 def test_none_default_raises(self, annotation, kind) -> None:
2915 _assert_build_error(annotation, default=None, kind=kind, match="not Optional")
2916
2917 def test_optional_none_default_builds(self) -> None:
2918 parser = build_parser_from_function(_make_func(str | None, default=None))
2919 assert parser.parse_args([]).value is None
2920
2921 @pytest.mark.parametrize(
2922 "annotation",
2923 [
2924 pytest.param(Any, id="any"),
2925 pytest.param(object, id="object"),
2926 pytest.param(_MISSING, id="unannotated"),
2927 ],
2928 )
2929 def test_none_accepting_types_exempt(self, annotation) -> None:
2930 assert build_parser_from_function(_make_func(annotation, default=None)).parse_args([]).value is None
2931
2932
2933 # ---------------------------------------------------------------------------
2934 # Tightened action= contract (result type must match the declared type)
2935 # ---------------------------------------------------------------------------
2936
2937
2938 class TestActionTightening:
2939 @pytest.mark.parametrize(
2940 ("annotation", "pattern"),
2941 [
2942 pytest.param(Annotated[str, Option("-t", action="append")], "list", id="append_on_scalar"),
2943 pytest.param(Annotated[set[str], Option("-t", action="append")], "list", id="append_on_set"),
2944 pytest.param(Annotated[tuple[str, str], Option("-t", action="append")], "list", id="append_on_tuple"),
2945 pytest.param(Annotated[str, Option("-t", action="extend")], "list", id="extend_on_scalar"),
2946 pytest.param(Annotated[bool, Option("-c", action="count")], "int", id="count_on_bool"),
2947 pytest.param(Annotated[str, Option("-c", action="store_const")], "const", id="store_const"),
2948 pytest.param(Annotated[list[str], Option("-c", action="append_const")], "const", id="append_const"),
2949 pytest.param(Annotated[str, Option("-c", action="frobnicate")], "not supported", id="unknown_action"),
2950 pytest.param(Annotated[list[str], Option("-c", action="store_true")], "collection", id="noncollection_action"),
2951 pytest.param(Annotated[int, Option("-c", action="store")], "not supported", id="explicit_store"),
2952 pytest.param(Annotated[int, Option("-c", action="store", const=5)], "ambiguous", id="store_with_const"),
2953 # The ambiguity wins even when the const's type also mismatches the declared type.
2954 pytest.param(Annotated[int, Option("-c", action="store", const="x")], "ambiguous", id="store_with_mistyped_const"),
2955 ],
2956 )
2957 def test_action_type_mismatch_raises(self, annotation, pattern) -> None:
2958 _assert_build_error(annotation, match=pattern)
2959
2960 def test_append_on_list_accumulates(self) -> None:
2961 parser = build_parser_from_function(_make_func(Annotated[list[str], Option("--tag", action="append")]))
2962 assert parser.parse_args([]).value == []
2963 assert parser.parse_args(["--tag", "a", "--tag", "b"]).value == ["a", "b"]
2964
2965 def test_extend_on_list_flattens_and_converts(self) -> None:
2966 parser = build_parser_from_function(_make_func(Annotated[list[int], Option("-n", action="extend")]))
2967 assert parser.parse_args([]).value == []
2968 assert parser.parse_args(["-n", "1", "2", "-n", "3"]).value == [1, 2, 3]
2969
2970 def test_count_no_default_yields_zero(self) -> None:
2971 annotation = Annotated[int, Option("-l", action="count")]
2972 action = _action_for(annotation)
2973 assert action.required is False
2974 assert build_parser_from_function(_make_func(annotation)).parse_args([]).value == 0
2975
2976 def test_append_with_nargs_raises(self) -> None:
2977 _assert_build_error(Annotated[list[str], Option("--tag", action="append", nargs=2)], match="nargs")
2978
2979 @pytest.mark.parametrize(
2980 ("annotation", "omit_value"),
2981 [
2982 pytest.param(Annotated[int | None, Option("-c", action="count")], None, id="count_optional"),
2983 pytest.param(Annotated[list[str] | None, Option("-t", action="append")], None, id="append_optional"),
2984 pytest.param(Annotated[bool | None, Option("-v", action="store_true")], None, id="store_true_optional"),
2985 pytest.param(Annotated[bool | None, Option("-q", action="store_false")], None, id="store_false_optional"),
2986 ],
2987 )
2988 def test_self_defaulting_action_optional_yields_none(self, annotation, omit_value) -> None:
2989 assert build_parser_from_function(_make_func(annotation)).parse_args([]).value is omit_value
2990
2991 @pytest.mark.parametrize(
2992 ("annotation", "omit_value"),
2993 [
2994 pytest.param(Annotated[bool, Option("-v", action="store_true")], False, id="store_true"),
2995 pytest.param(Annotated[bool, Option("-q", action="store_false")], True, id="store_false"),
2996 ],
2997 )
2998 def test_store_bool_action_non_optional_default(self, annotation, omit_value) -> None:
2999 """A non-Optional store_true/store_false still defaults to its natural absence value."""
3000 assert build_parser_from_function(_make_func(annotation)).parse_args([]).value is omit_value
3001
3002
3003 # ---------------------------------------------------------------------------
3004 # const= on Option (store_const / append_const), inferred from the declared type
3005 # ---------------------------------------------------------------------------
3006
3007
3008 class TestConstOption:
3009 def test_const_to_kwargs(self) -> None:
3010 assert Option("-c", const=5).to_kwargs()["const"] == 5
3011
3012 def test_const_none_to_kwargs_preserved(self) -> None:
3013 """An explicit const=None is kept (distinct from no const given)."""
3014 assert Option("-c", const=None).to_kwargs()["const"] is None
3015 assert "const" not in Option("-c").to_kwargs()
3016
3017 def test_const_on_scalar_infers_store_const(self) -> None:
3018 p = build_parser_from_function(_make_func(Annotated[int, Option("-v", const=2)], default=0))
3019 assert p.parse_args([]).value == 0
3020 assert p.parse_args(["-v"]).value == 2
3021
3022 def test_const_on_list_infers_append_const(self) -> None:
3023 p = build_parser_from_function(_make_func(Annotated[list[str], Option("--tag", const="x")]))
3024 assert p.parse_args([]).value == []
3025 assert p.parse_args(["--tag", "--tag"]).value == ["x", "x"]
3026
3027 def test_explicit_store_const(self) -> None:
3028 annotation = Annotated[int, Option("-v", action="store_const", const=2)]
3029 assert build_parser_from_function(_make_func(annotation, default=0)).parse_args(["-v"]).value == 2
3030
3031 def test_explicit_append_const(self) -> None:
3032 annotation = Annotated[list[str], Option("--tag", action="append_const", const="x")]
3033 assert build_parser_from_function(_make_func(annotation)).parse_args(["--tag"]).value == ["x"]
3034
3035 def test_store_const_optional_absent_is_none(self) -> None:
3036 p = build_parser_from_function(_make_func(Annotated[str | None, Option("-m", const="fast")], default=None))
3037 assert p.parse_args([]).value is None
3038 assert p.parse_args(["-m"]).value == "fast"
3039
3040 def test_const_enum_member_stored_as_member(self) -> None:
3041 class Color(enum.Enum):
3042 RED = "red"
3043 GREEN = "green"
3044
3045 annotation = Annotated[Color | None, Option("-c", const=Color.RED)]
3046 assert build_parser_from_function(_make_func(annotation, default=None)).parse_args(["-c"]).value is Color.RED
3047
3048 @pytest.mark.parametrize(
3049 ("annotation", "default", "expected"),
3050 [
3051 # const matching the declared (non-str) scalar type is accepted and stored verbatim.
3052 pytest.param(Annotated[float, Option("-x", const=1.5)], 0.0, 1.5, id="float_const"),
3053 pytest.param(Annotated[float, Option("-x", const=5)], 0.0, 5, id="float_const_int_ok"),
3054 pytest.param(
3055 Annotated[decimal.Decimal, Option("-x", const=decimal.Decimal("1.5"))],
3056 decimal.Decimal(0),
3057 decimal.Decimal("1.5"),
3058 id="decimal_const",
3059 ),
3060 pytest.param(Annotated[Path, Option("-x", const=Path("/tmp"))], Path("."), Path("/tmp"), id="path_const"),
3061 ],
3062 )
3063 def test_const_matching_scalar_type_accepted(self, annotation, default, expected) -> None:
3064 p = build_parser_from_function(_make_func(annotation, default=default))
3065 assert p.parse_args(["-x"]).value == expected
3066
3067 def test_path_store_const_drops_inferred_completer(self) -> None:
3068 """A Path const infers store_const (a zero-arg action); the inferred path completer must be
3069 dropped, else argparse rejects a completer on an action that takes no value."""
3070 p = build_parser_from_function(_make_func(Annotated[Path, Option("-x", const=Path("/tmp"))], default=Path(".")))
3071 assert p.parse_args([]).value == Path(".")
3072 assert p.parse_args(["-x"]).value == Path("/tmp")
3073
3074 def test_path_append_const_drops_inferred_completer(self) -> None:
3075 """append_const on list[Path] is also a zero-arg action; its inferred completer is dropped too."""
3076 p = build_parser_from_function(
3077 _make_func(Annotated[list[Path], Option("-x", action="append_const", const=Path("/tmp"))])
3078 )
3079 assert p.parse_args(["-x", "-x"]).value == [Path("/tmp"), Path("/tmp")]
3080
3081 # --- error cases ---
3082
3083 @pytest.mark.parametrize(
3084 ("annotation", "default", "match"),
3085 [
3086 pytest.param(Annotated[int, Option("-n", const="notanint")], 0, "const", id="type_mismatch_scalar"),
3087 pytest.param(Annotated[Literal["a", "b"], Option("-m", const="c")], "a", "const", id="not_a_literal_member"),
3088 pytest.param(Annotated[float, Option("-x", const="s")], 0.0, "const", id="type_mismatch_float"),
3089 pytest.param(Annotated[float, Option("-x", const=True)], 0.0, "const", id="float_const_rejects_bool"),
3090 pytest.param(
3091 Annotated[decimal.Decimal, Option("-x", const=5)], decimal.Decimal(0), "const", id="type_mismatch_decimal"
3092 ),
3093 pytest.param(Annotated[Path, Option("-x", const="/tmp")], Path("."), "const", id="type_mismatch_path"),
3094 pytest.param(
3095 Annotated[list[str], Option("-x", action="store_const", const="v")],
3096 _MISSING,
3097 "'list' is a collection",
3098 id="store_const_on_list",
3099 ),
3100 pytest.param(
3101 Annotated[str, Option("-x", action="append_const", const="v")],
3102 "",
3103 "'str' is not a list",
3104 id="append_const_on_scalar",
3105 ),
3106 pytest.param(Annotated[str, Option("-x", action="store_const")], "", "const", id="action_without_const"),
3107 pytest.param(Annotated[int, Option("-x", action="count", const=2)], 0, "const", id="incompatible_action"),
3108 pytest.param(Annotated[set[str] | None, Option("-x", const="v")], None, "'set' is not a list", id="const_on_set"),
3109 pytest.param(Annotated[int, Option("-x", const=5)], _MISSING, "default", id="non_optional_no_default"),
3110 ],
3111 )
3112 def test_const_error(self, annotation, default, match) -> None:
3113 _assert_build_error(annotation, default=default, match=match)
3114
3115
3116 class TestNargsOptionalConst:
3117 """A scalar Option with an explicit nargs + const is argparse's optional-value-with-fallback idiom.
3118
3119 It must NOT collapse to a value-less store_const (which would drop the explicit nargs and the type
3120 converter); it keeps the ``store`` action so absent -> default, bare flag -> const, flag VALUE -> value.
3121 """
3122
3123 def test_str_optional_nargs_const_three_way(self) -> None:
3124 annotation = Annotated[str | None, Option("--log", nargs="?", const="CONSOLE")]
3125 p = build_parser_from_function(_make_func(annotation, name="log", default="OFF"))
3126 act = next(a for a in p._actions if a.dest == "log")
3127 assert isinstance(act, argparse._StoreAction) # not _StoreConstAction
3128 assert act.nargs == "?"
3129 assert act.const == "CONSOLE"
3130 assert p.parse_args([]).log == "OFF" # absent -> default
3131 assert p.parse_args(["--log"]).log == "CONSOLE" # bare flag -> const
3132 assert p.parse_args(["--log", "FILE"]).log == "FILE" # flag VALUE -> value
3133
3134 def test_int_optional_nargs_const_converts_supplied_value(self) -> None:
3135 """The supplied VALUE still runs through the inferred converter; the const is stored verbatim."""
3136 annotation = Annotated[int | None, Option("--n", nargs="?", const=99)]
3137 p = build_parser_from_function(_make_func(annotation, name="n", default=0))
3138 assert p.parse_args([]).n == 0
3139 assert p.parse_args(["--n"]).n == 99
3140 assert p.parse_args(["--n", "7"]).n == 7 # type=int applied to the value
3141
3142 def test_nargs_const_still_validates_const_type(self) -> None:
3143 """const must still match the declared type even on the nargs='?' path (stored verbatim)."""
3144 _assert_build_error(Annotated[int, Option("--n", nargs="?", const="notint")], name="n", default=0, match="const")
3145
3146 def test_scalar_const_without_nargs_still_store_const(self) -> None:
3147 """Regression guard: const alone (no nargs) keeps inferring the value-less store_const."""
3148 p = build_parser_from_function(_make_func(Annotated[str, Option("--log", const="X")], name="log", default="off"))
3149 act = next(a for a in p._actions if a.dest == "log")
3150 assert isinstance(act, argparse._StoreConstAction)
3151 assert p.parse_args(["--log"]).log == "X"
3152 with pytest.raises(SystemExit):
3153 p.parse_args(["--log", "Y"]) # value-less action rejects a supplied value
3154
3155
3156 class TestZeroArgActionRejectsUserCompletion:
3157 """A user-supplied completer/choices_provider on a value-less action has nothing to complete.
3158
3159 Raw cmd2 raises in this case, so @with_annotated must fail loud rather than silently dropping the
3160 user's request. A *type-inferred* completer (e.g. Path's) is still dropped silently -- only an
3161 explicit one is rejected.
3162 """
3163
3164 def _provider(self) -> list[str]:
3165 return ["a", "b"]
3166
3167 @pytest.mark.parametrize("action", ["store_true", "store_false"])
3168 def test_bool_flag_action_rejects_user_completer(self, action) -> None:
3169 annotation = Annotated[bool, Option("--flag", action=action, completer=cmd2.Cmd.path_complete)]
3170 _assert_build_error(annotation, name="flag", default=False, match="cannot be used with action")
3171
3172 def test_count_action_rejects_user_choices_provider(self) -> None:
3173 annotation = Annotated[
3174 int, Option("-v", action="count", choices_provider=TestZeroArgActionRejectsUserCompletion._provider)
3175 ]
3176 _assert_build_error(annotation, name="v", default=0, match="cannot be used with action")
3177
3178 def test_store_const_rejects_user_completer(self) -> None:
3179 annotation = Annotated[str, Option("-m", action="store_const", const="x", completer=cmd2.Cmd.path_complete)]
3180 _assert_build_error(annotation, name="m", default="off", match="cannot be used with action")
3181
3182 def test_append_const_rejects_user_choices_provider(self) -> None:
3183 annotation = Annotated[
3184 list[str],
3185 Option(
3186 "--tag", action="append_const", const="x", choices_provider=TestZeroArgActionRejectsUserCompletion._provider
3187 ),
3188 ]
3189 _assert_build_error(annotation, name="tag", match="cannot be used with action")
3190
3191 def test_value_action_keeps_user_completer(self) -> None:
3192 """Control: a value-consuming option still accepts a user completer (not a zero-arg action)."""
3193 annotation = Annotated[str, Option("--path", completer=cmd2.Cmd.path_complete)]
3194 p = build_parser_from_function(_make_func(annotation, name="path", default=""))
3195 act = next(a for a in p._actions if a.dest == "path")
3196 assert act.get_completer() is cmd2.Cmd.path_complete
3197
3198
3199 class TestConstArgumentRejected:
3200 def test_argument_const_raises(self) -> None:
3201 _assert_build_error(Annotated[str, Argument(const="x")], match="const")
3202
3203 def test_positional_const_via_no_metadata_path(self) -> None:
3204 """A const on a parameter that resolves to a positional is rejected, not silently ignored."""
3205
3206 def do_x(self, name: Annotated[str, Argument(const="x")], other: str = "y") -> None: ...
3207
3208 with pytest.raises(TypeError, match="const"):
3209 build_parser_from_function(do_x)
3210
3211
3212 # ---------------------------------------------------------------------------
3213 # Custom ``argparse.Action`` subclasses pass through to ``add_argument``
3214 # ---------------------------------------------------------------------------
3215
3216
3217 class _UpperAction(argparse.Action):
3218 """Test action: store the upper-case value."""
3219
3220 def __call__(
3221 self,
3222 _parser: argparse.ArgumentParser,
3223 ns: argparse.Namespace,
3224 values: Any,
3225 _option_string: str | None = None,
3226 ) -> None:
3227 setattr(ns, self.dest, values.upper() if isinstance(values, str) else values)
3228
3229
3230 class _FlagAction(argparse.Action):
3231 """Test action: a presence-flag that takes no command-line value."""
3232
3233 def __init__(self, **kwargs: Any) -> None:
3234 super().__init__(nargs=0, **kwargs)
3235
3236 def __call__(
3237 self,
3238 _parser: argparse.ArgumentParser,
3239 ns: argparse.Namespace,
3240 _values: Any,
3241 _option_string: str | None = None,
3242 ) -> None:
3243 setattr(ns, self.dest, True)
3244
3245
3246 class _ListAction(argparse.Action):
3247 """Test action: store values as a plain list (no container_factory wrap)."""
3248
3249 def __call__(
3250 self,
3251 _parser: argparse.ArgumentParser,
3252 ns: argparse.Namespace,
3253 values: Any,
3254 _option_string: str | None = None,
3255 ) -> None:
3256 setattr(ns, self.dest, list(values))
3257
3258
3259 class _ConstAction(argparse.Action):
3260 """Test action: store ``self.const`` on presence."""
3261
3262 def __init__(self, **kwargs: Any) -> None:
3263 super().__init__(nargs=0, **kwargs)
3264
3265 def __call__(
3266 self,
3267 _parser: argparse.ArgumentParser,
3268 ns: argparse.Namespace,
3269 _values: Any,
3270 _option_string: str | None = None,
3271 ) -> None:
3272 setattr(ns, self.dest, self.const)
3273
3274
3275 class TestCustomActionClass:
3276 def test_scalar_class_action_passes_through(self) -> None:
3277 """A class action runs verbatim; the type-inferred passthrough doesn't get in the way."""
3278
3279 def f(self, name: Annotated[str, Option("--name", action=_UpperAction)] = "") -> None: ...
3280
3281 parser = build_parser_from_function(f)
3282 assert parser.parse_args(["--name", "hi"]).name == "HI"
3283
3284 def test_class_action_overrides_inferred_boolean_optional(self) -> None:
3285 """A class action on a bool option replaces the inferred ``BooleanOptionalAction``."""
3286
3287 def f(self, loud: Annotated[bool, Option("--loud", action=_FlagAction)] = False) -> None: ...
3288
3289 parser = build_parser_from_function(f)
3290 assert parser.parse_args(["--loud"]).loud is True
3291
3292 def test_class_action_on_list_drops_container_factory(self) -> None:
3293 """A class action on ``list[T]`` doesn't receive the casting action's ``container_factory``."""
3294
3295 def f(self, xs: Annotated[list[str], Option("--xs", action=_ListAction, nargs="+")] = ()) -> None: ...
3296
3297 parser = build_parser_from_function(f)
3298 assert parser.parse_args(["--xs", "a", "b"]).xs == ["a", "b"]
3299
3300 def test_class_action_with_const_skips_type_check(self) -> None:
3301 """``const`` paired with a class action is not validated against the declared type."""
3302 sentinel = object()
3303
3304 def f(self, mode: Annotated[str, Option("-m", action=_ConstAction, const=sentinel)] = "x") -> None: ...
3305
3306 parser = build_parser_from_function(f)
3307 assert parser.parse_args(["-m"]).mode is sentinel
3308
3309 def test_class_action_uses_inferred_converter_on_scalar(self) -> None:
3310 """The inferred ``type=int`` reaches the class action so values still coerce."""
3311
3312 class CaptureAction(argparse.Action):
3313 def __call__(self, _p: Any, ns: Any, values: Any, _o: str | None = None) -> None:
3314 setattr(ns, self.dest, ("seen", values))
3315
3316 def f(self, n: Annotated[int, Option("-n", action=CaptureAction)] = 0) -> None: ...
3317
3318 parser = build_parser_from_function(f)
3319 assert parser.parse_args(["-n", "5"]).n == ("seen", 5)
3320
3321 def test_unknown_string_action_still_rejected(self) -> None:
3322 """A typo in an action string is still caught -- only class actions are exempt."""
3323 _assert_build_error(Annotated[str, Option("-x", action="frobnicate")], match="not supported")
3324
3325
3326 # ---------------------------------------------------------------------------
3327 # ``extra_kwargs`` rejects argparse kwargs that the decorator derives elsewhere
3328 # ---------------------------------------------------------------------------
3329
3330
3331 class TestReservedExtraKwargs:
3332 @pytest.mark.parametrize("kw", ["type", "dest", "action", "required"])
3333 def test_argument_rejects_reserved_kwarg(self, kw: str) -> None:
3334 with pytest.raises(TypeError, match=kw):
3335 Argument(**{kw: "x"})
3336
3337 @pytest.mark.parametrize("kw", ["type", "dest"])
3338 def test_option_rejects_reserved_kwarg(self, kw: str) -> None:
3339 with pytest.raises(TypeError, match=kw):
3340 Option("--x", **{kw: "x"})
3341
3342 def test_option_keeps_named_action_and_required(self) -> None:
3343 """``action=`` and ``required=`` are named parameters of ``Option`` and must still work."""
3344 opt = Option("--x", action="store_true", required=True)
3345 assert opt.action == "store_true"
3346 assert opt.required is True
3347
3348 def test_error_message_includes_remediation_hint(self) -> None:
3349 """The error names the offending kwarg and points at the signature-derived source."""
3350 with pytest.raises(TypeError) as excinfo:
3351 Option("--x", type=int)
3352 msg = str(excinfo.value)
3353 assert "type" in msg
3354 assert "annotation" in msg
3355
3356 def test_unknown_registered_kwarg_still_passes_through(self) -> None:
3357 """A user-registered custom add_argument kwarg still flows through ``extra_kwargs``."""
3358 # The custom parameter ``annotated_custom_attr`` is registered at module import.
3359 action = _action_for(Annotated[str, Argument(annotated_custom_attr="value")])
3360 assert action.get_annotated_custom_attr() == "value" # type: ignore[attr-defined]
3361
3362
3363 # ---------------------------------------------------------------------------
3364 # ``default=`` as a metadata kwarg: equivalent to a signature default, with conflict and
3365 # SUPPRESS rejected.
3366 # ---------------------------------------------------------------------------
3367
3368
3369 class TestMetadataDefault:
3370 def test_option_metadata_default_equivalent_to_signature_default(self) -> None:
3371 """``Option(default=v)`` (no sig default) behaves the same as ``Option() = v``."""
3372
3373 def f_meta(self, name: Annotated[str, Option("--name", default="HI")]) -> None: ...
3374 def f_sig(self, name: Annotated[str, Option("--name")] = "HI") -> None: ...
3375
3376 p_meta = build_parser_from_function(f_meta)
3377 p_sig = build_parser_from_function(f_sig)
3378 assert p_meta.parse_args([]).name == p_sig.parse_args([]).name == "HI"
3379 assert p_meta.parse_args(["--name", "X"]).name == p_sig.parse_args(["--name", "X"]).name == "X"
3380
3381 def test_argument_metadata_default_equivalent_to_signature_default(self) -> None:
3382 """``Argument(default=v)`` (no sig default) behaves the same as ``Argument() = v``."""
3383
3384 def f_meta(self, name: Annotated[str, Argument(default="POS")]) -> None: ...
3385 def f_sig(self, name: Annotated[str, Argument()] = "POS") -> None: ...
3386
3387 p_meta = build_parser_from_function(f_meta)
3388 p_sig = build_parser_from_function(f_sig)
3389 assert p_meta.parse_args([]).name == p_sig.parse_args([]).name == "POS"
3390 assert p_meta.parse_args(["X"]).name == p_sig.parse_args(["X"]).name == "X"
3391
3392 def test_metadata_default_makes_option_not_required(self) -> None:
3393 """A metadata default removes ``required`` -- same as a signature default."""
3394 action = _action_for(Annotated[str, Option("--x", default="HI")])
3395 assert action.required is False
3396
3397 def test_metadata_default_makes_positional_nargs_optional(self) -> None:
3398 """A metadata default on a positional sets ``nargs='?'`` -- same as a signature default."""
3399 action = _action_for(Annotated[str, Argument(default="HI")])
3400 assert action.nargs == "?"
3401
3402 def test_default_conflict_signature_and_metadata_raises(self) -> None:
3403 """Both a signature default and a metadata default is a conflict."""
3404
3405 def f(self, name: Annotated[str, Option("--name", default="HI")] = "hello") -> None: ...
3406
3407 with pytest.raises(TypeError, match="default in both"):
3408 build_parser_from_function(f)
3409
3410 def test_default_conflict_message_names_both_values(self) -> None:
3411 """The conflict error message includes both candidate values."""
3412
3413 def f(self, name: Annotated[str, Option("--name", default="meta")] = "sig") -> None: ...
3414
3415 with pytest.raises(TypeError) as excinfo:
3416 build_parser_from_function(f)
3417 msg = str(excinfo.value)
3418 assert "'sig'" in msg
3419 assert "'meta'" in msg
3420
3421 def test_argparse_suppress_metadata_default_rejected(self) -> None:
3422 """``default=argparse.SUPPRESS`` in metadata is rejected (kwarg would vanish)."""
3423
3424 def f(self, name: Annotated[str, Option("--name", default=argparse.SUPPRESS)]) -> None: ...
3425
3426 with pytest.raises(TypeError, match="SUPPRESS"):
3427 build_parser_from_function(f)
3428
3429 def test_argparse_suppress_signature_default_rejected(self) -> None:
3430 """``= argparse.SUPPRESS`` in the signature is rejected as well."""
3431
3432 def f(self, name: str = argparse.SUPPRESS) -> None: ...
3433
3434 with pytest.raises(TypeError, match="SUPPRESS"):
3435 build_parser_from_function(f)
3436
3437 def test_metadata_default_none_on_non_optional_rejected(self) -> None:
3438 """The 'None default on non-Optional' rule applies to a metadata default as well."""
3439 _assert_build_error(Annotated[str, Option("--x", default=None)], match="None")
3440
3441 def test_metadata_default_none_on_optional_accepted(self) -> None:
3442 """``default=None`` on a ``T | None`` annotation is fine (consistent with signature defaults)."""
3443 action = _action_for(Annotated[str | None, Option("--x", default=None)])
3444 assert action.default is None
3445 assert action.required is False
3446
3447 def test_metadata_default_with_explicit_action(self) -> None:
3448 """A metadata default flows through to the action layer (here: store_const)."""
3449 annotation = Annotated[int, Option("-v", action="store_const", const=2, default=0)]
3450 parser = build_parser_from_function(_make_func(annotation))
3451 assert parser.parse_args([]).value == 0
3452 assert parser.parse_args(["-v"]).value == 2
3453
3454
3455 # ---------------------------------------------------------------------------
3456 # A variable-arity positional must be the last positional
3457 # ---------------------------------------------------------------------------
3458
3459
3460 class TestPositionalOrdering:
3461 def test_optional_positional_before_required_raises(self) -> None:
3462 def do_x(self, a: str | None, b: str) -> None: ...
3463
3464 with pytest.raises(TypeError, match="variable arity"):
3465 build_parser_from_function(do_x)
3466
3467 def test_list_positional_before_positional_raises(self) -> None:
3468 def do_x(self, items: list[str], b: str) -> None: ...
3469
3470 with pytest.raises(TypeError, match="variable arity"):
3471 build_parser_from_function(do_x)
3472
3473 def test_required_positional_before_star_args_builds(self) -> None:
3474 def do_x(self, a: str, *args: str) -> None: ...
3475
3476 parser = build_parser_from_function(do_x)
3477 ns = parser.parse_args(["one", "two", "three"])
3478 assert ns.a == "one"
3479 assert ns.args == ("two", "three")
3480
3481 def test_ranged_nargs_collection_before_positional_raises(self) -> None:
3482 def do_x(self, items: Annotated[list[str], Argument(nargs=(1, 3))], b: str) -> None: ...
3483
3484 with pytest.raises(TypeError, match="variable arity"):
3485 build_parser_from_function(do_x)
3486
3487
3488 # ---------------------------------------------------------------------------
3489 # Ranged nargs (min, max) tuples
3490 # ---------------------------------------------------------------------------
3491
3492
3493 class TestRangedNargs:
3494 def test_ranged_nargs_on_scalar_raises(self) -> None:
3495 _assert_build_error(Annotated[str, Argument(nargs=(2, 4))], match="not a collection type")
3496
3497 def test_ranged_nargs_on_list_builds(self) -> None:
3498 parser = build_parser_from_function(_make_func(Annotated[list[str], Argument(nargs=(2, 4))]))
3499 assert parser.parse_args(["a", "b", "c"]).value == ["a", "b", "c"]
3500
3501 def test_ranged_nargs_zero_one_on_scalar_builds(self) -> None:
3502 # cmd2 collapses the (0, 1) range to OPTIONAL ('?'), which yields a single optional value
3503 # (not a list), so it is allowed on a scalar, like nargs='?'. Absent -> None.
3504 parser = build_parser_from_function(_make_func(Annotated[str, Argument(nargs=(0, 1))]))
3505 assert parser.parse_args(["x"]).value == "x"
3506 assert parser.parse_args([]).value is None
3507
3508 def test_optional_scalar_positional_nargs_question_builds(self) -> None:
3509 # An explicit nargs='?' on a scalar positional is the standard argparse optional-positional;
3510 # it is allowed (absent -> None). Developers wanting type-safe absence use 'T | None'.
3511 parser = build_parser_from_function(_make_func(Annotated[int, Argument(nargs="?")]))
3512 assert parser.parse_args(["5"]).value == 5
3513 assert parser.parse_args([]).value is None
3514
3515
3516 # ---------------------------------------------------------------------------
3517 # Subcommands group configuration (required / metavar / title / description)
3518 # ---------------------------------------------------------------------------
3519
3520
3521 class TestSubcommandGroupConfig:
3522 @staticmethod
3523 def _base_parser(**subcommand_kwargs):
3524 @with_annotated(base_command=True, **subcommand_kwargs)
3525 def do_root(self, cmd2_subcommand_func) -> None: ...
3526
3527 builder = getattr(do_root, constants.ARGPARSE_COMMAND_ATTR_SPEC).parser_source
3528 return builder()
3529
3530 @staticmethod
3531 def _subparsers_action(parser):
3532 return next(a for a in parser._actions if isinstance(a, argparse._SubParsersAction))
3533
3534 def test_defaults_required_with_subcommand_metavar(self) -> None:
3535 action = self._subparsers_action(self._base_parser())
3536 assert action.required is True
3537 assert action.metavar == "SUBCOMMAND"
3538
3539 def test_subcommand_required_false(self) -> None:
3540 action = self._subparsers_action(self._base_parser(subcommand_required=False))
3541 assert action.required is False
3542
3543 def test_subcommand_metavar_override(self) -> None:
3544 action = self._subparsers_action(self._base_parser(subcommand_metavar="CMD"))
3545 assert action.metavar == "CMD"
3546
3547 def test_subcommand_title_and_description(self) -> None:
3548 parser = self._base_parser(subcommand_title="Commands", subcommand_description="pick one")
3549 group = next((g for g in parser._action_groups if g.title == "Commands"), None)
3550 assert group is not None
3551 assert group.description == "pick one"
3552
3553 def test_subparsers_default_to_positionals_group(self) -> None:
3554 """Without a title/description the subparsers belong to argparse's own positionals group."""
3555 parser = self._base_parser()
3556 action = self._subparsers_action(parser)
3557 assert action in parser._positionals._group_actions
3558 # No untitled group is created to hold them.
3559 assert [g for g in parser._action_groups if g.title is None] == []
3560
3561 def test_subparsers_listed_under_positional_arguments_in_help(self) -> None:
3562 """The subcommands are documented in --help like argparse and Cmd2ArgumentParser do."""
3563 parser = self._base_parser()
3564 help_text = parser.format_help()
3565 _, header, rest = help_text.partition("Positional Arguments:")
3566 assert header, f"no positional arguments section in:\n{help_text}"
3567 assert "SUBCOMMAND" in rest.partition("Options:")[0]
3568
3569 @pytest.mark.parametrize(
3570 ("kwargs", "expected_title"),
3571 [
3572 pytest.param({"subcommand_title": "Commands"}, "Commands", id="title-only"),
3573 pytest.param({"subcommand_description": "pick one"}, "subcommands", id="description-only"),
3574 ],
3575 )
3576 def test_subparsers_move_out_of_positionals_when_titled(self, kwargs, expected_title) -> None:
3577 """Supplying either knob still opts into a dedicated group, argparse's documented behavior."""
3578 parser = self._base_parser(**kwargs)
3579 action = self._subparsers_action(parser)
3580 assert action not in parser._positionals._group_actions
3581 group = next(g for g in parser._action_groups if action in g._group_actions)
3582 assert group.title == expected_title
3583
3584
3585 # ---------------------------------------------------------------------------
3586 # Rich objects are accepted for description / epilog (HelpContent)
3587 # ---------------------------------------------------------------------------
3588
3589
3590 class TestRichHelpContent:
3591 def test_rich_description_and_epilog_accepted(self) -> None:
3592 from rich.text import Text
3593
3594 desc = Text("a rich description")
3595 parser = build_parser_from_function(_make_func(str), description=desc, epilog=Text("epilog"))
3596 assert parser.description is desc
3597
3598
3599 # ---------------------------------------------------------------------------
3600 # Docstring auto-extraction for parser description
3601 # ---------------------------------------------------------------------------
3602
3603
3604 class TestDocstringDescription:
3605 """The first paragraph of ``func.__doc__`` fills ``description`` when none is given."""
3606
3607 def test_first_paragraph_used_when_no_description(self) -> None:
3608 def func(self, name: str) -> None:
3609 """Summary line for the command.
3610
3611 More detail here that should not appear in description.
3612
3613 :param name: a name
3614 """
3615
3616 parser = build_parser_from_function(func)
3617 assert parser.description == "Summary line for the command."
3618
3619 def test_multiline_first_paragraph_preserved(self) -> None:
3620 def func(self, name: str) -> None:
3621 """First line continues
3622 onto the second line without a blank gap.
3623
3624 Detail paragraph below the blank line is dropped.
3625 """
3626
3627 parser = build_parser_from_function(func)
3628 assert parser.description == "First line continues\nonto the second line without a blank gap."
3629
3630 def test_explicit_description_overrides_docstring(self) -> None:
3631 def func(self, name: str) -> None:
3632 """Auto summary."""
3633
3634 parser = build_parser_from_function(func, description="explicit")
3635 assert parser.description == "explicit"
3636
3637 def test_no_docstring_means_no_description(self) -> None:
3638 def func(self, name: str) -> None: ...
3639
3640 parser = build_parser_from_function(func)
3641 assert parser.description is None
3642
3643 def test_empty_docstring_means_no_description(self) -> None:
3644 def func(self, name: str) -> None:
3645 """ """
3646
3647 parser = build_parser_from_function(func)
3648 assert parser.description is None
3649
3650 def test_field_directive_without_blank_line_does_not_leak(self) -> None:
3651 """A ``:param:`` directly under the summary (no blank line) is stripped, not leaked."""
3652
3653 def func(self, name: str) -> None:
3654 """Summary line.
3655 :param name: should not leak into the description
3656 """
3657
3658 parser = build_parser_from_function(func)
3659 assert parser.description == "Summary line."
3660
3661 def test_decorator_uses_docstring(self) -> None:
3662 @with_annotated
3663 def do_run(self, name: str) -> None:
3664 """Run the thing.
3665
3666 Extra detail.
3667 """
3668
3669 builder = getattr(do_run, constants.ARGPARSE_COMMAND_ATTR_SPEC).parser_source
3670 assert builder().description == "Run the thing."
3671
3672 def test_subcommand_uses_docstring(self) -> None:
3673 @with_annotated(subcommand_to="team")
3674 def team_add(self, name: str) -> None:
3675 """Add a member to the team."""
3676
3677 spec = getattr(team_add, constants.SUBCOMMAND_ATTR_SPEC)
3678 assert spec.parser_source().description == "Add a member to the team."
3679
3680
3681 # ---------------------------------------------------------------------------
3682 # Group(required=...) for mutually exclusive groups
3683 # ---------------------------------------------------------------------------
3684
3685
3686 class TestMutuallyExclusiveGroupRequired:
3687 """``Group(required=True)`` reaches ``add_mutually_exclusive_group(required=True)``."""
3688
3689 def test_required_mutex_group_flag_set(self) -> None:
3690 def func(self, verbose: bool = False, quiet: bool = False) -> None: ...
3691
3692 parser = build_parser_from_function(func, mutually_exclusive_groups=(Group("verbose", "quiet", required=True),))
3693 assert parser._mutually_exclusive_groups[0].required is True
3694
3695 def test_default_mutex_group_not_required(self) -> None:
3696 def func(self, verbose: bool = False, quiet: bool = False) -> None: ...
3697
3698 parser = build_parser_from_function(func, mutually_exclusive_groups=(Group("verbose", "quiet"),))
3699 assert parser._mutually_exclusive_groups[0].required is False
3700
3701 def test_required_mutex_group_argparse_enforces(self) -> None:
3702 def func(self, verbose: bool = False, quiet: bool = False) -> None: ...
3703
3704 parser = build_parser_from_function(func, mutually_exclusive_groups=(Group("verbose", "quiet", required=True),))
3705 with pytest.raises(SystemExit):
3706 parser.parse_args([])
3707
3708 def test_required_on_plain_group_rejected(self) -> None:
3709 """``required=True`` is only valid in mutex groups; argparse doesn't support it elsewhere."""
3710
3711 def func(self, host: str, port: int = 22) -> None: ...
3712
3713 with pytest.raises(ValueError, match="only valid in mutually_exclusive_groups"):
3714 build_parser_from_function(func, groups=(Group("host", "port", required=True),))
3715
3716
3717 # ---------------------------------------------------------------------------
3718 # Parser-level kwargs: prog / usage / parents / argument_default
3719 # ---------------------------------------------------------------------------
3720
3721
3722 class TestParserLevelKwargs:
3723 """Forward ``prog``, ``usage``, ``parents``, ``argument_default`` to the parser ctor."""
3724
3725 def test_prog_passthrough(self) -> None:
3726 parser = build_parser_from_function(_make_func(str), prog="myprog")
3727 assert parser.prog == "myprog"
3728
3729 def test_usage_passthrough(self) -> None:
3730 parser = build_parser_from_function(_make_func(str), usage="usage: do stuff")
3731 assert parser.usage == "usage: do stuff"
3732
3733 def test_parents_passthrough(self) -> None:
3734 """argparse ``parents=`` copies argument actions from each parent into the new parser."""
3735 parent = argparse.ArgumentParser(add_help=False)
3736 parent.add_argument("--shared", help="from parent")
3737
3738 parser = build_parser_from_function(_make_func(str), parents=[parent])
3739 dests = {a.dest for a in parser._actions}
3740 assert "shared" in dests
3741
3742 def test_argument_default_passthrough(self) -> None:
3743 sentinel = "DEFAULT_FROM_PARSER"
3744 parser = build_parser_from_function(_make_func(str), argument_default=sentinel)
3745 assert parser.argument_default == sentinel
3746
3747 def test_decorator_passes_parser_kwargs(self) -> None:
3748 @with_annotated(prog="myprog", usage="usage line")
3749 def do_run(self, name: str) -> None: ...
3750
3751 builder = getattr(do_run, constants.ARGPARSE_COMMAND_ATTR_SPEC).parser_source
3752 parser = builder()
3753 assert parser.prog == "myprog"
3754 assert parser.usage == "usage line"
3755
3756 def test_prog_rejected_with_subcommand_to(self) -> None:
3757 """cmd2's subcommand machinery rewrites ``prog`` from the parent hierarchy."""
3758 with pytest.raises(TypeError, match=r"prog .* not supported with subcommand_to"):
3759
3760 @with_annotated(subcommand_to="team", prog="something")
3761 def team_add(self, name: str) -> None: ...
3762
3763 def test_usage_allowed_on_subcommand(self) -> None:
3764 """``usage`` doesn't conflict with subcommand prog rewriting."""
3765
3766 @with_annotated(subcommand_to="team", usage="team add NAME")
3767 def team_add(self, name: str) -> None: ...
3768
3769 spec = getattr(team_add, constants.SUBCOMMAND_ATTR_SPEC)
3770 assert spec.parser_source().usage == "team add NAME"
3771
3772 def test_parents_allowed_on_subcommand(self) -> None:
3773 parent = argparse.ArgumentParser(add_help=False)
3774 parent.add_argument("--shared")
3775
3776 @with_annotated(subcommand_to="team", parents=[parent])
3777 def team_add(self, name: str) -> None: ...
3778
3779 spec = getattr(team_add, constants.SUBCOMMAND_ATTR_SPEC)
3780 dests = {a.dest for a in spec.parser_source()._actions}
3781 assert "shared" in dests
3782
3783
3784 # ---------------------------------------------------------------------------
3785 # Less-common parser-level kwargs: prefix_chars / fromfile_prefix_chars /
3786 # conflict_handler / add_help / allow_abbrev / exit_on_error
3787 # ---------------------------------------------------------------------------
3788
3789
3790 class TestParserLowLevelKwargs:
3791 """Forward the remaining argparse parser ctor kwargs."""
3792
3793 def test_prefix_chars_passthrough(self) -> None:
3794 """A non-default ``prefix_chars`` propagates so ``Option('+flag')`` would be legal."""
3795 parser = build_parser_from_function(_make_func(str), prefix_chars="+-")
3796 assert parser.prefix_chars == "+-"
3797
3798 def test_fromfile_prefix_chars_enables_argument_files(self) -> None:
3799 """argparse loads tokens from a file when an arg starts with the prefix char."""
3800 import tempfile
3801
3802 def func(self, name: str) -> None: ...
3803
3804 parser = build_parser_from_function(func, fromfile_prefix_chars="@")
3805 with tempfile.NamedTemporaryFile("w", suffix=".args", delete=False) as fh:
3806 fh.write("alice\n")
3807 path = fh.name
3808 try:
3809 ns = parser.parse_args([f"@{path}"])
3810 assert ns.name == "alice"
3811 finally:
3812 Path(path).unlink()
3813
3814 def test_conflict_handler_resolve_lets_parents_be_overridden(self) -> None:
3815 """``conflict_handler='resolve'`` allows a parent's ``--flag`` to be redefined."""
3816 parent = argparse.ArgumentParser(add_help=False)
3817 parent.add_argument("--mode", default="parent")
3818
3819 def func(self, mode: str = "child") -> None: ...
3820
3821 parser = build_parser_from_function(func, parents=[parent], conflict_handler="resolve")
3822 ns = parser.parse_args([])
3823 # The locally-declared --mode wins after the resolve.
3824 assert ns.mode == "child"
3825
3826 def test_add_help_false_drops_help_action(self) -> None:
3827 parser = build_parser_from_function(_make_func(str), add_help=False)
3828 assert all(not isinstance(a, argparse._HelpAction) for a in parser._actions)
3829
3830 def test_allow_abbrev_false_rejects_prefix_match(self) -> None:
3831 """With abbreviations off, ``--verb`` no longer matches ``--verbose``."""
3832
3833 def func(self, verbose: bool = False) -> None: ...
3834
3835 parser = build_parser_from_function(func, allow_abbrev=False)
3836 with pytest.raises(SystemExit):
3837 parser.parse_args(["--verb"])
3838
3839 def test_exit_on_error_false_raises_argument_error(self) -> None:
3840 """``exit_on_error=False`` surfaces parse failures as exceptions instead of sys.exit."""
3841
3842 def func(self, count: int) -> None: ...
3843
3844 parser = build_parser_from_function(func, exit_on_error=False)
3845 with pytest.raises(argparse.ArgumentError):
3846 parser.parse_args(["not-an-int"])
3847
3848 def test_decorator_threads_all_low_level_kwargs(self) -> None:
3849 """End-to-end: each kwarg lands on the parser when set on the decorator."""
3850
3851 @with_annotated(
3852 prefix_chars="+-",
3853 conflict_handler="resolve",
3854 add_help=False,
3855 allow_abbrev=False,
3856 exit_on_error=False,
3857 fromfile_prefix_chars="@",
3858 )
3859 def do_run(self, name: str) -> None: ...
3860
3861 builder = getattr(do_run, constants.ARGPARSE_COMMAND_ATTR_SPEC).parser_source
3862 parser = builder()
3863 assert parser.prefix_chars == "+-"
3864 assert parser.fromfile_prefix_chars == "@"
3865 assert parser.conflict_handler == "resolve"
3866 assert all(not isinstance(a, argparse._HelpAction) for a in parser._actions)
3867 assert parser.allow_abbrev is False
3868 assert parser.exit_on_error is False
3869
3870
3871 class TestExplicitChoicesValueSpace:
3872 """Explicit ``choices=`` are reconciled with the inferred type converter and completer."""
3873
3874 def test_string_choices_converted_to_declared_type(self) -> None:
3875 """choices=['1','2'] on an int parameter match after argparse runs the int converter."""
3876 p = build_parser_from_function(_make_func(Annotated[int, Option("--x", choices=["1", "2"])], default=1, name="x"))
3877 action = next(a for a in p._actions if a.dest == "x")
3878 assert action.choices == [1, 2]
3879 assert p.parse_args(["--x", "1"]).x == 1
3880 with pytest.raises(SystemExit):
3881 p.parse_args(["--x", "3"])
3882
3883 def test_already_typed_choices_left_untouched(self) -> None:
3884 p = build_parser_from_function(_make_func(Annotated[int, Option("--x", choices=[1, 2])], default=1, name="x"))
3885 action = next(a for a in p._actions if a.dest == "x")
3886 assert action.choices == [1, 2]
3887
3888 def test_choice_invalid_for_type_is_build_error(self) -> None:
3889 _assert_build_error(Annotated[int, Option("--x", choices=["1", "nope"])], default=1, match="not a valid")
3890
3891 def test_explicit_choices_kept_over_inferred_path_completer(self) -> None:
3892 """An explicit choices= on a Path is retained (and the inferred path completer dropped)."""
3893 p = build_parser_from_function(_make_func(Annotated[Path, Argument(choices=[Path("/a"), Path("/b")])], name="p"))
3894 action = next(a for a in p._actions if a.dest == "p")
3895 assert action.choices == [Path("/a"), Path("/b")]
3896 assert getattr(action, "completer", None) is None
3897 assert p.parse_args(["/a"]).p == Path("/a")
3898 with pytest.raises(SystemExit):
3899 p.parse_args(["/c"])
3900
3901 def test_user_completer_still_overrides_choices(self) -> None:
3902 """A user-supplied completer continues to drive completion in place of static choices."""
3903
3904 def completer(self, *args: Any) -> list[str]:
3905 return ["x"]
3906
3907 p = build_parser_from_function(
3908 _make_func(Annotated[str, Option("--x", choices=["a", "b"], completer=completer)], default="a", name="x")
3909 )
3910 action = next(a for a in p._actions if a.dest == "x")
3911 assert action.choices is None
3912
3913
3914 class TestStrConstValidation:
3915 """A const on a str parameter must itself be a str (it is stored verbatim, not converted)."""
3916
3917 def test_non_str_const_on_str_rejected(self) -> None:
3918 _assert_build_error(Annotated[str, Option("--x", const=123)], default="a", match="does not match")
3919
3920 def test_str_const_on_str_accepted(self) -> None:
3921 p = build_parser_from_function(_make_func(Annotated[str, Option("--x", const="fast")], default="slow", name="x"))
3922 assert p.parse_args(["--x"]).x == "fast"
3923
3924 def test_const_on_untyped_param_not_validated(self) -> None:
3925 """Any/object/unannotated are genuinely untyped, so a const of any type is accepted."""
3926 p = build_parser_from_function(_make_func(Annotated[Any, Option("--x", const=123)], default=None, name="x"))
3927 assert p.parse_args(["--x"]).x == 123
3928
3929
3930 class TestArgumentDefaultSuppressGuard:
3931 """``argument_default=argparse.SUPPRESS`` is rejected outright by @with_annotated.
3932
3933 SUPPRESS drops an absent argument from the parsed namespace, but @with_annotated builds the call
3934 from the signature, so every declared parameter is expected at invocation -- a vanished argument
3935 can never be valid. The rejection is unconditional (it never inspects the signature), so one
3936 direct-build case and one subcommand-registration case cover it.
3937 """
3938
3939 def test_suppress_rejected(self) -> None:
3940 def do_t(self, a: int, b: str = "x"): ...
3941
3942 with pytest.raises(TypeError, match="SUPPRESS"):
3943 build_parser_from_function(do_t, argument_default=argparse.SUPPRESS)
3944
3945 def test_suppress_rejected_in_subcommand(self) -> None:
3946 """The subcommand path shares the same builder, so the rejection fires at registration too."""
3947
3948 class App(cmd2.Cmd):
3949 @with_annotated(base_command=True)
3950 def do_calc(self, cmd2_subcommand_func) -> None:
3951 if cmd2_subcommand_func:
3952 cmd2_subcommand_func()
3953
3954 @with_annotated(subcommand_to="calc", argument_default=argparse.SUPPRESS, help="sum values")
3955 def calc_sum(self, value: str = "x") -> None: ...
3956
3957 with pytest.raises(TypeError, match="SUPPRESS"):
3958 App()
3959
3960
3961 class TestHelpKwargReserved:
3962 """Raw ``help=`` is rejected so it cannot silently shadow the mapped ``help_text=``."""
3963
3964 def test_raw_help_rejected(self) -> None:
3965 with pytest.raises(TypeError, match="help_text"):
3966 Option("--x", help="raw")
3967
3968 def test_help_text_still_works(self) -> None:
3969 action = _action_for(Annotated[str, Option("--x", help_text="mapped")], default="a")
3970 assert action.help == "mapped"
3971
3972
3973 class TestEnumAcceptsNameAndValue:
3974 """Enum parameters accept member values AND names (documented behavior, locked here)."""
3975
3976 def test_enum_accepts_both_name_and_value(self) -> None:
3977 class Color(enum.Enum):
3978 RED = "r"
3979 GREEN = "g"
3980
3981 p = build_parser_from_function(_make_func(Color, name="c"))
3982 assert p.parse_args(["r"]).c is Color.RED
3983 assert p.parse_args(["RED"]).c is Color.RED
3984
3985
3986 class _AliasColor(enum.Enum):
3987 """An enum that maps extra command-line spellings to members via the standard ``_missing_`` hook."""
3988
3989 RED = "red"
3990 GREEN = "green"
3991 BLUE = "blue"
3992
3993 @classmethod
3994 def _missing_(cls, value: object) -> "_AliasColor | None":
3995 return {"auto": cls.RED, "default": cls.RED}.get(str(value).lower())
3996
3997
3998 class TestAllowUnknownEntry:
3999 """``allow_unknown_entry=True`` lets an Enum's ``_missing_`` hook resolve otherwise-unknown tokens."""
4000
4001 def test_missing_not_consulted_without_flag(self) -> None:
4002 """By default the converter ignores ``_missing_`` -- an alias is rejected (current behavior)."""
4003 parser = build_parser_from_function(_make_func(_AliasColor, name="c"))
4004 with pytest.raises(SystemExit):
4005 parser.parse_args(["auto"])
4006
4007 def test_flag_consults_missing(self) -> None:
4008 """With the flag, an unknown token is resolved through the enum's ``_missing_`` hook."""
4009 parser = build_parser_from_function(_make_func(Annotated[_AliasColor, Argument(allow_unknown_entry=True)], name="c"))
4010 assert parser.parse_args(["auto"]).c is _AliasColor.RED
4011 assert parser.parse_args(["default"]).c is _AliasColor.RED
4012
4013 def test_flag_still_accepts_canonical_value_and_name(self) -> None:
4014 """Enabling the flag does not regress value or name lookup; ``_missing_`` is only a fallback."""
4015 parser = build_parser_from_function(_make_func(Annotated[_AliasColor, Argument(allow_unknown_entry=True)], name="c"))
4016 assert parser.parse_args(["red"]).c is _AliasColor.RED # by value
4017 assert parser.parse_args(["GREEN"]).c is _AliasColor.GREEN # by name
4018
4019 def test_flag_preserves_intenum_value_bridge(self) -> None:
4020 """An IntEnum value typed as a string still resolves with the flag on (str-bridge intact)."""
4021
4022 class IntColor(enum.IntEnum):
4023 red = 1
4024 green = 2
4025
4026 @classmethod
4027 def _missing_(cls, value: object) -> "IntColor | None":
4028 return cls.red if str(value).lower() == "auto" else None
4029
4030 parser = build_parser_from_function(_make_func(Annotated[IntColor, Argument(allow_unknown_entry=True)], name="c"))
4031 assert parser.parse_args(["1"]).c is IntColor.red # int value via str-bridge
4032 assert parser.parse_args(["auto"]).c is IntColor.red # _missing_
4033
4034 def test_flag_unknown_without_missing_match_still_errors(self) -> None:
4035 """A token neither matched nor rescued by ``_missing_`` is still rejected with the choices."""
4036 parser = build_parser_from_function(_make_func(Annotated[_AliasColor, Argument(allow_unknown_entry=True)], name="c"))
4037 with pytest.raises(SystemExit):
4038 parser.parse_args(["bogus"])
4039
4040 def test_flag_on_option(self) -> None:
4041 """The flag also works on an ``Option`` (keyword) parameter."""
4042 parser = build_parser_from_function(
4043 _make_func(Annotated[_AliasColor | None, Option("--c", allow_unknown_entry=True)], name="c", default=None)
4044 )
4045 assert parser.parse_args(["--c", "auto"]).c is _AliasColor.RED
4046
4047 def test_flag_on_collection_element(self) -> None:
4048 """The flag propagates to an Enum used as a collection element."""
4049 parser = build_parser_from_function(
4050 _make_func(Annotated[list[_AliasColor], Argument(allow_unknown_entry=True)], name="cs")
4051 )
4052 assert parser.parse_args(["auto", "blue"]).cs == [_AliasColor.RED, _AliasColor.BLUE]
4053
4054 def test_make_enum_type_flag_directly(self) -> None:
4055 """Unit-level: ``_make_enum_type`` honors ``_missing_`` only when ``allow_unknown_entry`` is set."""
4056 without = _make_enum_type(_AliasColor)
4057 with pytest.raises(argparse.ArgumentTypeError):
4058 without("auto")
4059 with_flag = _make_enum_type(_AliasColor, allow_unknown_entry=True)
4060 assert with_flag("auto") is _AliasColor.RED
4061
4062 def test_missing_exception_propagates_not_swallowed(self) -> None:
4063 """A ``_missing_`` that raises is surfaced, not masked as an 'invalid choice' error."""
4064
4065 class Raises(enum.Enum):
4066 a = "a"
4067
4068 @classmethod
4069 def _missing_(cls, value: object) -> "Raises | None":
4070 raise ValueError("boom in _missing_")
4071
4072 conv = _make_enum_type(Raises, allow_unknown_entry=True)
4073 with pytest.raises(ValueError, match="boom in _missing_"):
4074 conv("zzz")
4075
4076 def test_flag_without_missing_handler_is_inert(self) -> None:
4077 """An Enum with no ``_missing_`` override inherits the default (returns None), so the flag is inert."""
4078
4079 class NoHandler(enum.Enum):
4080 a = "a"
4081
4082 parser = build_parser_from_function(_make_func(Annotated[NoHandler, Argument(allow_unknown_entry=True)], name="c"))
4083 assert parser.parse_args(["a"]).c is NoHandler.a # canonical value still works
4084 with pytest.raises(SystemExit):
4085 parser.parse_args(["zzz"]) # unknown token still rejected; the flag added nothing
4086
4087
4088 class _OtherColor(enum.Enum):
4089 """A third, disjoint Enum used to exercise multi-member unions."""
4090
4091 cyan = "cyan"
4092 magenta = "magenta"
4093
4094
4095 class _StrictColor(enum.Enum):
4096 """An Enum whose ``_missing_`` *raises* on an unknown token, as a strict enum typically does."""
4097
4098 crimson = "crimson"
4099
4100 @classmethod
4101 def _missing_(cls, value: object) -> "_StrictColor | None":
4102 raise ValueError(f"{value!r} is not a valid _StrictColor")
4103
4104
4105 class TestEnumUnion:
4106 """A union of Enums (``EnumA | EnumB``) resolves by trying each member's converter in order."""
4107
4108 @pytest.mark.parametrize(
4109 ("annotation", "token", "expected"),
4110 [
4111 pytest.param(_Color | _IntColor, "red", _Color.red, id="first-member-value"),
4112 pytest.param(_Color | _IntColor, "2", _IntColor.green, id="second-member-value"),
4113 pytest.param(_IntColor | _Color, "1", _IntColor.red, id="intenum-value"),
4114 pytest.param(_IntColor | _Color, "green", _IntColor.green, id="member-name-first-wins"),
4115 pytest.param(_Color | _PlainColor, "red", _Color.red, id="shared-repr-first-wins"),
4116 pytest.param(_PlainColor | _Color, "red", _PlainColor.RED, id="shared-repr-order-flips"),
4117 pytest.param(_Color | _IntColor | _OtherColor, "blue", _Color.blue, id="three-member-first"),
4118 pytest.param(_Color | _IntColor | _OtherColor, "2", _IntColor.green, id="three-member-middle"),
4119 pytest.param(_Color | _IntColor | _OtherColor, "cyan", _OtherColor.cyan, id="three-member-last"),
4120 ],
4121 )
4122 def test_resolution(self, annotation: Any, token: str, expected: enum.Enum) -> None:
4123 """A token resolves to the first union member whose converter accepts it."""
4124 parser = build_parser_from_function(_make_func(annotation, name="c"))
4125 assert parser.parse_args([token]).c is expected
4126
4127 @pytest.mark.parametrize(
4128 "annotation",
4129 [
4130 pytest.param(_Color | Literal["auto"], id="literal-member"),
4131 pytest.param(_Color | int, id="non-enum-member"),
4132 pytest.param(str | int, id="plain-scalars"),
4133 # `... | None` is stripped and the remaining union rebuilt, so the same rule applies.
4134 pytest.param(_Color | int | None, id="non-enum-member-optional"),
4135 pytest.param(_Color | Literal["auto"] | None, id="literal-member-optional"),
4136 ],
4137 )
4138 def test_out_of_scope_union_rejected(self, annotation: Any) -> None:
4139 """Scope is Enum-only: a union with a Literal or non-Enum member is rejected as ambiguous."""
4140 with pytest.raises(TypeError, match="ambiguous"):
4141 build_parser_from_function(_make_func(annotation, name="c"))
4142
4143 def test_invalid_value_rejected(self) -> None:
4144 """A token no member accepts is rejected at parse time."""
4145 parser = build_parser_from_function(_make_func(_Color | _IntColor, name="c"))
4146 with pytest.raises(SystemExit):
4147 parser.parse_args(["bogus"])
4148
4149 def test_optional_union_without_default_is_optional_positional(self) -> None:
4150 """``A | B | None`` with no default is a positional ``nargs='?'`` yielding None when absent."""
4151 action = _get_param_action(_make_func(_Color | _IntColor | None, name="c"))
4152 assert action.option_strings == [] # positional
4153 assert action.nargs == "?"
4154 parser = build_parser_from_function(_make_func(_Color | _IntColor | None, name="c"))
4155 assert parser.parse_args([]).c is None
4156 assert parser.parse_args(["red"]).c is _Color.red
4157
4158 def test_optional_union_with_default_is_option(self) -> None:
4159 """``A | B | None = None`` becomes a ``--flag`` option."""
4160 parser = build_parser_from_function(_make_func(_Color | _IntColor | None, name="c", default=None))
4161 assert parser.parse_args([]).c is None
4162 assert parser.parse_args(["--c", "blue"]).c is _Color.blue
4163
4164 def test_union_as_collection_element(self) -> None:
4165 """A union works as a collection element type."""
4166 parser = build_parser_from_function(_make_func(list[_Color | _IntColor], name="cs"))
4167 assert parser.parse_args(["red", "2"]).cs == [_Color.red, _IntColor.green]
4168
4169 def test_allow_unknown_entry_threads_into_union_members(self) -> None:
4170 """``allow_unknown_entry`` propagates to each member, so a member's ``_missing_`` still fires."""
4171 parser = build_parser_from_function(
4172 _make_func(Annotated[_AliasColor | _IntColor, Argument(allow_unknown_entry=True)], name="c")
4173 )
4174 assert parser.parse_args(["auto"]).c is _AliasColor.RED # _AliasColor._missing_
4175 assert parser.parse_args(["2"]).c is _IntColor.green
4176
4177 def test_shared_representation_choices_are_deduped(self) -> None:
4178 """When members share a text representation the merged choices show it once (not once per member)."""
4179 # _Color and _PlainColor both spell their members "red"/"green"/"blue".
4180 action = _get_param_action(_make_func(_Color | _PlainColor, name="c"))
4181 texts = [c.text if isinstance(c, CompletionItem) else str(c) for c in action.choices]
4182 assert texts == ["red", "green", "blue"] # deduped, order preserved (first member wins)
4183
4184 def test_member_whose_missing_raises_does_not_preempt_later_members(self) -> None:
4185 """A member whose ``_missing_`` *raises* declines the token; the union keeps trying later members.
4186
4187 A strict Enum (one whose ``_missing_`` raises rather than returning ``None``) listed before a
4188 member that accepts the token must not abort the whole union -- the raise means "not mine",
4189 same as a clean rejection, so resolution falls through to the next member.
4190 """
4191 parser = build_parser_from_function(
4192 _make_func(Annotated[_StrictColor | _IntColor, Argument(allow_unknown_entry=True)], name="c")
4193 )
4194 # _StrictColor._missing_("2") raises, but _IntColor accepts "2" -- the later member still wins.
4195 assert parser.parse_args(["2"]).c is _IntColor.green
4196 # The strict member still claims its own token first.
4197 assert parser.parse_args(["crimson"]).c is _StrictColor.crimson
4198
4199 def test_all_members_declining_reports_invalid_choice_not_member_error(self) -> None:
4200 """When every member declines -- even one whose ``_missing_`` raises -- the union reports invalid choice.
4201
4202 The deferred member error must not surface as-is; the user sees the standard merged-choices
4203 rejection, raised only after all members have been tried.
4204 """
4205 converter = _get_param_action(
4206 _make_func(Annotated[_StrictColor | _IntColor, Argument(allow_unknown_entry=True)], name="c")
4207 ).type
4208 with pytest.raises(argparse.ArgumentTypeError, match="invalid choice"):
4209 converter("bogus")
4210
4211 def test_union_choices_preserve_display_meta(self) -> None:
4212 """Merged union choices keep each member's ``display_meta`` (the per-member tab-completion hint)."""
4213 action = _get_param_action(_make_func(_Color | _IntColor, name="c"))
4214 meta = {c.text: c.display_meta for c in action.choices if isinstance(c, CompletionItem)}
4215 assert meta == {"red": "red", "green": "green", "blue": "blue", "1": "red", "2": "green", "3": "blue"}
4216
4217
4218 # ---------------------------------------------------------------------------
4219 # converter / preprocess metadata
4220 # ---------------------------------------------------------------------------
4221
4222
4223 def _hex(value: str) -> int:
4224 """Parse a hexadecimal integer (test converter)."""
4225 return int(value, 16)
4226
4227
4228 def _csv_ints(value: str) -> set[int]:
4229 """Parse a comma-separated list of ints into a set (single token -> collection)."""
4230 return {int(piece) for piece in value.split(",")}
4231
4232
4233 def _parse_iso(value: str) -> datetime.datetime:
4234 """Parse an ISO-8601 timestamp (test converter for an otherwise-unsupported type)."""
4235 return datetime.datetime.fromisoformat(value)
4236
4237
4238 class TestConverter:
4239 """`Argument`/`Option` ``converter=`` replaces the inferred ``type=`` converter."""
4240
4241 def test_converter_becomes_type(self) -> None:
4242 """A supplied converter is emitted as argparse ``type=``, replacing the inferred one."""
4243 action = _action_for(Annotated[int, Argument(converter=_hex)])
4244 assert action.type is _hex
4245
4246 def test_converter_allows_unsupported_annotation_type(self) -> None:
4247 """A converter suppresses the 'unsupported scalar type' error: the annotation may be anything."""
4248 action = _action_for(Annotated[datetime.datetime, Argument(converter=_parse_iso)])
4249 assert action.type is _parse_iso
4250
4251 def test_converter_parses_end_to_end(self) -> None:
4252 """The converter runs at parse time, producing its own value-space."""
4253 parser = build_parser_from_function(_make_func(Annotated[int, Argument(converter=_hex)], name="addr"))
4254 assert parser.parse_args(["ff"]).addr == 255
4255
4256 def test_converter_drops_inferred_enum_choices(self) -> None:
4257 """Replacing the converter on an Enum drops the inferred choices (user owns the value-space)."""
4258 action = _action_for(Annotated[_Color, Argument(converter=str)])
4259 assert action.choices is None
4260
4261 def test_converter_drops_inferred_path_completer(self) -> None:
4262 """Replacing the converter on a Path drops the inferred path completer."""
4263 action = _action_for(Annotated[Path, Argument(converter=str)])
4264 assert action.get_completer() is None # type: ignore[attr-defined]
4265
4266 def test_converter_applies_per_element_on_collection(self) -> None:
4267 """On a ``list[T]`` the converter runs per token (argparse applies ``type=`` per value)."""
4268 parser = build_parser_from_function(_make_func(Annotated[list[int], Option("--n", converter=_hex)], name="n"))
4269 assert parser.parse_args(["--n", "ff", "10"]).n == [255, 16]
4270
4271 def test_converter_single_token_to_collection(self) -> None:
4272 """A non-collection annotation (Any) keeps a single token, so the converter may return a collection."""
4273 parser = build_parser_from_function(_make_func(Annotated[Any, Option("--idx", converter=_csv_ints)], name="idx"))
4274 assert parser.parse_args(["--idx", "1,3,5"]).idx == {1, 3, 5}
4275
4276 def test_converter_runs_explicit_choices_through_itself(self) -> None:
4277 """Explicit ``choices`` are run through the user converter for argparse's post-conversion match."""
4278 action = _action_for(Annotated[int, Argument(converter=_hex, choices=["ff", "10"])])
4279 assert action.choices == [255, 16]
4280
4281 def test_converter_allows_unsupported_collection_element(self) -> None:
4282 """A converter on ``list[Unsupported]`` keeps the collection shape and suppresses the element error."""
4283 parser = build_parser_from_function(
4284 _make_func(Annotated[list[datetime.datetime], Option("--ts", converter=_parse_iso)], name="ts")
4285 )
4286 parsed = parser.parse_args(["--ts", "2020-01-01", "2021-06-15"]).ts
4287 assert parsed == [_parse_iso("2020-01-01"), _parse_iso("2021-06-15")]
4288
4289 def test_converter_allows_ambiguous_union(self) -> None:
4290 """A converter suppresses the 'ambiguous union' error: a multi-member union is legal."""
4291 parser = build_parser_from_function(_make_func(Annotated[int | str, Argument(converter=_hex)], name="addr"))
4292 assert parser.parse_args(["ff"]).addr == 255
4293
4294 def test_converter_on_optional_single_member(self) -> None:
4295 """A converter legalizes ``T | None``: the optional collapses to ``T`` and the converter owns conversion."""
4296 parser = build_parser_from_function(
4297 _make_func(
4298 Annotated[datetime.datetime | None, Option("--until", converter=_parse_iso)],
4299 name="until",
4300 kind="kw",
4301 default=None,
4302 )
4303 )
4304 assert parser.parse_args(["--until", "2020-01-01"]).until == _parse_iso("2020-01-01")
4305 assert parser.parse_args([]).until is None
4306
4307 def test_converter_keeps_user_completer(self) -> None:
4308 """``converter=`` drops the *inferred* completer, but a user-supplied ``completer=`` survives."""
4309 action = _action_for(Annotated[Path, Argument(converter=str, completer=cmd2.Cmd.path_complete)])
4310 assert action.get_completer() is cmd2.Cmd.path_complete # type: ignore[attr-defined]
4311
4312 def test_converter_rejects_invalid_explicit_choice(self) -> None:
4313 """A choice the user converter rejects is a build-time error (run through the converter, not the inferred type)."""
4314 _assert_build_error(
4315 Annotated[int, Argument(converter=_hex, choices=["ff", "zz"])],
4316 match="not a valid",
4317 )
4318
4319
4320 class TestPreprocess:
4321 """`Argument`/`Option` ``preprocess=`` runs before the inferred converter, keeping inference."""
4322
4323 def test_preprocess_runs_before_inferred_converter(self) -> None:
4324 """The token is transformed before the inferred Enum converter sees it."""
4325 parser = build_parser_from_function(_make_func(Annotated[_Color, Argument(preprocess=str.lower)], name="c"))
4326 assert parser.parse_args(["RED"]).c is _Color.red
4327
4328 def test_preprocess_keeps_inferred_choices(self) -> None:
4329 """The inferred Enum choices survive (preprocess composes with, not replaces, the converter)."""
4330 action = _action_for(Annotated[_Color, Argument(preprocess=str.lower)])
4331 assert action.choices == _COLOR_CHOICE_ITEMS
4332
4333 def test_preprocess_keeps_inferred_path_completer(self) -> None:
4334 """The inferred path completer survives a preprocess hook."""
4335 action = _action_for(Annotated[Path, Argument(preprocess=str.strip)])
4336 assert action.get_completer() is cmd2.Cmd.path_complete # type: ignore[attr-defined]
4337
4338 def test_preprocess_on_str_passthrough_becomes_type(self) -> None:
4339 """With no inferred converter (plain ``str``), preprocess becomes the ``type=`` directly."""
4340 parser = build_parser_from_function(_make_func(Annotated[str, Argument(preprocess=str.upper)], name="s"))
4341 assert parser.parse_args(["abc"]).s == "ABC"
4342
4343 def test_preprocess_applies_per_element_on_collection(self) -> None:
4344 """On a ``list[T]`` preprocess runs per token, before the per-token inferred converter."""
4345 parser = build_parser_from_function(_make_func(Annotated[list[_Color], Option("--c", preprocess=str.lower)], name="c"))
4346 assert parser.parse_args(["--c", "RED", "Blue"]).c == [_Color.red, _Color.blue]
4347
4348 def test_preprocess_keeps_enum_class_introspection(self) -> None:
4349 """The wrapped converter still exposes ``_cmd2_enum_class`` for introspection."""
4350 action = _action_for(Annotated[_Color, Argument(preprocess=str.lower)])
4351 assert action.type._cmd2_enum_class is _Color
4352
4353 def test_preprocess_keeps_inferred_converter_name(self) -> None:
4354 """The wrapper copies the inner converter's ``__name__`` so argparse error messages stay meaningful."""
4355 action = _action_for(Annotated[_Color, Argument(preprocess=str.lower)])
4356 assert action.type.__name__ == _Color.__name__
4357
4358 def test_preprocess_runs_explicit_choices_through_composed_type(self) -> None:
4359 """Explicit ``choices`` are run through the preprocess+converter wrapper (``RED`` -> lower -> Enum)."""
4360 action = _action_for(Annotated[_Color, Argument(preprocess=str.lower, choices=["RED"])])
4361 assert action.choices == [_Color.red]
4362
4363
4364 class TestConverterPreprocessConstraints:
4365 """Build-time rejections for ``converter=`` / ``preprocess=`` misuse."""
4366
4367 def test_converter_and_preprocess_together_rejected(self) -> None:
4368 """Supplying both is ambiguous -- fold the preprocessing into the converter."""
4369 _assert_build_error(
4370 Annotated[int, Argument(converter=_hex, preprocess=str.strip)],
4371 match="converter= and preprocess=",
4372 )
4373
4374 def test_converter_on_value_less_action_rejected(self) -> None:
4375 """A converter on a zero-argument action has nothing to convert."""
4376 _assert_build_error(
4377 Annotated[bool, Option("--flag", action="store_true", converter=_hex)],
4378 match="takes no value",
4379 kind="kw",
4380 )
4381
4382 def test_preprocess_on_value_less_action_rejected(self) -> None:
4383 """A preprocess hook on a zero-argument action has nothing to transform."""
4384 _assert_build_error(
4385 Annotated[bool, Option("--flag", action="store_true", preprocess=str.strip)],
4386 match="takes no value",
4387 kind="kw",
4388 )
4389
4390 def test_reserved_type_hint_points_at_converter(self) -> None:
4391 """A raw ``type=`` is still rejected, now pointing the user at ``converter=``."""
4392 with pytest.raises(TypeError, match="converter="):
4393 Argument(type=int)
4394
4395
4396 # ---------------------------------------------------------------------------
4397 # Dataclass argument blocks (#1689): a dataclass-typed parameter expands its
4398 # fields into the parser (flat: field name == arg name) and is reconstructed
4399 # into an instance at call time.
4400 # ---------------------------------------------------------------------------
4401
4402
4403 @dataclass
4404 class _CommonArgs(ArgumentBlock):
4405 verbose: Annotated[bool, Option("-v", "--verbose")] = False
4406 output: Annotated[Path | None, Option("--output")] = None
4407
4408
4409 @dataclass
4410 class _TracedArgs(_CommonArgs):
4411 """Inheritance is the "shared base block" reuse mechanism (and carries the ArgumentBlock trait)."""
4412
4413 trace: bool = False
4414
4415
4416 class TestDataclassBlockParser:
4417 """A dataclass-typed parameter expands its fields into flat parser arguments."""
4418
4419 def test_block_fields_become_arguments(self) -> None:
4420 def do_build(self, target: str, common: _CommonArgs) -> None: ...
4421
4422 parser = build_parser_from_function(do_build)
4423 dests = {action.dest for action in parser._actions}
4424 assert {"target", "verbose", "output"} <= dests
4425 # The block parameter itself is a container, not an argument.
4426 assert "common" not in dests
4427
4428 def test_block_field_option_strings_preserved(self) -> None:
4429 def do_build(self, target: str, common: _CommonArgs) -> None: ...
4430
4431 parser = build_parser_from_function(do_build)
4432 # A field's Annotated Option metadata drives its flags exactly as a top-level option would
4433 # (a bool option expands to --verbose/--no-verbose via BooleanOptionalAction).
4434 verbose = next(a for a in parser._actions if a.dest == "verbose")
4435 assert "-v" in verbose.option_strings
4436 assert "--verbose" in verbose.option_strings
4437 output = next(a for a in parser._actions if a.dest == "output")
4438 assert output.option_strings == ["--output"]
4439
4440 def test_inherited_block_fields_expand(self) -> None:
4441 def do_build(self, target: str, opts: _TracedArgs) -> None: ...
4442
4443 parser = build_parser_from_function(do_build)
4444 dests = {action.dest for action in parser._actions}
4445 assert {"target", "verbose", "output", "trace"} <= dests
4446
4447
4448 class _DataclassBlockApp(cmd2.Cmd):
4449 def __init__(self) -> None:
4450 super().__init__()
4451 self.last_block: object = None
4452
4453 @with_annotated
4454 def do_build(self, target: str, common: _CommonArgs) -> None:
4455 self.last_block = common
4456 self.poutput(f"target={target} verbose={common.verbose} output={common.output}")
4457
4458 @with_annotated
4459 def do_test(self, suite: str, opts: _TracedArgs) -> None:
4460 self.poutput(f"suite={suite} verbose={opts.verbose} trace={opts.trace}")
4461
4462
4463 @pytest.fixture
4464 def block_app() -> _DataclassBlockApp:
4465 app = _DataclassBlockApp()
4466 app.stdout = cmd2.utils.StdSim(app.stdout)
4467 return app
4468
4469
4470 class TestDataclassBlockRuntime:
4471 """The block is reconstructed into a dataclass instance and passed to the command."""
4472
4473 def test_block_reconstructed_with_defaults(self, block_app) -> None:
4474 out, _err = run_cmd(block_app, "build app")
4475 assert out == ["target=app verbose=False output=None"]
4476
4477 def test_block_field_from_command_line(self, block_app) -> None:
4478 out, _err = run_cmd(block_app, "build app --verbose --output /tmp/x")
4479 assert out == [f"target=app verbose=True output={Path('/tmp/x')}"]
4480
4481 def test_block_instance_type(self, block_app) -> None:
4482 """The reconstructed argument is an actual instance of the declared dataclass."""
4483 run_cmd(block_app, "build app --verbose")
4484 assert isinstance(block_app.last_block, _CommonArgs)
4485 assert block_app.last_block.verbose is True
4486
4487 def test_block_field_values_and_types(self, block_app) -> None:
4488 """Each field on the reconstructed instance holds the converted value at its declared type."""
4489 run_cmd(block_app, "build app --verbose --output /tmp/x")
4490 block = block_app.last_block
4491 assert block.verbose is True
4492 assert isinstance(block.output, Path) # converted from str to Path, not left as a string
4493 assert block.output == Path("/tmp/x")
4494
4495 def test_block_field_defaults_on_instance(self, block_app) -> None:
4496 """An omitted field is filled by the dataclass constructor, not left absent on the instance."""
4497 run_cmd(block_app, "build app")
4498 block = block_app.last_block
4499 assert block.verbose is False
4500 assert block.output is None
4501
4502 def test_inherited_block_runtime(self, block_app) -> None:
4503 out, _err = run_cmd(block_app, "test smoke --trace")
4504 assert out == ["suite=smoke verbose=False trace=True"]
4505
4506
4507 @dataclass
4508 class _PositionalBlock(ArgumentBlock):
4509 """A field with no default becomes a positional argument."""
4510
4511 name: str
4512 count: int = 1
4513
4514
4515 @dataclass
4516 class _FactoryBlock(ArgumentBlock):
4517 tags: Annotated[list[str], Option("--tag", action="append")] = field(default_factory=list)
4518
4519
4520 @dataclass
4521 class _NestedBlock(ArgumentBlock):
4522 inner: _CommonArgs = field(default_factory=_CommonArgs)
4523
4524
4525 @dataclass
4526 class _ForwardFieldBlock(ArgumentBlock):
4527 # Stringized field annotations exercise the same get_type_hints() resolution path as a dataclass
4528 # defined in a module using ``from __future__ import annotations``.
4529 verbose: "Annotated[bool, Option('-v', '--verbose')]" = False
4530 tags: "Annotated[list[str], Option('--tag', action='append')]" = field(default_factory=list)
4531
4532
4533 class TestDataclassBlockEdgeCases:
4534 def test_block_positional_field(self) -> None:
4535 def do_x(self, common: _PositionalBlock) -> None: ...
4536
4537 parser = build_parser_from_function(do_x)
4538 name = next(a for a in parser._actions if a.dest == "name")
4539 assert name.option_strings == [] # positional
4540 count = next(a for a in parser._actions if a.dest == "count")
4541 assert count.option_strings == ["--count"]
4542
4543 def test_block_positional_field_runtime(self) -> None:
4544 class App(cmd2.Cmd):
4545 @with_annotated
4546 def do_x(self, common: _PositionalBlock) -> None:
4547 self.poutput(f"{common.name}:{common.count}")
4548
4549 app = App()
4550 app.stdout = cmd2.utils.StdSim(app.stdout)
4551 assert run_cmd(app, "x bob --count 3")[0] == ["bob:3"]
4552
4553 def test_block_default_factory(self) -> None:
4554 class App(cmd2.Cmd):
4555 @with_annotated
4556 def do_x(self, opts: _FactoryBlock) -> None:
4557 self.poutput(f"tags={opts.tags}")
4558
4559 app = App()
4560 app.stdout = cmd2.utils.StdSim(app.stdout)
4561 assert run_cmd(app, "x")[0] == ["tags=[]"]
4562 assert run_cmd(app, "x --tag a --tag b")[0] == ["tags=['a', 'b']"]
4563
4564 def test_default_factory_not_shared_across_calls(self) -> None:
4565 """Each invocation gets a fresh default_factory value (no shared-mutable-default bug)."""
4566
4567 class App(cmd2.Cmd):
4568 @with_annotated
4569 def do_x(self, opts: _FactoryBlock) -> None:
4570 opts.tags.append("mutated")
4571 self.poutput(f"tags={opts.tags}")
4572
4573 app = App()
4574 app.stdout = cmd2.utils.StdSim(app.stdout)
4575 # First call mutates its (default) list; the second call must not see that mutation.
4576 assert run_cmd(app, "x")[0] == ["tags=['mutated']"]
4577 assert run_cmd(app, "x")[0] == ["tags=['mutated']"]
4578
4579 def test_block_field_default_emits_suppress(self) -> None:
4580 """A field-default block field emits SUPPRESS so the dataclass constructor fills the default."""
4581
4582 def do_x(self, common: _CommonArgs) -> None: ...
4583
4584 parser = build_parser_from_function(do_x)
4585 verbose = next(a for a in parser._actions if a.dest == "verbose")
4586 assert verbose.default is argparse.SUPPRESS
4587 # An absent field stays out of the parsed namespace entirely.
4588 assert not hasattr(parser.parse_args([]), "verbose")
4589
4590 def test_nested_dataclass_field_rejected(self) -> None:
4591 """A dataclass field whose type is itself a dataclass is not a supported scalar (no recursion)."""
4592
4593 def do_x(self, opts: _NestedBlock) -> None: ...
4594
4595 with pytest.raises(TypeError, match="Unsupported parameter type"):
4596 build_parser_from_function(do_x)
4597
4598 def test_field_name_collides_with_explicit_param(self) -> None:
4599 """A block field whose name collides with an explicit parameter is a clear build error."""
4600
4601 @dataclass
4602 class Blk(ArgumentBlock):
4603 target: Annotated[str, Option("--target")] = "z"
4604
4605 def do_x(self, target: str, blk: Blk) -> None: ...
4606
4607 with pytest.raises(TypeError, match=r"target.*more than once"):
4608 build_parser_from_function(do_x)
4609
4610 def test_field_name_collides_across_two_blocks(self) -> None:
4611 """Two blocks sharing a field name collide regardless of flags (same namespace dest)."""
4612
4613 @dataclass
4614 class BlkA(ArgumentBlock):
4615 x: Annotated[int, Option("--x")] = 0
4616
4617 @dataclass
4618 class BlkB(ArgumentBlock):
4619 x: Annotated[int, Option("--xx")] = 0 # different flag, same field/dest name
4620
4621 def do_x(self, a: BlkA, b: BlkB) -> None: ...
4622
4623 with pytest.raises(TypeError, match=r"x.*more than once"):
4624 build_parser_from_function(do_x)
4625
4626 def test_field_named_like_block_param_rejected(self) -> None:
4627 """A block field whose name equals the block parameter name is rejected: the field's flat argument
4628 and the parameter receiving the block instance would share one keyword-argument key."""
4629
4630 @dataclass
4631 class Opts(ArgumentBlock):
4632 opts: Annotated[str, Option("--opts")] = "x"
4633
4634 def do_x(self, opts: Opts) -> None: ...
4635
4636 with pytest.raises(TypeError, match=r"field 'opts' collides with the block parameter name 'opts'"):
4637 build_parser_from_function(do_x)
4638
4639 def test_init_false_field_named_like_block_param_allowed(self) -> None:
4640 """A field(init=False) is not a command-line argument, so sharing the block parameter name is fine
4641 (no flat argument shadows the parameter) and must not be rejected."""
4642
4643 @dataclass
4644 class Opts(ArgumentBlock):
4645 name: Annotated[str, Option("--name")] = "n"
4646 opts: str = field(init=False, default="z")
4647
4648 def do_x(self, opts: Opts) -> None: ...
4649
4650 parser = build_parser_from_function(do_x)
4651 assert {a.dest for a in parser._actions if a.dest != "help"} == {"name"}
4652
4653 def test_block_field_append_action_without_dataclass_default_rejected(self) -> None:
4654 """An append block field with no dataclass default would emit a shared `[]` argparse default that
4655 argparse reuses across invocations; reject it (the default must live on the dataclass field)."""
4656
4657 @dataclass
4658 class Blk(ArgumentBlock):
4659 tags: Annotated[list[str], Option("--tag", action="append")] # no dataclass default
4660
4661 def do_x(self, blk: Blk) -> None: ...
4662
4663 with pytest.raises(TypeError, match=r"field 'tags'.*default.*must live on the dataclass field"):
4664 build_parser_from_function(do_x)
4665
4666 def test_block_field_metadata_default_without_dataclass_default_rejected(self) -> None:
4667 """A metadata `Option(default=...)` on a block field with no dataclass default bypasses the
4668 dataclass as the single source of truth; reject it."""
4669
4670 @dataclass
4671 class Blk(ArgumentBlock):
4672 count: Annotated[int, Option("--count", default=3)] # default in metadata, not the field
4673
4674 def do_x(self, blk: Blk) -> None: ...
4675
4676 with pytest.raises(TypeError, match=r"field 'count'.*default.*must live on the dataclass field"):
4677 build_parser_from_function(do_x)
4678
4679 def test_block_field_metadata_default_none_without_dataclass_default_rejected(self) -> None:
4680 """A metadata `Option(default=None)` on a block field with no dataclass default still bypasses the
4681 dataclass as the single source of truth; `None` is not exempt from the rule."""
4682
4683 @dataclass
4684 class Blk(ArgumentBlock):
4685 count: Annotated[int, Option("--count", default=None)] # default in metadata, not the field
4686
4687 def do_x(self, blk: Blk) -> None: ...
4688
4689 with pytest.raises(TypeError, match=r"field 'count'.*default.*must live on the dataclass field"):
4690 build_parser_from_function(do_x)
4691
4692 def test_post_init_runs(self) -> None:
4693 """Reconstruction goes through the dataclass constructor, so __post_init__ runs."""
4694
4695 @dataclass
4696 class PostInit(ArgumentBlock):
4697 width: int = 2
4698 doubled: int = 0
4699
4700 def __post_init__(self) -> None:
4701 self.doubled = self.width * 2
4702
4703 class App(cmd2.Cmd):
4704 @with_annotated
4705 def do_x(self, opts: PostInit) -> None:
4706 self.poutput(f"doubled={opts.doubled}")
4707
4708 app = App()
4709 app.stdout = cmd2.utils.StdSim(app.stdout)
4710 assert run_cmd(app, "x --width 5")[0] == ["doubled=10"]
4711 assert run_cmd(app, "x")[0] == ["doubled=4"]
4712
4713 def test_required_field_errors_when_omitted(self) -> None:
4714 """A field with no default is a required argument."""
4715
4716 @dataclass
4717 class Req(ArgumentBlock):
4718 host: Annotated[str, Option("--host")]
4719
4720 class App(cmd2.Cmd):
4721 @with_annotated
4722 def do_x(self, opts: Req) -> None:
4723 self.poutput(opts.host)
4724
4725 app = App()
4726 app.stdout = cmd2.utils.StdSim(app.stdout)
4727 _out, err = run_cmd(app, "x")
4728 assert any("host" in line.lower() and ("required" in line.lower() or "error" in line.lower()) for line in err)
4729 assert run_cmd(app, "x --host db")[0] == ["db"]
4730
4731 def test_plain_dataclass_is_not_a_block(self) -> None:
4732 """A plain @dataclass (no ArgumentBlock trait) is never expanded; it is an ordinary value."""
4733
4734 @dataclass
4735 class Plain:
4736 x: int = 0
4737 y: int = 0
4738
4739 def do_x(self, p: Plain) -> None: ...
4740
4741 # Without the trait it falls through to the normal type path: a dataclass scalar with no converter
4742 # is an unsupported type (it is not silently decomposed into x/y).
4743 with pytest.raises(TypeError, match="Unsupported parameter type"):
4744 build_parser_from_function(do_x)
4745
4746 def test_plain_dataclass_with_converter_is_single_value(self) -> None:
4747 """A plain @dataclass used as a single value (via a converter) is one argument, not a block."""
4748
4749 @dataclass
4750 class Point:
4751 x: int = 0
4752 y: int = 0
4753
4754 def parse_point(s: str) -> Point:
4755 a, b = s.split(",")
4756 return Point(int(a), int(b))
4757
4758 class App(cmd2.Cmd):
4759 @with_annotated
4760 def do_x(self, p: Annotated[Point, Argument(converter=parse_point)]) -> None:
4761 self.poutput(f"{type(p).__name__}({p.x},{p.y})")
4762
4763 app = App()
4764 app.stdout = cmd2.utils.StdSim(app.stdout)
4765 parser = build_parser_from_function(App.do_x.__wrapped__) # single 'p' arg, not decomposed
4766 assert [a.dest for a in parser._actions if a.dest != "help"] == ["p"]
4767 assert run_cmd(app, "x 3,4")[0] == ["Point(3,4)"]
4768
4769 def test_optional_block_rejected(self) -> None:
4770 """An ArgumentBlock combined with Optional (``Block | None``) is rejected with a clear message."""
4771
4772 @dataclass
4773 class Blk(ArgumentBlock):
4774 x: int = 0
4775
4776 def do_x(self, blk: Blk | None) -> None: ...
4777
4778 with pytest.raises(TypeError, match="bare annotation"):
4779 build_parser_from_function(do_x)
4780
4781 def test_union_of_blocks_rejected(self) -> None:
4782 """A union of ArgumentBlocks (``BlockA | BlockB``) is rejected with a clear message."""
4783
4784 @dataclass
4785 class BlkA(ArgumentBlock):
4786 x: int = 0
4787
4788 @dataclass
4789 class BlkB(ArgumentBlock):
4790 y: int = 0
4791
4792 def do_x(self, blk: BlkA | BlkB) -> None: ...
4793
4794 with pytest.raises(TypeError, match="bare annotation"):
4795 build_parser_from_function(do_x)
4796
4797 def test_annotated_block_rejected(self) -> None:
4798 """An ArgumentBlock wrapped in Annotated is rejected (a block must be the bare annotation)."""
4799
4800 @dataclass
4801 class Blk(ArgumentBlock):
4802 x: int = 0
4803
4804 def do_x(self, blk: Annotated[Blk, "doc"]) -> None: ...
4805
4806 with pytest.raises(TypeError, match="bare annotation"):
4807 build_parser_from_function(do_x)
4808
4809 def test_argument_block_without_dataclass_rejected(self) -> None:
4810 """An ArgumentBlock subclass that is not a @dataclass has no fields; reject with guidance."""
4811
4812 class NotADataclass(ArgumentBlock):
4813 x: int = 0
4814
4815 def do_x(self, blk: NotADataclass) -> None: ...
4816
4817 with pytest.raises(TypeError, match="must be decorated with @dataclass"):
4818 build_parser_from_function(do_x)
4819
4820 def test_stringized_field_annotations_resolve(self) -> None:
4821 """A block whose field hints are strings (forward refs / ``from __future__ import annotations``)
4822 resolves through get_type_hints and behaves identically.
4823 """
4824
4825 class App(cmd2.Cmd):
4826 @with_annotated
4827 def do_x(self, target: "str", common: "_ForwardFieldBlock") -> None:
4828 self.poutput(f"{target} verbose={common.verbose} tags={common.tags}")
4829
4830 app = App()
4831 app.stdout = cmd2.utils.StdSim(app.stdout)
4832 assert run_cmd(app, "x app --verbose --tag a --tag b")[0] == ["app verbose=True tags=['a', 'b']"]
4833 assert run_cmd(app, "x app2")[0] == ["app2 verbose=False tags=[]"]
4834
4835 def test_block_parameter_default_rejected(self) -> None:
4836 """The dataclass owns its fields' defaults, so a default on the block parameter is rejected."""
4837
4838 @dataclass
4839 class Blk(ArgumentBlock):
4840 verbose: Annotated[bool, Option("-v")] = False
4841
4842 def do_x(self, blk: Blk = Blk()) -> None: ... # noqa: B008 — the block-param default is the thing under test
4843
4844 with pytest.raises(TypeError, match="cannot have a default value"):
4845 build_parser_from_function(do_x)
4846
4847 def test_field_name_collides_with_reserved_namespace_attr(self) -> None:
4848 """A field named like a cmd2-injected namespace attr would be overwritten at parse time; reject it."""
4849
4850 @dataclass
4851 class Blk(ArgumentBlock):
4852 cmd2_statement: Annotated[str, Option("--stmt")] = "x"
4853
4854 def do_x(self, blk: Blk) -> None: ...
4855
4856 with pytest.raises(TypeError, match="reserved cmd2 namespace attribute"):
4857 build_parser_from_function(do_x)
4858
4859 def test_block_field_both_defaults_error_names_dataclass_source(self) -> None:
4860 """A field with both a dataclass default and a metadata default is rejected, naming the right source.
4861
4862 The block field's signature default lives on the dataclass (its internal ``param_default`` is a
4863 placeholder ``None``), so the conflict message must say "dataclass field", not "function signature (None)".
4864 """
4865
4866 @dataclass
4867 class Blk(ArgumentBlock):
4868 level: Annotated[int, Option("--level", default=5)] = 2
4869
4870 def do_x(self, blk: Blk) -> None: ...
4871
4872 with pytest.raises(TypeError, match=r"both the dataclass field and the metadata \(5\)"):
4873 build_parser_from_function(do_x)
4874
4875 def test_initvar_field_rejected(self) -> None:
4876 """An InitVar is required by the constructor but never becomes a CLI argument; reject it clearly."""
4877
4878 @dataclass
4879 class Blk(ArgumentBlock):
4880 ratio: InitVar[int]
4881 name: Annotated[str, Option("--name")] = "n"
4882
4883 def __post_init__(self, ratio: int) -> None:
4884 self.ratio = ratio
4885
4886 def do_x(self, blk: Blk) -> None: ...
4887
4888 with pytest.raises(TypeError, match="InitVar"):
4889 build_parser_from_function(do_x)
4890
4891 def test_init_false_field_not_expanded(self) -> None:
4892 """A field(init=False) is not a constructor argument, so it gets no CLI option and is left to
4893 __post_init__ / its default rather than being expanded into a command-line value."""
4894
4895 @dataclass
4896 class Blk(ArgumentBlock):
4897 name: Annotated[str, Option("--name")] = "n"
4898 computed: str = field(init=False, default="auto")
4899
4900 def __post_init__(self) -> None:
4901 self.computed = self.name.upper()
4902
4903 def do_x(self, blk: Blk) -> None: ...
4904
4905 parser = build_parser_from_function(do_x)
4906 dests = {a.dest for a in parser._actions if a.dest != "help"}
4907 assert dests == {"name"} # computed (init=False) is not a command-line argument
4908
4909 class App(cmd2.Cmd):
4910 @with_annotated
4911 def do_x(self, blk: Blk) -> None:
4912 self.poutput(f"name={blk.name} computed={blk.computed}")
4913
4914 app = App()
4915 app.stdout = cmd2.utils.StdSim(app.stdout)
4916 assert run_cmd(app, "x --name bob")[0] == ["name=bob computed=BOB"]
4917
4918 def test_unresolvable_field_hint_raises_block_error(self) -> None:
4919 """An unresolvable forward reference on a block field aborts with a clear, ArgumentBlock-specific
4920 error rather than leaking the opaque NameError raised by typing.get_type_hints."""
4921
4922 @dataclass
4923 class Blk(ArgumentBlock):
4924 x: Annotated["NoSuchType", Option("--x")] = 0 # noqa: F821 -- intentionally undefined
4925
4926 def do_x(self, blk: Blk) -> None: ...
4927
4928 with pytest.raises(TypeError, match=r"Failed to resolve type hints for ArgumentBlock"):
4929 build_parser_from_function(do_x)
4930
4931
4932 class _SubcommandBlockApp(cmd2.Cmd):
4933 @with_annotated(base_command=True)
4934 def do_db(self, cmd2_subcommand_func) -> None:
4935 if cmd2_subcommand_func:
4936 cmd2_subcommand_func()
4937
4938 @with_annotated(subcommand_to="db")
4939 def db_migrate(self, name: str, common: _CommonArgs) -> None:
4940 self.poutput(f"migrate {name} verbose={common.verbose}")
4941
4942
4943 class TestDataclassBlockSubcommand:
4944 def test_subcommand_block_reconstructed(self) -> None:
4945 app = _SubcommandBlockApp()
4946 app.stdout = cmd2.utils.StdSim(app.stdout)
4947 out, _err = run_cmd(app, "db migrate users --verbose")
4948 assert out == ["migrate users verbose=True"]
4949
4950
4951 # ---------------------------------------------------------------------------
4952 # Shared blocks: a command declares an inheritable block as ``cmd2_base_args``
4953 # and its subcommands receive it as ``cmd2_parent_args`` instead of re-declaring
4954 # the arguments. This is the typed answer to passing parent-level args down to
4955 # subcommands (#1690).
4956 # ---------------------------------------------------------------------------
4957
4958
4959 @dataclass
4960 class _SharedOpts(ArgumentBlock):
4961 verbose: Annotated[bool, Option("-v", "--verbose")] = False
4962 level: Annotated[int, Option("--level")] = 1
4963
4964
4965 class _InheritBlockApp(cmd2.Cmd):
4966 def __init__(self) -> None:
4967 super().__init__()
4968 self.received: object = None
4969
4970 @with_annotated(base_command=True)
4971 def do_root(self, cmd2_subcommand_func, cmd2_base_args: _SharedOpts) -> None:
4972 """Parent declares the inheritable block, so its fields land on the base parser."""
4973 if cmd2_subcommand_func:
4974 cmd2_subcommand_func()
4975
4976 @with_annotated(subcommand_to="root", help="show the inherited block")
4977 def root_show(self, cmd2_parent_args: _SharedOpts) -> None:
4978 self.received = cmd2_parent_args
4979 self.poutput(f"verbose={cmd2_parent_args.verbose} level={cmd2_parent_args.level}")
4980
4981
4982 @pytest.fixture
4983 def inherit_app() -> _InheritBlockApp:
4984 app = _InheritBlockApp()
4985 app.stdout = cmd2.utils.StdSim(app.stdout)
4986 return app
4987
4988
4989 class TestParentArgsInheritance:
4990 def test_subcommand_inherits_parent_block_values(self, inherit_app) -> None:
4991 """Values parsed on the parent flow into the subcommand's inherited block."""
4992 out, _err = run_cmd(inherit_app, "root --verbose --level 5 show")
4993 assert out == ["verbose=True level=5"]
4994
4995 def test_inherited_block_uses_parent_defaults_when_omitted(self, inherit_app) -> None:
4996 """An option the parent did not receive arrives at its declared default, not absent."""
4997 out, _err = run_cmd(inherit_app, "root show")
4998 assert out == ["verbose=False level=1"]
4999
5000 def test_inherited_block_reconstructed_instance(self, inherit_app) -> None:
5001 """The subcommand receives a real dataclass instance, not loose values."""
5002 run_cmd(inherit_app, "root --verbose show")
5003 assert isinstance(inherit_app.received, _SharedOpts)
5004 assert inherit_app.received.verbose is True
5005
5006 def test_inherited_block_fields_not_re_added_to_subparser(self, inherit_app) -> None:
5007 """The inherited block adds no arguments to the subparser; its flags live only on the parent."""
5008 _out, err = run_cmd(inherit_app, "root show --verbose")
5009 assert any("unrecognized arguments" in line for line in err), err
5010
5011 def test_grandparent_declares_leaf_inherits(self) -> None:
5012 """A leaf subcommand inherits a block its grandparent declared (an intermediate level in between)."""
5013
5014 class App(cmd2.Cmd):
5015 @with_annotated(base_command=True)
5016 def do_root(self, cmd2_subcommand_func, cmd2_base_args: _SharedOpts) -> None:
5017 if cmd2_subcommand_func:
5018 cmd2_subcommand_func()
5019
5020 @with_annotated(subcommand_to="root", base_command=True)
5021 def root_show(self, cmd2_subcommand_func) -> None:
5022 if cmd2_subcommand_func:
5023 cmd2_subcommand_func()
5024
5025 @with_annotated(subcommand_to="root show")
5026 def root_show_detail(self, cmd2_parent_args: _SharedOpts) -> None:
5027 self.poutput(f"verbose={cmd2_parent_args.verbose}")
5028
5029 app = App()
5030 app.stdout = cmd2.utils.StdSim(app.stdout)
5031 assert run_cmd(app, "root --verbose show detail")[0] == ["verbose=True"]
5032
5033 def test_intermediate_declares_leaf_inherits(self) -> None:
5034 """An intermediate command declares the block and a deeper subcommand inherits it.
5035
5036 The intermediate command's handler never runs in the dispatch chain (only the entry base command
5037 and the leaf do), so the marker must come from the *parser* at parse time, not a running handler.
5038 """
5039
5040 class App(cmd2.Cmd):
5041 @with_annotated(base_command=True)
5042 def do_root(self, cmd2_subcommand_func) -> None:
5043 if cmd2_subcommand_func:
5044 cmd2_subcommand_func()
5045
5046 @with_annotated(subcommand_to="root", base_command=True)
5047 def root_show(self, cmd2_subcommand_func, cmd2_base_args: _SharedOpts) -> None:
5048 if cmd2_subcommand_func:
5049 cmd2_subcommand_func()
5050
5051 @with_annotated(subcommand_to="root show")
5052 def root_show_detail(self, cmd2_parent_args: _SharedOpts) -> None:
5053 self.poutput(f"verbose={cmd2_parent_args.verbose}")
5054
5055 app = App()
5056 app.stdout = cmd2.utils.StdSim(app.stdout)
5057 assert run_cmd(app, "root show --verbose detail")[0] == ["verbose=True"]
5058
5059 def test_inherited_field_colliding_with_own_arg_rejected(self) -> None:
5060 """An inherited field that also names the subcommand's own argument is rejected at build time."""
5061
5062 def root_show(self, verbose: str, cmd2_parent_args: _SharedOpts) -> None: ...
5063
5064 with pytest.raises(TypeError, match="inherited ArgumentBlock field"):
5065 build_parser_from_function(root_show)
5066
5067 def test_parent_args_must_be_bare_block(self) -> None:
5068 """``cmd2_parent_args`` must be annotated with a bare ArgumentBlock subclass."""
5069
5070 def root_show(self, cmd2_parent_args: int) -> None: ...
5071
5072 with pytest.raises(TypeError, match="must be annotated with a bare ArgumentBlock"):
5073 build_parser_from_function(root_show)
5074
5075 def test_parent_args_default_rejected(self) -> None:
5076 """An inherited block always comes from the parent, so a default on it is rejected."""
5077
5078 def root_show(self, cmd2_parent_args: _SharedOpts = _SharedOpts()) -> None: ... # noqa: B008
5079
5080 with pytest.raises(TypeError, match="cannot have a default value"):
5081 build_parser_from_function(root_show)
5082
5083 def test_base_args_must_be_block(self) -> None:
5084 """``cmd2_base_args`` must be annotated with a bare ArgumentBlock subclass."""
5085
5086 def do_root(self, cmd2_base_args: int) -> None: ...
5087
5088 with pytest.raises(TypeError, match="must be annotated with a bare ArgumentBlock"):
5089 build_parser_from_function(do_root)
5090
5091 def test_missing_parent_declaration_errors_at_runtime(self) -> None:
5092 """A cmd2_parent_args subcommand whose ancestors never declare cmd2_base_args errors when first run.
5093
5094 Registration succeeds (the misconfiguration is detectable only once the shared namespace exists), so
5095 the app constructs cleanly and the clear error surfaces on first invocation of the subcommand.
5096 """
5097
5098 class App(cmd2.Cmd):
5099 @with_annotated(base_command=True)
5100 def do_root(self, cmd2_subcommand_func) -> None: # parent does NOT declare cmd2_base_args
5101 if cmd2_subcommand_func:
5102 cmd2_subcommand_func()
5103
5104 @with_annotated(subcommand_to="root")
5105 def root_show(self, cmd2_parent_args: _SharedOpts) -> None: ...
5106
5107 app = App() # construction must NOT raise
5108 app.stdout = cmd2.utils.StdSim(app.stdout)
5109 _out, err = run_cmd(app, "root show")
5110 assert any("no ancestor command declares" in line for line in err), err
5111
5112 def test_type_mismatch_errors_at_runtime(self) -> None:
5113 """A cmd2_parent_args whose type no ancestor declared as cmd2_base_args errors when first run."""
5114
5115 @dataclass
5116 class _OtherOpts(ArgumentBlock):
5117 level: Annotated[int, Option("--level")] = 0
5118
5119 class App(cmd2.Cmd):
5120 @with_annotated(base_command=True)
5121 def do_root(self, cmd2_subcommand_func, cmd2_base_args: _SharedOpts) -> None:
5122 if cmd2_subcommand_func:
5123 cmd2_subcommand_func()
5124
5125 @with_annotated(subcommand_to="root")
5126 def root_show(self, cmd2_parent_args: _OtherOpts) -> None: ...
5127
5128 app = App()
5129 app.stdout = cmd2.utils.StdSim(app.stdout)
5130 _out, err = run_cmd(app, "root show")
5131 assert any("no ancestor command declares" in line for line in err), err
5132
5133 def test_directly_supplied_inherited_block_skips_reconstruction_and_check(self) -> None:
5134 """A block already supplied (a direct call passing the instance) is used as-is.
5135
5136 Reconstruction is skipped, and for an inherited block so is the ancestor-presence check -- the
5137 caller provided the instance, so there is nothing to reconstruct or verify.
5138 """
5139 spec = _BlockSpec(_SharedOpts, ["verbose", "level"], inherited=True)
5140 provided = _SharedOpts(verbose=True, level=9)
5141 func_kwargs = {"cmd2_parent_args": provided}
5142 # An empty namespace carries no presence marker; the directly-supplied instance must bypass it.
5143 _reconstruct_dataclass_blocks(func_kwargs, {"cmd2_parent_args": spec}, argparse.Namespace())
5144 assert func_kwargs["cmd2_parent_args"] is provided
5145
5146 def test_directly_supplied_block_pops_stray_field_values(self) -> None:
5147 """A directly-supplied instance wins, and parsed field values are dropped (not stranded as stray kwargs).
5148
5149 A programmatic call may pass the block instance while the command line also parsed some of its fields
5150 into the namespace. Those expanded field names are not parameters of the command function, so they must
5151 be popped even though reconstruction is skipped -- otherwise the call fails with an unexpected keyword.
5152 """
5153 spec = _BlockSpec(_SharedOpts, ["verbose", "level"], inherited=False)
5154 provided = _SharedOpts(verbose=True, level=9)
5155 # 'verbose' was parsed from the command line; 'cmd2_parent_args'/'common' supplied directly.
5156 func_kwargs = {"common": provided, "verbose": False, "target": "app"}
5157 _reconstruct_dataclass_blocks(func_kwargs, {"common": spec}, argparse.Namespace())
5158 assert func_kwargs["common"] is provided
5159 assert "verbose" not in func_kwargs # the stray parsed field value was dropped
5160 assert func_kwargs["target"] == "app" # an unrelated command parameter is untouched
5161
5162 def test_directly_supplied_block_via_command_does_not_strand_fields(self) -> None:
5163 """End-to-end: passing a block instance to a decorated command while the line parses a field succeeds."""
5164
5165 class App(cmd2.Cmd):
5166 @with_annotated
5167 def do_build(self, target: str, common: _CommonArgs) -> None:
5168 self.poutput(f"target={target} verbose={common.verbose}")
5169
5170 app = App()
5171 app.stdout = cmd2.utils.StdSim(app.stdout)
5172 # The directly-supplied instance is used; the parsed --verbose does not crash the call as a stray kwarg.
5173 app.do_build("app --verbose", common=_CommonArgs(verbose=False))
5174 assert app.stdout.getvalue().splitlines() == ["target=app verbose=False"]
5175
5176
5177 # ---------------------------------------------------------------------------
5178 # A base command and its subcommands share one parsed namespace. Each shared
5179 # (cmd2_base_args/cmd2_parent_args) block field parses into a type-qualified
5180 # dest, so two blocks of different types that happen to share a field name never
5181 # collide on one attribute -- an inherited block always sees its own type's
5182 # value rather than whatever a different block at another chain level wrote.
5183 # ---------------------------------------------------------------------------
5184
5185
5186 @dataclass
5187 class _ChainBaseA(ArgumentBlock):
5188 level: Annotated[int, Option("--level")] = 1
5189 only_a: Annotated[str, Option("--only-a")] = "a"
5190
5191
5192 @dataclass
5193 class _ChainBaseBSameName(ArgumentBlock):
5194 level: Annotated[int, Option("--level")] = 2 # same field name as _ChainBaseA, different type
5195
5196
5197 @dataclass
5198 class _ChainBaseBDistinct(ArgumentBlock):
5199 region: Annotated[str, Option("--region")] = "us" # distinct field name
5200
5201
5202 class TestBaseArgsChainNamespacing:
5203 def test_same_field_name_in_different_block_types_is_isolated(self) -> None:
5204 """Two base_args blocks of different types sharing a field name do not collide: the leaf inheriting
5205 _ChainBaseA sees root's value, not the _ChainBaseBSameName value parsed at the intervening level."""
5206
5207 class App(cmd2.Cmd):
5208 @with_annotated(base_command=True)
5209 def do_root(self, cmd2_subcommand_func, cmd2_base_args: _ChainBaseA) -> None:
5210 if cmd2_subcommand_func:
5211 cmd2_subcommand_func()
5212
5213 @with_annotated(subcommand_to="root", base_command=True)
5214 def root_mid(self, cmd2_subcommand_func, cmd2_base_args: _ChainBaseBSameName) -> None:
5215 if cmd2_subcommand_func:
5216 cmd2_subcommand_func()
5217
5218 @with_annotated(subcommand_to="root mid")
5219 def root_mid_leaf(self, cmd2_parent_args: _ChainBaseA) -> None:
5220 self.poutput(f"level={cmd2_parent_args.level} only_a={cmd2_parent_args.only_a}")
5221
5222 app = App()
5223 app.stdout = cmd2.utils.StdSim(app.stdout)
5224 out, _err = run_cmd(app, "root --level 5 mid --level 9 leaf")
5225 assert out == ["level=5 only_a=a"] # root's BaseA.level, not mid's BaseB.level=9
5226
5227 def test_distinct_fields_across_base_args_levels(self) -> None:
5228 """Distinct field names across levels also reach the inherited block with the right value."""
5229
5230 class App(cmd2.Cmd):
5231 @with_annotated(base_command=True)
5232 def do_root(self, cmd2_subcommand_func, cmd2_base_args: _ChainBaseA) -> None:
5233 if cmd2_subcommand_func:
5234 cmd2_subcommand_func()
5235
5236 @with_annotated(subcommand_to="root", base_command=True)
5237 def root_mid(self, cmd2_subcommand_func, cmd2_base_args: _ChainBaseBDistinct) -> None:
5238 if cmd2_subcommand_func:
5239 cmd2_subcommand_func()
5240
5241 @with_annotated(subcommand_to="root mid")
5242 def root_mid_leaf(self, cmd2_parent_args: _ChainBaseA) -> None:
5243 self.poutput(f"level={cmd2_parent_args.level} only_a={cmd2_parent_args.only_a}")
5244
5245 app = App()
5246 app.stdout = cmd2.utils.StdSim(app.stdout)
5247 out, _err = run_cmd(app, "root --level 5 mid --region eu leaf")
5248 assert out == ["level=5 only_a=a"]
5249
5250 def test_same_base_args_type_at_two_levels_nearest_wins(self) -> None:
5251 """Reusing the *same* block type at two levels shares one (type-qualified) dest, so the nearest
5252 level that sets the flag wins -- a well-defined override, not a cross-type corruption."""
5253
5254 class App(cmd2.Cmd):
5255 @with_annotated(base_command=True)
5256 def do_root(self, cmd2_subcommand_func, cmd2_base_args: _ChainBaseA) -> None:
5257 if cmd2_subcommand_func:
5258 cmd2_subcommand_func()
5259
5260 @with_annotated(subcommand_to="root", base_command=True)
5261 def root_mid(self, cmd2_subcommand_func, cmd2_base_args: _ChainBaseA) -> None:
5262 if cmd2_subcommand_func:
5263 cmd2_subcommand_func()
5264
5265 @with_annotated(subcommand_to="root mid")
5266 def root_mid_leaf(self, cmd2_parent_args: _ChainBaseA) -> None:
5267 self.poutput(f"level={cmd2_parent_args.level}")
5268
5269 app = App()
5270 app.stdout = cmd2.utils.StdSim(app.stdout)
5271 assert run_cmd(app, "root --level 5 mid --level 9 leaf")[0] == ["level=9"] # nearest (mid) wins
5272 assert run_cmd(app, "root --level 5 mid leaf")[0] == ["level=5"] # absent mid does not overwrite
5273
5274 def test_positional_shared_field_keeps_clean_metavar(self) -> None:
5275 """A positional field in a shared block parses into a type-qualified dest (so it can't collide
5276 across a chain), but its help metavar stays the field name -- the qualified dest never leaks."""
5277
5278 @dataclass
5279 class Base(ArgumentBlock):
5280 target: Annotated[str, Argument()] # positional
5281 level: Annotated[int, Option("--level")] = 1
5282
5283 def do_x(self, cmd2_base_args: Base) -> None: ...
5284
5285 parser = build_parser_from_function(do_x)
5286 positional = next(a for a in parser._actions if not a.option_strings and a.dest != "help")
5287 assert positional.metavar == "target" # field name shown in help, not the internal dest
5288 assert positional.dest != "target" # but the dest is type-qualified to avoid chain collisions
5289
5290
5291 # ---------------------------------------------------------------------------
5292 # Field-type matrix through a block. The conversion / collection-casting /
5293 # action paths are tested at the top-level-parameter level elsewhere; these
5294 # confirm they also work through a block field's expansion + reconstruction.
5295 # ---------------------------------------------------------------------------
5296
5297
5298 @dataclass
5299 class _MultiBlockA(ArgumentBlock):
5300 a: Annotated[int, Option("--a")] = 0
5301
5302
5303 @dataclass
5304 class _MultiBlockB(ArgumentBlock):
5305 b: Annotated[int, Option("--b")] = 0
5306
5307
5308 @dataclass
5309 class _SetBlock(ArgumentBlock):
5310 val: Annotated[set[str], Option("--val", nargs="*")] = field(default_factory=set)
5311
5312
5313 @dataclass
5314 class _FrozensetBlock(ArgumentBlock):
5315 val: Annotated[frozenset[str], Option("--val", nargs="*")] = field(default_factory=frozenset)
5316
5317
5318 @dataclass
5319 class _TupleBlock(ArgumentBlock):
5320 val: Annotated[tuple[int, int], Option("--val")] = (0, 0) # fixed arity inferred from the tuple
5321
5322
5323 @dataclass
5324 class _TupleNargsBlock(ArgumentBlock):
5325 val: Annotated[tuple[int, int], Option("--val", nargs=2)] = (0, 0) # explicit nargs honored
5326
5327
5328 class _BlockColor(enum.Enum):
5329 RED = "red"
5330 GREEN = "green"
5331
5332
5333 @dataclass
5334 class _EnumBlock(ArgumentBlock):
5335 mode: _BlockColor = _BlockColor.RED
5336
5337
5338 @dataclass
5339 class _LiteralBlock(ArgumentBlock):
5340 mode: Annotated[Literal["fast", "slow"], Option("--mode")] = "fast"
5341
5342
5343 class TestDataclassBlockFieldTypes:
5344 def test_multiple_blocks_in_one_command(self) -> None:
5345 """Two distinct blocks in one signature each reconstruct from their own fields without cross-talk."""
5346
5347 class App(cmd2.Cmd):
5348 @with_annotated
5349 def do_x(self, first: _MultiBlockA, second: _MultiBlockB) -> None:
5350 self.poutput(f"a={first.a} b={second.b} types={type(first).__name__},{type(second).__name__}")
5351
5352 app = App()
5353 app.stdout = cmd2.utils.StdSim(app.stdout)
5354 assert run_cmd(app, "x --a 1 --b 2")[0] == ["a=1 b=2 types=_MultiBlockA,_MultiBlockB"]
5355
5356 @pytest.mark.parametrize(
5357 ("blk_cls", "cli", "expected", "expected_type"),
5358 [
5359 (_SetBlock, "x --val a b a", {"a", "b"}, set),
5360 (_FrozensetBlock, "x --val a b", frozenset({"a", "b"}), frozenset),
5361 (_TupleBlock, "x --val 3 4", (3, 4), tuple),
5362 (_TupleNargsBlock, "x --val 7 8", (7, 8), tuple),
5363 ],
5364 ids=["set", "frozenset", "tuple", "tuple-nargs"],
5365 )
5366 def test_collection_block_field_reconstructs(self, blk_cls, cli, expected, expected_type) -> None:
5367 """A collection block field goes through the casting action and rebuilds as the declared container."""
5368 captured: dict[str, object] = {}
5369
5370 class App(cmd2.Cmd):
5371 @with_annotated
5372 def do_x(self, blk: blk_cls) -> None:
5373 captured["val"] = blk.val
5374
5375 app = App()
5376 app.stdout = cmd2.utils.StdSim(app.stdout)
5377 run_cmd(app, cli)
5378 assert captured["val"] == expected
5379 assert type(captured["val"]) is expected_type
5380
5381 @pytest.mark.parametrize(
5382 ("blk_cls", "cli", "expected"),
5383 [
5384 (_EnumBlock, "x --mode green", _BlockColor.GREEN),
5385 (_LiteralBlock, "x --mode slow", "slow"),
5386 ],
5387 ids=["enum", "literal"],
5388 )
5389 def test_choice_block_field_reconstructs(self, blk_cls, cli, expected) -> None:
5390 """An Enum/Literal block field converts the token (to the member, not the raw string) before reconstruction."""
5391 captured: dict[str, object] = {}
5392
5393 class App(cmd2.Cmd):
5394 @with_annotated
5395 def do_x(self, blk: blk_cls) -> None:
5396 captured["mode"] = blk.mode
5397
5398 app = App()
5399 app.stdout = cmd2.utils.StdSim(app.stdout)
5400 run_cmd(app, cli)
5401 assert captured["mode"] == expected # for the enum, == holds only against the member, proving conversion
5402
5403 def test_store_const_block_field_with_dataclass_default(self) -> None:
5404 """A store_const block field with a dataclass default: the field default emits SUPPRESS so the
5405 constructor supplies it when the flag is absent, and the const when present."""
5406
5407 @dataclass
5408 class Blk(ArgumentBlock):
5409 level: Annotated[int, Option("--hi", action="store_const", const=10)] = 1
5410
5411 class App(cmd2.Cmd):
5412 @with_annotated
5413 def do_x(self, blk: Blk) -> None:
5414 self.poutput(f"level={blk.level}")
5415
5416 app = App()
5417 app.stdout = cmd2.utils.StdSim(app.stdout)
5418 assert run_cmd(app, "x")[0] == ["level=1"] # absent -> dataclass default, not the const
5419 assert run_cmd(app, "x --hi")[0] == ["level=10"] # present -> the const
5420
5421 def test_converter_on_block_field(self) -> None:
5422 """A user converter= on a block field runs during parsing and feeds the reconstructed instance."""
5423
5424 @dataclass
5425 class Blk(ArgumentBlock):
5426 count: Annotated[int, Option("--count", converter=lambda s: int(s) * 2)] = 0
5427
5428 class App(cmd2.Cmd):
5429 @with_annotated
5430 def do_x(self, blk: Blk) -> None:
5431 self.poutput(f"count={blk.count}")
5432
5433 app = App()
5434 app.stdout = cmd2.utils.StdSim(app.stdout)
5435 assert run_cmd(app, "x --count 5")[0] == ["count=10"]
5436
5437 def test_optional_bool_block_field_defaults_to_none(self) -> None:
5438 """A bool | None block field (Optional flag) reconstructs to None when absent and True when given."""
5439
5440 @dataclass
5441 class Blk(ArgumentBlock):
5442 flag: Annotated[bool | None, Option("--flag")] = None
5443
5444 captured: dict[str, object] = {}
5445
5446 class App(cmd2.Cmd):
5447 @with_annotated
5448 def do_x(self, blk: Blk) -> None:
5449 captured["flag"] = blk.flag
5450
5451 app = App()
5452 app.stdout = cmd2.utils.StdSim(app.stdout)
5453 run_cmd(app, "x")
5454 assert captured["flag"] is None
5455 run_cmd(app, "x --flag")
5456 assert captured["flag"] is True
5457
5458 def test_classvar_field_is_not_expanded(self) -> None:
5459 """A ClassVar is not a dataclass field, so it produces no argument and does not break reconstruction."""
5460
5461 @dataclass
5462 class Blk(ArgumentBlock):
5463 name: Annotated[str, Option("--name")] = "n"
5464 kind: ClassVar[str] = "fixed"
5465
5466 class App(cmd2.Cmd):
5467 @with_annotated
5468 def do_x(self, blk: Blk) -> None:
5469 self.poutput(f"name={blk.name} kind={blk.kind}")
5470
5471 parser = build_parser_from_function(App.do_x)
5472 assert {a.dest for a in parser._actions if a.dest != "help"} == {"name"}
5473 app = App()
5474 app.stdout = cmd2.utils.StdSim(app.stdout)
5475 assert run_cmd(app, "x --name bob")[0] == ["name=bob kind=fixed"]
5476
5477
5478 @dataclass
5479 class _VarBlock(ArgumentBlock):
5480 x: Annotated[int, Option("--x")] = 0
5481
5482
5483 def _block_var_positional(self, *args: _VarBlock) -> None: ...
5484
5485
5486 def _block_var_keyword(self, **kwargs: _VarBlock) -> None: ...
5487
5488
5489 @dataclass
5490 class _ReservedCmd2Block(ArgumentBlock):
5491 cmd2_subcommand_func: Annotated[str, Option("--x")] = "z"
5492
5493
5494 @dataclass
5495 class _ReservedArgparseBlock(ArgumentBlock):
5496 dest: Annotated[str, Option("--d")] = "z"
5497
5498
5499 class TestDataclassBlockValidationExtra:
5500 """Rejection branches that were reachable but previously untested."""
5501
5502 @pytest.mark.parametrize("func", [_block_var_positional, _block_var_keyword], ids=["var_positional", "var_keyword"])
5503 def test_block_in_variadic_position_rejected(self, func) -> None:
5504 """An ArgumentBlock used as *args / **kwargs is a wrapped position, not a bare block parameter."""
5505 with pytest.raises(TypeError, match="wrapped position"):
5506 build_parser_from_function(func)
5507
5508 def test_count_block_field_without_dataclass_default_rejected(self) -> None:
5509 """A count block field has an action default (0) but no dataclass default, so it bypasses the
5510 dataclass as the single source of truth -- the rule fires for a scalar action default too."""
5511
5512 @dataclass
5513 class Blk(ArgumentBlock):
5514 verbosity: Annotated[int, Option("--v", action="count")] # no dataclass default
5515
5516 def do_x(self, blk: Blk) -> None: ...
5517
5518 with pytest.raises(TypeError, match=r"field 'verbosity'.*must live on the dataclass field"):
5519 build_parser_from_function(do_x)
5520
5521 @pytest.mark.parametrize(
5522 ("blk_cls", "exc", "match"),
5523 [
5524 (_ReservedCmd2Block, TypeError, "reserved cmd2 namespace attribute"),
5525 (_ReservedArgparseBlock, ValueError, "reserved by argparse"),
5526 ],
5527 ids=["cmd2_namespace", "argparse"],
5528 )
5529 def test_reserved_block_field_name_rejected(self, blk_cls, exc, match) -> None:
5530 """A block field whose name is reserved (by cmd2's namespace or by argparse) is rejected."""
5531
5532 def do_x(self, blk: blk_cls) -> None: ...
5533
5534 with pytest.raises(exc, match=match):
5535 build_parser_from_function(do_x)
5536
5537
5538 def _optional_base_args(self, cmd2_base_args: _SharedOpts | None) -> None: ...
5539
5540
5541 def _optional_parent_args(self, cmd2_parent_args: _SharedOpts | None) -> None: ...
5542
5543
5544 class TestSharedBlockEdgeCases:
5545 """Edge cases of the cmd2_base_args / cmd2_parent_args shared-block machinery."""
5546
5547 @pytest.mark.parametrize("func", [_optional_base_args, _optional_parent_args], ids=["base_args", "parent_args"])
5548 def test_optional_magic_block_param_rejected(self, func) -> None:
5549 """A magic param (cmd2_base_args/cmd2_parent_args) wrapped in Optional is not a bare block."""
5550 with pytest.raises(TypeError, match="must be annotated with a bare ArgumentBlock"):
5551 build_parser_from_function(func)
5552
5553 def test_subclass_parent_args_against_superclass_base_args_errors(self) -> None:
5554 """Sharing is keyed by exact type: a cmd2_parent_args typed as a subclass of the ancestor's
5555 cmd2_base_args is a different type, so it errors at runtime like any unmatched inherited block."""
5556
5557 @dataclass
5558 class _Base(ArgumentBlock):
5559 level: Annotated[int, Option("--level")] = 0
5560
5561 @dataclass
5562 class _Sub(_Base):
5563 extra: Annotated[int, Option("--extra")] = 0
5564
5565 class App(cmd2.Cmd):
5566 @with_annotated(base_command=True)
5567 def do_root(self, cmd2_subcommand_func, cmd2_base_args: _Base) -> None:
5568 if cmd2_subcommand_func:
5569 cmd2_subcommand_func()
5570
5571 @with_annotated(subcommand_to="root")
5572 def root_show(self, cmd2_parent_args: _Sub) -> None: ...
5573
5574 app = App()
5575 app.stdout = cmd2.utils.StdSim(app.stdout)
5576 _out, err = run_cmd(app, "root show")
5577 assert any("no ancestor command declares" in line for line in err), err
5578
5579 def test_base_command_reconstructs_its_own_base_args(self) -> None:
5580 """The declaring base command reconstructs its OWN cmd2_base_args block (shared, not inherited)."""
5581
5582 captured: dict[str, object] = {}
5583
5584 class App(cmd2.Cmd):
5585 @with_annotated(base_command=True)
5586 def do_root(self, cmd2_subcommand_func, cmd2_base_args: _SharedOpts) -> None:
5587 captured["block"] = cmd2_base_args
5588 if cmd2_subcommand_func:
5589 cmd2_subcommand_func()
5590
5591 @with_annotated(subcommand_to="root")
5592 def root_show(self, cmd2_parent_args: _SharedOpts) -> None:
5593 self.poutput("ran")
5594
5595 app = App()
5596 app.stdout = cmd2.utils.StdSim(app.stdout)
5597 run_cmd(app, "root --verbose --level 7 show")
5598 assert isinstance(captured["block"], _SharedOpts)
5599 assert captured["block"].verbose is True
5600 assert captured["block"].level == 7
5601
5602 def test_same_base_args_type_in_two_independent_trees_no_leak(self) -> None:
5603 """The same block type used by two unrelated base commands does not leak across them: each command
5604 parses its own namespace, so the shared (type-qualified) dest is isolated per command."""
5605
5606 class App(cmd2.Cmd):
5607 @with_annotated(base_command=True)
5608 def do_root1(self, cmd2_subcommand_func, cmd2_base_args: _SharedOpts) -> None:
5609 if cmd2_subcommand_func:
5610 cmd2_subcommand_func()
5611
5612 @with_annotated(subcommand_to="root1")
5613 def root1_show(self, cmd2_parent_args: _SharedOpts) -> None:
5614 self.poutput(f"root1 level={cmd2_parent_args.level}")
5615
5616 @with_annotated(base_command=True)
5617 def do_root2(self, cmd2_subcommand_func, cmd2_base_args: _SharedOpts) -> None:
5618 if cmd2_subcommand_func:
5619 cmd2_subcommand_func()
5620
5621 @with_annotated(subcommand_to="root2")
5622 def root2_show(self, cmd2_parent_args: _SharedOpts) -> None:
5623 self.poutput(f"root2 level={cmd2_parent_args.level}")
5624
5625 app = App()
5626 app.stdout = cmd2.utils.StdSim(app.stdout)
5627 assert run_cmd(app, "root1 --level 3 show")[0] == ["root1 level=3"]
5628 assert run_cmd(app, "root2 --level 8 show")[0] == ["root2 level=8"]
5629
5630 def test_flat_field_kwarg_on_shared_block_is_not_supported(self) -> None:
5631 """A shared block's fields use a type-qualified dest, so a programmatic flat-field kwarg by bare name
5632 is not folded into the block (pass the block instance instead). Pins the shared-vs-regular asymmetry."""
5633
5634 class App(cmd2.Cmd):
5635 @with_annotated(base_command=True)
5636 def do_root(self, cmd2_subcommand_func, cmd2_base_args: _SharedOpts) -> None:
5637 if cmd2_subcommand_func:
5638 cmd2_subcommand_func()
5639
5640 @with_annotated(subcommand_to="root")
5641 def root_show(self, cmd2_parent_args: _SharedOpts) -> None: ...
5642
5643 app = App()
5644 app.stdout = cmd2.utils.StdSim(app.stdout)
5645 with pytest.raises(TypeError, match="unexpected keyword argument"):
5646 app.do_root("show", level=5)