def test_badandgoodbackslashreplaceexceptions(self):
# "backslashreplace" complains about a non-exception passed in
self.assertRaises(
TypeError,
codecs.backslashreplace_errors,
42
)
# "backslashreplace" complains about the wrong exception types
self.assertRaises(
TypeError,
codecs.backslashreplace_errors,
UnicodeError("ouch")
)
# "backslashreplace" can only be used for encoding
self.assertRaises(
TypeError,
codecs.backslashreplace_errors,
UnicodeDecodeError("ascii", bytearray(b"\xff"), 0, 1, "ouch")
)
self.assertRaises(
TypeError,
codecs.backslashreplace_errors,
UnicodeTranslateError("\u3042", 0, 1, "ouch")
)
# Use the correct exception
tests = [
("\u3042", "\\u3042"),
("\n", "\\x0a"),
("a", "\\x61"),
("\x00", "\\x00"),
("\xff", "\\xff"),
("\u0100", "\\u0100"),
("\uffff", "\\uffff"),
("\U00010000", "\\U00010000"),
("\U0010ffff", "\\U0010ffff"),
# Lone surrogates
("\ud800", "\\ud800"),
("\udfff", "\\udfff"),
("\ud800\udfff", "\\ud800\\udfff"),
]
for s, r in tests:
with self.subTest(str=s):
self.assertEqual(
codecs.backslashreplace_errors(
UnicodeEncodeError("ascii", "a" + s + "b",
1, 1 + len(s), "ouch")),
(r, 1 + len(s))
)
评论列表
文章目录