コード例 #1
0
    def _get_param_value(self, param):
        """Get the converted value for an inspect.Parameter."""
        value = getattr(self.namespace, param.name)
        typ = self._get_type(param)

        if isinstance(typ, tuple):
            raise TypeError("{}: Legacy tuple type annotation!".format(
                self.name))
        elif issubclass(typ, typing.Union):
            # this is... slightly evil, I know
            types = list(typ.__union_params__)
            if param.default is not inspect.Parameter.empty:
                types.append(type(param.default))
            choices = self.get_arg_info(param).choices
            value = argparser.multitype_conv(param, types, value,
                                             str_choices=choices)
        elif typ is str:
            choices = self.get_arg_info(param).choices
            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)

        return value
コード例 #2
0
    def _get_param_value(self, param):
        """Get the converted value for an inspect.Parameter."""
        value = getattr(self.namespace, param.name)
        typ = self._get_type(param)

        if isinstance(typ, tuple):
            raise TypeError("{}: Legacy tuple type annotation!".format(
                self.name))
        elif type(typ) is type(typing.Union):  # flake8: disable=E721
            # this is... slightly evil, I know
            # We also can't use isinstance here because typing.Union doesn't
            # support that.
            # pylint: disable=no-member,useless-suppression
            try:
                types = list(typ.__union_params__)
            except AttributeError:
                types = list(typ.__args__)
            # pylint: enable=no-member,useless-suppression
            if param.default is not inspect.Parameter.empty:
                types.append(type(param.default))
            choices = self.get_arg_info(param).choices
            value = argparser.multitype_conv(param, types, value,
                                             str_choices=choices)
        elif typ is str:
            choices = self.get_arg_info(param).choices
            value = argparser.type_conv(param, typ, value, str_choices=choices)
        elif typ is bool:  # no type conversion for flags
            assert isinstance(value, bool)
        elif typ is None:
            pass
        else:
            value = argparser.type_conv(param, typ, value)

        return value
コード例 #3
0
def test_conv_str_choices_invalid():
    """Calling str type with str_choices and invalid value."""
    param = inspect.Parameter('foo', inspect.Parameter.POSITIONAL_ONLY)
    with pytest.raises(cmdexc.ArgumentTypeError,
                       match='foo: Invalid value '
                       'val3 - expected one of: val1, val2'):
        argparser.type_conv(param, str, 'val3', str_choices=['val1', 'val2'])
コード例 #4
0
def test_conv_str_choices_invalid():
    """Calling str type with str_choices and invalid value."""
    param = inspect.Parameter("foo", inspect.Parameter.POSITIONAL_ONLY)
    with pytest.raises(cmdexc.ArgumentTypeError) as excinfo:
        argparser.type_conv(param, str, "val3", str_choices=["val1", "val2"])
    msg = "foo: Invalid value val3 - expected one of: val1, val2"
    assert str(excinfo.value) == msg
コード例 #5
0
    def _get_param_value(self, param):
        """Get the converted value for an inspect.Parameter."""
        value = getattr(self.namespace, param.name)
        typ = self._get_type(param)

        if isinstance(typ, tuple):
            raise TypeError("{}: Legacy tuple type annotation!".format(
                self.name))
        elif issubclass(typ, typing.Union):
            # this is... slightly evil, I know
            types = list(typ.__union_params__)  # pylint: disable=no-member
            if param.default is not inspect.Parameter.empty:
                types.append(type(param.default))
            choices = self.get_arg_info(param).choices
            value = argparser.multitype_conv(param,
                                             types,
                                             value,
                                             str_choices=choices)
        elif typ is str:
            choices = self.get_arg_info(param).choices
            value = argparser.type_conv(param, typ, value, str_choices=choices)
        elif typ is bool:  # no type conversion for flags
            assert isinstance(value, bool)
        elif typ is None:
            pass
        else:
            value = argparser.type_conv(param, typ, value)

        return value
コード例 #6
0
def test_conv_str_type():
    """Using a str literal as type used to mean exactly that's a valid value.

    This got replaced by @cmdutils.argument(..., choices=...), so we make sure
    no string annotations are there anymore.
    """
    param = inspect.Parameter('foo', inspect.Parameter.POSITIONAL_ONLY)
    with pytest.raises(TypeError, match='foo: Legacy string type!'):
        argparser.type_conv(param, 'val', None)
