blob: bf583c25b0b6d22112ffb41f043e156223f4288e [file] [log] [blame]
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001import test.test_support, unittest
2import sys, codecs, htmlentitydefs, unicodedata
3
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004class PosReturn:
5 # this can be used for configurable callbacks
6
7 def __init__(self):
8 self.pos = 0
9
10 def handle(self, exc):
11 oldpos = self.pos
12 realpos = oldpos
13 if realpos<0:
14 realpos = len(exc.object) + realpos
15 # if we don't advance this time, terminate on the next call
16 # otherwise we'd get an endless loop
17 if realpos <= exc.start:
18 self.pos = len(exc.object)
19 return (u"<?>", oldpos)
20
Walter Dörwald3aeb6322002-09-02 13:14:32 +000021class CodecCallbackTest(unittest.TestCase):
22
23 def test_xmlcharrefreplace(self):
24 # replace unencodable characters which numeric character entities.
25 # For ascii, latin-1 and charmaps this is completely implemented
26 # in C and should be reasonably fast.
27 s = u"\u30b9\u30d1\u30e2 \xe4nd eggs"
28 self.assertEqual(
29 s.encode("ascii", "xmlcharrefreplace"),
30 "&#12473;&#12497;&#12514; &#228;nd eggs"
31 )
32 self.assertEqual(
33 s.encode("latin-1", "xmlcharrefreplace"),
34 "&#12473;&#12497;&#12514; \xe4nd eggs"
35 )
36
37 def test_xmlcharnamereplace(self):
38 # This time use a named character entity for unencodable
39 # characters, if one is available.
40 names = {}
41 for (key, value) in htmlentitydefs.entitydefs.items():
42 if len(value)==1:
43 names[unicode(value, "latin-1")] = unicode(key, "latin-1")
44 else:
45 names[unichr(int(value[2:-1]))] = unicode(key, "latin-1")
46
47 def xmlcharnamereplace(exc):
48 if not isinstance(exc, UnicodeEncodeError):
49 raise TypeError("don't know how to handle %r" % exc)
50 l = []
51 for c in exc.object[exc.start:exc.end]:
52 try:
53 l.append(u"&%s;" % names[c])
54 except KeyError:
55 l.append(u"&#%d;" % ord(c))
56 return (u"".join(l), exc.end)
57
58 codecs.register_error(
59 "test.xmlcharnamereplace", xmlcharnamereplace)
60
61 sin = u"\xab\u211c\xbb = \u2329\u1234\u20ac\u232a"
62 sout = "&laquo;&real;&raquo; = &lang;&#4660;&euro;&rang;"
63 self.assertEqual(sin.encode("ascii", "test.xmlcharnamereplace"), sout)
64 sout = "\xab&real;\xbb = &lang;&#4660;&euro;&rang;"
65 self.assertEqual(sin.encode("latin-1", "test.xmlcharnamereplace"), sout)
66 sout = "\xab&real;\xbb = &lang;&#4660;\xa4&rang;"
67 self.assertEqual(sin.encode("iso-8859-15", "test.xmlcharnamereplace"), sout)
68
69 def test_uninamereplace(self):
70 # We're using the names from the unicode database this time,
Walter Dörwald00445d22002-11-25 17:58:02 +000071 # and we're doing "syntax highlighting" here, i.e. we include
Walter Dörwald3aeb6322002-09-02 13:14:32 +000072 # the replaced text in ANSI escape sequences. For this it is
73 # useful that the error handler is not called for every single
74 # unencodable character, but for a complete sequence of
75 # unencodable characters, otherwise we would output many
76 # unneccessary escape sequences.
77
78 def uninamereplace(exc):
79 if not isinstance(exc, UnicodeEncodeError):
80 raise TypeError("don't know how to handle %r" % exc)
81 l = []
82 for c in exc.object[exc.start:exc.end]:
83 l.append(unicodedata.name(c, u"0x%x" % ord(c)))
84 return (u"\033[1m%s\033[0m" % u", ".join(l), exc.end)
85
86 codecs.register_error(
87 "test.uninamereplace", uninamereplace)
88
89 sin = u"\xac\u1234\u20ac\u8000"
Martin v. Löwis74a530d2002-11-23 19:41:01 +000090 sout = "\033[1mNOT SIGN, ETHIOPIC SYLLABLE SEE, EURO SIGN, CJK UNIFIED IDEOGRAPH-8000\033[0m"
Walter Dörwald3aeb6322002-09-02 13:14:32 +000091 self.assertEqual(sin.encode("ascii", "test.uninamereplace"), sout)
92
Martin v. Löwis74a530d2002-11-23 19:41:01 +000093 sout = "\xac\033[1mETHIOPIC SYLLABLE SEE, EURO SIGN, CJK UNIFIED IDEOGRAPH-8000\033[0m"
Walter Dörwald3aeb6322002-09-02 13:14:32 +000094 self.assertEqual(sin.encode("latin-1", "test.uninamereplace"), sout)
95
Martin v. Löwis74a530d2002-11-23 19:41:01 +000096 sout = "\xac\033[1mETHIOPIC SYLLABLE SEE\033[0m\xa4\033[1mCJK UNIFIED IDEOGRAPH-8000\033[0m"
Walter Dörwald3aeb6322002-09-02 13:14:32 +000097 self.assertEqual(sin.encode("iso-8859-15", "test.uninamereplace"), sout)
98
99 def test_backslashescape(self):
100 # Does the same as the "unicode-escape" encoding, but with different
101 # base encodings.
102 sin = u"a\xac\u1234\u20ac\u8000"
103 if sys.maxunicode > 0xffff:
104 sin += unichr(sys.maxunicode)
105 sout = "a\\xac\\u1234\\u20ac\\u8000"
106 if sys.maxunicode > 0xffff:
107 sout += "\\U%08x" % sys.maxunicode
108 self.assertEqual(sin.encode("ascii", "backslashreplace"), sout)
109
110 sout = "a\xac\\u1234\\u20ac\\u8000"
111 if sys.maxunicode > 0xffff:
112 sout += "\\U%08x" % sys.maxunicode
113 self.assertEqual(sin.encode("latin-1", "backslashreplace"), sout)
114
115 sout = "a\xac\\u1234\xa4\\u8000"
116 if sys.maxunicode > 0xffff:
117 sout += "\\U%08x" % sys.maxunicode
118 self.assertEqual(sin.encode("iso-8859-15", "backslashreplace"), sout)
119
120 def test_relaxedutf8(self):
121 # This is the test for a decoding callback handler,
122 # that relaxes the UTF-8 minimal encoding restriction.
123 # A null byte that is encoded as "\xc0\x80" will be
124 # decoded as a null byte. All other illegal sequences
125 # will be handled strictly.
126 def relaxedutf8(exc):
127 if not isinstance(exc, UnicodeDecodeError):
128 raise TypeError("don't know how to handle %r" % exc)
129 if exc.object[exc.start:exc.end].startswith("\xc0\x80"):
130 return (u"\x00", exc.start+2) # retry after two bytes
131 else:
132 raise exc
133
134 codecs.register_error(
135 "test.relaxedutf8", relaxedutf8)
136
137 sin = "a\x00b\xc0\x80c\xc3\xbc\xc0\x80\xc0\x80"
138 sout = u"a\x00b\x00c\xfc\x00\x00"
139 self.assertEqual(sin.decode("utf-8", "test.relaxedutf8"), sout)
140 sin = "\xc0\x80\xc0\x81"
141 self.assertRaises(UnicodeError, sin.decode, "utf-8", "test.relaxedutf8")
142
143 def test_charmapencode(self):
144 # For charmap encodings the replacement string will be
145 # mapped through the encoding again. This means, that
146 # to be able to use e.g. the "replace" handler, the
147 # charmap has to have a mapping for "?".
148 charmap = dict([ (ord(c), 2*c.upper()) for c in "abcdefgh"])
149 sin = u"abc"
150 sout = "AABBCC"
151 self.assertEquals(codecs.charmap_encode(sin, "strict", charmap)[0], sout)
152
153 sin = u"abcA"
154 self.assertRaises(UnicodeError, codecs.charmap_encode, sin, "strict", charmap)
155
156 charmap[ord("?")] = "XYZ"
157 sin = u"abcDEF"
158 sout = "AABBCCXYZXYZXYZ"
159 self.assertEquals(codecs.charmap_encode(sin, "replace", charmap)[0], sout)
160
161 charmap[ord("?")] = u"XYZ"
162 self.assertRaises(TypeError, codecs.charmap_encode, sin, "replace", charmap)
163
164 charmap[ord("?")] = u"XYZ"
165 self.assertRaises(TypeError, codecs.charmap_encode, sin, "replace", charmap)
166
167 def test_callbacks(self):
168 def handler1(exc):
169 if not isinstance(exc, UnicodeEncodeError) \
170 and not isinstance(exc, UnicodeDecodeError):
171 raise TypeError("don't know how to handle %r" % exc)
172 l = [u"<%d>" % ord(exc.object[pos]) for pos in xrange(exc.start, exc.end)]
173 return (u"[%s]" % u"".join(l), exc.end)
174
175 codecs.register_error("test.handler1", handler1)
176
177 def handler2(exc):
178 if not isinstance(exc, UnicodeDecodeError):
179 raise TypeError("don't know how to handle %r" % exc)
180 l = [u"<%d>" % ord(exc.object[pos]) for pos in xrange(exc.start, exc.end)]
181 return (u"[%s]" % u"".join(l), exc.end+1) # skip one character
182
183 codecs.register_error("test.handler2", handler2)
184
185 s = "\x00\x81\x7f\x80\xff"
186
187 self.assertEqual(
188 s.decode("ascii", "test.handler1"),
189 u"\x00[<129>]\x7f[<128>][<255>]"
190 )
191 self.assertEqual(
192 s.decode("ascii", "test.handler2"),
193 u"\x00[<129>][<128>]"
194 )
195
196 self.assertEqual(
197 "\\u3042\u3xxx".decode("unicode-escape", "test.handler1"),
198 u"\u3042[<92><117><51><120>]xx"
199 )
200
201 self.assertEqual(
202 "\\u3042\u3xx".decode("unicode-escape", "test.handler1"),
203 u"\u3042[<92><117><51><120><120>]"
204 )
205
206 self.assertEqual(
207 codecs.charmap_decode("abc", "test.handler1", {ord("a"): u"z"})[0],
208 u"z[<98>][<99>]"
209 )
210
211 self.assertEqual(
212 u"g\xfc\xdfrk".encode("ascii", "test.handler1"),
213 u"g[<252><223>]rk"
214 )
215
216 self.assertEqual(
217 u"g\xfc\xdf".encode("ascii", "test.handler1"),
218 u"g[<252><223>]"
219 )
220
221 def test_longstrings(self):
222 # test long strings to check for memory overflow problems
223 errors = [ "strict", "ignore", "replace", "xmlcharrefreplace", "backslashreplace"]
224 # register the handlers under different names,
225 # to prevent the codec from recognizing the name
226 for err in errors:
227 codecs.register_error("test." + err, codecs.lookup_error(err))
228 l = 1000
229 errors += [ "test." + err for err in errors ]
230 for uni in [ s*l for s in (u"x", u"\u3042", u"a\xe4") ]:
231 for enc in ("ascii", "latin-1", "iso-8859-1", "iso-8859-15", "utf-8", "utf-7", "utf-16"):
232 for err in errors:
Tim Peters3de75262002-11-09 05:26:15 +0000233 try:
234 uni.encode(enc, err)
235 except UnicodeError:
236 pass
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000237
238 def check_exceptionobjectargs(self, exctype, args, msg):
239 # Test UnicodeError subclasses: construction, attribute assignment and __str__ conversion
240 # check with one missing argument
241 self.assertRaises(TypeError, exctype, *args[:-1])
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000242 # check with one argument too much
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000243 self.assertRaises(TypeError, exctype, *(args + ["too much"]))
244 # check with one argument of the wrong type
245 wrongargs = [ "spam", u"eggs", 42, 1.0, None ]
246 for i in xrange(len(args)):
247 for wrongarg in wrongargs:
248 if type(wrongarg) is type(args[i]):
Tim Peters3de75262002-11-09 05:26:15 +0000249 continue
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000250 # build argument array
251 callargs = []
252 for j in xrange(len(args)):
253 if i==j:
254 callargs.append(wrongarg)
255 else:
256 callargs.append(args[i])
257 self.assertRaises(TypeError, exctype, *callargs)
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000258
259 # check with the correct number and type of arguments
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000260 exc = exctype(*args)
261 self.assertEquals(str(exc), msg)
262
263 def test_unicodeencodeerror(self):
264 self.check_exceptionobjectargs(
265 UnicodeEncodeError,
266 ["ascii", u"g\xfcrk", 1, 2, "ouch"],
267 "'ascii' codec can't encode character '\ufc' in position 1: ouch"
268 )
269 self.check_exceptionobjectargs(
270 UnicodeEncodeError,
271 ["ascii", u"g\xfcrk", 1, 4, "ouch"],
272 "'ascii' codec can't encode characters in position 1-3: ouch"
273 )
274 self.check_exceptionobjectargs(
275 UnicodeEncodeError,
276 ["ascii", u"\xfcx", 0, 1, "ouch"],
277 "'ascii' codec can't encode character '\ufc' in position 0: ouch"
278 )
279
280 def test_unicodedecodeerror(self):
281 self.check_exceptionobjectargs(
282 UnicodeDecodeError,
283 ["ascii", "g\xfcrk", 1, 2, "ouch"],
284 "'ascii' codec can't decode byte 0xfc in position 1: ouch"
285 )
286 self.check_exceptionobjectargs(
287 UnicodeDecodeError,
288 ["ascii", "g\xfcrk", 1, 3, "ouch"],
289 "'ascii' codec can't decode bytes in position 1-2: ouch"
290 )
291
292 def test_unicodetranslateerror(self):
293 self.check_exceptionobjectargs(
294 UnicodeTranslateError,
295 [u"g\xfcrk", 1, 2, "ouch"],
296 "can't translate character '\\ufc' in position 1: ouch"
297 )
298 self.check_exceptionobjectargs(
299 UnicodeTranslateError,
300 [u"g\xfcrk", 1, 3, "ouch"],
301 "can't translate characters in position 1-2: ouch"
302 )
303
304 def test_badandgoodstrictexceptions(self):
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000305 # "strict" complains about a non-exception passed in
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000306 self.assertRaises(
307 TypeError,
308 codecs.strict_errors,
309 42
310 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000311 # "strict" complains about the wrong exception type
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000312 self.assertRaises(
313 Exception,
314 codecs.strict_errors,
315 Exception("ouch")
316 )
317
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000318 # If the correct exception is passed in, "strict" raises it
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000319 self.assertRaises(
320 UnicodeEncodeError,
321 codecs.strict_errors,
322 UnicodeEncodeError("ascii", u"\u3042", 0, 1, "ouch")
323 )
324
325 def test_badandgoodignoreexceptions(self):
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000326 # "ignore" complains about a non-exception passed in
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000327 self.assertRaises(
328 TypeError,
329 codecs.ignore_errors,
330 42
331 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000332 # "ignore" complains about the wrong exception type
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000333 self.assertRaises(
334 TypeError,
335 codecs.ignore_errors,
336 UnicodeError("ouch")
337 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000338 # If the correct exception is passed in, "ignore" returns an empty replacement
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000339 self.assertEquals(
340 codecs.ignore_errors(UnicodeEncodeError("ascii", u"\u3042", 0, 1, "ouch")),
341 (u"", 1)
342 )
343 self.assertEquals(
344 codecs.ignore_errors(UnicodeDecodeError("ascii", "\xff", 0, 1, "ouch")),
345 (u"", 1)
346 )
347 self.assertEquals(
348 codecs.ignore_errors(UnicodeTranslateError(u"\u3042", 0, 1, "ouch")),
349 (u"", 1)
350 )
351
352 def test_badandgoodreplaceexceptions(self):
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000353 # "replace" complains about a non-exception passed in
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000354 self.assertRaises(
355 TypeError,
356 codecs.replace_errors,
357 42
358 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000359 # "replace" complains about the wrong exception type
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000360 self.assertRaises(
361 TypeError,
362 codecs.replace_errors,
363 UnicodeError("ouch")
364 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000365 # With the correct exception, "ignore" returns an empty replacement
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000366 self.assertEquals(
367 codecs.replace_errors(UnicodeEncodeError("ascii", u"\u3042", 0, 1, "ouch")),
368 (u"?", 1)
369 )
370 self.assertEquals(
371 codecs.replace_errors(UnicodeDecodeError("ascii", "\xff", 0, 1, "ouch")),
372 (u"\ufffd", 1)
373 )
374 self.assertEquals(
375 codecs.replace_errors(UnicodeTranslateError(u"\u3042", 0, 1, "ouch")),
376 (u"\ufffd", 1)
377 )
378
379 def test_badandgoodxmlcharrefreplaceexceptions(self):
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000380 # "xmlcharrefreplace" complains about a non-exception passed in
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000381 self.assertRaises(
382 TypeError,
383 codecs.xmlcharrefreplace_errors,
384 42
385 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000386 # "xmlcharrefreplace" complains about the wrong exception types
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000387 self.assertRaises(
388 TypeError,
389 codecs.xmlcharrefreplace_errors,
390 UnicodeError("ouch")
391 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000392 # "xmlcharrefreplace" can only be used for encoding
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000393 self.assertRaises(
394 TypeError,
395 codecs.xmlcharrefreplace_errors,
396 UnicodeDecodeError("ascii", "\xff", 0, 1, "ouch")
397 )
398 self.assertRaises(
399 TypeError,
400 codecs.xmlcharrefreplace_errors,
401 UnicodeTranslateError(u"\u3042", 0, 1, "ouch")
402 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000403 # Use the correct exception
404 self.assertEquals(
405 codecs.xmlcharrefreplace_errors(UnicodeEncodeError("ascii", u"\u3042", 0, 1, "ouch")),
406 (u"&#%d;" % 0x3042, 1)
407 )
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000408
409 def test_badandgoodbackslashreplaceexceptions(self):
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000410 # "backslashreplace" complains about a non-exception passed in
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000411 self.assertRaises(
412 TypeError,
413 codecs.backslashreplace_errors,
414 42
415 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000416 # "backslashreplace" complains about the wrong exception types
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000417 self.assertRaises(
418 TypeError,
419 codecs.backslashreplace_errors,
420 UnicodeError("ouch")
421 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000422 # "backslashreplace" can only be used for encoding
423 self.assertRaises(
424 TypeError,
425 codecs.backslashreplace_errors,
426 UnicodeDecodeError("ascii", "\xff", 0, 1, "ouch")
427 )
428 self.assertRaises(
429 TypeError,
430 codecs.backslashreplace_errors,
431 UnicodeTranslateError(u"\u3042", 0, 1, "ouch")
432 )
433 # Use the correct exception
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000434 self.assertEquals(
435 codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\u3042", 0, 1, "ouch")),
436 (u"\\u3042", 1)
437 )
438 self.assertEquals(
439 codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\x00", 0, 1, "ouch")),
440 (u"\\x00", 1)
441 )
442 self.assertEquals(
443 codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\xff", 0, 1, "ouch")),
444 (u"\\xff", 1)
445 )
446 self.assertEquals(
447 codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\u0100", 0, 1, "ouch")),
448 (u"\\u0100", 1)
449 )
450 self.assertEquals(
451 codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\uffff", 0, 1, "ouch")),
452 (u"\\uffff", 1)
453 )
454 if sys.maxunicode>0xffff:
455 self.assertEquals(
456 codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\U00010000", 0, 1, "ouch")),
457 (u"\\U00010000", 1)
458 )
459 self.assertEquals(
460 codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\U0010ffff", 0, 1, "ouch")),
461 (u"\\U0010ffff", 1)
462 )
463
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000464 def test_badhandlerresults(self):
465 results = ( 42, u"foo", (1,2,3), (u"foo", 1, 3), (u"foo", None), (u"foo",), ("foo", 1, 3), ("foo", None), ("foo",) )
466 encs = ("ascii", "latin-1", "iso-8859-1", "iso-8859-15")
467
468 for res in results:
469 codecs.register_error("test.badhandler", lambda: res)
470 for enc in encs:
471 self.assertRaises(
472 TypeError,
473 u"\u3042".encode,
474 enc,
475 "test.badhandler"
476 )
477 for (enc, bytes) in (
478 ("ascii", "\xff"),
479 ("utf-8", "\xff"),
480 ("utf-7", "+x-")
481 ):
482 self.assertRaises(
483 TypeError,
484 bytes.decode,
485 enc,
486 "test.badhandler"
487 )
488
489 def test_lookup(self):
490 self.assertEquals(codecs.strict_errors, codecs.lookup_error("strict"))
491 self.assertEquals(codecs.ignore_errors, codecs.lookup_error("ignore"))
492 self.assertEquals(codecs.strict_errors, codecs.lookup_error("strict"))
493 self.assertEquals(
494 codecs.xmlcharrefreplace_errors,
495 codecs.lookup_error("xmlcharrefreplace")
496 )
497 self.assertEquals(
498 codecs.backslashreplace_errors,
499 codecs.lookup_error("backslashreplace")
500 )
501
Walter Dörwald9ab7dd42002-09-06 17:21:40 +0000502 def test_unencodablereplacement(self):
503 def unencrepl(exc):
504 if isinstance(exc, UnicodeEncodeError):
505 return (u"\u4242", exc.end)
506 else:
507 raise TypeError("don't know how to handle %r" % exc)
508 codecs.register_error("test.unencreplhandler", unencrepl)
509 for enc in ("ascii", "iso-8859-1", "iso-8859-15"):
510 self.assertRaises(
511 UnicodeEncodeError,
512 u"\u4242".encode,
513 enc,
514 "test.unencreplhandler"
515 )
516
Walter Dörwald30537a42003-01-08 23:22:13 +0000517 def test_badregistercall(self):
518 # enhance coverage of:
519 # Modules/_codecsmodule.c::register_error()
520 # Python/codecs.c::PyCodec_RegisterError()
521 self.assertRaises(TypeError, codecs.register_error, 42)
522 self.assertRaises(TypeError, codecs.register_error, "test.dummy", 42)
523
524 def test_unknownhandler(self):
525 # enhance coverage of:
526 # Modules/_codecsmodule.c::lookup_error()
527 self.assertRaises(LookupError, codecs.lookup_error, "test.unknown")
528
529 def test_xmlcharrefvalues(self):
530 # enhance coverage of:
531 # Python/codecs.c::PyCodec_XMLCharRefReplaceErrors()
532 # and inline implementations
533 v = (1, 5, 10, 50, 100, 500, 1000, 5000, 10000, 50000)
Walter Dörwald0cb27dd2003-01-09 11:38:50 +0000534 if sys.maxunicode>=100000:
Walter Dörwald30537a42003-01-08 23:22:13 +0000535 v += (100000, 500000, 1000000)
536 s = u"".join([unichr(x) for x in v])
537 codecs.register_error("test.xmlcharrefreplace", codecs.xmlcharrefreplace_errors)
538 for enc in ("ascii", "iso-8859-15"):
539 for err in ("xmlcharrefreplace", "test.xmlcharrefreplace"):
540 s.encode(enc, err)
541
542 def test_decodehelper(self):
543 # enhance coverage of:
544 # Objects/unicodeobject.c::unicode_decode_call_errorhandler()
545 # and callers
546 self.assertRaises(LookupError, "\xff".decode, "ascii", "test.unknown")
547
548 def baddecodereturn1(exc):
549 return 42
550 codecs.register_error("test.baddecodereturn1", baddecodereturn1)
551 self.assertRaises(TypeError, "\xff".decode, "ascii", "test.baddecodereturn1")
552 self.assertRaises(TypeError, "\\".decode, "unicode-escape", "test.baddecodereturn1")
553 self.assertRaises(TypeError, "\\x0".decode, "unicode-escape", "test.baddecodereturn1")
554 self.assertRaises(TypeError, "\\x0y".decode, "unicode-escape", "test.baddecodereturn1")
555 self.assertRaises(TypeError, "\\Uffffeeee".decode, "unicode-escape", "test.baddecodereturn1")
556 self.assertRaises(TypeError, "\\uyyyy".decode, "raw-unicode-escape", "test.baddecodereturn1")
557
558 def baddecodereturn2(exc):
559 return (u"?", None)
560 codecs.register_error("test.baddecodereturn2", baddecodereturn2)
561 self.assertRaises(TypeError, "\xff".decode, "ascii", "test.baddecodereturn2")
562
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000563 handler = PosReturn()
564 codecs.register_error("test.posreturn", handler.handle)
Walter Dörwald30537a42003-01-08 23:22:13 +0000565
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000566 # Valid negative position
567 handler.pos = -1
568 self.assertEquals("\xff0".decode("ascii", "test.posreturn"), u"<?>0")
569
570 # Valid negative position
571 handler.pos = -2
572 self.assertEquals("\xff0".decode("ascii", "test.posreturn"), u"<?><?>")
573
574 # Negative position out of bounds
575 handler.pos = -3
576 self.assertRaises(IndexError, "\xff0".decode, "ascii", "test.posreturn")
577
578 # Valid positive position
579 handler.pos = 1
580 self.assertEquals("\xff0".decode("ascii", "test.posreturn"), u"<?>0")
581
582 # Largest valid positive position (one beyond end of input
583 handler.pos = 2
584 self.assertEquals("\xff0".decode("ascii", "test.posreturn"), u"<?>")
585
586 # Invalid positive position
587 handler.pos = 3
588 self.assertRaises(IndexError, "\xff0".decode, "ascii", "test.posreturn")
589
590 # Restart at the "0"
591 handler.pos = 6
592 self.assertEquals("\\uyyyy0".decode("raw-unicode-escape", "test.posreturn"), u"<?>0")
Walter Dörwald30537a42003-01-08 23:22:13 +0000593
594 class D(dict):
595 def __getitem__(self, key):
596 raise ValueError
597 self.assertRaises(UnicodeError, codecs.charmap_decode, "\xff", "strict", {0xff: None})
598 self.assertRaises(ValueError, codecs.charmap_decode, "\xff", "strict", D())
599 self.assertRaises(TypeError, codecs.charmap_decode, "\xff", "strict", {0xff: sys.maxunicode+1})
600
601 def test_encodehelper(self):
602 # enhance coverage of:
603 # Objects/unicodeobject.c::unicode_encode_call_errorhandler()
604 # and callers
605 self.assertRaises(LookupError, u"\xff".encode, "ascii", "test.unknown")
606
607 def badencodereturn1(exc):
608 return 42
609 codecs.register_error("test.badencodereturn1", badencodereturn1)
610 self.assertRaises(TypeError, u"\xff".encode, "ascii", "test.badencodereturn1")
611
612 def badencodereturn2(exc):
613 return (u"?", None)
614 codecs.register_error("test.badencodereturn2", badencodereturn2)
615 self.assertRaises(TypeError, u"\xff".encode, "ascii", "test.badencodereturn2")
616
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000617 handler = PosReturn()
618 codecs.register_error("test.posreturn", handler.handle)
Walter Dörwald30537a42003-01-08 23:22:13 +0000619
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000620 # Valid negative position
621 handler.pos = -1
622 self.assertEquals(u"\xff0".encode("ascii", "test.posreturn"), "<?>0")
623
624 # Valid negative position
625 handler.pos = -2
626 self.assertEquals(u"\xff0".encode("ascii", "test.posreturn"), "<?><?>")
627
628 # Negative position out of bounds
629 handler.pos = -3
630 self.assertRaises(IndexError, u"\xff0".encode, "ascii", "test.posreturn")
631
632 # Valid positive position
633 handler.pos = 1
634 self.assertEquals(u"\xff0".encode("ascii", "test.posreturn"), "<?>0")
635
636 # Largest valid positive position (one beyond end of input
637 handler.pos = 2
638 self.assertEquals(u"\xff0".encode("ascii", "test.posreturn"), "<?>")
639
640 # Invalid positive position
641 handler.pos = 3
642 self.assertRaises(IndexError, u"\xff0".encode, "ascii", "test.posreturn")
643
644 handler.pos = 0
Walter Dörwald30537a42003-01-08 23:22:13 +0000645
646 class D(dict):
647 def __getitem__(self, key):
648 raise ValueError
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000649 for err in ("strict", "replace", "xmlcharrefreplace", "backslashreplace", "test.posreturn"):
Walter Dörwald30537a42003-01-08 23:22:13 +0000650 self.assertRaises(UnicodeError, codecs.charmap_encode, u"\xff", err, {0xff: None})
651 self.assertRaises(ValueError, codecs.charmap_encode, u"\xff", err, D())
652 self.assertRaises(TypeError, codecs.charmap_encode, u"\xff", err, {0xff: 300})
653
654 def test_translatehelper(self):
655 # enhance coverage of:
656 # Objects/unicodeobject.c::unicode_encode_call_errorhandler()
657 # and callers
658 # (Unfortunately the errors argument is not directly accessible
659 # from Python, so we can't test that much)
660 class D(dict):
661 def __getitem__(self, key):
662 raise ValueError
663 self.assertRaises(ValueError, u"\xff".translate, D())
664 self.assertRaises(TypeError, u"\xff".translate, {0xff: sys.maxunicode+1})
665 self.assertRaises(TypeError, u"\xff".translate, {0xff: ()})
666
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000667def test_main():
668 suite = unittest.TestSuite()
669 suite.addTest(unittest.makeSuite(CodecCallbackTest))
670 test.test_support.run_suite(suite)
671
672if __name__ == "__main__":
673 test_main()