blob: 7b073534881ae3b72f43a8e8bd9e4c15236b71d9 [file] [log] [blame]
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001import test.test_support, unittest
Fred Draked995e112008-05-20 06:08:38 +00002import sys, codecs, htmlentitydefs, unicodedata
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003
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örwald690402f2005-11-17 18:51:34 +000021# A UnicodeEncodeError object with a bad start attribute
22class BadStartUnicodeEncodeError(UnicodeEncodeError):
23 def __init__(self):
24 UnicodeEncodeError.__init__(self, "ascii", u"", 0, 1, "bad")
25 self.start = []
26
Walter Dörwald690402f2005-11-17 18:51:34 +000027# A UnicodeEncodeError object with a bad object attribute
28class BadObjectUnicodeEncodeError(UnicodeEncodeError):
29 def __init__(self):
30 UnicodeEncodeError.__init__(self, "ascii", u"", 0, 1, "bad")
31 self.object = []
32
33# A UnicodeDecodeError object without an end attribute
34class NoEndUnicodeDecodeError(UnicodeDecodeError):
35 def __init__(self):
36 UnicodeDecodeError.__init__(self, "ascii", "", 0, 1, "bad")
37 del self.end
38
39# A UnicodeDecodeError object with a bad object attribute
40class BadObjectUnicodeDecodeError(UnicodeDecodeError):
41 def __init__(self):
42 UnicodeDecodeError.__init__(self, "ascii", "", 0, 1, "bad")
43 self.object = []
44
45# A UnicodeTranslateError object without a start attribute
46class NoStartUnicodeTranslateError(UnicodeTranslateError):
47 def __init__(self):
48 UnicodeTranslateError.__init__(self, u"", 0, 1, "bad")
49 del self.start
50
51# A UnicodeTranslateError object without an end attribute
52class NoEndUnicodeTranslateError(UnicodeTranslateError):
53 def __init__(self):
54 UnicodeTranslateError.__init__(self, u"", 0, 1, "bad")
55 del self.end
56
57# A UnicodeTranslateError object without an object attribute
58class NoObjectUnicodeTranslateError(UnicodeTranslateError):
59 def __init__(self):
60 UnicodeTranslateError.__init__(self, u"", 0, 1, "bad")
61 del self.object
62
Walter Dörwald3aeb6322002-09-02 13:14:32 +000063class CodecCallbackTest(unittest.TestCase):
64
65 def test_xmlcharrefreplace(self):
66 # replace unencodable characters which numeric character entities.
67 # For ascii, latin-1 and charmaps this is completely implemented
68 # in C and should be reasonably fast.
Serhiy Storchakae822b032013-08-06 16:56:26 +030069 s = u"\u30b9\u30d1\u30e2 \xe4nd egg\u0161"
Walter Dörwald3aeb6322002-09-02 13:14:32 +000070 self.assertEqual(
71 s.encode("ascii", "xmlcharrefreplace"),
Serhiy Storchakae822b032013-08-06 16:56:26 +030072 "&#12473;&#12497;&#12514; &#228;nd egg&#353;"
Walter Dörwald3aeb6322002-09-02 13:14:32 +000073 )
74 self.assertEqual(
75 s.encode("latin-1", "xmlcharrefreplace"),
Serhiy Storchakae822b032013-08-06 16:56:26 +030076 "&#12473;&#12497;&#12514; \xe4nd egg&#353;"
Walter Dörwald3aeb6322002-09-02 13:14:32 +000077 )
Serhiy Storchakae822b032013-08-06 16:56:26 +030078 self.assertEqual(
79 s.encode("iso-8859-15", "xmlcharrefreplace"),
80 "&#12473;&#12497;&#12514; \xe4nd egg\xa8"
81 )
82
83 def test_xmlcharrefreplace_with_surrogates(self):
84 tests = [(u'\U0001f49d', '&#128157;'),
85 (u'\ud83d', '&#55357;'),
86 (u'\udc9d', '&#56477;'),
Serhiy Storchakae822b032013-08-06 16:56:26 +030087 ]
Serhiy Storchaka1fdc7022013-10-31 17:06:03 +020088 if u'\ud83d\udc9d' != u'\U0001f49d':
89 tests += [(u'\ud83d\udc9d', '&#55357;&#56477;')]
Serhiy Storchakae822b032013-08-06 16:56:26 +030090 for encoding in ['ascii', 'latin1', 'iso-8859-15']:
91 for s, exp in tests:
92 self.assertEqual(s.encode(encoding, 'xmlcharrefreplace'),
93 exp, msg='%r.encode(%r)' % (s, encoding))
94 self.assertEqual((s+'X').encode(encoding, 'xmlcharrefreplace'),
95 exp+'X',
96 msg='%r.encode(%r)' % (s + 'X', encoding))
Walter Dörwald3aeb6322002-09-02 13:14:32 +000097
98 def test_xmlcharnamereplace(self):
99 # This time use a named character entity for unencodable
100 # characters, if one is available.
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000101
102 def xmlcharnamereplace(exc):
103 if not isinstance(exc, UnicodeEncodeError):
104 raise TypeError("don't know how to handle %r" % exc)
105 l = []
106 for c in exc.object[exc.start:exc.end]:
107 try:
Fred Draked995e112008-05-20 06:08:38 +0000108 l.append(u"&%s;" % htmlentitydefs.codepoint2name[ord(c)])
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000109 except KeyError:
110 l.append(u"&#%d;" % ord(c))
111 return (u"".join(l), exc.end)
112
113 codecs.register_error(
114 "test.xmlcharnamereplace", xmlcharnamereplace)
115
116 sin = u"\xab\u211c\xbb = \u2329\u1234\u20ac\u232a"
117 sout = "&laquo;&real;&raquo; = &lang;&#4660;&euro;&rang;"
118 self.assertEqual(sin.encode("ascii", "test.xmlcharnamereplace"), sout)
119 sout = "\xab&real;\xbb = &lang;&#4660;&euro;&rang;"
120 self.assertEqual(sin.encode("latin-1", "test.xmlcharnamereplace"), sout)
121 sout = "\xab&real;\xbb = &lang;&#4660;\xa4&rang;"
122 self.assertEqual(sin.encode("iso-8859-15", "test.xmlcharnamereplace"), sout)
123
124 def test_uninamereplace(self):
125 # We're using the names from the unicode database this time,
Walter Dörwald00445d22002-11-25 17:58:02 +0000126 # and we're doing "syntax highlighting" here, i.e. we include
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000127 # the replaced text in ANSI escape sequences. For this it is
128 # useful that the error handler is not called for every single
129 # unencodable character, but for a complete sequence of
130 # unencodable characters, otherwise we would output many
Mark Dickinson3e4caeb2009-02-21 20:27:01 +0000131 # unnecessary escape sequences.
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000132
133 def uninamereplace(exc):
134 if not isinstance(exc, UnicodeEncodeError):
135 raise TypeError("don't know how to handle %r" % exc)
136 l = []
137 for c in exc.object[exc.start:exc.end]:
138 l.append(unicodedata.name(c, u"0x%x" % ord(c)))
139 return (u"\033[1m%s\033[0m" % u", ".join(l), exc.end)
140
141 codecs.register_error(
142 "test.uninamereplace", uninamereplace)
143
144 sin = u"\xac\u1234\u20ac\u8000"
Martin v. Löwis74a530d2002-11-23 19:41:01 +0000145 sout = "\033[1mNOT SIGN, ETHIOPIC SYLLABLE SEE, EURO SIGN, CJK UNIFIED IDEOGRAPH-8000\033[0m"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000146 self.assertEqual(sin.encode("ascii", "test.uninamereplace"), sout)
147
Martin v. Löwis74a530d2002-11-23 19:41:01 +0000148 sout = "\xac\033[1mETHIOPIC SYLLABLE SEE, EURO SIGN, CJK UNIFIED IDEOGRAPH-8000\033[0m"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000149 self.assertEqual(sin.encode("latin-1", "test.uninamereplace"), sout)
150
Martin v. Löwis74a530d2002-11-23 19:41:01 +0000151 sout = "\xac\033[1mETHIOPIC SYLLABLE SEE\033[0m\xa4\033[1mCJK UNIFIED IDEOGRAPH-8000\033[0m"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000152 self.assertEqual(sin.encode("iso-8859-15", "test.uninamereplace"), sout)
153
154 def test_backslashescape(self):
155 # Does the same as the "unicode-escape" encoding, but with different
156 # base encodings.
157 sin = u"a\xac\u1234\u20ac\u8000"
158 if sys.maxunicode > 0xffff:
159 sin += unichr(sys.maxunicode)
160 sout = "a\\xac\\u1234\\u20ac\\u8000"
161 if sys.maxunicode > 0xffff:
162 sout += "\\U%08x" % sys.maxunicode
163 self.assertEqual(sin.encode("ascii", "backslashreplace"), sout)
164
165 sout = "a\xac\\u1234\\u20ac\\u8000"
166 if sys.maxunicode > 0xffff:
167 sout += "\\U%08x" % sys.maxunicode
168 self.assertEqual(sin.encode("latin-1", "backslashreplace"), sout)
169
170 sout = "a\xac\\u1234\xa4\\u8000"
171 if sys.maxunicode > 0xffff:
172 sout += "\\U%08x" % sys.maxunicode
173 self.assertEqual(sin.encode("iso-8859-15", "backslashreplace"), sout)
174
Ezio Melottie57e50c2010-06-05 17:51:07 +0000175 def test_decoding_callbacks(self):
176 # This is a test for a decoding callback handler
177 # that allows the decoding of the invalid sequence
178 # "\xc0\x80" and returns "\x00" instead of raising an error.
179 # All other illegal sequences will be handled strictly.
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000180 def relaxedutf8(exc):
181 if not isinstance(exc, UnicodeDecodeError):
182 raise TypeError("don't know how to handle %r" % exc)
Ezio Melottie57e50c2010-06-05 17:51:07 +0000183 if exc.object[exc.start:exc.start+2] == "\xc0\x80":
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000184 return (u"\x00", exc.start+2) # retry after two bytes
185 else:
186 raise exc
187
Ezio Melottie57e50c2010-06-05 17:51:07 +0000188 codecs.register_error("test.relaxedutf8", relaxedutf8)
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000189
Ezio Melottie57e50c2010-06-05 17:51:07 +0000190 # all the "\xc0\x80" will be decoded to "\x00"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000191 sin = "a\x00b\xc0\x80c\xc3\xbc\xc0\x80\xc0\x80"
192 sout = u"a\x00b\x00c\xfc\x00\x00"
193 self.assertEqual(sin.decode("utf-8", "test.relaxedutf8"), sout)
Ezio Melottie57e50c2010-06-05 17:51:07 +0000194
195 # "\xc0\x81" is not valid and a UnicodeDecodeError will be raised
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000196 sin = "\xc0\x80\xc0\x81"
Ezio Melottie57e50c2010-06-05 17:51:07 +0000197 self.assertRaises(UnicodeDecodeError, sin.decode,
198 "utf-8", "test.relaxedutf8")
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000199
200 def test_charmapencode(self):
201 # For charmap encodings the replacement string will be
202 # mapped through the encoding again. This means, that
203 # to be able to use e.g. the "replace" handler, the
204 # charmap has to have a mapping for "?".
205 charmap = dict([ (ord(c), 2*c.upper()) for c in "abcdefgh"])
206 sin = u"abc"
207 sout = "AABBCC"
Ezio Melotti2623a372010-11-21 13:34:58 +0000208 self.assertEqual(codecs.charmap_encode(sin, "strict", charmap)[0], sout)
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000209
210 sin = u"abcA"
211 self.assertRaises(UnicodeError, codecs.charmap_encode, sin, "strict", charmap)
212
213 charmap[ord("?")] = "XYZ"
214 sin = u"abcDEF"
215 sout = "AABBCCXYZXYZXYZ"
Ezio Melotti2623a372010-11-21 13:34:58 +0000216 self.assertEqual(codecs.charmap_encode(sin, "replace", charmap)[0], sout)
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000217
218 charmap[ord("?")] = u"XYZ"
219 self.assertRaises(TypeError, codecs.charmap_encode, sin, "replace", charmap)
220
221 charmap[ord("?")] = u"XYZ"
222 self.assertRaises(TypeError, codecs.charmap_encode, sin, "replace", charmap)
223
Walter Dörwalda47d1c02005-08-30 10:23:14 +0000224 def test_decodeunicodeinternal(self):
225 self.assertRaises(
226 UnicodeDecodeError,
227 "\x00\x00\x00\x00\x00".decode,
228 "unicode-internal",
229 )
230 if sys.maxunicode > 0xffff:
231 def handler_unicodeinternal(exc):
232 if not isinstance(exc, UnicodeDecodeError):
233 raise TypeError("don't know how to handle %r" % exc)
234 return (u"\x01", 1)
235
236 self.assertEqual(
237 "\x00\x00\x00\x00\x00".decode("unicode-internal", "ignore"),
238 u"\u0000"
239 )
240
241 self.assertEqual(
242 "\x00\x00\x00\x00\x00".decode("unicode-internal", "replace"),
243 u"\u0000\ufffd"
244 )
245
246 codecs.register_error("test.hui", handler_unicodeinternal)
247
248 self.assertEqual(
249 "\x00\x00\x00\x00\x00".decode("unicode-internal", "test.hui"),
250 u"\u0000\u0001\u0000"
251 )
252
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000253 def test_callbacks(self):
254 def handler1(exc):
255 if not isinstance(exc, UnicodeEncodeError) \
256 and not isinstance(exc, UnicodeDecodeError):
257 raise TypeError("don't know how to handle %r" % exc)
258 l = [u"<%d>" % ord(exc.object[pos]) for pos in xrange(exc.start, exc.end)]
259 return (u"[%s]" % u"".join(l), exc.end)
260
261 codecs.register_error("test.handler1", handler1)
262
263 def handler2(exc):
264 if not isinstance(exc, UnicodeDecodeError):
265 raise TypeError("don't know how to handle %r" % exc)
266 l = [u"<%d>" % ord(exc.object[pos]) for pos in xrange(exc.start, exc.end)]
267 return (u"[%s]" % u"".join(l), exc.end+1) # skip one character
268
269 codecs.register_error("test.handler2", handler2)
270
271 s = "\x00\x81\x7f\x80\xff"
272
273 self.assertEqual(
274 s.decode("ascii", "test.handler1"),
275 u"\x00[<129>]\x7f[<128>][<255>]"
276 )
277 self.assertEqual(
278 s.decode("ascii", "test.handler2"),
279 u"\x00[<129>][<128>]"
280 )
281
282 self.assertEqual(
283 "\\u3042\u3xxx".decode("unicode-escape", "test.handler1"),
Serhiy Storchakac8e58122013-01-29 10:20:34 +0200284 u"\u3042[<92><117><51>]xxx"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000285 )
286
287 self.assertEqual(
288 "\\u3042\u3xx".decode("unicode-escape", "test.handler1"),
Serhiy Storchakac8e58122013-01-29 10:20:34 +0200289 u"\u3042[<92><117><51>]xx"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000290 )
291
292 self.assertEqual(
293 codecs.charmap_decode("abc", "test.handler1", {ord("a"): u"z"})[0],
294 u"z[<98>][<99>]"
295 )
296
297 self.assertEqual(
298 u"g\xfc\xdfrk".encode("ascii", "test.handler1"),
299 u"g[<252><223>]rk"
300 )
301
302 self.assertEqual(
303 u"g\xfc\xdf".encode("ascii", "test.handler1"),
304 u"g[<252><223>]"
305 )
306
307 def test_longstrings(self):
308 # test long strings to check for memory overflow problems
Walter Dörwald6e390802007-08-17 16:41:28 +0000309 errors = [ "strict", "ignore", "replace", "xmlcharrefreplace",
310 "backslashreplace"]
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000311 # register the handlers under different names,
312 # to prevent the codec from recognizing the name
313 for err in errors:
314 codecs.register_error("test." + err, codecs.lookup_error(err))
315 l = 1000
316 errors += [ "test." + err for err in errors ]
317 for uni in [ s*l for s in (u"x", u"\u3042", u"a\xe4") ]:
Walter Dörwald6e390802007-08-17 16:41:28 +0000318 for enc in ("ascii", "latin-1", "iso-8859-1", "iso-8859-15",
319 "utf-8", "utf-7", "utf-16", "utf-32"):
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000320 for err in errors:
Tim Peters3de75262002-11-09 05:26:15 +0000321 try:
322 uni.encode(enc, err)
323 except UnicodeError:
324 pass
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000325
326 def check_exceptionobjectargs(self, exctype, args, msg):
327 # Test UnicodeError subclasses: construction, attribute assignment and __str__ conversion
328 # check with one missing argument
329 self.assertRaises(TypeError, exctype, *args[:-1])
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000330 # check with one argument too much
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000331 self.assertRaises(TypeError, exctype, *(args + ["too much"]))
332 # check with one argument of the wrong type
333 wrongargs = [ "spam", u"eggs", 42, 1.0, None ]
334 for i in xrange(len(args)):
335 for wrongarg in wrongargs:
336 if type(wrongarg) is type(args[i]):
Tim Peters3de75262002-11-09 05:26:15 +0000337 continue
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000338 # build argument array
339 callargs = []
340 for j in xrange(len(args)):
341 if i==j:
342 callargs.append(wrongarg)
343 else:
344 callargs.append(args[i])
345 self.assertRaises(TypeError, exctype, *callargs)
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000346
347 # check with the correct number and type of arguments
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000348 exc = exctype(*args)
Ezio Melotti2623a372010-11-21 13:34:58 +0000349 self.assertEqual(str(exc), msg)
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000350
351 def test_unicodeencodeerror(self):
352 self.check_exceptionobjectargs(
353 UnicodeEncodeError,
354 ["ascii", u"g\xfcrk", 1, 2, "ouch"],
Walter Dörwalda54b92b2003-08-12 17:34:49 +0000355 "'ascii' codec can't encode character u'\\xfc' in position 1: ouch"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000356 )
357 self.check_exceptionobjectargs(
358 UnicodeEncodeError,
359 ["ascii", u"g\xfcrk", 1, 4, "ouch"],
360 "'ascii' codec can't encode characters in position 1-3: ouch"
361 )
362 self.check_exceptionobjectargs(
363 UnicodeEncodeError,
364 ["ascii", u"\xfcx", 0, 1, "ouch"],
Walter Dörwalda54b92b2003-08-12 17:34:49 +0000365 "'ascii' codec can't encode character u'\\xfc' in position 0: ouch"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000366 )
Walter Dörwaldfd196bd2003-08-12 17:32:43 +0000367 self.check_exceptionobjectargs(
368 UnicodeEncodeError,
369 ["ascii", u"\u0100x", 0, 1, "ouch"],
Walter Dörwalda54b92b2003-08-12 17:34:49 +0000370 "'ascii' codec can't encode character u'\\u0100' in position 0: ouch"
Walter Dörwaldfd196bd2003-08-12 17:32:43 +0000371 )
372 self.check_exceptionobjectargs(
373 UnicodeEncodeError,
374 ["ascii", u"\uffffx", 0, 1, "ouch"],
Walter Dörwalda54b92b2003-08-12 17:34:49 +0000375 "'ascii' codec can't encode character u'\\uffff' in position 0: ouch"
Walter Dörwaldfd196bd2003-08-12 17:32:43 +0000376 )
377 if sys.maxunicode > 0xffff:
378 self.check_exceptionobjectargs(
379 UnicodeEncodeError,
380 ["ascii", u"\U00010000x", 0, 1, "ouch"],
Walter Dörwalda54b92b2003-08-12 17:34:49 +0000381 "'ascii' codec can't encode character u'\\U00010000' in position 0: ouch"
Walter Dörwaldfd196bd2003-08-12 17:32:43 +0000382 )
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000383
384 def test_unicodedecodeerror(self):
385 self.check_exceptionobjectargs(
386 UnicodeDecodeError,
387 ["ascii", "g\xfcrk", 1, 2, "ouch"],
388 "'ascii' codec can't decode byte 0xfc in position 1: ouch"
389 )
390 self.check_exceptionobjectargs(
391 UnicodeDecodeError,
392 ["ascii", "g\xfcrk", 1, 3, "ouch"],
393 "'ascii' codec can't decode bytes in position 1-2: ouch"
394 )
395
396 def test_unicodetranslateerror(self):
397 self.check_exceptionobjectargs(
398 UnicodeTranslateError,
399 [u"g\xfcrk", 1, 2, "ouch"],
Walter Dörwalda54b92b2003-08-12 17:34:49 +0000400 "can't translate character u'\\xfc' in position 1: ouch"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000401 )
402 self.check_exceptionobjectargs(
403 UnicodeTranslateError,
Walter Dörwaldfd196bd2003-08-12 17:32:43 +0000404 [u"g\u0100rk", 1, 2, "ouch"],
Walter Dörwalda54b92b2003-08-12 17:34:49 +0000405 "can't translate character u'\\u0100' in position 1: ouch"
Walter Dörwaldfd196bd2003-08-12 17:32:43 +0000406 )
407 self.check_exceptionobjectargs(
408 UnicodeTranslateError,
409 [u"g\uffffrk", 1, 2, "ouch"],
Walter Dörwalda54b92b2003-08-12 17:34:49 +0000410 "can't translate character u'\\uffff' in position 1: ouch"
Walter Dörwaldfd196bd2003-08-12 17:32:43 +0000411 )
412 if sys.maxunicode > 0xffff:
413 self.check_exceptionobjectargs(
414 UnicodeTranslateError,
415 [u"g\U00010000rk", 1, 2, "ouch"],
Walter Dörwalda54b92b2003-08-12 17:34:49 +0000416 "can't translate character u'\\U00010000' in position 1: ouch"
Walter Dörwaldfd196bd2003-08-12 17:32:43 +0000417 )
418 self.check_exceptionobjectargs(
419 UnicodeTranslateError,
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000420 [u"g\xfcrk", 1, 3, "ouch"],
421 "can't translate characters in position 1-2: ouch"
422 )
423
424 def test_badandgoodstrictexceptions(self):
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000425 # "strict" complains about a non-exception passed in
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000426 self.assertRaises(
427 TypeError,
428 codecs.strict_errors,
429 42
430 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000431 # "strict" complains about the wrong exception type
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000432 self.assertRaises(
433 Exception,
434 codecs.strict_errors,
435 Exception("ouch")
436 )
437
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000438 # If the correct exception is passed in, "strict" raises it
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000439 self.assertRaises(
440 UnicodeEncodeError,
441 codecs.strict_errors,
442 UnicodeEncodeError("ascii", u"\u3042", 0, 1, "ouch")
443 )
Serhiy Storchaka27923892015-03-15 23:41:10 +0200444 self.assertRaises(
445 UnicodeDecodeError,
446 codecs.strict_errors,
447 UnicodeDecodeError("ascii", "\xff", 0, 1, "ouch")
448 )
449 self.assertRaises(
450 UnicodeTranslateError,
451 codecs.strict_errors,
452 UnicodeTranslateError(u"\u3042", 0, 1, "ouch")
453 )
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000454
455 def test_badandgoodignoreexceptions(self):
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000456 # "ignore" complains about a non-exception passed in
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000457 self.assertRaises(
458 TypeError,
459 codecs.ignore_errors,
460 42
461 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000462 # "ignore" complains about the wrong exception type
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000463 self.assertRaises(
464 TypeError,
465 codecs.ignore_errors,
466 UnicodeError("ouch")
467 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000468 # If the correct exception is passed in, "ignore" returns an empty replacement
Ezio Melotti2623a372010-11-21 13:34:58 +0000469 self.assertEqual(
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000470 codecs.ignore_errors(UnicodeEncodeError("ascii", u"\u3042", 0, 1, "ouch")),
471 (u"", 1)
472 )
Ezio Melotti2623a372010-11-21 13:34:58 +0000473 self.assertEqual(
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000474 codecs.ignore_errors(UnicodeDecodeError("ascii", "\xff", 0, 1, "ouch")),
475 (u"", 1)
476 )
Ezio Melotti2623a372010-11-21 13:34:58 +0000477 self.assertEqual(
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000478 codecs.ignore_errors(UnicodeTranslateError(u"\u3042", 0, 1, "ouch")),
479 (u"", 1)
480 )
481
482 def test_badandgoodreplaceexceptions(self):
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000483 # "replace" complains about a non-exception passed in
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000484 self.assertRaises(
485 TypeError,
486 codecs.replace_errors,
487 42
488 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000489 # "replace" complains about the wrong exception type
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000490 self.assertRaises(
491 TypeError,
492 codecs.replace_errors,
493 UnicodeError("ouch")
494 )
Walter Dörwald690402f2005-11-17 18:51:34 +0000495 self.assertRaises(
Walter Dörwald690402f2005-11-17 18:51:34 +0000496 TypeError,
497 codecs.replace_errors,
498 BadObjectUnicodeEncodeError()
499 )
500 self.assertRaises(
Walter Dörwald690402f2005-11-17 18:51:34 +0000501 TypeError,
502 codecs.replace_errors,
503 BadObjectUnicodeDecodeError()
504 )
Walter Dörwald29ddfba2004-12-14 21:28:07 +0000505 # With the correct exception, "replace" returns an "?" or u"\ufffd" replacement
Ezio Melotti2623a372010-11-21 13:34:58 +0000506 self.assertEqual(
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000507 codecs.replace_errors(UnicodeEncodeError("ascii", u"\u3042", 0, 1, "ouch")),
508 (u"?", 1)
509 )
Ezio Melotti2623a372010-11-21 13:34:58 +0000510 self.assertEqual(
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000511 codecs.replace_errors(UnicodeDecodeError("ascii", "\xff", 0, 1, "ouch")),
512 (u"\ufffd", 1)
513 )
Ezio Melotti2623a372010-11-21 13:34:58 +0000514 self.assertEqual(
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000515 codecs.replace_errors(UnicodeTranslateError(u"\u3042", 0, 1, "ouch")),
516 (u"\ufffd", 1)
517 )
518
519 def test_badandgoodxmlcharrefreplaceexceptions(self):
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000520 # "xmlcharrefreplace" complains about a non-exception passed in
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000521 self.assertRaises(
522 TypeError,
523 codecs.xmlcharrefreplace_errors,
524 42
525 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000526 # "xmlcharrefreplace" complains about the wrong exception types
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000527 self.assertRaises(
528 TypeError,
529 codecs.xmlcharrefreplace_errors,
530 UnicodeError("ouch")
531 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000532 # "xmlcharrefreplace" can only be used for encoding
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000533 self.assertRaises(
534 TypeError,
535 codecs.xmlcharrefreplace_errors,
536 UnicodeDecodeError("ascii", "\xff", 0, 1, "ouch")
537 )
538 self.assertRaises(
539 TypeError,
540 codecs.xmlcharrefreplace_errors,
541 UnicodeTranslateError(u"\u3042", 0, 1, "ouch")
542 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000543 # Use the correct exception
Serhiy Storchaka27923892015-03-15 23:41:10 +0200544 cs = (0, 1, 9, 10, 99, 100, 999, 1000, 9999, 10000)
545 cs += (0xdfff, 0xd800)
546 s = u"".join(unichr(c) for c in cs)
547 s += u"\U0001869f\U000186a0\U000f423f\U000f4240"
548 cs += (99999, 100000, 999999, 1000000)
Ezio Melotti2623a372010-11-21 13:34:58 +0000549 self.assertEqual(
Walter Dörwald690402f2005-11-17 18:51:34 +0000550 codecs.xmlcharrefreplace_errors(
551 UnicodeEncodeError("ascii", s, 0, len(s), "ouch")
552 ),
Serhiy Storchaka27923892015-03-15 23:41:10 +0200553 (u"".join(u"&#%d;" % c for c in cs), len(s))
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000554 )
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000555
556 def test_badandgoodbackslashreplaceexceptions(self):
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000557 # "backslashreplace" complains about a non-exception passed in
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000558 self.assertRaises(
559 TypeError,
560 codecs.backslashreplace_errors,
561 42
562 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000563 # "backslashreplace" complains about the wrong exception types
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000564 self.assertRaises(
565 TypeError,
566 codecs.backslashreplace_errors,
567 UnicodeError("ouch")
568 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000569 # "backslashreplace" can only be used for encoding
570 self.assertRaises(
571 TypeError,
572 codecs.backslashreplace_errors,
573 UnicodeDecodeError("ascii", "\xff", 0, 1, "ouch")
574 )
575 self.assertRaises(
576 TypeError,
577 codecs.backslashreplace_errors,
578 UnicodeTranslateError(u"\u3042", 0, 1, "ouch")
579 )
580 # Use the correct exception
Serhiy Storchaka27923892015-03-15 23:41:10 +0200581 tests = [
582 (u"\u3042", u"\\u3042"),
583 (u"\n", u"\\x0a"),
584 (u"a", u"\\x61"),
585 (u"\x00", u"\\x00"),
586 (u"\xff", u"\\xff"),
587 (u"\u0100", u"\\u0100"),
588 (u"\uffff", u"\\uffff"),
589 # Lone surrogates
590 (u"\ud800", u"\\ud800"),
591 (u"\udfff", u"\\udfff"),
592 ]
593 if sys.maxunicode > 0xffff:
594 tests += [
595 (u"\U00010000", u"\\U00010000"),
596 (u"\U0010ffff", u"\\U0010ffff"),
597 ]
598 else:
599 tests += [
600 (u"\U00010000", u"\\ud800\\udc00"),
601 (u"\U0010ffff", u"\\udbff\\udfff"),
602 ]
603 for s, r in tests:
Ezio Melotti2623a372010-11-21 13:34:58 +0000604 self.assertEqual(
Serhiy Storchaka27923892015-03-15 23:41:10 +0200605 codecs.backslashreplace_errors(
606 UnicodeEncodeError("ascii", s, 0, len(s), "ouch")),
607 (r, len(s))
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000608 )
609
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000610 def test_badhandlerresults(self):
611 results = ( 42, u"foo", (1,2,3), (u"foo", 1, 3), (u"foo", None), (u"foo",), ("foo", 1, 3), ("foo", None), ("foo",) )
612 encs = ("ascii", "latin-1", "iso-8859-1", "iso-8859-15")
613
614 for res in results:
Benjamin Peterson910f2162009-01-18 21:11:38 +0000615 codecs.register_error("test.badhandler", lambda x: res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000616 for enc in encs:
617 self.assertRaises(
618 TypeError,
619 u"\u3042".encode,
620 enc,
621 "test.badhandler"
622 )
623 for (enc, bytes) in (
624 ("ascii", "\xff"),
625 ("utf-8", "\xff"),
Walter Dörwalda47d1c02005-08-30 10:23:14 +0000626 ("utf-7", "+x-"),
627 ("unicode-internal", "\x00"),
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000628 ):
629 self.assertRaises(
630 TypeError,
631 bytes.decode,
632 enc,
633 "test.badhandler"
634 )
635
636 def test_lookup(self):
Ezio Melotti2623a372010-11-21 13:34:58 +0000637 self.assertEqual(codecs.strict_errors, codecs.lookup_error("strict"))
638 self.assertEqual(codecs.ignore_errors, codecs.lookup_error("ignore"))
639 self.assertEqual(codecs.strict_errors, codecs.lookup_error("strict"))
640 self.assertEqual(
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000641 codecs.xmlcharrefreplace_errors,
642 codecs.lookup_error("xmlcharrefreplace")
643 )
Ezio Melotti2623a372010-11-21 13:34:58 +0000644 self.assertEqual(
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000645 codecs.backslashreplace_errors,
646 codecs.lookup_error("backslashreplace")
647 )
648
Walter Dörwald9ab7dd42002-09-06 17:21:40 +0000649 def test_unencodablereplacement(self):
650 def unencrepl(exc):
651 if isinstance(exc, UnicodeEncodeError):
652 return (u"\u4242", exc.end)
653 else:
654 raise TypeError("don't know how to handle %r" % exc)
655 codecs.register_error("test.unencreplhandler", unencrepl)
656 for enc in ("ascii", "iso-8859-1", "iso-8859-15"):
657 self.assertRaises(
658 UnicodeEncodeError,
659 u"\u4242".encode,
660 enc,
661 "test.unencreplhandler"
662 )
663
Walter Dörwald30537a42003-01-08 23:22:13 +0000664 def test_badregistercall(self):
665 # enhance coverage of:
666 # Modules/_codecsmodule.c::register_error()
667 # Python/codecs.c::PyCodec_RegisterError()
668 self.assertRaises(TypeError, codecs.register_error, 42)
669 self.assertRaises(TypeError, codecs.register_error, "test.dummy", 42)
670
Walter Dörwalde22d3392005-11-17 08:52:34 +0000671 def test_badlookupcall(self):
672 # enhance coverage of:
673 # Modules/_codecsmodule.c::lookup_error()
674 self.assertRaises(TypeError, codecs.lookup_error)
675
Walter Dörwald30537a42003-01-08 23:22:13 +0000676 def test_unknownhandler(self):
677 # enhance coverage of:
678 # Modules/_codecsmodule.c::lookup_error()
679 self.assertRaises(LookupError, codecs.lookup_error, "test.unknown")
680
681 def test_xmlcharrefvalues(self):
682 # enhance coverage of:
683 # Python/codecs.c::PyCodec_XMLCharRefReplaceErrors()
684 # and inline implementations
685 v = (1, 5, 10, 50, 100, 500, 1000, 5000, 10000, 50000)
Walter Dörwald0cb27dd2003-01-09 11:38:50 +0000686 if sys.maxunicode>=100000:
Tim Petersf2715e02003-02-19 02:35:07 +0000687 v += (100000, 500000, 1000000)
Walter Dörwald30537a42003-01-08 23:22:13 +0000688 s = u"".join([unichr(x) for x in v])
689 codecs.register_error("test.xmlcharrefreplace", codecs.xmlcharrefreplace_errors)
690 for enc in ("ascii", "iso-8859-15"):
691 for err in ("xmlcharrefreplace", "test.xmlcharrefreplace"):
692 s.encode(enc, err)
693
694 def test_decodehelper(self):
695 # enhance coverage of:
696 # Objects/unicodeobject.c::unicode_decode_call_errorhandler()
697 # and callers
698 self.assertRaises(LookupError, "\xff".decode, "ascii", "test.unknown")
699
700 def baddecodereturn1(exc):
701 return 42
702 codecs.register_error("test.baddecodereturn1", baddecodereturn1)
703 self.assertRaises(TypeError, "\xff".decode, "ascii", "test.baddecodereturn1")
704 self.assertRaises(TypeError, "\\".decode, "unicode-escape", "test.baddecodereturn1")
705 self.assertRaises(TypeError, "\\x0".decode, "unicode-escape", "test.baddecodereturn1")
706 self.assertRaises(TypeError, "\\x0y".decode, "unicode-escape", "test.baddecodereturn1")
707 self.assertRaises(TypeError, "\\Uffffeeee".decode, "unicode-escape", "test.baddecodereturn1")
708 self.assertRaises(TypeError, "\\uyyyy".decode, "raw-unicode-escape", "test.baddecodereturn1")
709
710 def baddecodereturn2(exc):
711 return (u"?", None)
712 codecs.register_error("test.baddecodereturn2", baddecodereturn2)
713 self.assertRaises(TypeError, "\xff".decode, "ascii", "test.baddecodereturn2")
714
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000715 handler = PosReturn()
716 codecs.register_error("test.posreturn", handler.handle)
Walter Dörwald30537a42003-01-08 23:22:13 +0000717
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000718 # Valid negative position
719 handler.pos = -1
Ezio Melotti2623a372010-11-21 13:34:58 +0000720 self.assertEqual("\xff0".decode("ascii", "test.posreturn"), u"<?>0")
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000721
722 # Valid negative position
723 handler.pos = -2
Ezio Melotti2623a372010-11-21 13:34:58 +0000724 self.assertEqual("\xff0".decode("ascii", "test.posreturn"), u"<?><?>")
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000725
726 # Negative position out of bounds
727 handler.pos = -3
728 self.assertRaises(IndexError, "\xff0".decode, "ascii", "test.posreturn")
729
730 # Valid positive position
731 handler.pos = 1
Ezio Melotti2623a372010-11-21 13:34:58 +0000732 self.assertEqual("\xff0".decode("ascii", "test.posreturn"), u"<?>0")
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000733
Walter Dörwald29ddfba2004-12-14 21:28:07 +0000734 # Largest valid positive position (one beyond end of input)
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000735 handler.pos = 2
Ezio Melotti2623a372010-11-21 13:34:58 +0000736 self.assertEqual("\xff0".decode("ascii", "test.posreturn"), u"<?>")
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000737
738 # Invalid positive position
739 handler.pos = 3
740 self.assertRaises(IndexError, "\xff0".decode, "ascii", "test.posreturn")
741
742 # Restart at the "0"
743 handler.pos = 6
Ezio Melotti2623a372010-11-21 13:34:58 +0000744 self.assertEqual("\\uyyyy0".decode("raw-unicode-escape", "test.posreturn"), u"<?>0")
Walter Dörwald30537a42003-01-08 23:22:13 +0000745
746 class D(dict):
747 def __getitem__(self, key):
748 raise ValueError
749 self.assertRaises(UnicodeError, codecs.charmap_decode, "\xff", "strict", {0xff: None})
750 self.assertRaises(ValueError, codecs.charmap_decode, "\xff", "strict", D())
Antoine Pitroue3ae3212012-11-17 21:14:58 +0100751 self.assertRaises(TypeError, codecs.charmap_decode, "\xff", "strict", {0xff: 0x110000})
Walter Dörwald30537a42003-01-08 23:22:13 +0000752
753 def test_encodehelper(self):
754 # enhance coverage of:
755 # Objects/unicodeobject.c::unicode_encode_call_errorhandler()
756 # and callers
757 self.assertRaises(LookupError, u"\xff".encode, "ascii", "test.unknown")
758
759 def badencodereturn1(exc):
760 return 42
761 codecs.register_error("test.badencodereturn1", badencodereturn1)
762 self.assertRaises(TypeError, u"\xff".encode, "ascii", "test.badencodereturn1")
763
764 def badencodereturn2(exc):
765 return (u"?", None)
766 codecs.register_error("test.badencodereturn2", badencodereturn2)
767 self.assertRaises(TypeError, u"\xff".encode, "ascii", "test.badencodereturn2")
768
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000769 handler = PosReturn()
770 codecs.register_error("test.posreturn", handler.handle)
Walter Dörwald30537a42003-01-08 23:22:13 +0000771
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000772 # Valid negative position
773 handler.pos = -1
Ezio Melotti2623a372010-11-21 13:34:58 +0000774 self.assertEqual(u"\xff0".encode("ascii", "test.posreturn"), "<?>0")
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000775
776 # Valid negative position
777 handler.pos = -2
Ezio Melotti2623a372010-11-21 13:34:58 +0000778 self.assertEqual(u"\xff0".encode("ascii", "test.posreturn"), "<?><?>")
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000779
780 # Negative position out of bounds
781 handler.pos = -3
782 self.assertRaises(IndexError, u"\xff0".encode, "ascii", "test.posreturn")
783
784 # Valid positive position
785 handler.pos = 1
Ezio Melotti2623a372010-11-21 13:34:58 +0000786 self.assertEqual(u"\xff0".encode("ascii", "test.posreturn"), "<?>0")
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000787
788 # Largest valid positive position (one beyond end of input
789 handler.pos = 2
Ezio Melotti2623a372010-11-21 13:34:58 +0000790 self.assertEqual(u"\xff0".encode("ascii", "test.posreturn"), "<?>")
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000791
792 # Invalid positive position
793 handler.pos = 3
794 self.assertRaises(IndexError, u"\xff0".encode, "ascii", "test.posreturn")
795
796 handler.pos = 0
Walter Dörwald30537a42003-01-08 23:22:13 +0000797
798 class D(dict):
799 def __getitem__(self, key):
800 raise ValueError
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000801 for err in ("strict", "replace", "xmlcharrefreplace", "backslashreplace", "test.posreturn"):
Walter Dörwald30537a42003-01-08 23:22:13 +0000802 self.assertRaises(UnicodeError, codecs.charmap_encode, u"\xff", err, {0xff: None})
803 self.assertRaises(ValueError, codecs.charmap_encode, u"\xff", err, D())
804 self.assertRaises(TypeError, codecs.charmap_encode, u"\xff", err, {0xff: 300})
805
806 def test_translatehelper(self):
807 # enhance coverage of:
808 # Objects/unicodeobject.c::unicode_encode_call_errorhandler()
809 # and callers
810 # (Unfortunately the errors argument is not directly accessible
811 # from Python, so we can't test that much)
812 class D(dict):
813 def __getitem__(self, key):
814 raise ValueError
815 self.assertRaises(ValueError, u"\xff".translate, D())
816 self.assertRaises(TypeError, u"\xff".translate, {0xff: sys.maxunicode+1})
817 self.assertRaises(TypeError, u"\xff".translate, {0xff: ()})
818
Walter Dörwald4894c302003-10-24 14:25:28 +0000819 def test_bug828737(self):
820 charmap = {
821 ord("&"): u"&amp;",
822 ord("<"): u"&lt;",
823 ord(">"): u"&gt;",
824 ord('"'): u"&quot;",
825 }
Tim Peters58eb11c2004-01-18 20:29:55 +0000826
Walter Dörwald4894c302003-10-24 14:25:28 +0000827 for n in (1, 10, 100, 1000):
828 text = u'abc<def>ghi'*n
829 text.translate(charmap)
830
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000831def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +0000832 test.test_support.run_unittest(CodecCallbackTest)
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000833
834if __name__ == "__main__":
835 test_main()