def test_failure_type(self): # Prove there is no syntax error in the raw value. literal = parse_literal('1.0', acceptable_types=float) self.assertEqual(1.0, literal) # Now we can safely assume the ValueError is raise due to type checking. with self.assertRaises(ValueError): parse_literal('1.0', acceptable_types=int)
def _convert(val, acceptable_types): """Ensure that val is one of the acceptable types, converting it if needed. :param string val: The value we're parsing. :param acceptable_types: A tuple of expected types for val. :returns: The parsed value. :raises :class:`pants.options.errors.ParseError`: if there was a problem parsing the val as an acceptable type. """ return parse_literal(val, acceptable_types, raise_type=ParseError)
def _getinstance(self, section, option, type_, default=None): if not self.has_option(section, option): return default raw_value = self.get_value(section, option) # We jump through some hoops here to deal with the fact that `six.string_types` is a tuple of # types. if (type_ == six.string_types or (isinstance(type_, type) and issubclass(type_, six.string_types))): return raw_value key = '{}.{}'.format(section, option) return parse_literal(name=key, val=raw_value, acceptable_types=type_, raise_type=self.ConfigError)
def test_custom_error_type(self): class CustomError(Exception): pass with self.assertRaises(CustomError): parse_literal('1.0', acceptable_types=int, raise_type=CustomError)
def test_failure_syntax(self): with self.assertRaises(ValueError): # Only literals are allowed! parse_literal('1+2', acceptable_types=int)
def test_success_mixed(self): literal = parse_literal('42', acceptable_types=(float, int)) self.assertEqual(42, literal)
def test_success_simple(self): literal = parse_literal("'42'", acceptable_types=six.string_types) self.assertEqual('42', literal)