| 1 |
import codecs |
| 2 |
import html.entities |
| 3 |
import itertools |
| 4 |
import re |
| 5 |
import sys |
| 6 |
import unicodedata |
| 7 |
import unittest |
| 8 |
|
| 9 |
|
| 10 |
class PosReturn: |
| 11 |
# this can be used for configurable callbacks |
| 12 |
|
| 13 |
def __init__(self): |
| 14 |
self.pos = 0 |
| 15 |
|
| 16 |
def handle(self, exc): |
| 17 |
oldpos = self.pos |
| 18 |
realpos = oldpos |
| 19 |
if realpos<0: |
| 20 |
realpos = len(exc.object) + realpos |
| 21 |
# if we don't advance this time, terminate on the next call |
| 22 |
# otherwise we'd get an endless loop |
| 23 |
if realpos <= exc.start: |
| 24 |
self.pos = len(exc.object) |
| 25 |
return ("<?>", oldpos) |
| 26 |
|
| 27 |
class RepeatedPosReturn: |
| 28 |
def __init__(self, repl="<?>"): |
| 29 |
self.repl = repl |
| 30 |
self.pos = 0 |
| 31 |
self.count = 0 |
| 32 |
|
| 33 |
def handle(self, exc): |
| 34 |
if self.count > 0: |
| 35 |
self.count -= 1 |
| 36 |
return (self.repl, self.pos) |
| 37 |
return (self.repl, exc.end) |
| 38 |
|
| 39 |
# A UnicodeEncodeError object with a bad start attribute |
| 40 |
class BadStartUnicodeEncodeError(UnicodeEncodeError): |
| 41 |
def __init__(self): |
| 42 |
UnicodeEncodeError.__init__(self, "ascii", "", 0, 1, "bad") |
| 43 |
self.start = [] |
| 44 |
|
| 45 |
# A UnicodeEncodeError object with a bad object attribute |
| 46 |
class BadObjectUnicodeEncodeError(UnicodeEncodeError): |
| 47 |
def __init__(self): |
| 48 |
UnicodeEncodeError.__init__(self, "ascii", "", 0, 1, "bad") |
| 49 |
self.object = [] |
| 50 |
|
| 51 |
# A UnicodeDecodeError object without an end attribute |
| 52 |
class NoEndUnicodeDecodeError(UnicodeDecodeError): |
| 53 |
def __init__(self): |
| 54 |
UnicodeDecodeError.__init__(self, "ascii", bytearray(b""), 0, 1, "bad") |
| 55 |
del self.end |
| 56 |
|
| 57 |
# A UnicodeDecodeError object with a bad object attribute |
| 58 |
class BadObjectUnicodeDecodeError(UnicodeDecodeError): |
| 59 |
def __init__(self): |
| 60 |
UnicodeDecodeError.__init__(self, "ascii", bytearray(b""), 0, 1, "bad") |
| 61 |
self.object = [] |
| 62 |
|
| 63 |
# A UnicodeTranslateError object without a start attribute |
| 64 |
class NoStartUnicodeTranslateError(UnicodeTranslateError): |
| 65 |
def __init__(self): |
| 66 |
UnicodeTranslateError.__init__(self, "", 0, 1, "bad") |
| 67 |
del self.start |
| 68 |
|
| 69 |
# A UnicodeTranslateError object without an end attribute |
| 70 |
class NoEndUnicodeTranslateError(UnicodeTranslateError): |
| 71 |
def __init__(self): |
| 72 |
UnicodeTranslateError.__init__(self, "", 0, 1, "bad") |
| 73 |
del self.end |
| 74 |
|
| 75 |
# A UnicodeTranslateError object without an object attribute |
| 76 |
class NoObjectUnicodeTranslateError(UnicodeTranslateError): |
| 77 |
def __init__(self): |
| 78 |
UnicodeTranslateError.__init__(self, "", 0, 1, "bad") |
| 79 |
del self.object |
| 80 |
|
| 81 |
class CodecCallbackTest(unittest.TestCase): |
| 82 |
|
| 83 |
def test_xmlcharrefreplace(self): |
| 84 |
# replace unencodable characters which numeric character entities. |
| 85 |
# For ascii, latin-1 and charmaps this is completely implemented |
| 86 |
# in C and should be reasonably fast. |
| 87 |
s = "\u30b9\u30d1\u30e2 \xe4nd eggs" |
| 88 |
self.assertEqual( |
| 89 |
s.encode("ascii", "xmlcharrefreplace"), |
| 90 |
b"スパモ änd eggs" |
| 91 |
) |
| 92 |
self.assertEqual( |
| 93 |
s.encode("latin-1", "xmlcharrefreplace"), |
| 94 |
b"スパモ \xe4nd eggs" |
| 95 |
) |
| 96 |
|
| 97 |
def test_xmlcharnamereplace(self): |
| 98 |
# This time use a named character entity for unencodable |
| 99 |
# characters, if one is available. |
| 100 |
|
| 101 |
def xmlcharnamereplace(exc): |
| 102 |
if not isinstance(exc, UnicodeEncodeError): |
| 103 |
raise TypeError("don't know how to handle %r" % exc) |
| 104 |
l = [] |
| 105 |
for c in exc.object[exc.start:exc.end]: |
| 106 |
try: |
| 107 |
l.append("&%s;" % html.entities.codepoint2name[ord(c)]) |
| 108 |
except KeyError: |
| 109 |
l.append("&#%d;" % ord(c)) |
| 110 |
return ("".join(l), exc.end) |
| 111 |
|
| 112 |
codecs.register_error( |
| 113 |
"test.xmlcharnamereplace", xmlcharnamereplace) |
| 114 |
|
| 115 |
sin = "\xab\u211c\xbb = \u2329\u1234\u20ac\u232a" |
| 116 |
sout = b"«ℜ» = ⟨ሴ€⟩" |
| 117 |
self.assertEqual(sin.encode("ascii", "test.xmlcharnamereplace"), sout) |
| 118 |
sout = b"\xabℜ\xbb = ⟨ሴ€⟩" |
| 119 |
self.assertEqual(sin.encode("latin-1", "test.xmlcharnamereplace"), sout) |
| 120 |
sout = b"\xabℜ\xbb = ⟨ሴ\xa4⟩" |
| 121 |
self.assertEqual(sin.encode("iso-8859-15", "test.xmlcharnamereplace"), sout) |
| 122 |
|
| 123 |
def test_uninamereplace(self): |
| 124 |
# We're using the names from the unicode database this time, |
| 125 |
# and we're doing "syntax highlighting" here, i.e. we include |
| 126 |
# the replaced text in ANSI escape sequences. For this it is |
| 127 |
# useful that the error handler is not called for every single |
| 128 |
# unencodable character, but for a complete sequence of |
| 129 |
# unencodable characters, otherwise we would output many |
| 130 |
# unnecessary escape sequences. |
| 131 |
|
| 132 |
def uninamereplace(exc): |
| 133 |
if not isinstance(exc, UnicodeEncodeError): |
| 134 |
raise TypeError("don't know how to handle %r" % exc) |
| 135 |
l = [] |
| 136 |
for c in exc.object[exc.start:exc.end]: |
| 137 |
l.append(unicodedata.name(c, "0x%x" % ord(c))) |
| 138 |
return ("\033[1m%s\033[0m" % ", ".join(l), exc.end) |
| 139 |
|
| 140 |
codecs.register_error( |
| 141 |
"test.uninamereplace", uninamereplace) |
| 142 |
|
| 143 |
sin = "\xac\u1234\u20ac\u8000" |
| 144 |
sout = b"\033[1mNOT SIGN, ETHIOPIC SYLLABLE SEE, EURO SIGN, CJK UNIFIED IDEOGRAPH-8000\033[0m" |
| 145 |
self.assertEqual(sin.encode("ascii", "test.uninamereplace"), sout) |
| 146 |
|
| 147 |
sout = b"\xac\033[1mETHIOPIC SYLLABLE SEE, EURO SIGN, CJK UNIFIED IDEOGRAPH-8000\033[0m" |
| 148 |
self.assertEqual(sin.encode("latin-1", "test.uninamereplace"), sout) |
| 149 |
|
| 150 |
sout = b"\xac\033[1mETHIOPIC SYLLABLE SEE\033[0m\xa4\033[1mCJK UNIFIED IDEOGRAPH-8000\033[0m" |
| 151 |
self.assertEqual(sin.encode("iso-8859-15", "test.uninamereplace"), sout) |
| 152 |
|
| 153 |
def test_backslashescape(self): |
| 154 |
# Does the same as the "unicode-escape" encoding, but with different |
| 155 |
# base encodings. |
| 156 |
sin = "a\xac\u1234\u20ac\u8000\U0010ffff" |
| 157 |
sout = b"a\\xac\\u1234\\u20ac\\u8000\\U0010ffff" |
| 158 |
self.assertEqual(sin.encode("ascii", "backslashreplace"), sout) |
| 159 |
|
| 160 |
sout = b"a\xac\\u1234\\u20ac\\u8000\\U0010ffff" |
| 161 |
self.assertEqual(sin.encode("latin-1", "backslashreplace"), sout) |
| 162 |
|
| 163 |
sout = b"a\xac\\u1234\xa4\\u8000\\U0010ffff" |
| 164 |
self.assertEqual(sin.encode("iso-8859-15", "backslashreplace"), sout) |
| 165 |
|
| 166 |
def test_nameescape(self): |
| 167 |
# Does the same as backslashescape, but prefers ``\N{...}`` escape |
| 168 |
# sequences. |
| 169 |
sin = "a\xac\u1234\u20ac\u8000\U0010ffff" |
| 170 |
sout = (b'a\\N{NOT SIGN}\\N{ETHIOPIC SYLLABLE SEE}\\N{EURO SIGN}' |
| 171 |
b'\\N{CJK UNIFIED IDEOGRAPH-8000}\\U0010ffff') |
| 172 |
self.assertEqual(sin.encode("ascii", "namereplace"), sout) |
| 173 |
|
| 174 |
sout = (b'a\xac\\N{ETHIOPIC SYLLABLE SEE}\\N{EURO SIGN}' |
| 175 |
b'\\N{CJK UNIFIED IDEOGRAPH-8000}\\U0010ffff') |
| 176 |
self.assertEqual(sin.encode("latin-1", "namereplace"), sout) |
| 177 |
|
| 178 |
sout = (b'a\xac\\N{ETHIOPIC SYLLABLE SEE}\xa4' |
| 179 |
b'\\N{CJK UNIFIED IDEOGRAPH-8000}\\U0010ffff') |
| 180 |
self.assertEqual(sin.encode("iso-8859-15", "namereplace"), sout) |
| 181 |
|
| 182 |
def test_decoding_callbacks(self): |
| 183 |
# This is a test for a decoding callback handler |
| 184 |
# that allows the decoding of the invalid sequence |
| 185 |
# "\xc0\x80" and returns "\x00" instead of raising an error. |
| 186 |
# All other illegal sequences will be handled strictly. |
| 187 |
def relaxedutf8(exc): |
| 188 |
if not isinstance(exc, UnicodeDecodeError): |
| 189 |
raise TypeError("don't know how to handle %r" % exc) |
| 190 |
if exc.object[exc.start:exc.start+2] == b"\xc0\x80": |
| 191 |
return ("\x00", exc.start+2) # retry after two bytes |
| 192 |
else: |
| 193 |
raise exc |
| 194 |
|
| 195 |
codecs.register_error("test.relaxedutf8", relaxedutf8) |
| 196 |
|
| 197 |
# all the "\xc0\x80" will be decoded to "\x00" |
| 198 |
sin = b"a\x00b\xc0\x80c\xc3\xbc\xc0\x80\xc0\x80" |
| 199 |
sout = "a\x00b\x00c\xfc\x00\x00" |
| 200 |
self.assertEqual(sin.decode("utf-8", "test.relaxedutf8"), sout) |
| 201 |
|
| 202 |
# "\xc0\x81" is not valid and a UnicodeDecodeError will be raised |
| 203 |
sin = b"\xc0\x80\xc0\x81" |
| 204 |
self.assertRaises(UnicodeDecodeError, sin.decode, |
| 205 |
"utf-8", "test.relaxedutf8") |
| 206 |
|
| 207 |
def test_charmapencode(self): |
| 208 |
# For charmap encodings the replacement string will be |
| 209 |
# mapped through the encoding again. This means, that |
| 210 |
# to be able to use e.g. the "replace" handler, the |
| 211 |
# charmap has to have a mapping for "?". |
| 212 |
charmap = dict((ord(c), bytes(2*c.upper(), 'ascii')) for c in "abcdefgh") |
| 213 |
sin = "abc" |
| 214 |
sout = b"AABBCC" |
| 215 |
self.assertEqual(codecs.charmap_encode(sin, "strict", charmap)[0], sout) |
| 216 |
|
| 217 |
sin = "abcA" |
| 218 |
self.assertRaises(UnicodeError, codecs.charmap_encode, sin, "strict", charmap) |
| 219 |
|
| 220 |
charmap[ord("?")] = b"XYZ" |
| 221 |
sin = "abcDEF" |
| 222 |
sout = b"AABBCCXYZXYZXYZ" |
| 223 |
self.assertEqual(codecs.charmap_encode(sin, "replace", charmap)[0], sout) |
| 224 |
|
| 225 |
charmap[ord("?")] = "XYZ" # wrong type in mapping |
| 226 |
self.assertRaises(TypeError, codecs.charmap_encode, sin, "replace", charmap) |
| 227 |
|
| 228 |
def test_callbacks(self): |
| 229 |
def handler1(exc): |
| 230 |
r = range(exc.start, exc.end) |
| 231 |
if isinstance(exc, UnicodeEncodeError): |
| 232 |
l = ["<%d>" % ord(exc.object[pos]) for pos in r] |
| 233 |
elif isinstance(exc, UnicodeDecodeError): |
| 234 |
l = ["<%d>" % exc.object[pos] for pos in r] |
| 235 |
else: |
| 236 |
raise TypeError("don't know how to handle %r" % exc) |
| 237 |
return ("[%s]" % "".join(l), exc.end) |
| 238 |
|
| 239 |
codecs.register_error("test.handler1", handler1) |
| 240 |
|
| 241 |
def handler2(exc): |
| 242 |
if not isinstance(exc, UnicodeDecodeError): |
| 243 |
raise TypeError("don't know how to handle %r" % exc) |
| 244 |
l = ["<%d>" % exc.object[pos] for pos in range(exc.start, exc.end)] |
| 245 |
return ("[%s]" % "".join(l), exc.end+1) # skip one character |
| 246 |
|
| 247 |
codecs.register_error("test.handler2", handler2) |
| 248 |
|
| 249 |
s = b"\x00\x81\x7f\x80\xff" |
| 250 |
|
| 251 |
self.assertEqual( |
| 252 |
s.decode("ascii", "test.handler1"), |
| 253 |
"\x00[<129>]\x7f[<128>][<255>]" |
| 254 |
) |
| 255 |
self.assertEqual( |
| 256 |
s.decode("ascii", "test.handler2"), |
| 257 |
"\x00[<129>][<128>]" |
| 258 |
) |
| 259 |
|
| 260 |
self.assertEqual( |
| 261 |
b"\\u3042\\u3xxx".decode("unicode-escape", "test.handler1"), |
| 262 |
"\u3042[<92><117><51>]xxx" |
| 263 |
) |
| 264 |
|
| 265 |
self.assertEqual( |
| 266 |
b"\\u3042\\u3xx".decode("unicode-escape", "test.handler1"), |
| 267 |
"\u3042[<92><117><51>]xx" |
| 268 |
) |
| 269 |
|
| 270 |
self.assertEqual( |
| 271 |
codecs.charmap_decode(b"abc", "test.handler1", {ord("a"): "z"})[0], |
| 272 |
"z[<98>][<99>]" |
| 273 |
) |
| 274 |
|
| 275 |
self.assertEqual( |
| 276 |
"g\xfc\xdfrk".encode("ascii", "test.handler1"), |
| 277 |
b"g[<252><223>]rk" |
| 278 |
) |
| 279 |
|
| 280 |
self.assertEqual( |
| 281 |
"g\xfc\xdf".encode("ascii", "test.handler1"), |
| 282 |
b"g[<252><223>]" |
| 283 |
) |
| 284 |
|
| 285 |
def test_longstrings(self): |
| 286 |
# test long strings to check for memory overflow problems |
| 287 |
errors = [ "strict", "ignore", "replace", "xmlcharrefreplace", |
| 288 |
"backslashreplace", "namereplace"] |
| 289 |
# register the handlers under different names, |
| 290 |
# to prevent the codec from recognizing the name |
| 291 |
for err in errors: |
| 292 |
codecs.register_error("test." + err, codecs.lookup_error(err)) |
| 293 |
l = 1000 |
| 294 |
errors += [ "test." + err for err in errors ] |
| 295 |
for uni in [ s*l for s in ("x", "\u3042", "a\xe4") ]: |
| 296 |
for enc in ("ascii", "latin-1", "iso-8859-1", "iso-8859-15", |
| 297 |
"utf-8", "utf-7", "utf-16", "utf-32"): |
| 298 |
for err in errors: |
| 299 |
try: |
| 300 |
uni.encode(enc, err) |
| 301 |
except UnicodeError: |
| 302 |
pass |
| 303 |
|
| 304 |
def check_exceptionobjectargs(self, exctype, args, msg): |
| 305 |
# Test UnicodeError subclasses: construction, attribute assignment and __str__ conversion |
| 306 |
# check with one missing argument |
| 307 |
self.assertRaises(TypeError, exctype, *args[:-1]) |
| 308 |
# check with one argument too much |
| 309 |
self.assertRaises(TypeError, exctype, *(args + ["too much"])) |
| 310 |
# check with one argument of the wrong type |
| 311 |
wrongargs = [ "spam", b"eggs", b"spam", 42, 1.0, None ] |
| 312 |
for i in range(len(args)): |
| 313 |
for wrongarg in wrongargs: |
| 314 |
if type(wrongarg) is type(args[i]): |
| 315 |
continue |
| 316 |
# build argument array |
| 317 |
callargs = [] |
| 318 |
for j in range(len(args)): |
| 319 |
if i==j: |
| 320 |
callargs.append(wrongarg) |
| 321 |
else: |
| 322 |
callargs.append(args[i]) |
| 323 |
self.assertRaises(TypeError, exctype, *callargs) |
| 324 |
|
| 325 |
# check with the correct number and type of arguments |
| 326 |
exc = exctype(*args) |
| 327 |
self.assertEqual(str(exc), msg) |
| 328 |
|
| 329 |
def test_unicodeencodeerror(self): |
| 330 |
self.check_exceptionobjectargs( |
| 331 |
UnicodeEncodeError, |
| 332 |
["ascii", "g\xfcrk", 1, 2, "ouch"], |
| 333 |
"'ascii' codec can't encode character '\\xfc' in position 1: ouch" |
| 334 |
) |
| 335 |
self.check_exceptionobjectargs( |
| 336 |
UnicodeEncodeError, |
| 337 |
["ascii", "g\xfcrk", 1, 4, "ouch"], |
| 338 |
"'ascii' codec can't encode characters in position 1-3: ouch" |
| 339 |
) |
| 340 |
self.check_exceptionobjectargs( |
| 341 |
UnicodeEncodeError, |
| 342 |
["ascii", "\xfcx", 0, 1, "ouch"], |
| 343 |
"'ascii' codec can't encode character '\\xfc' in position 0: ouch" |
| 344 |
) |
| 345 |
self.check_exceptionobjectargs( |
| 346 |
UnicodeEncodeError, |
| 347 |
["ascii", "\u0100x", 0, 1, "ouch"], |
| 348 |
"'ascii' codec can't encode character '\\u0100' in position 0: ouch" |
| 349 |
) |
| 350 |
self.check_exceptionobjectargs( |
| 351 |
UnicodeEncodeError, |
| 352 |
["ascii", "\uffffx", 0, 1, "ouch"], |
| 353 |
"'ascii' codec can't encode character '\\uffff' in position 0: ouch" |
| 354 |
) |
| 355 |
self.check_exceptionobjectargs( |
| 356 |
UnicodeEncodeError, |
| 357 |
["ascii", "\U00010000x", 0, 1, "ouch"], |
| 358 |
"'ascii' codec can't encode character '\\U00010000' in position 0: ouch" |
| 359 |
) |
| 360 |
|
| 361 |
def test_unicodedecodeerror(self): |
| 362 |
self.check_exceptionobjectargs( |
| 363 |
UnicodeDecodeError, |
| 364 |
["ascii", bytearray(b"g\xfcrk"), 1, 2, "ouch"], |
| 365 |
"'ascii' codec can't decode byte 0xfc in position 1: ouch" |
| 366 |
) |
| 367 |
self.check_exceptionobjectargs( |
| 368 |
UnicodeDecodeError, |
| 369 |
["ascii", bytearray(b"g\xfcrk"), 1, 3, "ouch"], |
| 370 |
"'ascii' codec can't decode bytes in position 1-2: ouch" |
| 371 |
) |
| 372 |
|
| 373 |
def test_unicodetranslateerror(self): |
| 374 |
self.check_exceptionobjectargs( |
| 375 |
UnicodeTranslateError, |
| 376 |
["g\xfcrk", 1, 2, "ouch"], |
| 377 |
"can't translate character '\\xfc' in position 1: ouch" |
| 378 |
) |
| 379 |
self.check_exceptionobjectargs( |
| 380 |
UnicodeTranslateError, |
| 381 |
["g\u0100rk", 1, 2, "ouch"], |
| 382 |
"can't translate character '\\u0100' in position 1: ouch" |
| 383 |
) |
| 384 |
self.check_exceptionobjectargs( |
| 385 |
UnicodeTranslateError, |
| 386 |
["g\uffffrk", 1, 2, "ouch"], |
| 387 |
"can't translate character '\\uffff' in position 1: ouch" |
| 388 |
) |
| 389 |
self.check_exceptionobjectargs( |
| 390 |
UnicodeTranslateError, |
| 391 |
["g\U00010000rk", 1, 2, "ouch"], |
| 392 |
"can't translate character '\\U00010000' in position 1: ouch" |
| 393 |
) |
| 394 |
self.check_exceptionobjectargs( |
| 395 |
UnicodeTranslateError, |
| 396 |
["g\xfcrk", 1, 3, "ouch"], |
| 397 |
"can't translate characters in position 1-2: ouch" |
| 398 |
) |
| 399 |
|
| 400 |
def test_badandgoodstrictexceptions(self): |
| 401 |
# "strict" complains about a non-exception passed in |
| 402 |
self.assertRaises( |
| 403 |
TypeError, |
| 404 |
codecs.strict_errors, |
| 405 |
42 |
| 406 |
) |
| 407 |
# "strict" complains about the wrong exception type |
| 408 |
self.assertRaises( |
| 409 |
Exception, |
| 410 |
codecs.strict_errors, |
| 411 |
Exception("ouch") |
| 412 |
) |
| 413 |
|
| 414 |
# If the correct exception is passed in, "strict" raises it |
| 415 |
self.assertRaises( |
| 416 |
UnicodeEncodeError, |
| 417 |
codecs.strict_errors, |
| 418 |
UnicodeEncodeError("ascii", "\u3042", 0, 1, "ouch") |
| 419 |
) |
| 420 |
self.assertRaises( |
| 421 |
UnicodeDecodeError, |
| 422 |
codecs.strict_errors, |
| 423 |
UnicodeDecodeError("ascii", bytearray(b"\xff"), 0, 1, "ouch") |
| 424 |
) |
| 425 |
self.assertRaises( |
| 426 |
UnicodeTranslateError, |
| 427 |
codecs.strict_errors, |
| 428 |
UnicodeTranslateError("\u3042", 0, 1, "ouch") |
| 429 |
) |
| 430 |
|
| 431 |
def test_badandgoodignoreexceptions(self): |
| 432 |
# "ignore" complains about a non-exception passed in |
| 433 |
self.assertRaises( |
| 434 |
TypeError, |
| 435 |
codecs.ignore_errors, |
| 436 |
42 |
| 437 |
) |
| 438 |
# "ignore" complains about the wrong exception type |
| 439 |
self.assertRaises( |
| 440 |
TypeError, |
| 441 |
codecs.ignore_errors, |
| 442 |
UnicodeError("ouch") |
| 443 |
) |
| 444 |
# If the correct exception is passed in, "ignore" returns an empty replacement |
| 445 |
self.assertEqual( |
| 446 |
codecs.ignore_errors( |
| 447 |
UnicodeEncodeError("ascii", "a\u3042b", 1, 2, "ouch")), |
| 448 |
("", 2) |
| 449 |
) |
| 450 |
self.assertEqual( |
| 451 |
codecs.ignore_errors( |
| 452 |
UnicodeDecodeError("ascii", bytearray(b"a\xffb"), 1, 2, "ouch")), |
| 453 |
("", 2) |
| 454 |
) |
| 455 |
self.assertEqual( |
| 456 |
codecs.ignore_errors( |
| 457 |
UnicodeTranslateError("a\u3042b", 1, 2, "ouch")), |
| 458 |
("", 2) |
| 459 |
) |
| 460 |
|
| 461 |
def test_badandgoodreplaceexceptions(self): |
| 462 |
# "replace" complains about a non-exception passed in |
| 463 |
self.assertRaises( |
| 464 |
TypeError, |
| 465 |
codecs.replace_errors, |
| 466 |
42 |
| 467 |
) |
| 468 |
# "replace" complains about the wrong exception type |
| 469 |
self.assertRaises( |
| 470 |
TypeError, |
| 471 |
codecs.replace_errors, |
| 472 |
UnicodeError("ouch") |
| 473 |
) |
| 474 |
self.assertRaises( |
| 475 |
TypeError, |
| 476 |
codecs.replace_errors, |
| 477 |
BadObjectUnicodeEncodeError() |
| 478 |
) |
| 479 |
self.assertRaises( |
| 480 |
TypeError, |
| 481 |
codecs.replace_errors, |
| 482 |
BadObjectUnicodeDecodeError() |
| 483 |
) |
| 484 |
# With the correct exception, "replace" returns an "?" or "\ufffd" replacement |
| 485 |
self.assertEqual( |
| 486 |
codecs.replace_errors( |
| 487 |
UnicodeEncodeError("ascii", "a\u3042b", 1, 2, "ouch")), |
| 488 |
("?", 2) |
| 489 |
) |
| 490 |
self.assertEqual( |
| 491 |
codecs.replace_errors( |
| 492 |
UnicodeDecodeError("ascii", bytearray(b"a\xffb"), 1, 2, "ouch")), |
| 493 |
("\ufffd", 2) |
| 494 |
) |
| 495 |
self.assertEqual( |
| 496 |
codecs.replace_errors( |
| 497 |
UnicodeTranslateError("a\u3042b", 1, 2, "ouch")), |
| 498 |
("\ufffd", 2) |
| 499 |
) |
| 500 |
|
| 501 |
def test_badandgoodxmlcharrefreplaceexceptions(self): |
| 502 |
# "xmlcharrefreplace" complains about a non-exception passed in |
| 503 |
self.assertRaises( |
| 504 |
TypeError, |
| 505 |
codecs.xmlcharrefreplace_errors, |
| 506 |
42 |
| 507 |
) |
| 508 |
# "xmlcharrefreplace" complains about the wrong exception types |
| 509 |
self.assertRaises( |
| 510 |
TypeError, |
| 511 |
codecs.xmlcharrefreplace_errors, |
| 512 |
UnicodeError("ouch") |
| 513 |
) |
| 514 |
# "xmlcharrefreplace" can only be used for encoding |
| 515 |
self.assertRaises( |
| 516 |
TypeError, |
| 517 |
codecs.xmlcharrefreplace_errors, |
| 518 |
UnicodeDecodeError("ascii", bytearray(b"\xff"), 0, 1, "ouch") |
| 519 |
) |
| 520 |
self.assertRaises( |
| 521 |
TypeError, |
| 522 |
codecs.xmlcharrefreplace_errors, |
| 523 |
UnicodeTranslateError("\u3042", 0, 1, "ouch") |
| 524 |
) |
| 525 |
# Use the correct exception |
| 526 |
cs = (0, 1, 9, 10, 99, 100, 999, 1000, 9999, 10000, 99999, 100000, |
| 527 |
999999, 1000000) |
| 528 |
cs += (0xd800, 0xdfff) |
| 529 |
s = "".join(chr(c) for c in cs) |
| 530 |
self.assertEqual( |
| 531 |
codecs.xmlcharrefreplace_errors( |
| 532 |
UnicodeEncodeError("ascii", "a" + s + "b", |
| 533 |
1, 1 + len(s), "ouch") |
| 534 |
), |
| 535 |
("".join("&#%d;" % c for c in cs), 1 + len(s)) |
| 536 |
) |
| 537 |
|
| 538 |
def test_badandgoodbackslashreplaceexceptions(self): |
| 539 |
# "backslashreplace" complains about a non-exception passed in |
| 540 |
self.assertRaises( |
| 541 |
TypeError, |
| 542 |
codecs.backslashreplace_errors, |
| 543 |
42 |
| 544 |
) |
| 545 |
# "backslashreplace" complains about the wrong exception types |
| 546 |
self.assertRaises( |
| 547 |
TypeError, |
| 548 |
codecs.backslashreplace_errors, |
| 549 |
UnicodeError("ouch") |
| 550 |
) |
| 551 |
# Use the correct exception |
| 552 |
tests = [ |
| 553 |
("\u3042", "\\u3042"), |
| 554 |
("\n", "\\x0a"), |
| 555 |
("a", "\\x61"), |
| 556 |
("\x00", "\\x00"), |
| 557 |
("\xff", "\\xff"), |
| 558 |
("\u0100", "\\u0100"), |
| 559 |
("\uffff", "\\uffff"), |
| 560 |
("\U00010000", "\\U00010000"), |
| 561 |
("\U0010ffff", "\\U0010ffff"), |
| 562 |
# Lone surrogates |
| 563 |
("\ud800", "\\ud800"), |
| 564 |
("\udfff", "\\udfff"), |
| 565 |
("\ud800\udfff", "\\ud800\\udfff"), |
| 566 |
] |
| 567 |
for s, r in tests: |
| 568 |
with self.subTest(str=s): |
| 569 |
self.assertEqual( |
| 570 |
codecs.backslashreplace_errors( |
| 571 |
UnicodeEncodeError("ascii", "a" + s + "b", |
| 572 |
1, 1 + len(s), "ouch")), |
| 573 |
(r, 1 + len(s)) |
| 574 |
) |
| 575 |
self.assertEqual( |
| 576 |
codecs.backslashreplace_errors( |
| 577 |
UnicodeTranslateError("a" + s + "b", |
| 578 |
1, 1 + len(s), "ouch")), |
| 579 |
(r, 1 + len(s)) |
| 580 |
) |
| 581 |
tests = [ |
| 582 |
(b"a", "\\x61"), |
| 583 |
(b"\n", "\\x0a"), |
| 584 |
(b"\x00", "\\x00"), |
| 585 |
(b"\xff", "\\xff"), |
| 586 |
] |
| 587 |
for b, r in tests: |
| 588 |
with self.subTest(bytes=b): |
| 589 |
self.assertEqual( |
| 590 |
codecs.backslashreplace_errors( |
| 591 |
UnicodeDecodeError("ascii", bytearray(b"a" + b + b"b"), |
| 592 |
1, 2, "ouch")), |
| 593 |
(r, 2) |
| 594 |
) |
| 595 |
|
| 596 |
def test_badandgoodnamereplaceexceptions(self): |
| 597 |
# "namereplace" complains about a non-exception passed in |
| 598 |
self.assertRaises( |
| 599 |
TypeError, |
| 600 |
codecs.namereplace_errors, |
| 601 |
42 |
| 602 |
) |
| 603 |
# "namereplace" complains about the wrong exception types |
| 604 |
self.assertRaises( |
| 605 |
TypeError, |
| 606 |
codecs.namereplace_errors, |
| 607 |
UnicodeError("ouch") |
| 608 |
) |
| 609 |
# "namereplace" can only be used for encoding |
| 610 |
self.assertRaises( |
| 611 |
TypeError, |
| 612 |
codecs.namereplace_errors, |
| 613 |
UnicodeDecodeError("ascii", bytearray(b"\xff"), 0, 1, "ouch") |
| 614 |
) |
| 615 |
self.assertRaises( |
| 616 |
TypeError, |
| 617 |
codecs.namereplace_errors, |
| 618 |
UnicodeTranslateError("\u3042", 0, 1, "ouch") |
| 619 |
) |
| 620 |
# Use the correct exception |
| 621 |
tests = [ |
| 622 |
("\u3042", "\\N{HIRAGANA LETTER A}"), |
| 623 |
("\x00", "\\x00"), |
| 624 |
("\ufbf9", "\\N{ARABIC LIGATURE UIGHUR KIRGHIZ YEH WITH " |
| 625 |
"HAMZA ABOVE WITH ALEF MAKSURA ISOLATED FORM}"), |
| 626 |
("\U000e007f", "\\N{CANCEL TAG}"), |
| 627 |
("\U0010ffff", "\\U0010ffff"), |
| 628 |
# Lone surrogates |
| 629 |
("\ud800", "\\ud800"), |
| 630 |
("\udfff", "\\udfff"), |
| 631 |
("\ud800\udfff", "\\ud800\\udfff"), |
| 632 |
] |
| 633 |
for s, r in tests: |
| 634 |
with self.subTest(str=s): |
| 635 |
self.assertEqual( |
| 636 |
codecs.namereplace_errors( |
| 637 |
UnicodeEncodeError("ascii", "a" + s + "b", |
| 638 |
1, 1 + len(s), "ouch")), |
| 639 |
(r, 1 + len(s)) |
| 640 |
) |
| 641 |
|
| 642 |
def test_badandgoodsurrogateescapeexceptions(self): |
| 643 |
surrogateescape_errors = codecs.lookup_error('surrogateescape') |
| 644 |
# "surrogateescape" complains about a non-exception passed in |
| 645 |
self.assertRaises( |
| 646 |
TypeError, |
| 647 |
surrogateescape_errors, |
| 648 |
42 |
| 649 |
) |
| 650 |
# "surrogateescape" complains about the wrong exception types |
| 651 |
self.assertRaises( |
| 652 |
TypeError, |
| 653 |
surrogateescape_errors, |
| 654 |
UnicodeError("ouch") |
| 655 |
) |
| 656 |
# "surrogateescape" can not be used for translating |
| 657 |
self.assertRaises( |
| 658 |
TypeError, |
| 659 |
surrogateescape_errors, |
| 660 |
UnicodeTranslateError("\udc80", 0, 1, "ouch") |
| 661 |
) |
| 662 |
# Use the correct exception |
| 663 |
for s in ("a", "\udc7f", "\udd00"): |
| 664 |
with self.subTest(str=s): |
| 665 |
self.assertRaises( |
| 666 |
UnicodeEncodeError, |
| 667 |
surrogateescape_errors, |
| 668 |
UnicodeEncodeError("ascii", s, 0, 1, "ouch") |
| 669 |
) |
| 670 |
self.assertEqual( |
| 671 |
surrogateescape_errors( |
| 672 |
UnicodeEncodeError("ascii", "a\udc80b", 1, 2, "ouch")), |
| 673 |
(b"\x80", 2) |
| 674 |
) |
| 675 |
self.assertRaises( |
| 676 |
UnicodeDecodeError, |
| 677 |
surrogateescape_errors, |
| 678 |
UnicodeDecodeError("ascii", bytearray(b"a"), 0, 1, "ouch") |
| 679 |
) |
| 680 |
self.assertEqual( |
| 681 |
surrogateescape_errors( |
| 682 |
UnicodeDecodeError("ascii", bytearray(b"a\x80b"), 1, 2, "ouch")), |
| 683 |
("\udc80", 2) |
| 684 |
) |
| 685 |
|
| 686 |
def test_badandgoodsurrogatepassexceptions(self): |
| 687 |
surrogatepass_errors = codecs.lookup_error('surrogatepass') |
| 688 |
# "surrogatepass" complains about a non-exception passed in |
| 689 |
self.assertRaises( |
| 690 |
TypeError, |
| 691 |
surrogatepass_errors, |
| 692 |
42 |
| 693 |
) |
| 694 |
# "surrogatepass" complains about the wrong exception types |
| 695 |
self.assertRaises( |
| 696 |
TypeError, |
| 697 |
surrogatepass_errors, |
| 698 |
UnicodeError("ouch") |
| 699 |
) |
| 700 |
# "surrogatepass" can not be used for translating |
| 701 |
self.assertRaises( |
| 702 |
TypeError, |
| 703 |
surrogatepass_errors, |
| 704 |
UnicodeTranslateError("\ud800", 0, 1, "ouch") |
| 705 |
) |
| 706 |
# Use the correct exception |
| 707 |
for enc in ("utf-8", "utf-16le", "utf-16be", "utf-32le", "utf-32be"): |
| 708 |
with self.subTest(encoding=enc): |
| 709 |
self.assertRaises( |
| 710 |
UnicodeEncodeError, |
| 711 |
surrogatepass_errors, |
| 712 |
UnicodeEncodeError(enc, "a", 0, 1, "ouch") |
| 713 |
) |
| 714 |
self.assertRaises( |
| 715 |
UnicodeDecodeError, |
| 716 |
surrogatepass_errors, |
| 717 |
UnicodeDecodeError(enc, "a".encode(enc), 0, 1, "ouch") |
| 718 |
) |
| 719 |
for s in ("\ud800", "\udfff", "\ud800\udfff"): |
| 720 |
with self.subTest(str=s): |
| 721 |
self.assertRaises( |
| 722 |
UnicodeEncodeError, |
| 723 |
surrogatepass_errors, |
| 724 |
UnicodeEncodeError("ascii", s, 0, len(s), "ouch") |
| 725 |
) |
| 726 |
tests = [ |
| 727 |
("utf-8", "\ud800", b'\xed\xa0\x80', 3), |
| 728 |
("utf-16le", "\ud800", b'\x00\xd8', 2), |
| 729 |
("utf-16be", "\ud800", b'\xd8\x00', 2), |
| 730 |
("utf-32le", "\ud800", b'\x00\xd8\x00\x00', 4), |
| 731 |
("utf-32be", "\ud800", b'\x00\x00\xd8\x00', 4), |
| 732 |
("utf-8", "\udfff", b'\xed\xbf\xbf', 3), |
| 733 |
("utf-16le", "\udfff", b'\xff\xdf', 2), |
| 734 |
("utf-16be", "\udfff", b'\xdf\xff', 2), |
| 735 |
("utf-32le", "\udfff", b'\xff\xdf\x00\x00', 4), |
| 736 |
("utf-32be", "\udfff", b'\x00\x00\xdf\xff', 4), |
| 737 |
("utf-8", "\ud800\udfff", b'\xed\xa0\x80\xed\xbf\xbf', 3), |
| 738 |
("utf-16le", "\ud800\udfff", b'\x00\xd8\xff\xdf', 2), |
| 739 |
("utf-16be", "\ud800\udfff", b'\xd8\x00\xdf\xff', 2), |
| 740 |
("utf-32le", "\ud800\udfff", b'\x00\xd8\x00\x00\xff\xdf\x00\x00', 4), |
| 741 |
("utf-32be", "\ud800\udfff", b'\x00\x00\xd8\x00\x00\x00\xdf\xff', 4), |
| 742 |
] |
| 743 |
for enc, s, b, n in tests: |
| 744 |
with self.subTest(encoding=enc, str=s, bytes=b): |
| 745 |
self.assertEqual( |
| 746 |
surrogatepass_errors( |
| 747 |
UnicodeEncodeError(enc, "a" + s + "b", |
| 748 |
1, 1 + len(s), "ouch")), |
| 749 |
(b, 1 + len(s)) |
| 750 |
) |
| 751 |
self.assertEqual( |
| 752 |
surrogatepass_errors( |
| 753 |
UnicodeDecodeError(enc, bytearray(b"a" + b[:n] + b"b"), |
| 754 |
1, 1 + n, "ouch")), |
| 755 |
(s[:1], 1 + n) |
| 756 |
) |
| 757 |
|
| 758 |
def test_badhandlerresults(self): |
| 759 |
results = ( 42, "foo", (1,2,3), ("foo", 1, 3), ("foo", None), ("foo",), ("foo", 1, 3), ("foo", None), ("foo",) ) |
| 760 |
encs = ("ascii", "latin-1", "iso-8859-1", "iso-8859-15") |
| 761 |
|
| 762 |
for res in results: |
| 763 |
codecs.register_error("test.badhandler", lambda x: res) |
| 764 |
for enc in encs: |
| 765 |
self.assertRaises( |
| 766 |
TypeError, |
| 767 |
"\u3042".encode, |
| 768 |
enc, |
| 769 |
"test.badhandler" |
| 770 |
) |
| 771 |
for (enc, bytes) in ( |
| 772 |
("ascii", b"\xff"), |
| 773 |
("utf-8", b"\xff"), |
| 774 |
("utf-7", b"+x-"), |
| 775 |
): |
| 776 |
self.assertRaises( |
| 777 |
TypeError, |
| 778 |
bytes.decode, |
| 779 |
enc, |
| 780 |
"test.badhandler" |
| 781 |
) |
| 782 |
|
| 783 |
def test_lookup(self): |
| 784 |
self.assertEqual(codecs.strict_errors, codecs.lookup_error("strict")) |
| 785 |
self.assertEqual(codecs.ignore_errors, codecs.lookup_error("ignore")) |
| 786 |
self.assertEqual(codecs.strict_errors, codecs.lookup_error("strict")) |
| 787 |
self.assertEqual( |
| 788 |
codecs.xmlcharrefreplace_errors, |
| 789 |
codecs.lookup_error("xmlcharrefreplace") |
| 790 |
) |
| 791 |
self.assertEqual( |
| 792 |
codecs.backslashreplace_errors, |
| 793 |
codecs.lookup_error("backslashreplace") |
| 794 |
) |
| 795 |
self.assertEqual( |
| 796 |
codecs.namereplace_errors, |
| 797 |
codecs.lookup_error("namereplace") |
| 798 |
) |
| 799 |
|
| 800 |
def test_encode_nonascii_replacement(self): |
| 801 |
def handle(exc): |
| 802 |
if isinstance(exc, UnicodeEncodeError): |
| 803 |
return (repl, exc.end) |
| 804 |
raise TypeError("don't know how to handle %r" % exc) |
| 805 |
codecs.register_error("test.replacing", handle) |
| 806 |
|
| 807 |
for enc, input, repl in ( |
| 808 |
("ascii", "[¤]", "abc"), |
| 809 |
("iso-8859-1", "[€]", "½¾"), |
| 810 |
("iso-8859-15", "[¤]", "œŸ"), |
| 811 |
): |
| 812 |
res = input.encode(enc, "test.replacing") |
| 813 |
self.assertEqual(res, ("[" + repl + "]").encode(enc)) |
| 814 |
|
| 815 |
for enc, input, repl in ( |
| 816 |
("utf-8", "[\udc80]", "\U0001f40d"), |
| 817 |
("utf-16", "[\udc80]", "\U0001f40d"), |
| 818 |
("utf-32", "[\udc80]", "\U0001f40d"), |
| 819 |
): |
| 820 |
with self.subTest(encoding=enc): |
| 821 |
with self.assertRaises(UnicodeEncodeError) as cm: |
| 822 |
input.encode(enc, "test.replacing") |
| 823 |
exc = cm.exception |
| 824 |
self.assertEqual(exc.start, 1) |
| 825 |
self.assertEqual(exc.end, 2) |
| 826 |
self.assertEqual(exc.object, input) |
| 827 |
|
| 828 |
def test_encode_unencodable_replacement(self): |
| 829 |
def unencrepl(exc): |
| 830 |
if isinstance(exc, UnicodeEncodeError): |
| 831 |
return (repl, exc.end) |
| 832 |
else: |
| 833 |
raise TypeError("don't know how to handle %r" % exc) |
| 834 |
codecs.register_error("test.unencreplhandler", unencrepl) |
| 835 |
|
| 836 |
for enc, input, repl in ( |
| 837 |
("ascii", "[¤]", "½"), |
| 838 |
("iso-8859-1", "[€]", "œ"), |
| 839 |
("iso-8859-15", "[¤]", "½"), |
| 840 |
("utf-8", "[\udc80]", "\udcff"), |
| 841 |
("utf-16", "[\udc80]", "\udcff"), |
| 842 |
("utf-32", "[\udc80]", "\udcff"), |
| 843 |
): |
| 844 |
with self.subTest(encoding=enc): |
| 845 |
with self.assertRaises(UnicodeEncodeError) as cm: |
| 846 |
input.encode(enc, "test.unencreplhandler") |
| 847 |
exc = cm.exception |
| 848 |
self.assertEqual(exc.start, 1) |
| 849 |
self.assertEqual(exc.end, 2) |
| 850 |
self.assertEqual(exc.object, input) |
| 851 |
|
| 852 |
def test_encode_bytes_replacement(self): |
| 853 |
def handle(exc): |
| 854 |
if isinstance(exc, UnicodeEncodeError): |
| 855 |
return (repl, exc.end) |
| 856 |
raise TypeError("don't know how to handle %r" % exc) |
| 857 |
codecs.register_error("test.replacing", handle) |
| 858 |
|
| 859 |
# It works even if the bytes sequence is not decodable. |
| 860 |
for enc, input, repl in ( |
| 861 |
("ascii", "[¤]", b"\xbd\xbe"), |
| 862 |
("iso-8859-1", "[€]", b"\xbd\xbe"), |
| 863 |
("iso-8859-15", "[¤]", b"\xbd\xbe"), |
| 864 |
("utf-8", "[\udc80]", b"\xbd\xbe"), |
| 865 |
("utf-16le", "[\udc80]", b"\xbd\xbe"), |
| 866 |
("utf-16be", "[\udc80]", b"\xbd\xbe"), |
| 867 |
("utf-32le", "[\udc80]", b"\xbc\xbd\xbe\xbf"), |
| 868 |
("utf-32be", "[\udc80]", b"\xbc\xbd\xbe\xbf"), |
| 869 |
): |
| 870 |
with self.subTest(encoding=enc): |
| 871 |
res = input.encode(enc, "test.replacing") |
| 872 |
self.assertEqual(res, "[".encode(enc) + repl + "]".encode(enc)) |
| 873 |
|
| 874 |
def test_encode_odd_bytes_replacement(self): |
| 875 |
def handle(exc): |
| 876 |
if isinstance(exc, UnicodeEncodeError): |
| 877 |
return (repl, exc.end) |
| 878 |
raise TypeError("don't know how to handle %r" % exc) |
| 879 |
codecs.register_error("test.replacing", handle) |
| 880 |
|
| 881 |
input = "[\udc80]" |
| 882 |
# Tests in which the replacement bytestring contains not whole number |
| 883 |
# of code units. |
| 884 |
for enc, repl in ( |
| 885 |
*itertools.product(("utf-16le", "utf-16be"), |
| 886 |
[b"a", b"abc"]), |
| 887 |
*itertools.product(("utf-32le", "utf-32be"), |
| 888 |
[b"a", b"ab", b"abc", b"abcde"]), |
| 889 |
): |
| 890 |
with self.subTest(encoding=enc, repl=repl): |
| 891 |
with self.assertRaises(UnicodeEncodeError) as cm: |
| 892 |
input.encode(enc, "test.replacing") |
| 893 |
exc = cm.exception |
| 894 |
self.assertEqual(exc.start, 1) |
| 895 |
self.assertEqual(exc.end, 2) |
| 896 |
self.assertEqual(exc.object, input) |
| 897 |
self.assertEqual(exc.reason, "surrogates not allowed") |
| 898 |
|
| 899 |
def test_badregistercall(self): |
| 900 |
# enhance coverage of: |
| 901 |
# Modules/_codecsmodule.c::register_error() |
| 902 |
# Python/codecs.c::PyCodec_RegisterError() |
| 903 |
self.assertRaises(TypeError, codecs.register_error, 42) |
| 904 |
self.assertRaises(TypeError, codecs.register_error, "test.dummy", 42) |
| 905 |
|
| 906 |
def test_badlookupcall(self): |
| 907 |
# enhance coverage of: |
| 908 |
# Modules/_codecsmodule.c::lookup_error() |
| 909 |
self.assertRaises(TypeError, codecs.lookup_error) |
| 910 |
|
| 911 |
def test_unknownhandler(self): |
| 912 |
# enhance coverage of: |
| 913 |
# Modules/_codecsmodule.c::lookup_error() |
| 914 |
self.assertRaises(LookupError, codecs.lookup_error, "test.unknown") |
| 915 |
|
| 916 |
def test_xmlcharrefvalues(self): |
| 917 |
# enhance coverage of: |
| 918 |
# Python/codecs.c::PyCodec_XMLCharRefReplaceErrors() |
| 919 |
# and inline implementations |
| 920 |
v = (1, 5, 10, 50, 100, 500, 1000, 5000, 10000, 50000, 100000, |
| 921 |
500000, 1000000) |
| 922 |
s = "".join([chr(x) for x in v]) |
| 923 |
codecs.register_error("test.xmlcharrefreplace", codecs.xmlcharrefreplace_errors) |
| 924 |
for enc in ("ascii", "iso-8859-15"): |
| 925 |
for err in ("xmlcharrefreplace", "test.xmlcharrefreplace"): |
| 926 |
s.encode(enc, err) |
| 927 |
|
| 928 |
def test_decodehelper(self): |
| 929 |
# enhance coverage of: |
| 930 |
# Objects/unicodeobject.c::unicode_decode_call_errorhandler() |
| 931 |
# and callers |
| 932 |
self.assertRaises(LookupError, b"\xff".decode, "ascii", "test.unknown") |
| 933 |
|
| 934 |
def baddecodereturn1(exc): |
| 935 |
return 42 |
| 936 |
codecs.register_error("test.baddecodereturn1", baddecodereturn1) |
| 937 |
self.assertRaises(TypeError, b"\xff".decode, "ascii", "test.baddecodereturn1") |
| 938 |
self.assertRaises(TypeError, b"\\".decode, "unicode-escape", "test.baddecodereturn1") |
| 939 |
self.assertRaises(TypeError, b"\\x0".decode, "unicode-escape", "test.baddecodereturn1") |
| 940 |
self.assertRaises(TypeError, b"\\x0y".decode, "unicode-escape", "test.baddecodereturn1") |
| 941 |
self.assertRaises(TypeError, b"\\Uffffeeee".decode, "unicode-escape", "test.baddecodereturn1") |
| 942 |
self.assertRaises(TypeError, b"\\uyyyy".decode, "raw-unicode-escape", "test.baddecodereturn1") |
| 943 |
|
| 944 |
def baddecodereturn2(exc): |
| 945 |
return ("?", None) |
| 946 |
codecs.register_error("test.baddecodereturn2", baddecodereturn2) |
| 947 |
self.assertRaises(TypeError, b"\xff".decode, "ascii", "test.baddecodereturn2") |
| 948 |
|
| 949 |
handler = PosReturn() |
| 950 |
codecs.register_error("test.posreturn", handler.handle) |
| 951 |
|
| 952 |
# Valid negative position |
| 953 |
handler.pos = -1 |
| 954 |
self.assertEqual(b"\xff0".decode("ascii", "test.posreturn"), "<?>0") |
| 955 |
|
| 956 |
# Valid negative position |
| 957 |
handler.pos = -2 |
| 958 |
self.assertEqual(b"\xff0".decode("ascii", "test.posreturn"), "<?><?>") |
| 959 |
|
| 960 |
# Negative position out of bounds |
| 961 |
handler.pos = -3 |
| 962 |
self.assertRaises(IndexError, b"\xff0".decode, "ascii", "test.posreturn") |
| 963 |
|
| 964 |
# Valid positive position |
| 965 |
handler.pos = 1 |
| 966 |
self.assertEqual(b"\xff0".decode("ascii", "test.posreturn"), "<?>0") |
| 967 |
|
| 968 |
# Largest valid positive position (one beyond end of input) |
| 969 |
handler.pos = 2 |
| 970 |
self.assertEqual(b"\xff0".decode("ascii", "test.posreturn"), "<?>") |
| 971 |
|
| 972 |
# Invalid positive position |
| 973 |
handler.pos = 3 |
| 974 |
self.assertRaises(IndexError, b"\xff0".decode, "ascii", "test.posreturn") |
| 975 |
|
| 976 |
# Restart at the "0" |
| 977 |
handler.pos = 6 |
| 978 |
self.assertEqual(b"\\uyyyy0".decode("raw-unicode-escape", "test.posreturn"), "<?>0") |
| 979 |
|
| 980 |
class D(dict): |
| 981 |
def __getitem__(self, key): |
| 982 |
raise ValueError |
| 983 |
self.assertRaises(UnicodeError, codecs.charmap_decode, b"\xff", "strict", {0xff: None}) |
| 984 |
self.assertRaises(ValueError, codecs.charmap_decode, b"\xff", "strict", D()) |
| 985 |
self.assertRaises(TypeError, codecs.charmap_decode, b"\xff", "strict", {0xff: sys.maxunicode+1}) |
| 986 |
|
| 987 |
def test_encodehelper(self): |
| 988 |
# enhance coverage of: |
| 989 |
# Objects/unicodeobject.c::unicode_encode_call_errorhandler() |
| 990 |
# and callers |
| 991 |
self.assertRaises(LookupError, "\xff".encode, "ascii", "test.unknown") |
| 992 |
|
| 993 |
def badencodereturn1(exc): |
| 994 |
return 42 |
| 995 |
codecs.register_error("test.badencodereturn1", badencodereturn1) |
| 996 |
self.assertRaises(TypeError, "\xff".encode, "ascii", "test.badencodereturn1") |
| 997 |
|
| 998 |
def badencodereturn2(exc): |
| 999 |
return ("?", None) |
| 1000 |
codecs.register_error("test.badencodereturn2", badencodereturn2) |
| 1001 |
self.assertRaises(TypeError, "\xff".encode, "ascii", "test.badencodereturn2") |
| 1002 |
|
| 1003 |
handler = PosReturn() |
| 1004 |
codecs.register_error("test.posreturn", handler.handle) |
| 1005 |
|
| 1006 |
# Valid negative position |
| 1007 |
handler.pos = -1 |
| 1008 |
self.assertEqual("\xff0".encode("ascii", "test.posreturn"), b"<?>0") |
| 1009 |
|
| 1010 |
# Valid negative position |
| 1011 |
handler.pos = -2 |
| 1012 |
self.assertEqual("\xff0".encode("ascii", "test.posreturn"), b"<?><?>") |
| 1013 |
|
| 1014 |
# Negative position out of bounds |
| 1015 |
handler.pos = -3 |
| 1016 |
self.assertRaises(IndexError, "\xff0".encode, "ascii", "test.posreturn") |
| 1017 |
|
| 1018 |
# Valid positive position |
| 1019 |
handler.pos = 1 |
| 1020 |
self.assertEqual("\xff0".encode("ascii", "test.posreturn"), b"<?>0") |
| 1021 |
|
| 1022 |
# Largest valid positive position (one beyond end of input |
| 1023 |
handler.pos = 2 |
| 1024 |
self.assertEqual("\xff0".encode("ascii", "test.posreturn"), b"<?>") |
| 1025 |
|
| 1026 |
# Invalid positive position |
| 1027 |
handler.pos = 3 |
| 1028 |
self.assertRaises(IndexError, "\xff0".encode, "ascii", "test.posreturn") |
| 1029 |
|
| 1030 |
handler.pos = 0 |
| 1031 |
|
| 1032 |
class D(dict): |
| 1033 |
def __getitem__(self, key): |
| 1034 |
raise ValueError |
| 1035 |
for err in ("strict", "replace", "xmlcharrefreplace", |
| 1036 |
"backslashreplace", "namereplace", "test.posreturn"): |
| 1037 |
self.assertRaises(UnicodeError, codecs.charmap_encode, "\xff", err, {0xff: None}) |
| 1038 |
self.assertRaises(ValueError, codecs.charmap_encode, "\xff", err, D()) |
| 1039 |
self.assertRaises(TypeError, codecs.charmap_encode, "\xff", err, {0xff: 300}) |
| 1040 |
|
| 1041 |
def test_decodehelper_bug36819(self): |
| 1042 |
handler = RepeatedPosReturn("x") |
| 1043 |
codecs.register_error("test.bug36819", handler.handle) |
| 1044 |
|
| 1045 |
testcases = [ |
| 1046 |
("ascii", b"\xff"), |
| 1047 |
("utf-8", b"\xff"), |
| 1048 |
("utf-16be", b'\xdc\x80'), |
| 1049 |
("utf-32be", b'\x00\x00\xdc\x80'), |
| 1050 |
("iso-8859-6", b"\xff"), |
| 1051 |
] |
| 1052 |
for enc, bad in testcases: |
| 1053 |
input = "abcd".encode(enc) + bad |
| 1054 |
with self.subTest(encoding=enc): |
| 1055 |
handler.count = 50 |
| 1056 |
decoded = input.decode(enc, "test.bug36819") |
| 1057 |
self.assertEqual(decoded, 'abcdx' * 51) |
| 1058 |
|
| 1059 |
def test_encodehelper_bug36819(self): |
| 1060 |
handler = RepeatedPosReturn() |
| 1061 |
codecs.register_error("test.bug36819", handler.handle) |
| 1062 |
|
| 1063 |
input = "abcd\udc80" |
| 1064 |
encodings = ["ascii", "latin1", "utf-8", "utf-16", "utf-32"] # built-in |
| 1065 |
encodings += ["iso-8859-15"] # charmap codec |
| 1066 |
if sys.platform == 'win32': |
| 1067 |
encodings = ["mbcs", "oem"] # code page codecs |
| 1068 |
|
| 1069 |
handler.repl = "\udcff" |
| 1070 |
for enc in encodings: |
| 1071 |
with self.subTest(encoding=enc): |
| 1072 |
handler.count = 50 |
| 1073 |
with self.assertRaises(UnicodeEncodeError) as cm: |
| 1074 |
input.encode(enc, "test.bug36819") |
| 1075 |
exc = cm.exception |
| 1076 |
self.assertEqual(exc.start, 4) |
| 1077 |
self.assertEqual(exc.end, 5) |
| 1078 |
self.assertEqual(exc.object, input) |
| 1079 |
if sys.platform == "win32": |
| 1080 |
handler.count = 50 |
| 1081 |
with self.assertRaises(UnicodeEncodeError) as cm: |
| 1082 |
codecs.code_page_encode(437, input, "test.bug36819") |
| 1083 |
exc = cm.exception |
| 1084 |
self.assertEqual(exc.start, 4) |
| 1085 |
self.assertEqual(exc.end, 5) |
| 1086 |
self.assertEqual(exc.object, input) |
| 1087 |
|
| 1088 |
handler.repl = "x" |
| 1089 |
for enc in encodings: |
| 1090 |
with self.subTest(encoding=enc): |
| 1091 |
# The interpreter should segfault after a handful of attempts. |
| 1092 |
# 50 was chosen to try to ensure a segfault without a fix, |
| 1093 |
# but not OOM a machine with one. |
| 1094 |
handler.count = 50 |
| 1095 |
encoded = input.encode(enc, "test.bug36819") |
| 1096 |
self.assertEqual(encoded.decode(enc), "abcdx" * 51) |
| 1097 |
if sys.platform == "win32": |
| 1098 |
handler.count = 50 |
| 1099 |
encoded = codecs.code_page_encode(437, input, "test.bug36819") |
| 1100 |
self.assertEqual(encoded[0].decode(), "abcdx" * 51) |
| 1101 |
self.assertEqual(encoded[1], len(input)) |
| 1102 |
|
| 1103 |
def test_translatehelper(self): |
| 1104 |
# enhance coverage of: |
| 1105 |
# Objects/unicodeobject.c::unicode_encode_call_errorhandler() |
| 1106 |
# and callers |
| 1107 |
# (Unfortunately the errors argument is not directly accessible |
| 1108 |
# from Python, so we can't test that much) |
| 1109 |
class D(dict): |
| 1110 |
def __getitem__(self, key): |
| 1111 |
raise ValueError |
| 1112 |
#self.assertRaises(ValueError, "\xff".translate, D()) |
| 1113 |
self.assertRaises(ValueError, "\xff".translate, {0xff: sys.maxunicode+1}) |
| 1114 |
self.assertRaises(TypeError, "\xff".translate, {0xff: ()}) |
| 1115 |
|
| 1116 |
def test_bug828737(self): |
| 1117 |
charmap = { |
| 1118 |
ord("&"): "&", |
| 1119 |
ord("<"): "<", |
| 1120 |
ord(">"): ">", |
| 1121 |
ord('"'): """, |
| 1122 |
} |
| 1123 |
|
| 1124 |
for n in (1, 10, 100, 1000): |
| 1125 |
text = 'abc<def>ghi'*n |
| 1126 |
text.translate(charmap) |
| 1127 |
|
| 1128 |
def test_mutating_decode_handler(self): |
| 1129 |
baddata = [ |
| 1130 |
("ascii", b"\xff"), |
| 1131 |
("utf-7", b"++"), |
| 1132 |
("utf-8", b"\xff"), |
| 1133 |
("utf-16", b"\xff"), |
| 1134 |
("utf-32", b"\xff"), |
| 1135 |
("unicode-escape", b"\\u123g"), |
| 1136 |
("raw-unicode-escape", b"\\u123g"), |
| 1137 |
] |
| 1138 |
|
| 1139 |
def replacing(exc): |
| 1140 |
if isinstance(exc, UnicodeDecodeError): |
| 1141 |
exc.object = 42 |
| 1142 |
return ("\u4242", 0) |
| 1143 |
else: |
| 1144 |
raise TypeError("don't know how to handle %r" % exc) |
| 1145 |
codecs.register_error("test.replacing", replacing) |
| 1146 |
|
| 1147 |
for (encoding, data) in baddata: |
| 1148 |
with self.assertRaises(TypeError): |
| 1149 |
data.decode(encoding, "test.replacing") |
| 1150 |
|
| 1151 |
def mutating(exc): |
| 1152 |
if isinstance(exc, UnicodeDecodeError): |
| 1153 |
exc.object = b"" |
| 1154 |
return ("\u4242", 0) |
| 1155 |
else: |
| 1156 |
raise TypeError("don't know how to handle %r" % exc) |
| 1157 |
codecs.register_error("test.mutating", mutating) |
| 1158 |
# If the decoder doesn't pick up the modified input the following |
| 1159 |
# will lead to an endless loop |
| 1160 |
for (encoding, data) in baddata: |
| 1161 |
self.assertEqual(data.decode(encoding, "test.mutating"), "\u4242") |
| 1162 |
|
| 1163 |
def test_mutating_decode_handler_unicode_escape(self): |
| 1164 |
decode = codecs.unicode_escape_decode |
| 1165 |
def mutating(exc): |
| 1166 |
if isinstance(exc, UnicodeDecodeError): |
| 1167 |
r = data.get(exc.object[:exc.end]) |
| 1168 |
if r is not None: |
| 1169 |
exc.object = r[0] + exc.object[exc.end:] |
| 1170 |
return ('\u0404', r[1]) |
| 1171 |
raise AssertionError("don't know how to handle %r" % exc) |
| 1172 |
|
| 1173 |
codecs.register_error('test.mutating2', mutating) |
| 1174 |
data = { |
| 1175 |
br'\x0': (b'\\', 0), |
| 1176 |
br'\x3': (b'xxx\\', 3), |
| 1177 |
br'\x5': (b'x\\', 1), |
| 1178 |
} |
| 1179 |
def check(input, expected, msg): |
| 1180 |
with self.assertWarns(DeprecationWarning) as cm: |
| 1181 |
self.assertEqual(decode(input, 'test.mutating2'), (expected, len(input))) |
| 1182 |
self.assertIn(msg, str(cm.warning)) |
| 1183 |
|
| 1184 |
check(br'\x0n\z', '\u0404\n\\z', r"invalid escape sequence '\z'") |
| 1185 |
check(br'\x0n\501', '\u0404\n\u0141', r"invalid octal escape sequence '\501'") |
| 1186 |
check(br'\x0z', '\u0404\\z', r"invalid escape sequence '\z'") |
| 1187 |
|
| 1188 |
check(br'\x3n\zr', '\u0404\n\\zr', r"invalid escape sequence '\z'") |
| 1189 |
check(br'\x3zr', '\u0404\\zr', r"invalid escape sequence '\z'") |
| 1190 |
check(br'\x3z5', '\u0404\\z5', r"invalid escape sequence '\z'") |
| 1191 |
check(memoryview(br'\x3z5x')[:-1], '\u0404\\z5', r"invalid escape sequence '\z'") |
| 1192 |
check(memoryview(br'\x3z5xy')[:-2], '\u0404\\z5', r"invalid escape sequence '\z'") |
| 1193 |
|
| 1194 |
check(br'\x5n\z', '\u0404\n\\z', r"invalid escape sequence '\z'") |
| 1195 |
check(br'\x5n\501', '\u0404\n\u0141', r"invalid octal escape sequence '\501'") |
| 1196 |
check(br'\x5z', '\u0404\\z', r"invalid escape sequence '\z'") |
| 1197 |
check(memoryview(br'\x5zy')[:-1], '\u0404\\z', r"invalid escape sequence '\z'") |
| 1198 |
|
| 1199 |
# issue32583 |
| 1200 |
def test_crashing_decode_handler(self): |
| 1201 |
# better generating one more character to fill the extra space slot |
| 1202 |
# so in debug build it can steadily fail |
| 1203 |
def forward_shorter_than_end(exc): |
| 1204 |
if isinstance(exc, UnicodeDecodeError): |
| 1205 |
# size one character, 0 < forward < exc.end |
| 1206 |
return ('\ufffd', exc.start+1) |
| 1207 |
else: |
| 1208 |
raise TypeError("don't know how to handle %r" % exc) |
| 1209 |
codecs.register_error( |
| 1210 |
"test.forward_shorter_than_end", forward_shorter_than_end) |
| 1211 |
|
| 1212 |
self.assertEqual( |
| 1213 |
b'\xd8\xd8\xd8\xd8\xd8\x00\x00\x00'.decode( |
| 1214 |
'utf-16-le', 'test.forward_shorter_than_end'), |
| 1215 |
'\ufffd\ufffd\ufffd\ufffd\xd8\x00' |
| 1216 |
) |
| 1217 |
self.assertEqual( |
| 1218 |
b'\xd8\xd8\xd8\xd8\x00\xd8\x00\x00'.decode( |
| 1219 |
'utf-16-be', 'test.forward_shorter_than_end'), |
| 1220 |
'\ufffd\ufffd\ufffd\ufffd\xd8\x00' |
| 1221 |
) |
| 1222 |
self.assertEqual( |
| 1223 |
b'\x11\x11\x11\x11\x11\x00\x00\x00\x00\x00\x00'.decode( |
| 1224 |
'utf-32-le', 'test.forward_shorter_than_end'), |
| 1225 |
'\ufffd\ufffd\ufffd\u1111\x00' |
| 1226 |
) |
| 1227 |
self.assertEqual( |
| 1228 |
b'\x11\x11\x11\x00\x00\x11\x11\x00\x00\x00\x00'.decode( |
| 1229 |
'utf-32-be', 'test.forward_shorter_than_end'), |
| 1230 |
'\ufffd\ufffd\ufffd\u1111\x00' |
| 1231 |
) |
| 1232 |
|
| 1233 |
def replace_with_long(exc): |
| 1234 |
if isinstance(exc, UnicodeDecodeError): |
| 1235 |
exc.object = b"\x00" * 8 |
| 1236 |
return ('\ufffd', exc.start) |
| 1237 |
else: |
| 1238 |
raise TypeError("don't know how to handle %r" % exc) |
| 1239 |
codecs.register_error("test.replace_with_long", replace_with_long) |
| 1240 |
|
| 1241 |
self.assertEqual( |
| 1242 |
b'\x00'.decode('utf-16', 'test.replace_with_long'), |
| 1243 |
'\ufffd\x00\x00\x00\x00' |
| 1244 |
) |
| 1245 |
self.assertEqual( |
| 1246 |
b'\x00'.decode('utf-32', 'test.replace_with_long'), |
| 1247 |
'\ufffd\x00\x00' |
| 1248 |
) |
| 1249 |
|
| 1250 |
|
| 1251 |
def test_fake_error_class(self): |
| 1252 |
handlers = [ |
| 1253 |
codecs.strict_errors, |
| 1254 |
codecs.ignore_errors, |
| 1255 |
codecs.replace_errors, |
| 1256 |
codecs.backslashreplace_errors, |
| 1257 |
codecs.namereplace_errors, |
| 1258 |
codecs.xmlcharrefreplace_errors, |
| 1259 |
codecs.lookup_error('surrogateescape'), |
| 1260 |
codecs.lookup_error('surrogatepass'), |
| 1261 |
] |
| 1262 |
for cls in UnicodeEncodeError, UnicodeDecodeError, UnicodeTranslateError: |
| 1263 |
class FakeUnicodeError(str): |
| 1264 |
__class__ = cls |
| 1265 |
for handler in handlers: |
| 1266 |
with self.subTest(handler=handler, error_class=cls): |
| 1267 |
self.assertRaises(TypeError, handler, FakeUnicodeError()) |
| 1268 |
class FakeUnicodeError(Exception): |
| 1269 |
__class__ = cls |
| 1270 |
for handler in handlers: |
| 1271 |
with self.subTest(handler=handler, error_class=cls): |
| 1272 |
with self.assertRaises((TypeError, FakeUnicodeError)): |
| 1273 |
handler(FakeUnicodeError()) |
| 1274 |
|
| 1275 |
|
| 1276 |
if __name__ == "__main__": |
| 1277 |
unittest.main() |