コード例 #7
0
def test_conv_str_type():
    """Using a str literal as type used to mean exactly that's a valid value.

    This got replaced by @cmdutils.argument(..., choices=...), so we make sure
    no string annotations are there anymore.
    """
    param = inspect.Parameter('foo', inspect.Parameter.POSITIONAL_ONLY)
    with pytest.raises(TypeError, match='foo: Legacy string type!'):
        argparser.type_conv(param, 'val', None)
コード例 #8
0
def test_type_conv_invalid(typ, value, multi):
    param = inspect.Parameter("foo", inspect.Parameter.POSITIONAL_ONLY)

    with pytest.raises(cmdexc.ArgumentTypeError) as excinfo:
        if multi:
            argparser.multitype_conv(param, [typ], value)
        else:
            argparser.type_conv(param, typ, value)

    if multi:
        msg = "foo: Invalid value {}".format(value)
    elif typ is Enum:
        msg = "foo: Invalid value {} - expected one of: foo, " "foo-bar".format(value)
    else:
        msg = "foo: Invalid {} value {}".format(typ.__name__, value)
    assert str(excinfo.value) == msg
コード例 #9
0
def test_type_conv_invalid(typ, value, multi):
    param = inspect.Parameter('foo', inspect.Parameter.POSITIONAL_ONLY)

    if multi:
        msg = 'foo: Invalid value {}'.format(value)
    elif typ is Enum:
        msg = ('foo: Invalid value {} - expected one of: foo, '
               'foo-bar'.format(value))
    else:
        msg = 'foo: Invalid {} value {}'.format(typ.__name__, value)

    with pytest.raises(cmdexc.ArgumentTypeError, match=msg):
        if multi:
            argparser.multitype_conv(param, [typ], value)
        else:
            argparser.type_conv(param, typ, value)
コード例 #10
0
def test_type_conv_valid(types, value, expected, multi):
    param = inspect.Parameter("foo", inspect.Parameter.POSITIONAL_ONLY)

    if multi:
        assert argparser.multitype_conv(param, types, value) == expected
    elif len(types) == 1:
        assert argparser.type_conv(param, types[0], value) == expected
コード例 #11
0
def test_type_conv_invalid(typ, value, multi):
    param = inspect.Parameter('foo', inspect.Parameter.POSITIONAL_ONLY)

    if multi:
        msg = 'foo: Invalid value {}'.format(value)
    elif typ is Enum:
        msg = ('foo: Invalid value {} - expected one of: foo, '
               'foo-bar'.format(value))
    else:
        msg = 'foo: Invalid {} value {}'.format(typ.__name__, value)

    with pytest.raises(cmdexc.ArgumentTypeError, match=msg):
        if multi:
            argparser.multitype_conv(param, [typ], value)
        else:
            argparser.type_conv(param, typ, value)
コード例 #12
0
def test_conv_default_param(value, typ):
    """The default value should always be a valid choice."""
    def func(foo=value):
        pass

    param = inspect.signature(func).parameters['foo']
    assert argparser.type_conv(param, typ, value, str_choices=['val']) == value
コード例 #13
0
def test_type_conv_valid(types, value, expected, multi):
    param = inspect.Parameter('foo', inspect.Parameter.POSITIONAL_ONLY)

    if multi:
        assert argparser.multitype_conv(param, types, value) == expected
    elif len(types) == 1:
        assert argparser.type_conv(param, types[0], value) == expected
コード例 #14
0
def test_conv_default_param(value, typ):
    """The default value should always be a valid choice."""

    def func(foo=value):
        pass

    param = inspect.signature(func).parameters["foo"]
    assert argparser.type_conv(param, typ, value, str_choices=["val"]) == value
コード例 #15
0
def test_conv_str_choices_valid():
    """Calling str type with str_choices and valid value."""
    param = inspect.Parameter('foo', inspect.Parameter.POSITIONAL_ONLY)
    converted = argparser.type_conv(param,
                                    str,
                                    'val1',
                                    str_choices=['val1', 'val2'])
    assert converted == 'val1'
