Commits

mel  committed e7fad88

allow using custom namespace objects:
added optional 'namespace' arg to dispatch(), which is passed on to argparse ArgumentParser.parse_args()

  • Participants
  • Parent commits fb91ba7

Comments (0)

Files changed (2)

File argh/helpers.py

 
 def dispatch(parser, argv=None, add_help_command=True, encoding=None,
              intercept=False, completion=True, pre_call=None,
-             output_file=sys.stdout, raw_output=False):
+             output_file=sys.stdout, raw_output=False, namespace=None):
     """Parses given list of arguments using given parser, calls the relevant
     function and prints the result.
 
             argv.append('--help')
 
     # this will raise SystemExit if parsing fails
-    args = parser.parse_args(argv)
+    args = parser.parse_args(argv, namespace=namespace)
 
     if hasattr(args, 'function'):
         if pre_call:  # XXX undocumented because I'm unsure if it's OK
 def foo_bar(args):
     return args.foo, args.bar
 
+def custom_namespace(args):
+    return args.custom_value
+
 def whiner(args):
     yield 'Hello...'
     raise CommandError('I feel depressed.')
         """
         try:
             result = self._call_cmd(command_string, **kwargs)
-        except SystemExit:
-            self.fail('Argument parsing failed for {0}'.format(repr(command_string)))
+        except SystemExit, error:
+            self.fail('Argument parsing failed for {0!r}: {1!r}'.format(
+                command_string, error))
         self.assertEqual(result, expected_result)
 
     def assert_cmd_exits(self, command_string, message_regex=None):
 
 class ArghTestCase(BaseArghTestCase):
     commands = {
-        None: [echo, plain_echo, foo_bar, do_aliased, whiner],
+        None: [echo, plain_echo, foo_bar, do_aliased, whiner,
+               custom_namespace],
         'greet': [hello, howdy]
     }
 
     def test_command_error(self):
         self.assert_cmd_returns('whiner', 'Hello...\nI feel depressed.\n')
 
+    def test_custom_namespace(self):
+        namespace = argparse.Namespace()
+        namespace.custom_value = "foo"
+        self.assert_cmd_returns('custom-namespace', 'foo\n',
+                                namespace=namespace)
+
 
 class NoCommandsTestCase(BaseArghTestCase):
     "Edge case: no commands defined"