blob: 6105fc02fa62317c16824aa129167abc9a8e8332 [file] [log] [blame]
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001import test.support, unittest
Fred Drake3c50ea42008-05-17 22:02:32 +00002import sys, codecs, html.entities, 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)
Guido van Rossumef87d6e2007-05-02 19:09:54 +000019 return ("<?>", oldpos)
Walter Dörwald2e0b18a2003-01-31 17:19:08 +000020
Walter Dörwald690402f2005-11-17 18:51:34 +000021# A UnicodeEncodeError object with a bad start attribute
22class BadStartUnicodeEncodeError(UnicodeEncodeError):
23 def __init__(self):
Walter Dörwaldd2034312007-05-18 16:29:38 +000024 UnicodeEncodeError.__init__(self, "ascii", "", 0, 1, "bad")
Walter Dörwald690402f2005-11-17 18:51:34 +000025 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):
Walter Dörwaldd2034312007-05-18 16:29:38 +000030 UnicodeEncodeError.__init__(self, "ascii", "", 0, 1, "bad")
Walter Dörwald690402f2005-11-17 18:51:34 +000031 self.object = []
32
33# A UnicodeDecodeError object without an end attribute
34class NoEndUnicodeDecodeError(UnicodeDecodeError):
35 def __init__(self):
Guido van Rossum254348e2007-11-21 19:29:53 +000036 UnicodeDecodeError.__init__(self, "ascii", bytearray(b""), 0, 1, "bad")
Walter Dörwald690402f2005-11-17 18:51:34 +000037 del self.end
38
39# A UnicodeDecodeError object with a bad object attribute
40class BadObjectUnicodeDecodeError(UnicodeDecodeError):
41 def __init__(self):
Guido van Rossum254348e2007-11-21 19:29:53 +000042 UnicodeDecodeError.__init__(self, "ascii", bytearray(b""), 0, 1, "bad")
Walter Dörwald690402f2005-11-17 18:51:34 +000043 self.object = []
44
45# A UnicodeTranslateError object without a start attribute
46class NoStartUnicodeTranslateError(UnicodeTranslateError):
47 def __init__(self):
Walter Dörwaldd2034312007-05-18 16:29:38 +000048 UnicodeTranslateError.__init__(self, "", 0, 1, "bad")
Walter Dörwald690402f2005-11-17 18:51:34 +000049 del self.start
50
51# A UnicodeTranslateError object without an end attribute
52class NoEndUnicodeTranslateError(UnicodeTranslateError):
53 def __init__(self):
Walter Dörwaldd2034312007-05-18 16:29:38 +000054 UnicodeTranslateError.__init__(self, "", 0, 1, "bad")
Walter Dörwald690402f2005-11-17 18:51:34 +000055 del self.end
56
57# A UnicodeTranslateError object without an object attribute
58class NoObjectUnicodeTranslateError(UnicodeTranslateError):
59 def __init__(self):
Walter Dörwaldd2034312007-05-18 16:29:38 +000060 UnicodeTranslateError.__init__(self, "", 0, 1, "bad")
Walter Dörwald690402f2005-11-17 18:51:34 +000061 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.
Guido van Rossumef87d6e2007-05-02 19:09:54 +000069 s = "\u30b9\u30d1\u30e2 \xe4nd eggs"
Walter Dörwald3aeb6322002-09-02 13:14:32 +000070 self.assertEqual(
71 s.encode("ascii", "xmlcharrefreplace"),
Walter Dörwald00048f02007-05-09 10:44:06 +000072 b"&#12473;&#12497;&#12514; &#228;nd eggs"
Walter Dörwald3aeb6322002-09-02 13:14:32 +000073 )
74 self.assertEqual(
75 s.encode("latin-1", "xmlcharrefreplace"),
Walter Dörwald00048f02007-05-09 10:44:06 +000076 b"&#12473;&#12497;&#12514; \xe4nd eggs"
Walter Dörwald3aeb6322002-09-02 13:14:32 +000077 )
78
79 def test_xmlcharnamereplace(self):
80 # This time use a named character entity for unencodable
81 # characters, if one is available.
Walter Dörwald3aeb6322002-09-02 13:14:32 +000082
83 def xmlcharnamereplace(exc):
84 if not isinstance(exc, UnicodeEncodeError):
85 raise TypeError("don't know how to handle %r" % exc)
86 l = []
87 for c in exc.object[exc.start:exc.end]:
88 try:
Fred Drake3c50ea42008-05-17 22:02:32 +000089 l.append("&%s;" % html.entities.codepoint2name[ord(c)])
Walter Dörwald3aeb6322002-09-02 13:14:32 +000090 except KeyError:
Guido van Rossumef87d6e2007-05-02 19:09:54 +000091 l.append("&#%d;" % ord(c))
92 return ("".join(l), exc.end)
Walter Dörwald3aeb6322002-09-02 13:14:32 +000093
94 codecs.register_error(
95 "test.xmlcharnamereplace", xmlcharnamereplace)
96
Guido van Rossumef87d6e2007-05-02 19:09:54 +000097 sin = "\xab\u211c\xbb = \u2329\u1234\u20ac\u232a"
Walter Dörwald00048f02007-05-09 10:44:06 +000098 sout = b"&laquo;&real;&raquo; = &lang;&#4660;&euro;&rang;"
Walter Dörwald3aeb6322002-09-02 13:14:32 +000099 self.assertEqual(sin.encode("ascii", "test.xmlcharnamereplace"), sout)
Walter Dörwald00048f02007-05-09 10:44:06 +0000100 sout = b"\xab&real;\xbb = &lang;&#4660;&euro;&rang;"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000101 self.assertEqual(sin.encode("latin-1", "test.xmlcharnamereplace"), sout)
Walter Dörwald00048f02007-05-09 10:44:06 +0000102 sout = b"\xab&real;\xbb = &lang;&#4660;\xa4&rang;"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000103 self.assertEqual(sin.encode("iso-8859-15", "test.xmlcharnamereplace"), sout)
104
105 def test_uninamereplace(self):
106 # We're using the names from the unicode database this time,
Walter Dörwald00445d22002-11-25 17:58:02 +0000107 # and we're doing "syntax highlighting" here, i.e. we include
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000108 # the replaced text in ANSI escape sequences. For this it is
109 # useful that the error handler is not called for every single
110 # unencodable character, but for a complete sequence of
111 # unencodable characters, otherwise we would output many
Mark Dickinson934896d2009-02-21 20:59:32 +0000112 # unnecessary escape sequences.
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000113
114 def uninamereplace(exc):
115 if not isinstance(exc, UnicodeEncodeError):
116 raise TypeError("don't know how to handle %r" % exc)
117 l = []
118 for c in exc.object[exc.start:exc.end]:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000119 l.append(unicodedata.name(c, "0x%x" % ord(c)))
120 return ("\033[1m%s\033[0m" % ", ".join(l), exc.end)
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000121
122 codecs.register_error(
123 "test.uninamereplace", uninamereplace)
124
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000125 sin = "\xac\u1234\u20ac\u8000"
Walter Dörwald00048f02007-05-09 10:44:06 +0000126 sout = b"\033[1mNOT SIGN, ETHIOPIC SYLLABLE SEE, EURO SIGN, CJK UNIFIED IDEOGRAPH-8000\033[0m"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000127 self.assertEqual(sin.encode("ascii", "test.uninamereplace"), sout)
128
Walter Dörwald00048f02007-05-09 10:44:06 +0000129 sout = b"\xac\033[1mETHIOPIC SYLLABLE SEE, EURO SIGN, CJK UNIFIED IDEOGRAPH-8000\033[0m"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000130 self.assertEqual(sin.encode("latin-1", "test.uninamereplace"), sout)
131
Walter Dörwald00048f02007-05-09 10:44:06 +0000132 sout = b"\xac\033[1mETHIOPIC SYLLABLE SEE\033[0m\xa4\033[1mCJK UNIFIED IDEOGRAPH-8000\033[0m"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000133 self.assertEqual(sin.encode("iso-8859-15", "test.uninamereplace"), sout)
134
135 def test_backslashescape(self):
136 # Does the same as the "unicode-escape" encoding, but with different
137 # base encodings.
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000138 sin = "a\xac\u1234\u20ac\u8000"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000139 if sys.maxunicode > 0xffff:
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000140 sin += chr(sys.maxunicode)
Walter Dörwald00048f02007-05-09 10:44:06 +0000141 sout = b"a\\xac\\u1234\\u20ac\\u8000"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000142 if sys.maxunicode > 0xffff:
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000143 sout += bytes("\\U%08x" % sys.maxunicode, "ascii")
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000144 self.assertEqual(sin.encode("ascii", "backslashreplace"), sout)
145
Walter Dörwald00048f02007-05-09 10:44:06 +0000146 sout = b"a\xac\\u1234\\u20ac\\u8000"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000147 if sys.maxunicode > 0xffff:
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000148 sout += bytes("\\U%08x" % sys.maxunicode, "ascii")
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000149 self.assertEqual(sin.encode("latin-1", "backslashreplace"), sout)
150
Walter Dörwald00048f02007-05-09 10:44:06 +0000151 sout = b"a\xac\\u1234\xa4\\u8000"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000152 if sys.maxunicode > 0xffff:
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000153 sout += bytes("\\U%08x" % sys.maxunicode, "ascii")
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000154 self.assertEqual(sin.encode("iso-8859-15", "backslashreplace"), sout)
155
Ezio Melotti25bc0192010-07-03 05:18:50 +0000156 def test_decoding_callbacks(self):
157 # This is a test for a decoding callback handler
158 # that allows the decoding of the invalid sequence
159 # "\xc0\x80" and returns "\x00" instead of raising an error.
160 # All other illegal sequences will be handled strictly.
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000161 def relaxedutf8(exc):
162 if not isinstance(exc, UnicodeDecodeError):
163 raise TypeError("don't know how to handle %r" % exc)
Ezio Melotti25bc0192010-07-03 05:18:50 +0000164 if exc.object[exc.start:exc.start+2] == b"\xc0\x80":
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000165 return ("\x00", exc.start+2) # retry after two bytes
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000166 else:
167 raise exc
168
Ezio Melotti25bc0192010-07-03 05:18:50 +0000169 codecs.register_error("test.relaxedutf8", relaxedutf8)
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000170
Ezio Melotti25bc0192010-07-03 05:18:50 +0000171 # all the "\xc0\x80" will be decoded to "\x00"
Walter Dörwald00048f02007-05-09 10:44:06 +0000172 sin = b"a\x00b\xc0\x80c\xc3\xbc\xc0\x80\xc0\x80"
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000173 sout = "a\x00b\x00c\xfc\x00\x00"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000174 self.assertEqual(sin.decode("utf-8", "test.relaxedutf8"), sout)
Ezio Melotti25bc0192010-07-03 05:18:50 +0000175
176 # "\xc0\x81" is not valid and a UnicodeDecodeError will be raised
Walter Dörwald00048f02007-05-09 10:44:06 +0000177 sin = b"\xc0\x80\xc0\x81"
Ezio Melotti25bc0192010-07-03 05:18:50 +0000178 self.assertRaises(UnicodeDecodeError, sin.decode,
179 "utf-8", "test.relaxedutf8")
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000180
181 def test_charmapencode(self):
182 # For charmap encodings the replacement string will be
183 # mapped through the encoding again. This means, that
184 # to be able to use e.g. the "replace" handler, the
185 # charmap has to have a mapping for "?".
Guido van Rossum98297ee2007-11-06 21:34:58 +0000186 charmap = dict((ord(c), bytes(2*c.upper(), 'ascii')) for c in "abcdefgh")
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000187 sin = "abc"
Walter Dörwald00048f02007-05-09 10:44:06 +0000188 sout = b"AABBCC"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000189 self.assertEquals(codecs.charmap_encode(sin, "strict", charmap)[0], sout)
190
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000191 sin = "abcA"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000192 self.assertRaises(UnicodeError, codecs.charmap_encode, sin, "strict", charmap)
193
Guido van Rossum98297ee2007-11-06 21:34:58 +0000194 charmap[ord("?")] = b"XYZ"
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000195 sin = "abcDEF"
Walter Dörwald00048f02007-05-09 10:44:06 +0000196 sout = b"AABBCCXYZXYZXYZ"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000197 self.assertEquals(codecs.charmap_encode(sin, "replace", charmap)[0], sout)
198
Walter Dörwald00048f02007-05-09 10:44:06 +0000199 charmap[ord("?")] = "XYZ" # wrong type in mapping
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000200 self.assertRaises(TypeError, codecs.charmap_encode, sin, "replace", charmap)
201
Walter Dörwalda47d1c02005-08-30 10:23:14 +0000202 def test_decodeunicodeinternal(self):
203 self.assertRaises(
204 UnicodeDecodeError,
Walter Dörwald00048f02007-05-09 10:44:06 +0000205 b"\x00\x00\x00\x00\x00".decode,
Walter Dörwalda47d1c02005-08-30 10:23:14 +0000206 "unicode-internal",
207 )
208 if sys.maxunicode > 0xffff:
209 def handler_unicodeinternal(exc):
210 if not isinstance(exc, UnicodeDecodeError):
211 raise TypeError("don't know how to handle %r" % exc)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000212 return ("\x01", 1)
Walter Dörwalda47d1c02005-08-30 10:23:14 +0000213
214 self.assertEqual(
Walter Dörwald00048f02007-05-09 10:44:06 +0000215 b"\x00\x00\x00\x00\x00".decode("unicode-internal", "ignore"),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000216 "\u0000"
Walter Dörwalda47d1c02005-08-30 10:23:14 +0000217 )
218
219 self.assertEqual(
Walter Dörwald00048f02007-05-09 10:44:06 +0000220 b"\x00\x00\x00\x00\x00".decode("unicode-internal", "replace"),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000221 "\u0000\ufffd"
Walter Dörwalda47d1c02005-08-30 10:23:14 +0000222 )
223
224 codecs.register_error("test.hui", handler_unicodeinternal)
225
226 self.assertEqual(
Walter Dörwald00048f02007-05-09 10:44:06 +0000227 b"\x00\x00\x00\x00\x00".decode("unicode-internal", "test.hui"),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000228 "\u0000\u0001\u0000"
Walter Dörwalda47d1c02005-08-30 10:23:14 +0000229 )
230
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000231 def test_callbacks(self):
232 def handler1(exc):
Walter Dörwald00048f02007-05-09 10:44:06 +0000233 r = range(exc.start, exc.end)
234 if isinstance(exc, UnicodeEncodeError):
235 l = ["<%d>" % ord(exc.object[pos]) for pos in r]
236 elif isinstance(exc, UnicodeDecodeError):
237 l = ["<%d>" % exc.object[pos] for pos in r]
238 else:
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000239 raise TypeError("don't know how to handle %r" % exc)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000240 return ("[%s]" % "".join(l), exc.end)
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000241
242 codecs.register_error("test.handler1", handler1)
243
244 def handler2(exc):
245 if not isinstance(exc, UnicodeDecodeError):
246 raise TypeError("don't know how to handle %r" % exc)
Walter Dörwald00048f02007-05-09 10:44:06 +0000247 l = ["<%d>" % exc.object[pos] for pos in range(exc.start, exc.end)]
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000248 return ("[%s]" % "".join(l), exc.end+1) # skip one character
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000249
250 codecs.register_error("test.handler2", handler2)
251
Walter Dörwald00048f02007-05-09 10:44:06 +0000252 s = b"\x00\x81\x7f\x80\xff"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000253
254 self.assertEqual(
255 s.decode("ascii", "test.handler1"),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000256 "\x00[<129>]\x7f[<128>][<255>]"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000257 )
258 self.assertEqual(
259 s.decode("ascii", "test.handler2"),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000260 "\x00[<129>][<128>]"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000261 )
262
263 self.assertEqual(
Walter Dörwald00048f02007-05-09 10:44:06 +0000264 b"\\u3042\u3xxx".decode("unicode-escape", "test.handler1"),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000265 "\u3042[<92><117><51><120>]xx"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000266 )
267
268 self.assertEqual(
Walter Dörwald00048f02007-05-09 10:44:06 +0000269 b"\\u3042\u3xx".decode("unicode-escape", "test.handler1"),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000270 "\u3042[<92><117><51><120><120>]"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000271 )
272
273 self.assertEqual(
Walter Dörwald00048f02007-05-09 10:44:06 +0000274 codecs.charmap_decode(b"abc", "test.handler1", {ord("a"): "z"})[0],
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000275 "z[<98>][<99>]"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000276 )
277
278 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000279 "g\xfc\xdfrk".encode("ascii", "test.handler1"),
Walter Dörwald00048f02007-05-09 10:44:06 +0000280 b"g[<252><223>]rk"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000281 )
282
283 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000284 "g\xfc\xdf".encode("ascii", "test.handler1"),
Walter Dörwald00048f02007-05-09 10:44:06 +0000285 b"g[<252><223>]"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000286 )
287
288 def test_longstrings(self):
289 # test long strings to check for memory overflow problems
Walter Dörwald41980ca2007-08-16 21:55:45 +0000290 errors = [ "strict", "ignore", "replace", "xmlcharrefreplace",
291 "backslashreplace"]
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000292 # register the handlers under different names,
293 # to prevent the codec from recognizing the name
294 for err in errors:
295 codecs.register_error("test." + err, codecs.lookup_error(err))
296 l = 1000
297 errors += [ "test." + err for err in errors ]
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000298 for uni in [ s*l for s in ("x", "\u3042", "a\xe4") ]:
Walter Dörwald41980ca2007-08-16 21:55:45 +0000299 for enc in ("ascii", "latin-1", "iso-8859-1", "iso-8859-15",
300 "utf-8", "utf-7", "utf-16", "utf-32"):
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000301 for err in errors:
Tim Peters3de75262002-11-09 05:26:15 +0000302 try:
303 uni.encode(enc, err)
304 except UnicodeError:
305 pass
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000306
307 def check_exceptionobjectargs(self, exctype, args, msg):
308 # Test UnicodeError subclasses: construction, attribute assignment and __str__ conversion
309 # check with one missing argument
310 self.assertRaises(TypeError, exctype, *args[:-1])
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000311 # check with one argument too much
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000312 self.assertRaises(TypeError, exctype, *(args + ["too much"]))
313 # check with one argument of the wrong type
Guido van Rossum98297ee2007-11-06 21:34:58 +0000314 wrongargs = [ "spam", b"eggs", b"spam", 42, 1.0, None ]
Guido van Rossum805365e2007-05-07 22:24:25 +0000315 for i in range(len(args)):
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000316 for wrongarg in wrongargs:
317 if type(wrongarg) is type(args[i]):
Tim Peters3de75262002-11-09 05:26:15 +0000318 continue
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000319 # build argument array
320 callargs = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000321 for j in range(len(args)):
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000322 if i==j:
323 callargs.append(wrongarg)
324 else:
325 callargs.append(args[i])
326 self.assertRaises(TypeError, exctype, *callargs)
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000327
328 # check with the correct number and type of arguments
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000329 exc = exctype(*args)
330 self.assertEquals(str(exc), msg)
331
332 def test_unicodeencodeerror(self):
333 self.check_exceptionobjectargs(
334 UnicodeEncodeError,
Walter Dörwaldd2034312007-05-18 16:29:38 +0000335 ["ascii", "g\xfcrk", 1, 2, "ouch"],
Walter Dörwald32a4c712007-06-20 09:25:34 +0000336 "'ascii' codec can't encode character '\\xfc' in position 1: ouch"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000337 )
338 self.check_exceptionobjectargs(
339 UnicodeEncodeError,
Walter Dörwaldd2034312007-05-18 16:29:38 +0000340 ["ascii", "g\xfcrk", 1, 4, "ouch"],
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000341 "'ascii' codec can't encode characters in position 1-3: ouch"
342 )
343 self.check_exceptionobjectargs(
344 UnicodeEncodeError,
Walter Dörwaldd2034312007-05-18 16:29:38 +0000345 ["ascii", "\xfcx", 0, 1, "ouch"],
Walter Dörwald32a4c712007-06-20 09:25:34 +0000346 "'ascii' codec can't encode character '\\xfc' in position 0: ouch"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000347 )
Walter Dörwaldfd196bd2003-08-12 17:32:43 +0000348 self.check_exceptionobjectargs(
349 UnicodeEncodeError,
Walter Dörwaldd2034312007-05-18 16:29:38 +0000350 ["ascii", "\u0100x", 0, 1, "ouch"],
Walter Dörwald32a4c712007-06-20 09:25:34 +0000351 "'ascii' codec can't encode character '\\u0100' in position 0: ouch"
Walter Dörwaldfd196bd2003-08-12 17:32:43 +0000352 )
353 self.check_exceptionobjectargs(
354 UnicodeEncodeError,
Walter Dörwaldd2034312007-05-18 16:29:38 +0000355 ["ascii", "\uffffx", 0, 1, "ouch"],
Walter Dörwald32a4c712007-06-20 09:25:34 +0000356 "'ascii' codec can't encode character '\\uffff' in position 0: ouch"
Walter Dörwaldfd196bd2003-08-12 17:32:43 +0000357 )
358 if sys.maxunicode > 0xffff:
359 self.check_exceptionobjectargs(
360 UnicodeEncodeError,
Walter Dörwaldd2034312007-05-18 16:29:38 +0000361 ["ascii", "\U00010000x", 0, 1, "ouch"],
Walter Dörwald32a4c712007-06-20 09:25:34 +0000362 "'ascii' codec can't encode character '\\U00010000' in position 0: ouch"
Walter Dörwaldfd196bd2003-08-12 17:32:43 +0000363 )
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000364
365 def test_unicodedecodeerror(self):
366 self.check_exceptionobjectargs(
367 UnicodeDecodeError,
Guido van Rossum254348e2007-11-21 19:29:53 +0000368 ["ascii", bytearray(b"g\xfcrk"), 1, 2, "ouch"],
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000369 "'ascii' codec can't decode byte 0xfc in position 1: ouch"
370 )
371 self.check_exceptionobjectargs(
372 UnicodeDecodeError,
Guido van Rossum254348e2007-11-21 19:29:53 +0000373 ["ascii", bytearray(b"g\xfcrk"), 1, 3, "ouch"],
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000374 "'ascii' codec can't decode bytes in position 1-2: ouch"
375 )
376
377 def test_unicodetranslateerror(self):
378 self.check_exceptionobjectargs(
379 UnicodeTranslateError,
Walter Dörwaldd2034312007-05-18 16:29:38 +0000380 ["g\xfcrk", 1, 2, "ouch"],
Walter Dörwald32a4c712007-06-20 09:25:34 +0000381 "can't translate character '\\xfc' in position 1: ouch"
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000382 )
383 self.check_exceptionobjectargs(
384 UnicodeTranslateError,
Walter Dörwaldd2034312007-05-18 16:29:38 +0000385 ["g\u0100rk", 1, 2, "ouch"],
Walter Dörwald32a4c712007-06-20 09:25:34 +0000386 "can't translate character '\\u0100' in position 1: ouch"
Walter Dörwaldfd196bd2003-08-12 17:32:43 +0000387 )
388 self.check_exceptionobjectargs(
389 UnicodeTranslateError,
Walter Dörwaldd2034312007-05-18 16:29:38 +0000390 ["g\uffffrk", 1, 2, "ouch"],
Walter Dörwald32a4c712007-06-20 09:25:34 +0000391 "can't translate character '\\uffff' in position 1: ouch"
Walter Dörwaldfd196bd2003-08-12 17:32:43 +0000392 )
393 if sys.maxunicode > 0xffff:
394 self.check_exceptionobjectargs(
395 UnicodeTranslateError,
Walter Dörwaldd2034312007-05-18 16:29:38 +0000396 ["g\U00010000rk", 1, 2, "ouch"],
Walter Dörwald32a4c712007-06-20 09:25:34 +0000397 "can't translate character '\\U00010000' in position 1: ouch"
Walter Dörwaldfd196bd2003-08-12 17:32:43 +0000398 )
399 self.check_exceptionobjectargs(
400 UnicodeTranslateError,
Walter Dörwaldd2034312007-05-18 16:29:38 +0000401 ["g\xfcrk", 1, 3, "ouch"],
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000402 "can't translate characters in position 1-2: ouch"
403 )
404
405 def test_badandgoodstrictexceptions(self):
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000406 # "strict" complains about a non-exception passed in
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000407 self.assertRaises(
408 TypeError,
409 codecs.strict_errors,
410 42
411 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000412 # "strict" complains about the wrong exception type
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000413 self.assertRaises(
414 Exception,
415 codecs.strict_errors,
416 Exception("ouch")
417 )
418
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000419 # If the correct exception is passed in, "strict" raises it
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000420 self.assertRaises(
421 UnicodeEncodeError,
422 codecs.strict_errors,
Walter Dörwaldd2034312007-05-18 16:29:38 +0000423 UnicodeEncodeError("ascii", "\u3042", 0, 1, "ouch")
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000424 )
425
426 def test_badandgoodignoreexceptions(self):
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000427 # "ignore" complains about a non-exception passed in
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000428 self.assertRaises(
429 TypeError,
430 codecs.ignore_errors,
431 42
432 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000433 # "ignore" complains about the wrong exception type
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000434 self.assertRaises(
435 TypeError,
436 codecs.ignore_errors,
437 UnicodeError("ouch")
438 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000439 # If the correct exception is passed in, "ignore" returns an empty replacement
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000440 self.assertEquals(
Walter Dörwald00048f02007-05-09 10:44:06 +0000441 codecs.ignore_errors(
Walter Dörwaldd2034312007-05-18 16:29:38 +0000442 UnicodeEncodeError("ascii", "\u3042", 0, 1, "ouch")),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000443 ("", 1)
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000444 )
445 self.assertEquals(
Walter Dörwald00048f02007-05-09 10:44:06 +0000446 codecs.ignore_errors(
Guido van Rossum254348e2007-11-21 19:29:53 +0000447 UnicodeDecodeError("ascii", bytearray(b"\xff"), 0, 1, "ouch")),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000448 ("", 1)
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000449 )
450 self.assertEquals(
Walter Dörwald00048f02007-05-09 10:44:06 +0000451 codecs.ignore_errors(
Walter Dörwaldd2034312007-05-18 16:29:38 +0000452 UnicodeTranslateError("\u3042", 0, 1, "ouch")),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000453 ("", 1)
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000454 )
455
456 def test_badandgoodreplaceexceptions(self):
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000457 # "replace" complains about a non-exception passed in
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000458 self.assertRaises(
459 TypeError,
460 codecs.replace_errors,
461 42
462 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000463 # "replace" complains about the wrong exception type
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000464 self.assertRaises(
465 TypeError,
466 codecs.replace_errors,
467 UnicodeError("ouch")
468 )
Walter Dörwald690402f2005-11-17 18:51:34 +0000469 self.assertRaises(
Walter Dörwald690402f2005-11-17 18:51:34 +0000470 TypeError,
471 codecs.replace_errors,
472 BadObjectUnicodeEncodeError()
473 )
474 self.assertRaises(
Walter Dörwald690402f2005-11-17 18:51:34 +0000475 TypeError,
476 codecs.replace_errors,
477 BadObjectUnicodeDecodeError()
478 )
Guido van Rossum805365e2007-05-07 22:24:25 +0000479 # With the correct exception, "replace" returns an "?" or "\ufffd" replacement
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000480 self.assertEquals(
Walter Dörwald00048f02007-05-09 10:44:06 +0000481 codecs.replace_errors(
Walter Dörwaldd2034312007-05-18 16:29:38 +0000482 UnicodeEncodeError("ascii", "\u3042", 0, 1, "ouch")),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000483 ("?", 1)
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000484 )
485 self.assertEquals(
Walter Dörwald00048f02007-05-09 10:44:06 +0000486 codecs.replace_errors(
Guido van Rossum254348e2007-11-21 19:29:53 +0000487 UnicodeDecodeError("ascii", bytearray(b"\xff"), 0, 1, "ouch")),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000488 ("\ufffd", 1)
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000489 )
490 self.assertEquals(
Walter Dörwald00048f02007-05-09 10:44:06 +0000491 codecs.replace_errors(
Walter Dörwaldd2034312007-05-18 16:29:38 +0000492 UnicodeTranslateError("\u3042", 0, 1, "ouch")),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000493 ("\ufffd", 1)
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000494 )
495
496 def test_badandgoodxmlcharrefreplaceexceptions(self):
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000497 # "xmlcharrefreplace" complains about a non-exception passed in
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000498 self.assertRaises(
499 TypeError,
500 codecs.xmlcharrefreplace_errors,
501 42
502 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000503 # "xmlcharrefreplace" complains about the wrong exception types
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000504 self.assertRaises(
505 TypeError,
506 codecs.xmlcharrefreplace_errors,
507 UnicodeError("ouch")
508 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000509 # "xmlcharrefreplace" can only be used for encoding
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000510 self.assertRaises(
511 TypeError,
512 codecs.xmlcharrefreplace_errors,
Guido van Rossum254348e2007-11-21 19:29:53 +0000513 UnicodeDecodeError("ascii", bytearray(b"\xff"), 0, 1, "ouch")
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000514 )
515 self.assertRaises(
516 TypeError,
517 codecs.xmlcharrefreplace_errors,
Walter Dörwaldd2034312007-05-18 16:29:38 +0000518 UnicodeTranslateError("\u3042", 0, 1, "ouch")
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000519 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000520 # Use the correct exception
Walter Dörwald690402f2005-11-17 18:51:34 +0000521 cs = (0, 1, 9, 10, 99, 100, 999, 1000, 9999, 10000, 0x3042)
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000522 s = "".join(chr(c) for c in cs)
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000523 self.assertEquals(
Walter Dörwald690402f2005-11-17 18:51:34 +0000524 codecs.xmlcharrefreplace_errors(
Walter Dörwaldd2034312007-05-18 16:29:38 +0000525 UnicodeEncodeError("ascii", s, 0, len(s), "ouch")
Walter Dörwald690402f2005-11-17 18:51:34 +0000526 ),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000527 ("".join("&#%d;" % ord(c) for c in s), len(s))
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000528 )
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000529
530 def test_badandgoodbackslashreplaceexceptions(self):
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000531 # "backslashreplace" complains about a non-exception passed in
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000532 self.assertRaises(
533 TypeError,
534 codecs.backslashreplace_errors,
535 42
536 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000537 # "backslashreplace" complains about the wrong exception types
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000538 self.assertRaises(
539 TypeError,
540 codecs.backslashreplace_errors,
541 UnicodeError("ouch")
542 )
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000543 # "backslashreplace" can only be used for encoding
544 self.assertRaises(
545 TypeError,
546 codecs.backslashreplace_errors,
Guido van Rossum254348e2007-11-21 19:29:53 +0000547 UnicodeDecodeError("ascii", bytearray(b"\xff"), 0, 1, "ouch")
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000548 )
549 self.assertRaises(
550 TypeError,
551 codecs.backslashreplace_errors,
Walter Dörwaldd2034312007-05-18 16:29:38 +0000552 UnicodeTranslateError("\u3042", 0, 1, "ouch")
Walter Dörwaldea4250d2003-01-20 02:34:07 +0000553 )
554 # Use the correct exception
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000555 self.assertEquals(
Walter Dörwald00048f02007-05-09 10:44:06 +0000556 codecs.backslashreplace_errors(
Walter Dörwaldd2034312007-05-18 16:29:38 +0000557 UnicodeEncodeError("ascii", "\u3042", 0, 1, "ouch")),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000558 ("\\u3042", 1)
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000559 )
560 self.assertEquals(
Walter Dörwald00048f02007-05-09 10:44:06 +0000561 codecs.backslashreplace_errors(
Walter Dörwaldd2034312007-05-18 16:29:38 +0000562 UnicodeEncodeError("ascii", "\x00", 0, 1, "ouch")),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000563 ("\\x00", 1)
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000564 )
565 self.assertEquals(
Walter Dörwald00048f02007-05-09 10:44:06 +0000566 codecs.backslashreplace_errors(
Walter Dörwaldd2034312007-05-18 16:29:38 +0000567 UnicodeEncodeError("ascii", "\xff", 0, 1, "ouch")),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000568 ("\\xff", 1)
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000569 )
570 self.assertEquals(
Walter Dörwald00048f02007-05-09 10:44:06 +0000571 codecs.backslashreplace_errors(
Walter Dörwaldd2034312007-05-18 16:29:38 +0000572 UnicodeEncodeError("ascii", "\u0100", 0, 1, "ouch")),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000573 ("\\u0100", 1)
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000574 )
575 self.assertEquals(
Walter Dörwald00048f02007-05-09 10:44:06 +0000576 codecs.backslashreplace_errors(
Walter Dörwaldd2034312007-05-18 16:29:38 +0000577 UnicodeEncodeError("ascii", "\uffff", 0, 1, "ouch")),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000578 ("\\uffff", 1)
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000579 )
Antoine Pitrouc9a8df22010-09-09 20:33:43 +0000580 # 1 on UCS-4 builds, 2 on UCS-2
581 len_wide = len("\U00010000")
582 self.assertEquals(
583 codecs.backslashreplace_errors(
584 UnicodeEncodeError("ascii", "\U00010000",
585 0, len_wide, "ouch")),
586 ("\\U00010000", len_wide)
587 )
588 self.assertEquals(
589 codecs.backslashreplace_errors(
590 UnicodeEncodeError("ascii", "\U0010ffff",
591 0, len_wide, "ouch")),
592 ("\\U0010ffff", len_wide)
593 )
594 # Lone surrogates (regardless of unicode width)
595 self.assertEquals(
596 codecs.backslashreplace_errors(
597 UnicodeEncodeError("ascii", "\ud800", 0, 1, "ouch")),
598 ("\\ud800", 1)
599 )
600 self.assertEquals(
601 codecs.backslashreplace_errors(
602 UnicodeEncodeError("ascii", "\udfff", 0, 1, "ouch")),
603 ("\\udfff", 1)
604 )
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000605
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000606 def test_badhandlerresults(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000607 results = ( 42, "foo", (1,2,3), ("foo", 1, 3), ("foo", None), ("foo",), ("foo", 1, 3), ("foo", None), ("foo",) )
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000608 encs = ("ascii", "latin-1", "iso-8859-1", "iso-8859-15")
609
610 for res in results:
Benjamin Petersonb58dda72009-01-18 22:27:04 +0000611 codecs.register_error("test.badhandler", lambda x: res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000612 for enc in encs:
613 self.assertRaises(
614 TypeError,
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000615 "\u3042".encode,
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000616 enc,
617 "test.badhandler"
618 )
619 for (enc, bytes) in (
Walter Dörwald00048f02007-05-09 10:44:06 +0000620 ("ascii", b"\xff"),
621 ("utf-8", b"\xff"),
622 ("utf-7", b"+x-"),
623 ("unicode-internal", b"\x00"),
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000624 ):
625 self.assertRaises(
626 TypeError,
627 bytes.decode,
628 enc,
629 "test.badhandler"
630 )
631
632 def test_lookup(self):
633 self.assertEquals(codecs.strict_errors, codecs.lookup_error("strict"))
634 self.assertEquals(codecs.ignore_errors, codecs.lookup_error("ignore"))
635 self.assertEquals(codecs.strict_errors, codecs.lookup_error("strict"))
636 self.assertEquals(
637 codecs.xmlcharrefreplace_errors,
638 codecs.lookup_error("xmlcharrefreplace")
639 )
640 self.assertEquals(
641 codecs.backslashreplace_errors,
642 codecs.lookup_error("backslashreplace")
643 )
644
Walter Dörwald9ab7dd42002-09-06 17:21:40 +0000645 def test_unencodablereplacement(self):
646 def unencrepl(exc):
647 if isinstance(exc, UnicodeEncodeError):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000648 return ("\u4242", exc.end)
Walter Dörwald9ab7dd42002-09-06 17:21:40 +0000649 else:
650 raise TypeError("don't know how to handle %r" % exc)
651 codecs.register_error("test.unencreplhandler", unencrepl)
652 for enc in ("ascii", "iso-8859-1", "iso-8859-15"):
653 self.assertRaises(
654 UnicodeEncodeError,
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000655 "\u4242".encode,
Walter Dörwald9ab7dd42002-09-06 17:21:40 +0000656 enc,
657 "test.unencreplhandler"
658 )
659
Walter Dörwald30537a42003-01-08 23:22:13 +0000660 def test_badregistercall(self):
661 # enhance coverage of:
662 # Modules/_codecsmodule.c::register_error()
663 # Python/codecs.c::PyCodec_RegisterError()
664 self.assertRaises(TypeError, codecs.register_error, 42)
665 self.assertRaises(TypeError, codecs.register_error, "test.dummy", 42)
666
Walter Dörwalde22d3392005-11-17 08:52:34 +0000667 def test_badlookupcall(self):
668 # enhance coverage of:
669 # Modules/_codecsmodule.c::lookup_error()
670 self.assertRaises(TypeError, codecs.lookup_error)
671
Walter Dörwald30537a42003-01-08 23:22:13 +0000672 def test_unknownhandler(self):
673 # enhance coverage of:
674 # Modules/_codecsmodule.c::lookup_error()
675 self.assertRaises(LookupError, codecs.lookup_error, "test.unknown")
676
677 def test_xmlcharrefvalues(self):
678 # enhance coverage of:
679 # Python/codecs.c::PyCodec_XMLCharRefReplaceErrors()
680 # and inline implementations
681 v = (1, 5, 10, 50, 100, 500, 1000, 5000, 10000, 50000)
Walter Dörwald0cb27dd2003-01-09 11:38:50 +0000682 if sys.maxunicode>=100000:
Tim Petersf2715e02003-02-19 02:35:07 +0000683 v += (100000, 500000, 1000000)
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000684 s = "".join([chr(x) for x in v])
Walter Dörwald30537a42003-01-08 23:22:13 +0000685 codecs.register_error("test.xmlcharrefreplace", codecs.xmlcharrefreplace_errors)
686 for enc in ("ascii", "iso-8859-15"):
687 for err in ("xmlcharrefreplace", "test.xmlcharrefreplace"):
688 s.encode(enc, err)
689
690 def test_decodehelper(self):
691 # enhance coverage of:
692 # Objects/unicodeobject.c::unicode_decode_call_errorhandler()
693 # and callers
Guido van Rossum09549f42007-08-27 20:40:10 +0000694 self.assertRaises(LookupError, b"\xff".decode, "ascii", "test.unknown")
Walter Dörwald30537a42003-01-08 23:22:13 +0000695
696 def baddecodereturn1(exc):
697 return 42
698 codecs.register_error("test.baddecodereturn1", baddecodereturn1)
Guido van Rossum09549f42007-08-27 20:40:10 +0000699 self.assertRaises(TypeError, b"\xff".decode, "ascii", "test.baddecodereturn1")
700 self.assertRaises(TypeError, b"\\".decode, "unicode-escape", "test.baddecodereturn1")
701 self.assertRaises(TypeError, b"\\x0".decode, "unicode-escape", "test.baddecodereturn1")
702 self.assertRaises(TypeError, b"\\x0y".decode, "unicode-escape", "test.baddecodereturn1")
703 self.assertRaises(TypeError, b"\\Uffffeeee".decode, "unicode-escape", "test.baddecodereturn1")
704 self.assertRaises(TypeError, b"\\uyyyy".decode, "raw-unicode-escape", "test.baddecodereturn1")
Walter Dörwald30537a42003-01-08 23:22:13 +0000705
706 def baddecodereturn2(exc):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000707 return ("?", None)
Walter Dörwald30537a42003-01-08 23:22:13 +0000708 codecs.register_error("test.baddecodereturn2", baddecodereturn2)
Guido van Rossum09549f42007-08-27 20:40:10 +0000709 self.assertRaises(TypeError, b"\xff".decode, "ascii", "test.baddecodereturn2")
Walter Dörwald30537a42003-01-08 23:22:13 +0000710
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000711 handler = PosReturn()
712 codecs.register_error("test.posreturn", handler.handle)
Walter Dörwald30537a42003-01-08 23:22:13 +0000713
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000714 # Valid negative position
715 handler.pos = -1
Walter Dörwald00048f02007-05-09 10:44:06 +0000716 self.assertEquals(b"\xff0".decode("ascii", "test.posreturn"), "<?>0")
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000717
718 # Valid negative position
719 handler.pos = -2
Walter Dörwald00048f02007-05-09 10:44:06 +0000720 self.assertEquals(b"\xff0".decode("ascii", "test.posreturn"), "<?><?>")
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000721
722 # Negative position out of bounds
723 handler.pos = -3
Walter Dörwald00048f02007-05-09 10:44:06 +0000724 self.assertRaises(IndexError, b"\xff0".decode, "ascii", "test.posreturn")
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000725
726 # Valid positive position
727 handler.pos = 1
Walter Dörwald00048f02007-05-09 10:44:06 +0000728 self.assertEquals(b"\xff0".decode("ascii", "test.posreturn"), "<?>0")
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000729
Walter Dörwald29ddfba2004-12-14 21:28:07 +0000730 # Largest valid positive position (one beyond end of input)
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000731 handler.pos = 2
Walter Dörwald00048f02007-05-09 10:44:06 +0000732 self.assertEquals(b"\xff0".decode("ascii", "test.posreturn"), "<?>")
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000733
734 # Invalid positive position
735 handler.pos = 3
Walter Dörwald00048f02007-05-09 10:44:06 +0000736 self.assertRaises(IndexError, b"\xff0".decode, "ascii", "test.posreturn")
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000737
738 # Restart at the "0"
739 handler.pos = 6
Walter Dörwald00048f02007-05-09 10:44:06 +0000740 self.assertEquals(b"\\uyyyy0".decode("raw-unicode-escape", "test.posreturn"), "<?>0")
Walter Dörwald30537a42003-01-08 23:22:13 +0000741
742 class D(dict):
743 def __getitem__(self, key):
744 raise ValueError
Walter Dörwald00048f02007-05-09 10:44:06 +0000745 self.assertRaises(UnicodeError, codecs.charmap_decode, b"\xff", "strict", {0xff: None})
746 self.assertRaises(ValueError, codecs.charmap_decode, b"\xff", "strict", D())
747 self.assertRaises(TypeError, codecs.charmap_decode, b"\xff", "strict", {0xff: sys.maxunicode+1})
Walter Dörwald30537a42003-01-08 23:22:13 +0000748
749 def test_encodehelper(self):
750 # enhance coverage of:
751 # Objects/unicodeobject.c::unicode_encode_call_errorhandler()
752 # and callers
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000753 self.assertRaises(LookupError, "\xff".encode, "ascii", "test.unknown")
Walter Dörwald30537a42003-01-08 23:22:13 +0000754
755 def badencodereturn1(exc):
756 return 42
757 codecs.register_error("test.badencodereturn1", badencodereturn1)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000758 self.assertRaises(TypeError, "\xff".encode, "ascii", "test.badencodereturn1")
Walter Dörwald30537a42003-01-08 23:22:13 +0000759
760 def badencodereturn2(exc):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000761 return ("?", None)
Walter Dörwald30537a42003-01-08 23:22:13 +0000762 codecs.register_error("test.badencodereturn2", badencodereturn2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000763 self.assertRaises(TypeError, "\xff".encode, "ascii", "test.badencodereturn2")
Walter Dörwald30537a42003-01-08 23:22:13 +0000764
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000765 handler = PosReturn()
766 codecs.register_error("test.posreturn", handler.handle)
Walter Dörwald30537a42003-01-08 23:22:13 +0000767
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000768 # Valid negative position
769 handler.pos = -1
Walter Dörwald00048f02007-05-09 10:44:06 +0000770 self.assertEquals("\xff0".encode("ascii", "test.posreturn"), b"<?>0")
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000771
772 # Valid negative position
773 handler.pos = -2
Walter Dörwald00048f02007-05-09 10:44:06 +0000774 self.assertEquals("\xff0".encode("ascii", "test.posreturn"), b"<?><?>")
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000775
776 # Negative position out of bounds
777 handler.pos = -3
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000778 self.assertRaises(IndexError, "\xff0".encode, "ascii", "test.posreturn")
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000779
780 # Valid positive position
781 handler.pos = 1
Walter Dörwald00048f02007-05-09 10:44:06 +0000782 self.assertEquals("\xff0".encode("ascii", "test.posreturn"), b"<?>0")
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000783
784 # Largest valid positive position (one beyond end of input
785 handler.pos = 2
Walter Dörwald00048f02007-05-09 10:44:06 +0000786 self.assertEquals("\xff0".encode("ascii", "test.posreturn"), b"<?>")
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000787
788 # Invalid positive position
789 handler.pos = 3
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000790 self.assertRaises(IndexError, "\xff0".encode, "ascii", "test.posreturn")
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000791
792 handler.pos = 0
Walter Dörwald30537a42003-01-08 23:22:13 +0000793
794 class D(dict):
795 def __getitem__(self, key):
796 raise ValueError
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000797 for err in ("strict", "replace", "xmlcharrefreplace", "backslashreplace", "test.posreturn"):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000798 self.assertRaises(UnicodeError, codecs.charmap_encode, "\xff", err, {0xff: None})
799 self.assertRaises(ValueError, codecs.charmap_encode, "\xff", err, D())
800 self.assertRaises(TypeError, codecs.charmap_encode, "\xff", err, {0xff: 300})
Walter Dörwald30537a42003-01-08 23:22:13 +0000801
802 def test_translatehelper(self):
803 # enhance coverage of:
804 # Objects/unicodeobject.c::unicode_encode_call_errorhandler()
805 # and callers
806 # (Unfortunately the errors argument is not directly accessible
807 # from Python, so we can't test that much)
808 class D(dict):
809 def __getitem__(self, key):
810 raise ValueError
Georg Brandledbcc132007-10-24 21:25:34 +0000811 #self.assertRaises(ValueError, "\xff".translate, D())
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000812 self.assertRaises(TypeError, "\xff".translate, {0xff: sys.maxunicode+1})
813 self.assertRaises(TypeError, "\xff".translate, {0xff: ()})
Walter Dörwald30537a42003-01-08 23:22:13 +0000814
Walter Dörwald4894c302003-10-24 14:25:28 +0000815 def test_bug828737(self):
816 charmap = {
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000817 ord("&"): "&amp;",
818 ord("<"): "&lt;",
819 ord(">"): "&gt;",
820 ord('"'): "&quot;",
Walter Dörwald4894c302003-10-24 14:25:28 +0000821 }
Tim Peters58eb11c2004-01-18 20:29:55 +0000822
Walter Dörwald4894c302003-10-24 14:25:28 +0000823 for n in (1, 10, 100, 1000):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000824 text = 'abc<def>ghi'*n
Walter Dörwald4894c302003-10-24 14:25:28 +0000825 text.translate(charmap)
826
Walter Dörwalde78178e2007-07-30 13:31:40 +0000827 def test_mutatingdecodehandler(self):
828 baddata = [
829 ("ascii", b"\xff"),
830 ("utf-7", b"++"),
831 ("utf-8", b"\xff"),
832 ("utf-16", b"\xff"),
Walter Dörwald41980ca2007-08-16 21:55:45 +0000833 ("utf-32", b"\xff"),
Walter Dörwalde78178e2007-07-30 13:31:40 +0000834 ("unicode-escape", b"\\u123g"),
835 ("raw-unicode-escape", b"\\u123g"),
836 ("unicode-internal", b"\xff"),
837 ]
838
839 def replacing(exc):
840 if isinstance(exc, UnicodeDecodeError):
841 exc.object = 42
842 return ("\u4242", 0)
843 else:
844 raise TypeError("don't know how to handle %r" % exc)
845 codecs.register_error("test.replacing", replacing)
846 for (encoding, data) in baddata:
847 self.assertRaises(TypeError, data.decode, encoding, "test.replacing")
848
849 def mutating(exc):
850 if isinstance(exc, UnicodeDecodeError):
851 exc.object[:] = b""
852 return ("\u4242", 0)
853 else:
854 raise TypeError("don't know how to handle %r" % exc)
855 codecs.register_error("test.mutating", mutating)
856 # If the decoder doesn't pick up the modified input the following
857 # will lead to an endless loop
858 for (encoding, data) in baddata:
859 self.assertRaises(TypeError, data.decode, encoding, "test.replacing")
860
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000861def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000862 test.support.run_unittest(CodecCallbackTest)
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000863
864if __name__ == "__main__":
865 test_main()