summaryrefslogtreecommitdiffstats
path: root/Lib/test/test_format.py
diff options
context:
space:
mode:
authorNikita Sobolev <mail@sobolevn.me>2021-09-24 15:18:04 (GMT)
committerGitHub <noreply@github.com>2021-09-24 15:18:04 (GMT)
commit8d8729146f21f61af66e70d3ae9501ea6bdccd09 (patch)
treeed5905df6eb9d2bbab7513b966039cc0642635ca /Lib/test/test_format.py
parent3f8b23f8ddab75d9b77a3997d54e663187e12cc8 (diff)
downloadcpython-8d8729146f21f61af66e70d3ae9501ea6bdccd09.zip
cpython-8d8729146f21f61af66e70d3ae9501ea6bdccd09.tar.gz
cpython-8d8729146f21f61af66e70d3ae9501ea6bdccd09.tar.bz2
bpo-20524: adds better error message for `.format()` (GH-28310)
It now lists the bad format_spec and the type of the object.
Diffstat (limited to 'Lib/test/test_format.py')
-rw-r--r--Lib/test/test_format.py28
1 files changed, 28 insertions, 0 deletions
diff --git a/Lib/test/test_format.py b/Lib/test/test_format.py
index ae0d4f7..16d29d1 100644
--- a/Lib/test/test_format.py
+++ b/Lib/test/test_format.py
@@ -519,5 +519,33 @@ class FormatTest(unittest.TestCase):
with self.assertRaisesRegex(ValueError, error_msg):
'{:_,}'.format(1)
+ def test_better_error_message_format(self):
+ # https://bugs.python.org/issue20524
+ for value in [12j, 12, 12.0, "12"]:
+ with self.subTest(value=value):
+ # The format spec must be invalid for all types we're testing.
+ # '%M' will suffice.
+ bad_format_spec = '%M'
+ err = re.escape("Invalid format specifier "
+ f"'{bad_format_spec}' for object of type "
+ f"'{type(value).__name__}'")
+ with self.assertRaisesRegex(ValueError, err):
+ f"xx{{value:{bad_format_spec}}}yy".format(value=value)
+
+ # Also test the builtin format() function.
+ with self.assertRaisesRegex(ValueError, err):
+ format(value, bad_format_spec)
+
+ # Also test f-strings.
+ with self.assertRaisesRegex(ValueError, err):
+ eval("f'xx{value:{bad_format_spec}}yy'")
+
+ def test_unicode_in_error_message(self):
+ str_err = re.escape(
+ "Invalid format specifier '%ЫйЯЧ' for object of type 'str'")
+ with self.assertRaisesRegex(ValueError, str_err):
+ "{a:%ЫйЯЧ}".format(a='a')
+
+
if __name__ == "__main__":
unittest.main()