From 4e245a4bbbefed99e550e196095ea65c851cf31d Mon Sep 17 00:00:00 2001 From: Taneli Hukkinen <3275109+hukkin@users.noreply.github.com> Date: Wed, 2 Oct 2024 08:25:57 +0300 Subject: [PATCH] `tomli.loads`: Raise TypeError not AttributeError. Improve message (#229) --- src/tomli/_parser.py | 7 ++++++- tests/test_error.py | 9 +++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/tomli/_parser.py b/src/tomli/_parser.py index 3cb340ee..660c88c0 100644 --- a/src/tomli/_parser.py +++ b/src/tomli/_parser.py @@ -71,7 +71,12 @@ def loads(__s: str, *, parse_float: ParseFloat = float) -> dict[str, Any]: # no # The spec allows converting "\r\n" to "\n", even in string # 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 out = Output(NestedDict(), Flags()) header: Key = () diff --git a/tests/test_error.py b/tests/test_error.py index 72446267..d2ef59a2 100644 --- a/tests/test_error.py +++ b/tests/test_error.py @@ -39,6 +39,15 @@ def test_invalid_char_quotes(self): tomllib.loads("v = '\n'") 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): self.assertEqual(tomllib.TOMLDecodeError().__module__, tomllib.__name__)