summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authormatbu <mat.bultel@gmail.com>2021-06-04 14:21:44 +0200
committermatbu <mat.bultel@gmail.com>2021-06-04 18:33:58 +0200
commit452fff3aadb01c41355a9254c6f21b76b5ed1609 (patch)
treeb1b5a3431d56ab2bfa17a198f1cbf90d59504a83
parentd562aae651f4e4346ee921d8eb67d24141695609 (diff)
downloadcliff-452fff3aadb01c41355a9254c6f21b76b5ed1609.tar.gz
Add conflict_handler parameter as attribut in Command class
Adding conflict_handler as attribut in the Command class in order to be able to take control of this parameter and change to different behavior that argparse is handling: error / resolve / ignore. Callers will be able to override it and get a proper Parser object. Change-Id: I327ece99a04bc8b2ebfa554dea643b1f2a456336
-rw-r--r--cliff/command.py3
-rw-r--r--cliff/tests/test_command.py46
2 files changed, 48 insertions, 1 deletions
diff --git a/cliff/command.py b/cliff/command.py
index f8d0501..0a02525 100644
--- a/cliff/command.py
+++ b/cliff/command.py
@@ -74,6 +74,7 @@ class Command(object, metaclass=abc.ABCMeta):
"""
deprecated = False
+ conflict_handler = 'ignore'
_description = ''
_epilog = None
@@ -156,7 +157,7 @@ class Command(object, metaclass=abc.ABCMeta):
epilog=self.get_epilog(),
prog=prog_name,
formatter_class=_argparse.SmartHelpFormatter,
- conflict_handler='ignore',
+ conflict_handler=self.conflict_handler,
)
for hook in self._hooks:
hook.obj.get_parser(parser)
diff --git a/cliff/tests/test_command.py b/cliff/tests/test_command.py
index 29c8c33..c9513d0 100644
--- a/cliff/tests/test_command.py
+++ b/cliff/tests/test_command.py
@@ -172,3 +172,49 @@ class TestArgumentParser(base.TestBase):
args = parser.parse_args(['-z', 'foo', 'a', 'b'])
self.assertEqual(args.zippy, 'foo')
self.assertEqual(args.zero, 'zero-default')
+
+ def test_with_conflict_handler(self):
+ cmd = TestCommand(None, None)
+ cmd.conflict_handler = 'resolve'
+ parser = cmd.get_parser('NAME')
+ self.assertEqual(parser.conflict_handler, 'resolve')
+
+ def test_raise_conflict_argument_error(self):
+ cmd = TestCommand(None, None)
+ parser = cmd.get_parser('NAME')
+ parser.add_argument(
+ '-f', '--foo',
+ dest='foo',
+ default='foo',
+ )
+ self.assertRaises(
+ argparse.ArgumentError,
+ parser.add_argument,
+ '-f',
+ )
+
+ def test_resolve_conflict_argument(self):
+ cmd = TestCommand(None, None)
+ cmd.conflict_handler = 'resolve'
+ parser = cmd.get_parser('NAME')
+ parser.add_argument(
+ '-f', '--foo',
+ dest='foo',
+ default='foo',
+ )
+ parser.add_argument(
+ '-f', '--foo',
+ dest='foo',
+ default='bar',
+ )
+ args = parser.parse_args(['a', 'b'])
+ self.assertEqual(args.foo, 'bar')
+
+ def test_wrong_conflict_handler(self):
+ cmd = TestCommand(None, None)
+ cmd.conflict_handler = 'wrong'
+ self.assertRaises(
+ ValueError,
+ cmd.get_parser,
+ 'NAME',
+ )