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