コード例 #16
0
ファイル: command.py プロジェクト: sauravsrijan/qutebrowser
    def _get_param_value(self, param):
        """Get the converted value for an inspect.Parameter."""
        value = getattr(self.namespace, param.name)
        typ = self._get_type(param)

        if isinstance(typ, tuple):
            raise TypeError("{}: Legacy tuple type annotation!".format(
                self.name))

        if hasattr(typing, 'UnionMeta'):
            # Python 3.5.2
            # pylint: disable=no-member,useless-suppression
            is_union = isinstance(typ, typing.UnionMeta)  # type: ignore
        else:
            is_union = getattr(typ, '__origin__', None) is typing.Union

        if is_union:
            # this is... slightly evil, I know
            try:
                types = list(typ.__args__)
            except AttributeError:
                # Python 3.5.2
                types = list(typ.__union_params__)
            # pylint: enable=no-member,useless-suppression
            if param.default is not inspect.Parameter.empty:
                types.append(type(param.default))
            choices = self.get_arg_info(param).choices
            value = argparser.multitype_conv(param,
                                             types,
                                             value,
                                             str_choices=choices)
        elif typ is str:
            choices = self.get_arg_info(param).choices
            value = argparser.type_conv(param, typ, value, str_choices=choices)
        elif typ is bool:  # no type conversion for flags
            if not isinstance(value, bool):
                raise AssertionError
        elif typ is None:
            pass
        else:
            value = argparser.type_conv(param, typ, value)

        return value
コード例 #17
0
    def _get_param_value(self, param):
        """Get the converted value for an inspect.Parameter."""
        value = getattr(self.namespace, param.name)
        typ = self._get_type(param)

        if isinstance(typ, tuple):
            raise TypeError("{}: Legacy tuple type annotation!".format(
                self.name))

        try:
            origin = typing.get_origin(typ)  # type: ignore[attr-defined]
        except AttributeError:
            # typing.get_origin was added in Python 3.8
            origin = getattr(typ, '__origin__', None)

        if origin is Union:
            try:
                types = list(
                    typing.get_args(typ))  # type: ignore[attr-defined]
            except AttributeError:
                # typing.get_args was added in Python 3.8
                types = list(typ.__args__)

            if param.default is not inspect.Parameter.empty:
                types.append(type(param.default))
            choices = self.get_arg_info(param).choices
            value = argparser.multitype_conv(param,
                                             types,
                                             value,
                                             str_choices=choices)
        elif typ is str:
            choices = self.get_arg_info(param).choices
            value = argparser.type_conv(param, typ, value, str_choices=choices)
        elif typ is bool:  # no type conversion for flags
            assert isinstance(value, bool)
        elif typ is None:
            pass
        else:
            value = argparser.type_conv(param, typ, value)

        return value
コード例 #18
0
ファイル: command.py プロジェクト: The-Compiler/qutebrowser
    def _get_param_value(self, param):
        """Get the converted value for an inspect.Parameter."""
        value = getattr(self.namespace, param.name)
        typ = self._get_type(param)

        if isinstance(typ, tuple):
            raise TypeError("{}: Legacy tuple type annotation!".format(
                self.name))

        if getattr(typ, '__origin__', None) is typing.Union or (
                # Older Python 3.5 patch versions
                # pylint: disable=no-member,useless-suppression
                hasattr(typing, 'UnionMeta') and
                isinstance(typ, typing.UnionMeta)):
            # this is... slightly evil, I know
            try:
                types = list(typ.__args__)
            except AttributeError:
                # Older Python 3.5 patch versions
                types = list(typ.__union_params__)
            # pylint: enable=no-member,useless-suppression
            if param.default is not inspect.Parameter.empty:
                types.append(type(param.default))
            choices = self.get_arg_info(param).choices
            value = argparser.multitype_conv(param, types, value,
                                             str_choices=choices)
        elif typ is str:
            choices = self.get_arg_info(param).choices
            value = argparser.type_conv(param, typ, value, str_choices=choices)
        elif typ is bool:  # no type conversion for flags
            assert isinstance(value, bool)
        elif typ is None:
            pass
        else:
            value = argparser.type_conv(param, typ, value)

        return value
コード例 #19
0
def test_conv_str_choices_valid():
    """Calling str type with str_choices and valid value."""
    param = inspect.Parameter("foo", inspect.Parameter.POSITIONAL_ONLY)
    converted = argparser.type_conv(param, str, "val1", str_choices=["val1", "val2"])
    assert converted == "val1"
コード例 #20
0
def test_conv_str_choices_invalid():
    """Calling str type with str_choices and invalid value."""
    param = inspect.Parameter('foo', inspect.Parameter.POSITIONAL_ONLY)
    with pytest.raises(cmdexc.ArgumentTypeError, match='foo: Invalid value '
                       'val3 - expected one of: val1, val2'):
        argparser.type_conv(param, str, 'val3', str_choices=['val1', 'val2'])
コード例 #21
0
def test_conv_str_choices_valid():
    """Calling str type with str_choices and valid value."""
    param = inspect.Parameter('foo', inspect.Parameter.POSITIONAL_ONLY)
    converted = argparser.type_conv(param, str, 'val1',
                                    str_choices=['val1', 'val2'])
    assert converted == 'val1'