Exemplo n.º 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__)  # 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
Exemplo n.º 2
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
Exemplo n.º 3
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)
Exemplo n.º 4
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
Exemplo n.º 5
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
Exemplo n.º 6
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)
Exemplo n.º 7
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
Exemplo n.º 8
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
Exemplo n.º 9
0
def test_multitype_conv(types, value, valid):
    converter = argparser.multitype_conv(types)

    if valid:
        converter(value)
    else:
        with pytest.raises(cmdexc.ArgumentTypeError) as excinfo:
            converter(value)
        assert str(excinfo.value) == 'Invalid value {}.'.format(value)
Exemplo n.º 10
0
def test_multitype_conv(types, value, valid):
    converter = argparser.multitype_conv(types)

    if valid:
        converter(value)
    else:
        with pytest.raises(cmdexc.ArgumentTypeError) as excinfo:
            converter(value)
        assert str(excinfo.value) == 'Invalid value {}.'.format(value)
Exemplo n.º 11
0
    def _get_typeconv(self, param, typ):
        """Get a dict with a type conversion for the parameter.

        Args:
            param: The inspect.Parameter to handle.
            typ: The type of the parameter.
        """
        type_conv = {}
        if utils.is_enum(typ):
            type_conv[param.name] = argparser.enum_getter(typ)
        elif isinstance(typ, tuple):
            if param.default is not inspect.Parameter.empty:
                typ = typ + (type(param.default),)
            type_conv[param.name] = argparser.multitype_conv(typ)
        return type_conv
Exemplo n.º 12
0
    def _get_typeconv(self, param, typ):
        """Get a dict with a type conversion for the parameter.

        Args:
            param: The inspect.Parameter to handle.
            typ: The type of the parameter.
        """
        type_conv = {}
        if utils.is_enum(typ):
            type_conv[param.name] = argparser.enum_getter(typ)
        elif isinstance(typ, tuple):
            if param.default is not inspect.Parameter.empty:
                typ = typ + (type(param.default),)
            type_conv[param.name] = argparser.multitype_conv(typ)
        return type_conv
Exemplo n.º 13
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))

        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
Exemplo n.º 14
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
Exemplo n.º 15
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))

        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
Exemplo n.º 16
0
def test_multitype_conv_invalid_type():
    """Test using an invalid type with a multitype converter."""
    param = inspect.Parameter('foo', inspect.Parameter.POSITIONAL_ONLY)
    with pytest.raises(ValueError, match="foo: Unknown type None!"):
        argparser.multitype_conv(param, [None], '')
Exemplo n.º 17
0
def test_multitype_conv_invalid_type():
    """Test using an invalid type with a multitype converter."""
    param = inspect.Parameter("foo", inspect.Parameter.POSITIONAL_ONLY)
    with pytest.raises(ValueError) as excinfo:
        argparser.multitype_conv(param, [None], "")
    assert str(excinfo.value) == "foo: Unknown type None!"
Exemplo n.º 18
0
def test_multitype_conv_invalid_type():
    converter = argparser.multitype_conv([None])
    with pytest.raises(ValueError) as excinfo:
        converter('')
    assert str(excinfo.value) == "Unknown type None!"
Exemplo n.º 19
0
def test_multitype_conv_invalid_type():
    """Test using an invalid type with a multitype converter."""
    param = inspect.Parameter('foo', inspect.Parameter.POSITIONAL_ONLY)
    with pytest.raises(ValueError, match="foo: Unknown type None!"):
        argparser.multitype_conv(param, [None], '')
Exemplo n.º 20
0
def test_multitype_conv_invalid_type():
    converter = argparser.multitype_conv([None])
    with pytest.raises(ValueError) as excinfo:
        converter('')
    assert str(excinfo.value) == "Unknown type None!"