From e4d84b0bfc6e8b348c07750eafb92cfe88ca880a Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Wed, 18 May 2016 06:59:26 +0200 Subject: [PATCH] Simplify argparser.type_check If the value isn't param.default, it will always be a string or a flag, as type_conv never gets called when the function is called from Python. --- qutebrowser/commands/argparser.py | 9 ++------- qutebrowser/commands/command.py | 2 ++ tests/unit/commands/test_argparser.py | 9 ++++----- 3 files changed, 8 insertions(+), 12 deletions(-) diff --git a/qutebrowser/commands/argparser.py b/qutebrowser/commands/argparser.py index a0ede657c..825e0d623 100644 --- a/qutebrowser/commands/argparser.py +++ b/qutebrowser/commands/argparser.py @@ -114,22 +114,17 @@ def type_conv(param, typ, value, *, str_choices=None): if value is param.default: return value + assert isinstance(value, str), repr(value) + if utils.is_enum(typ): - if isinstance(value, typ): - return value - assert isinstance(value, str) _check_choices(param, value, [arg_name(e.name) for e in typ]) return typ[value.replace('-', '_')] elif typ is str: - assert isinstance(value, str) if str_choices is not None: _check_choices(param, value, str_choices) return value elif callable(typ): # int, float, etc. - if isinstance(value, typ): - return value - assert isinstance(value, str) try: return typ(value) except (TypeError, ValueError): diff --git a/qutebrowser/commands/command.py b/qutebrowser/commands/command.py index 5fcbafe75..41d97481c 100644 --- a/qutebrowser/commands/command.py +++ b/qutebrowser/commands/command.py @@ -415,6 +415,8 @@ class Command: value = argparser.type_conv(param, typ, value, str_choices=choices) elif typ is None: pass + elif typ is bool: # no type conversion for flags + assert isinstance(value, bool) else: value = argparser.type_conv(param, typ, value) diff --git a/tests/unit/commands/test_argparser.py b/tests/unit/commands/test_argparser.py index 54ab31f52..f38f42fc1 100644 --- a/tests/unit/commands/test_argparser.py +++ b/tests/unit/commands/test_argparser.py @@ -80,11 +80,9 @@ class TestArgumentParser: @pytest.mark.parametrize('types, value, expected', [ - ([Enum], Enum.foo, Enum.foo), ([Enum], 'foo', Enum.foo), ([Enum], 'foo-bar', Enum.foo_bar), - ([int], 2, 2), ([int], '2', 2), ([int, str], 'foo', 'foo'), ]) @@ -132,12 +130,13 @@ def test_multitype_conv_invalid_type(): assert str(excinfo.value) == "foo: Unknown type None!" -def test_conv_default_param(): +@pytest.mark.parametrize('value, typ', [(None, None), (42, int)]) +def test_conv_default_param(value, typ): """The default value should always be a valid choice.""" - def func(foo=None): + def func(foo=value): pass param = inspect.signature(func).parameters['foo'] - assert argparser.type_conv(param, str, None, str_choices=['val']) is None + assert argparser.type_conv(param, typ, value, str_choices=['val']) == value def test_conv_str_type():