@@ -1104,3 +1104,46 @@ def __init__(self):
1104
1104
settable_attrib_name = 'some_value' ,
1105
1105
)
1106
1106
)
1107
+
1108
+
1109
+ class NsProviderSet (cmd2 .CommandSet ):
1110
+ # CommandSet which implements a namespace provider
1111
+ def __init__ (self , dummy ):
1112
+ # Use dummy argument so this won't be autoloaded by other tests
1113
+ super (NsProviderSet , self ).__init__ ()
1114
+
1115
+ def ns_provider (self ) -> argparse .Namespace :
1116
+ ns = argparse .Namespace ()
1117
+ # Save what was passed as self from with_argparser().
1118
+ ns .self = self
1119
+ return ns
1120
+
1121
+
1122
+ class NsProviderApp (cmd2 .Cmd ):
1123
+ # Used to test namespace providers in CommandSets
1124
+ def __init__ (self , * args , ** kwargs ) -> None :
1125
+ super ().__init__ (* args , ** kwargs )
1126
+ super (NsProviderApp , self ).__init__ (* args , ** kwargs )
1127
+
1128
+ @cmd2 .with_argparser (cmd2 .Cmd2ArgumentParser (), ns_provider = NsProviderSet .ns_provider )
1129
+ def do_test_ns (self , args : argparse .Namespace ) -> None :
1130
+ # Save args.self so the unit tests can read it.
1131
+ self .last_result = args .self
1132
+
1133
+
1134
+ def test_ns_provider ():
1135
+ """This exercises code in with_argparser() decorator that calls namespace providers"""
1136
+ ns_provider_set = NsProviderSet (1 )
1137
+ app = NsProviderApp (auto_load_commands = False )
1138
+
1139
+ # First test the case in which a namespace provider function resides in a CommandSet class which is registered.
1140
+ # with_argparser() will pass the CommandSet instance to the ns_provider() function.
1141
+ app .register_command_set (ns_provider_set )
1142
+ run_cmd (app , "test_ns" )
1143
+ assert app .last_result == ns_provider_set
1144
+
1145
+ # Now test the case in which a namespace provider function resides in a CommandSet class which is not registered.
1146
+ # with_argparser() will receive None from cmd2.Cmd._resolve_func_self() and therefore pass app as self to ns_provider().
1147
+ app .unregister_command_set (ns_provider_set )
1148
+ run_cmd (app , "test_ns" )
1149
+ assert app .last_result == app
0 commit comments