Replaced my dumb way of calculating seconds to midnight with Tim Peters' much more...
[python.git] / Lib / test / test_multibytecodec_support.py
blobbec32de1d5673e854601ba1ad30e24272265a6d0
1 #!/usr/bin/env python
3 # test_multibytecodec_support.py
4 # Common Unittest Routines for CJK codecs
7 import sys, codecs, os.path
8 import unittest
9 from test import test_support
10 from StringIO import StringIO
12 class TestBase:
13 encoding = '' # codec name
14 codec = None # codec tuple (with 4 elements)
15 tstring = '' # string to test StreamReader
17 codectests = None # must set. codec test tuple
18 roundtriptest = 1 # set if roundtrip is possible with unicode
19 has_iso10646 = 0 # set if this encoding contains whole iso10646 map
20 xmlcharnametest = None # string to test xmlcharrefreplace
21 unmappedunicode = u'\udeee' # a unicode codepoint that is not mapped.
23 def setUp(self):
24 if self.codec is None:
25 self.codec = codecs.lookup(self.encoding)
26 self.encode = self.codec.encode
27 self.decode = self.codec.decode
28 self.reader = self.codec.streamreader
29 self.writer = self.codec.streamwriter
30 self.incrementalencoder = self.codec.incrementalencoder
31 self.incrementaldecoder = self.codec.incrementaldecoder
33 def test_chunkcoding(self):
34 for native, utf8 in zip(*[StringIO(f).readlines()
35 for f in self.tstring]):
36 u = self.decode(native)[0]
37 self.assertEqual(u, utf8.decode('utf-8'))
38 if self.roundtriptest:
39 self.assertEqual(native, self.encode(u)[0])
41 def test_errorhandle(self):
42 for source, scheme, expected in self.codectests:
43 if type(source) == type(''):
44 func = self.decode
45 else:
46 func = self.encode
47 if expected:
48 result = func(source, scheme)[0]
49 self.assertEqual(result, expected)
50 else:
51 self.assertRaises(UnicodeError, func, source, scheme)
53 def test_xmlcharrefreplace(self):
54 if self.has_iso10646:
55 return
57 s = u"\u0b13\u0b23\u0b60 nd eggs"
58 self.assertEqual(
59 self.encode(s, "xmlcharrefreplace")[0],
60 "ଓଣୠ nd eggs"
63 def test_customreplace_encode(self):
64 if self.has_iso10646:
65 return
67 from htmlentitydefs import codepoint2name
69 def xmlcharnamereplace(exc):
70 if not isinstance(exc, UnicodeEncodeError):
71 raise TypeError("don't know how to handle %r" % exc)
72 l = []
73 for c in exc.object[exc.start:exc.end]:
74 if ord(c) in codepoint2name:
75 l.append(u"&%s;" % codepoint2name[ord(c)])
76 else:
77 l.append(u"&#%d;" % ord(c))
78 return (u"".join(l), exc.end)
80 codecs.register_error("test.xmlcharnamereplace", xmlcharnamereplace)
82 if self.xmlcharnametest:
83 sin, sout = self.xmlcharnametest
84 else:
85 sin = u"\xab\u211c\xbb = \u2329\u1234\u232a"
86 sout = "«ℜ» = ⟨ሴ⟩"
87 self.assertEqual(self.encode(sin,
88 "test.xmlcharnamereplace")[0], sout)
90 def test_callback_wrong_objects(self):
91 def myreplace(exc):
92 return (ret, exc.end)
93 codecs.register_error("test.cjktest", myreplace)
95 for ret in ([1, 2, 3], [], None, object(), 'string', ''):
96 self.assertRaises(TypeError, self.encode, self.unmappedunicode,
97 'test.cjktest')
99 def test_callback_long_index(self):
100 def myreplace(exc):
101 return (u'x', long(exc.end))
102 codecs.register_error("test.cjktest", myreplace)
103 self.assertEqual(self.encode(u'abcd' + self.unmappedunicode + u'efgh',
104 'test.cjktest'), ('abcdxefgh', 9))
106 def myreplace(exc):
107 return (u'x', sys.maxint + 1)
108 codecs.register_error("test.cjktest", myreplace)
109 self.assertRaises(IndexError, self.encode, self.unmappedunicode,
110 'test.cjktest')
112 def test_callback_None_index(self):
113 def myreplace(exc):
114 return (u'x', None)
115 codecs.register_error("test.cjktest", myreplace)
116 self.assertRaises(TypeError, self.encode, self.unmappedunicode,
117 'test.cjktest')
119 def test_callback_backward_index(self):
120 def myreplace(exc):
121 if myreplace.limit > 0:
122 myreplace.limit -= 1
123 return (u'REPLACED', 0)
124 else:
125 return (u'TERMINAL', exc.end)
126 myreplace.limit = 3
127 codecs.register_error("test.cjktest", myreplace)
128 self.assertEqual(self.encode(u'abcd' + self.unmappedunicode + u'efgh',
129 'test.cjktest'),
130 ('abcdREPLACEDabcdREPLACEDabcdREPLACEDabcdTERMINALefgh', 9))
132 def test_callback_forward_index(self):
133 def myreplace(exc):
134 return (u'REPLACED', exc.end + 2)
135 codecs.register_error("test.cjktest", myreplace)
136 self.assertEqual(self.encode(u'abcd' + self.unmappedunicode + u'efgh',
137 'test.cjktest'), ('abcdREPLACEDgh', 9))
139 def test_callback_index_outofbound(self):
140 def myreplace(exc):
141 return (u'TERM', 100)
142 codecs.register_error("test.cjktest", myreplace)
143 self.assertRaises(IndexError, self.encode, self.unmappedunicode,
144 'test.cjktest')
146 def test_incrementalencoder(self):
147 UTF8Reader = codecs.getreader('utf-8')
148 for sizehint in [None] + range(1, 33) + \
149 [64, 128, 256, 512, 1024]:
150 istream = UTF8Reader(StringIO(self.tstring[1]))
151 ostream = StringIO()
152 encoder = self.incrementalencoder()
153 while 1:
154 if sizehint is not None:
155 data = istream.read(sizehint)
156 else:
157 data = istream.read()
159 if not data:
160 break
161 e = encoder.encode(data)
162 ostream.write(e)
164 self.assertEqual(ostream.getvalue(), self.tstring[0])
166 def test_incrementaldecoder(self):
167 UTF8Writer = codecs.getwriter('utf-8')
168 for sizehint in [None, -1] + range(1, 33) + \
169 [64, 128, 256, 512, 1024]:
170 istream = StringIO(self.tstring[0])
171 ostream = UTF8Writer(StringIO())
172 decoder = self.incrementaldecoder()
173 while 1:
174 data = istream.read(sizehint)
175 if not data:
176 break
177 else:
178 u = decoder.decode(data)
179 ostream.write(u)
181 self.assertEqual(ostream.getvalue(), self.tstring[1])
183 def test_incrementalencoder_error_callback(self):
184 inv = self.unmappedunicode
186 e = self.incrementalencoder()
187 self.assertRaises(UnicodeEncodeError, e.encode, inv, True)
189 e.errors = 'ignore'
190 self.assertEqual(e.encode(inv, True), '')
192 e.reset()
193 def tempreplace(exc):
194 return (u'called', exc.end)
195 codecs.register_error('test.incremental_error_callback', tempreplace)
196 e.errors = 'test.incremental_error_callback'
197 self.assertEqual(e.encode(inv, True), 'called')
199 # again
200 e.errors = 'ignore'
201 self.assertEqual(e.encode(inv, True), '')
203 def test_streamreader(self):
204 UTF8Writer = codecs.getwriter('utf-8')
205 for name in ["read", "readline", "readlines"]:
206 for sizehint in [None, -1] + range(1, 33) + \
207 [64, 128, 256, 512, 1024]:
208 istream = self.reader(StringIO(self.tstring[0]))
209 ostream = UTF8Writer(StringIO())
210 func = getattr(istream, name)
211 while 1:
212 data = func(sizehint)
213 if not data:
214 break
215 if name == "readlines":
216 ostream.writelines(data)
217 else:
218 ostream.write(data)
220 self.assertEqual(ostream.getvalue(), self.tstring[1])
222 def test_streamwriter(self):
223 readfuncs = ('read', 'readline', 'readlines')
224 UTF8Reader = codecs.getreader('utf-8')
225 for name in readfuncs:
226 for sizehint in [None] + range(1, 33) + \
227 [64, 128, 256, 512, 1024]:
228 istream = UTF8Reader(StringIO(self.tstring[1]))
229 ostream = self.writer(StringIO())
230 func = getattr(istream, name)
231 while 1:
232 if sizehint is not None:
233 data = func(sizehint)
234 else:
235 data = func()
237 if not data:
238 break
239 if name == "readlines":
240 ostream.writelines(data)
241 else:
242 ostream.write(data)
244 self.assertEqual(ostream.getvalue(), self.tstring[0])
246 if len(u'\U00012345') == 2: # ucs2 build
247 _unichr = unichr
248 def unichr(v):
249 if v >= 0x10000:
250 return _unichr(0xd800 + ((v - 0x10000) >> 10)) + \
251 _unichr(0xdc00 + ((v - 0x10000) & 0x3ff))
252 else:
253 return _unichr(v)
254 _ord = ord
255 def ord(c):
256 if len(c) == 2:
257 return 0x10000 + ((_ord(c[0]) - 0xd800) << 10) + \
258 (ord(c[1]) - 0xdc00)
259 else:
260 return _ord(c)
262 class TestBase_Mapping(unittest.TestCase):
263 pass_enctest = []
264 pass_dectest = []
265 supmaps = []
267 def __init__(self, *args, **kw):
268 unittest.TestCase.__init__(self, *args, **kw)
269 self.open_mapping_file() # test it to report the error early
271 def open_mapping_file(self):
272 return test_support.open_urlresource(self.mapfileurl)
274 def test_mapping_file(self):
275 unichrs = lambda s: u''.join(map(unichr, map(eval, s.split('+'))))
276 urt_wa = {}
278 for line in self.open_mapping_file():
279 if not line:
280 break
281 data = line.split('#')[0].strip().split()
282 if len(data) != 2:
283 continue
285 csetval = eval(data[0])
286 if csetval <= 0x7F:
287 csetch = chr(csetval & 0xff)
288 elif csetval >= 0x1000000:
289 csetch = chr(csetval >> 24) + chr((csetval >> 16) & 0xff) + \
290 chr((csetval >> 8) & 0xff) + chr(csetval & 0xff)
291 elif csetval >= 0x10000:
292 csetch = chr(csetval >> 16) + \
293 chr((csetval >> 8) & 0xff) + chr(csetval & 0xff)
294 elif csetval >= 0x100:
295 csetch = chr(csetval >> 8) + chr(csetval & 0xff)
296 else:
297 continue
299 unich = unichrs(data[1])
300 if ord(unich) == 0xfffd or urt_wa.has_key(unich):
301 continue
302 urt_wa[unich] = csetch
304 self._testpoint(csetch, unich)
306 def test_mapping_supplemental(self):
307 for mapping in self.supmaps:
308 self._testpoint(*mapping)
310 def _testpoint(self, csetch, unich):
311 if (csetch, unich) not in self.pass_enctest:
312 self.assertEqual(unich.encode(self.encoding), csetch)
313 if (csetch, unich) not in self.pass_dectest:
314 self.assertEqual(unicode(csetch, self.encoding), unich)
316 def load_teststring(encoding):
317 from test import cjkencodings_test
318 return cjkencodings_test.teststring[encoding]