@@ -247,10 +247,56 @@ def test_preservelist(argparse_app) -> None:
247247
248248def test_invalid_parser_builder (argparse_app ):
249249 parser_builder = None
250- with pytest .raises (TypeError ):
250+ with pytest .raises (TypeError , match = "Invalid type for parser_builder" ):
251251 argparse_app ._build_parser (argparse_app , parser_builder , "fake_prog" )
252252
253253
254+ def test_invalid_parser_return_type (argparse_app ):
255+ def bad_builder ():
256+ return argparse .ArgumentParser ()
257+
258+ with pytest .raises (TypeError , match = "must be a Cmd2ArgumentParser or a subclass of it" ):
259+ argparse_app ._build_parser (argparse_app , bad_builder , "fake_prog" )
260+
261+
262+ def test_invalid_parser_return_type_staticmethod (argparse_app ):
263+ def bad_builder ():
264+ return argparse .ArgumentParser ()
265+
266+ sm = staticmethod (bad_builder )
267+
268+ with pytest .raises (TypeError , match = "must be a Cmd2ArgumentParser or a subclass of it" ):
269+ argparse_app ._build_parser (argparse_app , sm , "fake_prog" )
270+
271+
272+ def test_invalid_parser_return_type_classmethod (argparse_app ):
273+ def bad_builder (cls ):
274+ return argparse .ArgumentParser ()
275+
276+ cm = classmethod (bad_builder )
277+
278+ with pytest .raises (TypeError , match = "must be a Cmd2ArgumentParser or a subclass of it" ):
279+ argparse_app ._build_parser (argparse_app , cm , "fake_prog" )
280+
281+
282+ def test_invalid_parser_return_type_nameless_object (argparse_app ):
283+ # A class that is callable but has no __name__ attribute
284+ class NamelessBuilder :
285+ def __call__ (self ):
286+ return argparse .ArgumentParser ()
287+
288+ builder = NamelessBuilder ()
289+
290+ # Verify __name__ is actually missing
291+ assert not hasattr (builder , '__name__' )
292+
293+ # The error message should now contain the string representation of the object
294+ expected_msg = f"The parser returned by '{ builder } ' must be a Cmd2ArgumentParser"
295+
296+ with pytest .raises (TypeError , match = expected_msg ):
297+ argparse_app ._build_parser (argparse_app , builder , "fake_prog" )
298+
299+
254300def _build_has_subcmd_parser () -> cmd2 .Cmd2ArgumentParser :
255301 has_subcmds_parser = cmd2 .Cmd2ArgumentParser (description = "Tests as_subcmd_to decorator" )
256302 has_subcmds_parser .add_subparsers (dest = 'subcommand' , metavar = 'SUBCOMMAND' , required = True )
0 commit comments