예제 #1
0
    def test_class(self):
        """Test is_enum with a non-enum class."""
        class Test:

            """Test class for is_enum."""

            pass
        self.assertFalse(utils.is_enum(Test))
예제 #2
0
    def test_class(self):
        """Test is_enum with a non-enum class."""
        class Test:
            """Test class for is_enum."""

            pass

        assert not utils.is_enum(Test)
예제 #3
0
    def test_class(self):
        """Test is_enum with a non-enum class."""

        # pylint: disable=multiple-statements,missing-docstring
        class Test:
            pass

        self.assertFalse(utils.is_enum(Test))
예제 #4
0
    def test_class(self):
        """Test is_enum with a non-enum class."""
        class Test:

            """Test class for is_enum."""

            pass

        assert not utils.is_enum(Test)
예제 #5
0
    def _param_to_argparse_args(self, param, annotation_info):
        """Get argparse arguments for a parameter.

        Return:
            An (args, kwargs) tuple.

        Args:
            param: The inspect.Parameter object to get the args for.
            annotation_info: An AnnotationInfo tuple for the parameter.
        """

        kwargs = {}
        typ = self._get_type(param, annotation_info)
        param_type = self.ParamType.positional

        try:
            kwargs['help'] = self.docparser.arg_descs[param.name]
        except KeyError:
            pass

        if isinstance(typ, tuple):
            pass
        elif utils.is_enum(typ):
            kwargs['choices'] = [e.name.replace('_', '-') for e in typ]
            kwargs['metavar'] = param.name
        elif typ is bool:
            param_type = self.ParamType.flag
            kwargs['action'] = 'store_true'
        elif typ is not None:
            kwargs['type'] = typ

        if param.kind == inspect.Parameter.VAR_POSITIONAL:
            kwargs['nargs'] = '+'
        elif param.kind == inspect.Parameter.KEYWORD_ONLY:
            param_type = self.ParamType.flag
            kwargs['default'] = param.default
        elif typ is not bool and param.default is not inspect.Parameter.empty:
            kwargs['default'] = param.default
            kwargs['nargs'] = '?'

        args = []
        name = annotation_info.name or param.name
        shortname = annotation_info.flag or param.name[0]
        if param_type == self.ParamType.flag:
            long_flag = '--{}'.format(name)
            short_flag = '-{}'.format(shortname)
            args.append(long_flag)
            args.append(short_flag)
            self.opt_args[param.name] = long_flag, short_flag
        elif param_type == self.ParamType.positional:
            args.append(name)
            self.pos_args.append((param.name, name))
        else:
            raise ValueError("Invalid ParamType {}!".format(param_type))
        kwargs.update(annotation_info.kwargs)
        return args, kwargs
예제 #6
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
예제 #7
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
예제 #8
0
 def _convert(value):
     """Convert a value according to an iterable of possible arg types."""
     for typ in set(tpl):
         if isinstance(typ, str):
             if value == typ:
                 return value
         elif utils.is_enum(typ):
             return enum_getter(typ)(value)
         elif callable(typ):
             # int, float, etc.
             if isinstance(value, typ):
                 return value
             try:
                 return typ(value)
             except (TypeError, ValueError):
                 pass
     raise cmdexc.ArgumentTypeError('Invalid value {}.'.format(value))
예제 #9
0
    def _param_to_argparse_kwargs(self, param, annotation_info):
        """Get argparse keyword arguments for a parameter.

        Args:
            param: The inspect.Parameter object to get the args for.
            annotation_info: An AnnotationInfo tuple for the parameter.

        Return:
            A kwargs dict.
        """
        kwargs = {}
        typ = self._get_type(param, annotation_info)

        try:
            kwargs['help'] = self.docparser.arg_descs[param.name]
        except KeyError:
            pass

        kwargs['dest'] = param.name

        if isinstance(typ, tuple):
            kwargs['metavar'] = annotation_info.metavar or param.name
        elif utils.is_enum(typ):
            kwargs['choices'] = [arg_name(e.name) for e in typ]
            kwargs['metavar'] = annotation_info.metavar or param.name
        elif typ is bool:
            kwargs['action'] = 'store_true'
        elif typ is not None:
            kwargs['type'] = typ

        if param.kind == inspect.Parameter.VAR_POSITIONAL:
            kwargs['nargs'] = '+'
        elif param.kind == inspect.Parameter.KEYWORD_ONLY:
            kwargs['default'] = param.default
        elif typ is not bool and param.default is not inspect.Parameter.empty:
            kwargs['default'] = param.default
            kwargs['nargs'] = '?'
        kwargs.update(annotation_info.kwargs)
        return kwargs
