aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/Lib/test/test_multibytecodec_support.py
diff options
context:
space:
mode:
Diffstat (limited to 'Lib/test/test_multibytecodec_support.py')
-rw-r--r--Lib/test/test_multibytecodec_support.py161
1 files changed, 87 insertions, 74 deletions
diff --git a/Lib/test/test_multibytecodec_support.py b/Lib/test/test_multibytecodec_support.py
index 52a2e503722..ef63b6934d5 100644
--- a/Lib/test/test_multibytecodec_support.py
+++ b/Lib/test/test_multibytecodec_support.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
#
# test_multibytecodec_support.py
# Common Unittest Routines for CJK codecs
@@ -9,20 +9,20 @@ import os
import re
import sys
import unittest
-from httplib import HTTPException
-from test import test_support
-from StringIO import StringIO
+from http.client import HTTPException
+from test import support
+from io import BytesIO
class TestBase:
encoding = '' # codec name
codec = None # codec tuple (with 4 elements)
- tstring = '' # string to test StreamReader
+ tstring = None # must set. 2 strings to test StreamReader
codectests = None # must set. codec test tuple
roundtriptest = 1 # set if roundtrip is possible with unicode
has_iso10646 = 0 # set if this encoding contains whole iso10646 map
xmlcharnametest = None # string to test xmlcharrefreplace
- unmappedunicode = u'\udeee' # a unicode codepoint that is not mapped.
+ unmappedunicode = '\udeee' # a unicode codepoint that is not mapped.
def setUp(self):
if self.codec is None:
@@ -35,8 +35,14 @@ class TestBase:
self.incrementaldecoder = self.codec.incrementaldecoder
def test_chunkcoding(self):
- for native, utf8 in zip(*[StringIO(f).readlines()
- for f in self.tstring]):
+ tstring_lines = []
+ for b in self.tstring:
+ lines = b.split(b"\n")
+ last = lines.pop()
+ assert last == b""
+ lines = [line + b"\n" for line in lines]
+ tstring_lines.append(lines)
+ for native, utf8 in zip(*tstring_lines):
u = self.decode(native)[0]
self.assertEqual(u, utf8.decode('utf-8'))
if self.roundtriptest:
@@ -51,15 +57,15 @@ class TestBase:
if expected:
result = func(source, scheme)[0]
if func is self.decode:
- self.assertTrue(type(result) is unicode, type(result))
+ self.assertTrue(type(result) is str, type(result))
self.assertEqual(result, expected,
- '%r.decode(%r, %r)=%r != %r'
+ '%a.decode(%r, %r)=%a != %a'
% (source, self.encoding, scheme, result,
expected))
else:
self.assertTrue(type(result) is bytes, type(result))
self.assertEqual(result, expected,
- '%r.encode(%r, %r)=%r != %r'
+ '%a.encode(%r, %r)=%a != %a'
% (source, self.encoding, scheme, result,
expected))
else:
@@ -69,17 +75,17 @@ class TestBase:
if self.has_iso10646:
return
- s = u"\u0b13\u0b23\u0b60 nd eggs"
+ s = "\u0b13\u0b23\u0b60 nd eggs"
self.assertEqual(
self.encode(s, "xmlcharrefreplace")[0],
- "ଓଣୠ nd eggs"
+ b"ଓଣୠ nd eggs"
)
def test_customreplace_encode(self):
if self.has_iso10646:
return
- from htmlentitydefs import codepoint2name
+ from html.entities import codepoint2name
def xmlcharnamereplace(exc):
if not isinstance(exc, UnicodeEncodeError):
@@ -87,18 +93,18 @@ class TestBase:
l = []
for c in exc.object[exc.start:exc.end]:
if ord(c) in codepoint2name:
- l.append(u"&%s;" % codepoint2name[ord(c)])
+ l.append("&%s;" % codepoint2name[ord(c)])
else:
- l.append(u"&#%d;" % ord(c))
- return (u"".join(l), exc.end)
+ l.append("&#%d;" % ord(c))
+ return ("".join(l), exc.end)
codecs.register_error("test.xmlcharnamereplace", xmlcharnamereplace)
if self.xmlcharnametest:
sin, sout = self.xmlcharnametest
else:
- sin = u"\xab\u211c\xbb = \u2329\u1234\u232a"
- sout = "«ℜ» = ⟨ሴ⟩"
+ sin = "\xab\u211c\xbb = \u2329\u1234\u232a"
+ sout = b"«ℜ» = ⟨ሴ⟩"
self.assertEqual(self.encode(sin,
"test.xmlcharnamereplace")[0], sout)
@@ -107,26 +113,26 @@ class TestBase:
return (ret, exc.end)
codecs.register_error("test.cjktest", myreplace)
- for ret in ([1, 2, 3], [], None, object(), 'string', ''):
+ for ret in ([1, 2, 3], [], None, object(), b'string', b''):
self.assertRaises(TypeError, self.encode, self.unmappedunicode,
'test.cjktest')
def test_callback_long_index(self):
def myreplace(exc):
- return (u'x', long(exc.end))
+ return ('x', int(exc.end))
codecs.register_error("test.cjktest", myreplace)
- self.assertEqual(self.encode(u'abcd' + self.unmappedunicode + u'efgh',
- 'test.cjktest'), ('abcdxefgh', 9))
+ self.assertEqual(self.encode('abcd' + self.unmappedunicode + 'efgh',
+ 'test.cjktest'), (b'abcdxefgh', 9))
def myreplace(exc):
- return (u'x', sys.maxint + 1)
+ return ('x', sys.maxsize + 1)
codecs.register_error("test.cjktest", myreplace)
self.assertRaises(IndexError, self.encode, self.unmappedunicode,
'test.cjktest')
def test_callback_None_index(self):
def myreplace(exc):
- return (u'x', None)
+ return ('x', None)
codecs.register_error("test.cjktest", myreplace)
self.assertRaises(TypeError, self.encode, self.unmappedunicode,
'test.cjktest')
@@ -135,35 +141,35 @@ class TestBase:
def myreplace(exc):
if myreplace.limit > 0:
myreplace.limit -= 1
- return (u'REPLACED', 0)
+ return ('REPLACED', 0)
else:
- return (u'TERMINAL', exc.end)
+ return ('TERMINAL', exc.end)
myreplace.limit = 3
codecs.register_error("test.cjktest", myreplace)
- self.assertEqual(self.encode(u'abcd' + self.unmappedunicode + u'efgh',
+ self.assertEqual(self.encode('abcd' + self.unmappedunicode + 'efgh',
'test.cjktest'),
- ('abcdREPLACEDabcdREPLACEDabcdREPLACEDabcdTERMINALefgh', 9))
+ (b'abcdREPLACEDabcdREPLACEDabcdREPLACEDabcdTERMINALefgh', 9))
def test_callback_forward_index(self):
def myreplace(exc):
- return (u'REPLACED', exc.end + 2)
+ return ('REPLACED', exc.end + 2)
codecs.register_error("test.cjktest", myreplace)
- self.assertEqual(self.encode(u'abcd' + self.unmappedunicode + u'efgh',
- 'test.cjktest'), ('abcdREPLACEDgh', 9))
+ self.assertEqual(self.encode('abcd' + self.unmappedunicode + 'efgh',
+ 'test.cjktest'), (b'abcdREPLACEDgh', 9))
def test_callback_index_outofbound(self):
def myreplace(exc):
- return (u'TERM', 100)
+ return ('TERM', 100)
codecs.register_error("test.cjktest", myreplace)
self.assertRaises(IndexError, self.encode, self.unmappedunicode,
'test.cjktest')
def test_incrementalencoder(self):
UTF8Reader = codecs.getreader('utf-8')
- for sizehint in [None] + range(1, 33) + \
+ for sizehint in [None] + list(range(1, 33)) + \
[64, 128, 256, 512, 1024]:
- istream = UTF8Reader(StringIO(self.tstring[1]))
- ostream = StringIO()
+ istream = UTF8Reader(BytesIO(self.tstring[1]))
+ ostream = BytesIO()
encoder = self.incrementalencoder()
while 1:
if sizehint is not None:
@@ -180,10 +186,10 @@ class TestBase:
def test_incrementaldecoder(self):
UTF8Writer = codecs.getwriter('utf-8')
- for sizehint in [None, -1] + range(1, 33) + \
+ for sizehint in [None, -1] + list(range(1, 33)) + \
[64, 128, 256, 512, 1024]:
- istream = StringIO(self.tstring[0])
- ostream = UTF8Writer(StringIO())
+ istream = BytesIO(self.tstring[0])
+ ostream = UTF8Writer(BytesIO())
decoder = self.incrementaldecoder()
while 1:
data = istream.read(sizehint)
@@ -202,26 +208,26 @@ class TestBase:
self.assertRaises(UnicodeEncodeError, e.encode, inv, True)
e.errors = 'ignore'
- self.assertEqual(e.encode(inv, True), '')
+ self.assertEqual(e.encode(inv, True), b'')
e.reset()
def tempreplace(exc):
- return (u'called', exc.end)
+ return ('called', exc.end)
codecs.register_error('test.incremental_error_callback', tempreplace)
e.errors = 'test.incremental_error_callback'
- self.assertEqual(e.encode(inv, True), 'called')
+ self.assertEqual(e.encode(inv, True), b'called')
# again
e.errors = 'ignore'
- self.assertEqual(e.encode(inv, True), '')
+ self.assertEqual(e.encode(inv, True), b'')
def test_streamreader(self):
UTF8Writer = codecs.getwriter('utf-8')
for name in ["read", "readline", "readlines"]:
- for sizehint in [None, -1] + range(1, 33) + \
+ for sizehint in [None, -1] + list(range(1, 33)) + \
[64, 128, 256, 512, 1024]:
- istream = self.reader(StringIO(self.tstring[0]))
- ostream = UTF8Writer(StringIO())
+ istream = self.reader(BytesIO(self.tstring[0]))
+ ostream = UTF8Writer(BytesIO())
func = getattr(istream, name)
while 1:
data = func(sizehint)
@@ -238,10 +244,10 @@ class TestBase:
readfuncs = ('read', 'readline', 'readlines')
UTF8Reader = codecs.getreader('utf-8')
for name in readfuncs:
- for sizehint in [None] + range(1, 33) + \
+ for sizehint in [None] + list(range(1, 33)) + \
[64, 128, 256, 512, 1024]:
- istream = UTF8Reader(StringIO(self.tstring[1]))
- ostream = self.writer(StringIO())
+ istream = UTF8Reader(BytesIO(self.tstring[1]))
+ ostream = self.writer(BytesIO())
func = getattr(istream, name)
while 1:
if sizehint is not None:
@@ -258,6 +264,22 @@ class TestBase:
self.assertEqual(ostream.getvalue(), self.tstring[0])
+if len('\U00012345') == 2: # ucs2 build
+ _unichr = chr
+ def chr(v):
+ if v >= 0x10000:
+ return _unichr(0xd800 + ((v - 0x10000) >> 10)) + \
+ _unichr(0xdc00 + ((v - 0x10000) & 0x3ff))
+ else:
+ return _unichr(v)
+ _ord = ord
+ def ord(c):
+ if len(c) == 2:
+ return 0x10000 + ((_ord(c[0]) - 0xd800) << 10) + \
+ (ord(c[1]) - 0xdc00)
+ else:
+ return _ord(c)
+
class TestBase_Mapping(unittest.TestCase):
pass_enctest = []
pass_dectest = []
@@ -272,7 +294,7 @@ class TestBase_Mapping(unittest.TestCase):
self.skipTest("Could not retrieve "+self.mapfileurl)
def open_mapping_file(self):
- return test_support.open_urlresource(self.mapfileurl)
+ return support.open_urlresource(self.mapfileurl)
def test_mapping_file(self):
if self.mapfileurl.endswith('.xml'):
@@ -281,8 +303,7 @@ class TestBase_Mapping(unittest.TestCase):
self._test_mapping_file_plain()
def _test_mapping_file_plain(self):
- _unichr = lambda c: eval("u'\\U%08x'" % int(c, 16))
- unichrs = lambda s: u''.join(_unichr(c) for c in s.split('+'))
+ unichrs = lambda s: ''.join(map(chr, map(eval, s.split('+'))))
urt_wa = {}
with self.open_mapping_file() as f:
@@ -295,20 +316,20 @@ class TestBase_Mapping(unittest.TestCase):
csetval = eval(data[0])
if csetval <= 0x7F:
- csetch = chr(csetval & 0xff)
+ csetch = bytes([csetval & 0xff])
elif csetval >= 0x1000000:
- csetch = chr(csetval >> 24) + chr((csetval >> 16) & 0xff) + \
- chr((csetval >> 8) & 0xff) + chr(csetval & 0xff)
+ csetch = bytes([(csetval >> 24), ((csetval >> 16) & 0xff),
+ ((csetval >> 8) & 0xff), (csetval & 0xff)])
elif csetval >= 0x10000:
- csetch = chr(csetval >> 16) + \
- chr((csetval >> 8) & 0xff) + chr(csetval & 0xff)
+ csetch = bytes([(csetval >> 16), ((csetval >> 8) & 0xff),
+ (csetval & 0xff)])
elif csetval >= 0x100:
- csetch = chr(csetval >> 8) + chr(csetval & 0xff)
+ csetch = bytes([(csetval >> 8), (csetval & 0xff)])
else:
continue
unich = unichrs(data[1])
- if unich == u'\ufffd' or unich in urt_wa:
+ if ord(unich) == 0xfffd or unich in urt_wa:
continue
urt_wa[unich] = csetch
@@ -319,8 +340,8 @@ class TestBase_Mapping(unittest.TestCase):
ucmdata = f.read()
uc = re.findall('<a u="([A-F0-9]{4})" b="([0-9A-F ]+)"/>', ucmdata)
for uni, coded in uc:
- unich = unichr(int(uni, 16))
- codech = ''.join(chr(int(c, 16)) for c in coded.split())
+ unich = chr(int(uni, 16))
+ codech = bytes(int(c, 16) for c in coded.split())
self._testpoint(codech, unich)
def test_mapping_supplemental(self):
@@ -329,17 +350,9 @@ class TestBase_Mapping(unittest.TestCase):
def _testpoint(self, csetch, unich):
if (csetch, unich) not in self.pass_enctest:
- try:
- self.assertEqual(unich.encode(self.encoding), csetch)
- except UnicodeError, exc:
- self.fail('Encoding failed while testing %s -> %s: %s' % (
- repr(unich), repr(csetch), exc.reason))
+ self.assertEqual(unich.encode(self.encoding), csetch)
if (csetch, unich) not in self.pass_dectest:
- try:
- self.assertEqual(csetch.decode(self.encoding), unich)
- except UnicodeError, exc:
- self.fail('Decoding failed while testing %s -> %s: %s' % (
- repr(csetch), repr(unich), exc.reason))
+ self.assertEqual(str(csetch, self.encoding), unich)
def test_errorhandle(self):
for source, scheme, expected in self.codectests:
@@ -350,16 +363,16 @@ class TestBase_Mapping(unittest.TestCase):
if expected:
if isinstance(source, bytes):
result = func(self.encoding, scheme)
- self.assertTrue(type(result) is unicode, type(result))
+ self.assertTrue(type(result) is str, type(result))
self.assertEqual(result, expected,
- '%r.decode(%r, %r)=%r != %r'
+ '%a.decode(%r, %r)=%a != %a'
% (source, self.encoding, scheme, result,
expected))
else:
result = func(self.encoding, scheme)
self.assertTrue(type(result) is bytes, type(result))
self.assertEqual(result, expected,
- '%r.encode(%r, %r)=%r != %r'
+ '%a.encode(%r, %r)=%a != %a'
% (source, self.encoding, scheme, result,
expected))
else: