@@ -4679,6 +4679,46 @@ def do_x(self, blk: Blk) -> None: ...
46794679 with pytest .raises (TypeError , match = "InitVar" ):
46804680 build_parser_from_function (do_x )
46814681
4682+ def test_init_false_field_not_expanded (self ) -> None :
4683+ """A field(init=False) is not a constructor argument, so it gets no CLI option and is left to
4684+ __post_init__ / its default rather than being expanded into a command-line value."""
4685+
4686+ @dataclass
4687+ class Blk (ArgumentBlock ):
4688+ name : Annotated [str , Option ("--name" )] = "n"
4689+ computed : str = field (init = False , default = "auto" )
4690+
4691+ def __post_init__ (self ) -> None :
4692+ self .computed = self .name .upper ()
4693+
4694+ def do_x (self , blk : Blk ) -> None : ...
4695+
4696+ parser = build_parser_from_function (do_x )
4697+ dests = {a .dest for a in parser ._actions if a .dest != "help" }
4698+ assert dests == {"name" } # computed (init=False) is not a command-line argument
4699+
4700+ class App (cmd2 .Cmd ):
4701+ @with_annotated
4702+ def do_x (self , blk : Blk ) -> None :
4703+ self .poutput (f"name={ blk .name } computed={ blk .computed } " )
4704+
4705+ app = App ()
4706+ app .stdout = cmd2 .utils .StdSim (app .stdout )
4707+ assert run_cmd (app , "x --name bob" )[0 ] == ["name=bob computed=BOB" ]
4708+
4709+ def test_unresolvable_field_hint_raises_block_error (self ) -> None :
4710+ """An unresolvable forward reference on a block field aborts with a clear, ArgumentBlock-specific
4711+ error rather than leaking the opaque NameError raised by typing.get_type_hints."""
4712+
4713+ @dataclass
4714+ class Blk (ArgumentBlock ):
4715+ x : Annotated ["NoSuchType" , Option ("--x" )] = 0 # noqa: F821 -- intentionally undefined
4716+
4717+ def do_x (self , blk : Blk ) -> None : ...
4718+
4719+ with pytest .raises (TypeError , match = r"Failed to resolve type hints for ArgumentBlock" ):
4720+ build_parser_from_function (do_x )
4721+
46824722
46834723class _SubcommandBlockApp (cmd2 .Cmd ):
46844724 @with_annotated (base_command = True )
0 commit comments