예제 #10
0
    def _param_to_argparse_kwargs(self, param, annotation_info):
        """Get argparse keyword arguments for a parameter.

        Args:
            param: The inspect.Parameter object to get the args for.
            annotation_info: An AnnotationInfo tuple for the parameter.

        Return:
            A kwargs dict.
        """
        kwargs = {}
        typ = self._get_type(param, annotation_info)

        try:
            kwargs['help'] = self.docparser.arg_descs[param.name]
        except KeyError:
            pass

        kwargs['dest'] = param.name

        if isinstance(typ, tuple):
            kwargs['metavar'] = annotation_info.metavar or param.name
        elif utils.is_enum(typ):
            kwargs['choices'] = [arg_name(e.name) for e in typ]
            kwargs['metavar'] = annotation_info.metavar or param.name
        elif typ is bool:
            kwargs['action'] = 'store_true'
        elif typ is not None:
            kwargs['type'] = typ

        if param.kind == inspect.Parameter.VAR_POSITIONAL:
            kwargs['nargs'] = '+'
        elif param.kind == inspect.Parameter.KEYWORD_ONLY:
            kwargs['default'] = param.default
        elif typ is not bool and param.default is not inspect.Parameter.empty:
            kwargs['default'] = param.default
            kwargs['nargs'] = '?'
        kwargs.update(annotation_info.kwargs)
        return kwargs
예제 #11
0
def type_conv(param, typ, value, *, str_choices=None):
    """Convert a value based on a type.

    Args:
        param: The argparse.Parameter we're checking
        types: The allowed type
        value: The value to convert
        str_choices: The allowed choices if the type ends up being a string

    Return:
        The converted value
    """
    if isinstance(typ, str):
        raise TypeError("{}: Legacy string type!".format(param.name))

    if value is param.default:
        return value

    if not isinstance(value, str):
        raise AssertionError(repr(value))

    if utils.is_enum(typ):
        _check_choices(param, value, [arg_name(e.name) for e in typ])
        return typ[value.replace('-', '_')]
    elif typ is str:
        if str_choices is not None:
            _check_choices(param, value, str_choices)
        return value
    elif callable(typ):
        # int, float, etc.
        try:
            return typ(value)
        except (TypeError, ValueError):
            msg = '{}: Invalid {} value {}'.format(
                param.name, typ.__name__, value)
            raise cmdexc.ArgumentTypeError(msg)
    else:
        raise ValueError("{}: Unknown type {!r}!".format(param.name, typ))
예제 #12
0
def type_conv(param, typ, value, *, str_choices=None):
    """Convert a value based on a type.

    Args:
        param: The argparse.Parameter we're checking
        types: The allowed type
        value: The value to convert
        str_choices: The allowed choices if the type ends up being a string

    Return:
        The converted value
    """
    if isinstance(typ, str):
        raise TypeError("{}: Legacy string type!".format(param.name))

    if value is param.default:
        return value

    assert isinstance(value, str), repr(value)

    if utils.is_enum(typ):
        _check_choices(param, value, [arg_name(e.name) for e in typ])
        return typ[value.replace('-', '_')]
    elif typ is str:
        if str_choices is not None:
            _check_choices(param, value, str_choices)
        return value
    elif callable(typ):
        # int, float, etc.
        try:
            return typ(value)
        except (TypeError, ValueError):
            msg = '{}: Invalid {} value {}'.format(
                param.name, typ.__name__, value)
            raise cmdexc.ArgumentTypeError(msg)
    else:
        raise ValueError("{}: Unknown type {!r}!".format(param.name, typ))
예제 #13
0
 def test_class(self):
     """Test is_enum with a non-enum class."""
     # pylint: disable=multiple-statements,missing-docstring
     class Test: pass
     self.assertFalse(utils.is_enum(Test))
예제 #14
0
 def test_enum(self):
     """Test is_enum with an enum."""
     e = enum.Enum('Foo', 'bar, baz')
     self.assertTrue(utils.is_enum(e))
예제 #15
0
 def test_object(self):
     """Test is_enum with a non-enum object."""
     self.assertFalse(utils.is_enum(23))
예제 #16
0
 def test_object(self):
     """Test is_enum with a non-enum object."""
     assert not utils.is_enum(23)
예제 #17
0
 def test_object(self):
     """Test is_enum with a non-enum object."""
     assert not utils.is_enum(23)
예제 #18
0
 def test_enum(self):
     """Test is_enum with an enum."""
     e = enum.Enum('Foo', 'bar, baz')
     assert utils.is_enum(e)
예제 #19
0
 def test_object(self):
     """Test is_enum with a non-enum object."""
     self.assertFalse(utils.is_enum(23))