gh-124835: `tomllib.loads`: Raise TypeError not AttributeError. Improve message (#124587)

This commit is contained in:
Taneli Hukkinen 2024-10-02 05:58:08 +03:00 committed by GitHub
parent 120729d862
commit 9ce90206b7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 18 additions and 1 deletions

View File

@ -39,6 +39,15 @@ class TestError(unittest.TestCase):
tomllib.loads("v = '\n'") tomllib.loads("v = '\n'")
self.assertTrue(" '\\n' " in str(exc_info.exception)) self.assertTrue(" '\\n' " in str(exc_info.exception))
def test_type_error(self):
with self.assertRaises(TypeError) as exc_info:
tomllib.loads(b"v = 1") # type: ignore[arg-type]
self.assertEqual(str(exc_info.exception), "Expected str object, not 'bytes'")
with self.assertRaises(TypeError) as exc_info:
tomllib.loads(False) # type: ignore[arg-type]
self.assertEqual(str(exc_info.exception), "Expected str object, not 'bool'")
def test_module_name(self): def test_module_name(self):
self.assertEqual(tomllib.TOMLDecodeError().__module__, tomllib.__name__) self.assertEqual(tomllib.TOMLDecodeError().__module__, tomllib.__name__)

View File

@ -71,7 +71,12 @@ def loads(s: str, /, *, parse_float: ParseFloat = float) -> dict[str, Any]: # n
# The spec allows converting "\r\n" to "\n", even in string # The spec allows converting "\r\n" to "\n", even in string
# literals. Let's do so to simplify parsing. # literals. Let's do so to simplify parsing.
src = s.replace("\r\n", "\n") try:
src = s.replace("\r\n", "\n")
except (AttributeError, TypeError):
raise TypeError(
f"Expected str object, not '{type(s).__qualname__}'"
) from None
pos = 0 pos = 0
out = Output(NestedDict(), Flags()) out = Output(NestedDict(), Flags())
header: Key = () header: Key = ()

View File

@ -0,0 +1,3 @@
Make :func:`tomllib.loads` raise :exc:`TypeError` not :exc:`AttributeError`
on bad input types that do not have the ``replace`` attribute. Improve error
message when :class:`bytes` is received.