Commits

Jeff Allen  committed e3f1125 Merge

Merge codec work to trunk

  • Participants
  • Parent commits 318673e, c0072e7

Comments (0)

Files changed (4)

File Lib/test/test_codecs.py

+# test_codecs.py from CPython 2.7, modified for Jython
 from test import test_support
 import unittest
 import codecs
-import StringIO
+import locale
+import sys, StringIO
+if not test_support.is_jython:
+    import _testcapi
 
-class UTF16Test(unittest.TestCase):
+class Queue(object):
+    """
+    queue: write bytes at one end, read bytes from the other end
+    """
+    def __init__(self):
+        self._buffer = ""
+
+    def write(self, chars):
+        self._buffer += chars
+
+    def read(self, size=-1):
+        if size<0:
+            s = self._buffer
+            self._buffer = ""
+            return s
+        else:
+            s = self._buffer[:size]
+            self._buffer = self._buffer[size:]
+            return s
+
+class ReadTest(unittest.TestCase):
+    def check_partial(self, input, partialresults):
+        # get a StreamReader for the encoding and feed the bytestring version
+        # of input to the reader byte by byte. Read everything available from
+        # the StreamReader and check that the results equal the appropriate
+        # entries from partialresults.
+        q = Queue()
+        r = codecs.getreader(self.encoding)(q)
+        result = u""
+        for (c, partialresult) in zip(input.encode(self.encoding), partialresults):
+            q.write(c)
+            result += r.read()
+            self.assertEqual(result, partialresult)
+        # check that there's nothing left in the buffers
+        self.assertEqual(r.read(), u"")
+        self.assertEqual(r.bytebuffer, "")
+        self.assertEqual(r.charbuffer, u"")
+
+        # do the check again, this time using a incremental decoder
+        d = codecs.getincrementaldecoder(self.encoding)()
+        result = u""
+        for (c, partialresult) in zip(input.encode(self.encoding), partialresults):
+            result += d.decode(c)
+            self.assertEqual(result, partialresult)
+        # check that there's nothing left in the buffers
+        self.assertEqual(d.decode("", True), u"")
+        self.assertEqual(d.buffer, "")
+
+        # Check whether the reset method works properly
+        d.reset()
+        result = u""
+        for (c, partialresult) in zip(input.encode(self.encoding), partialresults):
+            result += d.decode(c)
+            self.assertEqual(result, partialresult)
+        # check that there's nothing left in the buffers
+        self.assertEqual(d.decode("", True), u"")
+        self.assertEqual(d.buffer, "")
+
+        # check iterdecode()
+        encoded = input.encode(self.encoding)
+        self.assertEqual(
+            input,
+            u"".join(codecs.iterdecode(encoded, self.encoding))
+        )
+
+    def test_readline(self):
+        def getreader(input):
+            stream = StringIO.StringIO(input.encode(self.encoding))
+            return codecs.getreader(self.encoding)(stream)
+
+        def readalllines(input, keepends=True, size=None):
+            reader = getreader(input)
+            lines = []
+            while True:
+                line = reader.readline(size=size, keepends=keepends)
+                if not line:
+                    break
+                lines.append(line)
+            return "|".join(lines)
+
+        s = u"foo\nbar\r\nbaz\rspam\u2028eggs"
+        sexpected = u"foo\n|bar\r\n|baz\r|spam\u2028|eggs"
+        sexpectednoends = u"foo|bar|baz|spam|eggs"
+        self.assertEqual(readalllines(s, True), sexpected)
+        self.assertEqual(readalllines(s, False), sexpectednoends)
+        self.assertEqual(readalllines(s, True, 10), sexpected)
+        self.assertEqual(readalllines(s, False, 10), sexpectednoends)
+
+        # Test long lines (multiple calls to read() in readline())
+        vw = []
+        vwo = []
+        for (i, lineend) in enumerate(u"\n \r\n \r \u2028".split()):
+            vw.append((i*200)*u"\3042" + lineend)
+            vwo.append((i*200)*u"\3042")
+        self.assertEqual(readalllines("".join(vw), True), "".join(vw))
+        self.assertEqual(readalllines("".join(vw), False),"".join(vwo))
+
+        # Test lines where the first read might end with \r, so the
+        # reader has to look ahead whether this is a lone \r or a \r\n
+        for size in xrange(80):
+            for lineend in u"\n \r\n \r \u2028".split():
+                s = 10*(size*u"a" + lineend + u"xxx\n")
+                reader = getreader(s)
+                for i in xrange(10):
+                    self.assertEqual(
+                        reader.readline(keepends=True),
+                        size*u"a" + lineend,
+                    )
+                reader = getreader(s)
+                for i in xrange(10):
+                    self.assertEqual(
+                        reader.readline(keepends=False),
+                        size*u"a",
+                    )
+
+    def test_bug1175396(self):
+        s = [
+            '<%!--===================================================\r\n',
+            '    BLOG index page: show recent articles,\r\n',
+            '    today\'s articles, or articles of a specific date.\r\n',
+            '========================================================--%>\r\n',
+            '<%@inputencoding="ISO-8859-1"%>\r\n',
+            '<%@pagetemplate=TEMPLATE.y%>\r\n',
+            '<%@import=import frog.util, frog%>\r\n',
+            '<%@import=import frog.objects%>\r\n',
+            '<%@import=from frog.storageerrors import StorageError%>\r\n',
+            '<%\r\n',
+            '\r\n',
+            'import logging\r\n',
+            'log=logging.getLogger("Snakelets.logger")\r\n',
+            '\r\n',
+            '\r\n',
+            'user=self.SessionCtx.user\r\n',
+            'storageEngine=self.SessionCtx.storageEngine\r\n',
+            '\r\n',
+            '\r\n',
+            'def readArticlesFromDate(date, count=None):\r\n',
+            '    entryids=storageEngine.listBlogEntries(date)\r\n',
+            '    entryids.reverse() # descending\r\n',
+            '    if count:\r\n',
+            '        entryids=entryids[:count]\r\n',
+            '    try:\r\n',
+            '        return [ frog.objects.BlogEntry.load(storageEngine, date, Id) for Id in entryids ]\r\n',
+            '    except StorageError,x:\r\n',
+            '        log.error("Error loading articles: "+str(x))\r\n',
+            '        self.abort("cannot load articles")\r\n',
+            '\r\n',
+            'showdate=None\r\n',
+            '\r\n',
+            'arg=self.Request.getArg()\r\n',
+            'if arg=="today":\r\n',
+            '    #-------------------- TODAY\'S ARTICLES\r\n',
+            '    self.write("<h2>Today\'s articles</h2>")\r\n',
+            '    showdate = frog.util.isodatestr() \r\n',
+            '    entries = readArticlesFromDate(showdate)\r\n',
+            'elif arg=="active":\r\n',
+            '    #-------------------- ACTIVE ARTICLES redirect\r\n',
+            '    self.Yredirect("active.y")\r\n',
+            'elif arg=="login":\r\n',
+            '    #-------------------- LOGIN PAGE redirect\r\n',
+            '    self.Yredirect("login.y")\r\n',
+            'elif arg=="date":\r\n',
+            '    #-------------------- ARTICLES OF A SPECIFIC DATE\r\n',
+            '    showdate = self.Request.getParameter("date")\r\n',
+            '    self.write("<h2>Articles written on %s</h2>"% frog.util.mediumdatestr(showdate))\r\n',
+            '    entries = readArticlesFromDate(showdate)\r\n',
+            'else:\r\n',
+            '    #-------------------- RECENT ARTICLES\r\n',
+            '    self.write("<h2>Recent articles</h2>")\r\n',
+            '    dates=storageEngine.listBlogEntryDates()\r\n',
+            '    if dates:\r\n',
+            '        entries=[]\r\n',
+            '        SHOWAMOUNT=10\r\n',
+            '        for showdate in dates:\r\n',
+            '            entries.extend( readArticlesFromDate(showdate, SHOWAMOUNT-len(entries)) )\r\n',
+            '            if len(entries)>=SHOWAMOUNT:\r\n',
+            '                break\r\n',
+            '                \r\n',
+        ]
+        stream = StringIO.StringIO("".join(s).encode(self.encoding))
+        reader = codecs.getreader(self.encoding)(stream)
+        for (i, line) in enumerate(reader):
+            self.assertEqual(line, s[i])
+
+    def test_readlinequeue(self):
+        q = Queue()
+        writer = codecs.getwriter(self.encoding)(q)
+        reader = codecs.getreader(self.encoding)(q)
+
+        # No lineends
+        writer.write(u"foo\r")
+        self.assertEqual(reader.readline(keepends=False), u"foo")
+        writer.write(u"\nbar\r")
+        self.assertEqual(reader.readline(keepends=False), u"")
+        self.assertEqual(reader.readline(keepends=False), u"bar")
+        writer.write(u"baz")
+        self.assertEqual(reader.readline(keepends=False), u"baz")
+        self.assertEqual(reader.readline(keepends=False), u"")
+
+        # Lineends
+        writer.write(u"foo\r")
+        self.assertEqual(reader.readline(keepends=True), u"foo\r")
+        writer.write(u"\nbar\r")
+        self.assertEqual(reader.readline(keepends=True), u"\n")
+        self.assertEqual(reader.readline(keepends=True), u"bar\r")
+        writer.write(u"baz")
+        self.assertEqual(reader.readline(keepends=True), u"baz")
+        self.assertEqual(reader.readline(keepends=True), u"")
+        writer.write(u"foo\r\n")
+        self.assertEqual(reader.readline(keepends=True), u"foo\r\n")
+
+    def test_bug1098990_a(self):
+        s1 = u"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy\r\n"
+        s2 = u"offending line: ladfj askldfj klasdj fskla dfzaskdj fasklfj laskd fjasklfzzzzaa%whereisthis!!!\r\n"
+        s3 = u"next line.\r\n"
+
+        s = (s1+s2+s3).encode(self.encoding)
+        stream = StringIO.StringIO(s)
+        reader = codecs.getreader(self.encoding)(stream)
+        self.assertEqual(reader.readline(), s1)
+        self.assertEqual(reader.readline(), s2)
+        self.assertEqual(reader.readline(), s3)
+        self.assertEqual(reader.readline(), u"")
+
+    def test_bug1098990_b(self):
+        s1 = u"aaaaaaaaaaaaaaaaaaaaaaaa\r\n"
+        s2 = u"bbbbbbbbbbbbbbbbbbbbbbbb\r\n"
+        s3 = u"stillokay:bbbbxx\r\n"
+        s4 = u"broken!!!!badbad\r\n"
+        s5 = u"againokay.\r\n"
+
+        s = (s1+s2+s3+s4+s5).encode(self.encoding)
+        stream = StringIO.StringIO(s)
+        reader = codecs.getreader(self.encoding)(stream)
+        self.assertEqual(reader.readline(), s1)
+        self.assertEqual(reader.readline(), s2)
+        self.assertEqual(reader.readline(), s3)
+        self.assertEqual(reader.readline(), s4)
+        self.assertEqual(reader.readline(), s5)
+        self.assertEqual(reader.readline(), u"")
+
+@unittest.skipIf(test_support.is_jython, "FIXME: Jython issue 2000 missing support for UTF-32")
+class UTF32Test(ReadTest):
+    encoding = "utf-32"
+
+    spamle = ('\xff\xfe\x00\x00'
+              's\x00\x00\x00p\x00\x00\x00a\x00\x00\x00m\x00\x00\x00'
+              's\x00\x00\x00p\x00\x00\x00a\x00\x00\x00m\x00\x00\x00')
+    spambe = ('\x00\x00\xfe\xff'
+              '\x00\x00\x00s\x00\x00\x00p\x00\x00\x00a\x00\x00\x00m'
+              '\x00\x00\x00s\x00\x00\x00p\x00\x00\x00a\x00\x00\x00m')
+
+    def test_only_one_bom(self):
+        _,_,reader,writer = codecs.lookup(self.encoding)
+        # encode some stream
+        s = StringIO.StringIO()
+        f = writer(s)
+        f.write(u"spam")
+        f.write(u"spam")
+        d = s.getvalue()
+        # check whether there is exactly one BOM in it
+        self.assertTrue(d == self.spamle or d == self.spambe)
+        # try to read it back
+        s = StringIO.StringIO(d)
+        f = reader(s)
+        self.assertEqual(f.read(), u"spamspam")
+
+    def test_badbom(self):
+        s = StringIO.StringIO(4*"\xff")
+        f = codecs.getreader(self.encoding)(s)
+        self.assertRaises(UnicodeError, f.read)
+
+        s = StringIO.StringIO(8*"\xff")
+        f = codecs.getreader(self.encoding)(s)
+        self.assertRaises(UnicodeError, f.read)
+
+    def test_partial(self):
+        self.check_partial(
+            u"\x00\xff\u0100\uffff",
+            [
+                u"", # first byte of BOM read
+                u"", # second byte of BOM read
+                u"", # third byte of BOM read
+                u"", # fourth byte of BOM read => byteorder known
+                u"",
+                u"",
+                u"",
+                u"\x00",
+                u"\x00",
+                u"\x00",
+                u"\x00",
+                u"\x00\xff",
+                u"\x00\xff",
+                u"\x00\xff",
+                u"\x00\xff",
+                u"\x00\xff\u0100",
+                u"\x00\xff\u0100",
+                u"\x00\xff\u0100",
+                u"\x00\xff\u0100",
+                u"\x00\xff\u0100\uffff",
+            ]
+        )
+
+    def test_handlers(self):
+        self.assertEqual((u'\ufffd', 1),
+                         codecs.utf_32_decode('\x01', 'replace', True))
+        self.assertEqual((u'', 1),
+                         codecs.utf_32_decode('\x01', 'ignore', True))
+
+    def test_errors(self):
+        self.assertRaises(UnicodeDecodeError, codecs.utf_32_decode,
+                          "\xff", "strict", True)
+
+    def test_issue8941(self):
+        # Issue #8941: insufficient result allocation when decoding into
+        # surrogate pairs on UCS-2 builds.
+        encoded_le = '\xff\xfe\x00\x00' + '\x00\x00\x01\x00' * 1024
+        self.assertEqual(u'\U00010000' * 1024,
+                         codecs.utf_32_decode(encoded_le)[0])
+        encoded_be = '\x00\x00\xfe\xff' + '\x00\x01\x00\x00' * 1024
+        self.assertEqual(u'\U00010000' * 1024,
+                         codecs.utf_32_decode(encoded_be)[0])
+
+@unittest.skipIf(test_support.is_jython, "FIXME: Jython issue 2000 missing support for UTF-32")
+class UTF32LETest(ReadTest):
+    encoding = "utf-32-le"
+
+    def test_partial(self):
+        self.check_partial(
+            u"\x00\xff\u0100\uffff",
+            [
+                u"",
+                u"",
+                u"",
+                u"\x00",
+                u"\x00",
+                u"\x00",
+                u"\x00",
+                u"\x00\xff",
+                u"\x00\xff",
+                u"\x00\xff",
+                u"\x00\xff",
+                u"\x00\xff\u0100",
+                u"\x00\xff\u0100",
+                u"\x00\xff\u0100",
+                u"\x00\xff\u0100",
+                u"\x00\xff\u0100\uffff",
+            ]
+        )
+
+    def test_simple(self):
+        self.assertEqual(u"\U00010203".encode(self.encoding), "\x03\x02\x01\x00")
+
+    def test_errors(self):
+        self.assertRaises(UnicodeDecodeError, codecs.utf_32_le_decode,
+                          "\xff", "strict", True)
+
+    def test_issue8941(self):
+        # Issue #8941: insufficient result allocation when decoding into
+        # surrogate pairs on UCS-2 builds.
+        encoded = '\x00\x00\x01\x00' * 1024
+        self.assertEqual(u'\U00010000' * 1024,
+                         codecs.utf_32_le_decode(encoded)[0])
+
+@unittest.skipIf(test_support.is_jython, "FIXME: Jython issue 2000 missing support for UTF-32")
+class UTF32BETest(ReadTest):
+    encoding = "utf-32-be"
+
+    def test_partial(self):
+        self.check_partial(
+            u"\x00\xff\u0100\uffff",
+            [
+                u"",
+                u"",
+                u"",
+                u"\x00",
+                u"\x00",
+                u"\x00",
+                u"\x00",
+                u"\x00\xff",
+                u"\x00\xff",
+                u"\x00\xff",
+                u"\x00\xff",
+                u"\x00\xff\u0100",
+                u"\x00\xff\u0100",
+                u"\x00\xff\u0100",
+                u"\x00\xff\u0100",
+                u"\x00\xff\u0100\uffff",
+            ]
+        )
+
+    def test_simple(self):
+        self.assertEqual(u"\U00010203".encode(self.encoding), "\x00\x01\x02\x03")
+
+    def test_errors(self):
+        self.assertRaises(UnicodeDecodeError, codecs.utf_32_be_decode,
+                          "\xff", "strict", True)
+
+    def test_issue8941(self):
+        # Issue #8941: insufficient result allocation when decoding into
+        # surrogate pairs on UCS-2 builds.
+        encoded = '\x00\x01\x00\x00' * 1024
+        self.assertEqual(u'\U00010000' * 1024,
+                         codecs.utf_32_be_decode(encoded)[0])
+
+
+class UTF16Test(ReadTest):
+    encoding = "utf-16"
 
     spamle = '\xff\xfes\x00p\x00a\x00m\x00s\x00p\x00a\x00m\x00'
     spambe = '\xfe\xff\x00s\x00p\x00a\x00m\x00s\x00p\x00a\x00m'
 
     def test_only_one_bom(self):
-        _,_,reader,writer = codecs.lookup("utf-16")
+        _,_,reader,writer = codecs.lookup(self.encoding)
         # encode some stream
         s = StringIO.StringIO()
         f = writer(s)
         f.write(u"spam")
         d = s.getvalue()
         # check whether there is exactly one BOM in it
-        self.assert_(d == self.spamle or d == self.spambe)
+        self.assertTrue(d == self.spamle or d == self.spambe)
         # try to read it back
         s = StringIO.StringIO(d)
         f = reader(s)
-        self.assertEquals(f.read(), u"spamspam")
+        self.assertEqual(f.read(), u"spamspam")
+
+    def test_badbom(self):
+        s = StringIO.StringIO("\xff\xff")
+        f = codecs.getreader(self.encoding)(s)
+        self.assertRaises(UnicodeError, f.read)
+
+        s = StringIO.StringIO("\xff\xff\xff\xff")
+        f = codecs.getreader(self.encoding)(s)
+        self.assertRaises(UnicodeError, f.read)
+
+    def test_partial(self):
+        self.check_partial(
+            u"\x00\xff\u0100\uffff",
+            [
+                u"", # first byte of BOM read
+                u"", # second byte of BOM read => byteorder known
+                u"",
+                u"\x00",
+                u"\x00",
+                u"\x00\xff",
+                u"\x00\xff",
+                u"\x00\xff\u0100",
+                u"\x00\xff\u0100",
+                u"\x00\xff\u0100\uffff",
+            ]
+        )
+
+    def test_handlers(self):
+        self.assertEqual((u'\ufffd', 1),
+                         codecs.utf_16_decode('\x01', 'replace', True))
+        self.assertEqual((u'', 1),
+                         codecs.utf_16_decode('\x01', 'ignore', True))
+
+    def test_errors(self):
+        self.assertRaises(UnicodeDecodeError, codecs.utf_16_decode, "\xff", "strict", True)
+
+    def test_bug691291(self):
+        # Files are always opened in binary mode, even if no binary mode was
+        # specified.  This means that no automatic conversion of '\n' is done
+        # on reading and writing.
+        s1 = u'Hello\r\nworld\r\n'
+
+        s = s1.encode(self.encoding)
+        self.addCleanup(test_support.unlink, test_support.TESTFN)
+        with open(test_support.TESTFN, 'wb') as fp:
+            fp.write(s)
+        with codecs.open(test_support.TESTFN, 'U', encoding=self.encoding) as reader:
+            self.assertEqual(reader.read(), s1)
+
+class UTF16LETest(ReadTest):
+    encoding = "utf-16-le"
+
+    def test_partial(self):
+        self.check_partial(
+            u"\x00\xff\u0100\uffff",
+            [
+                u"",
+                u"\x00",
+                u"\x00",
+                u"\x00\xff",
+                u"\x00\xff",
+                u"\x00\xff\u0100",
+                u"\x00\xff\u0100",
+                u"\x00\xff\u0100\uffff",
+            ]
+        )
+
+    def test_errors(self):
+        self.assertRaises(UnicodeDecodeError, codecs.utf_16_le_decode, "\xff", "strict", True)
+
+class UTF16BETest(ReadTest):
+    encoding = "utf-16-be"
+
+    def test_partial(self):
+        self.check_partial(
+            u"\x00\xff\u0100\uffff",
+            [
+                u"",
+                u"\x00",
+                u"\x00",
+                u"\x00\xff",
+                u"\x00\xff",
+                u"\x00\xff\u0100",
+                u"\x00\xff\u0100",
+                u"\x00\xff\u0100\uffff",
+            ]
+        )
+
+    def test_errors(self):
+        self.assertRaises(UnicodeDecodeError, codecs.utf_16_be_decode, "\xff", "strict", True)
+
+class UTF8Test(ReadTest):
+    encoding = "utf-8"
+
+    def test_partial(self):
+        self.check_partial(
+            u"\x00\xff\u07ff\u0800\uffff",
+            [
+                u"\x00",
+                u"\x00",
+                u"\x00\xff",
+                u"\x00\xff",
+                u"\x00\xff\u07ff",
+                u"\x00\xff\u07ff",
+                u"\x00\xff\u07ff",
+                u"\x00\xff\u07ff\u0800",
+                u"\x00\xff\u07ff\u0800",
+                u"\x00\xff\u07ff\u0800",
+                u"\x00\xff\u07ff\u0800\uffff",
+            ]
+        )
+
+class UTF7Test(ReadTest):
+    encoding = "utf-7"
+
+    def test_partial(self):
+        self.check_partial(
+            u"a+-b",
+            [
+                u"a",
+                u"a",
+                u"a+",
+                u"a+-",
+                u"a+-b",
+            ]
+        )
+
+class UTF16ExTest(unittest.TestCase):
+
+    def test_errors(self):
+        self.assertRaises(UnicodeDecodeError, codecs.utf_16_ex_decode, "\xff", "strict", 0, True)
+
+    def test_bad_args(self):
+        self.assertRaises(TypeError, codecs.utf_16_ex_decode)
+
+@unittest.skipIf(test_support.is_jython, "FIXME: Jython has no _codecs.readbuffer_encode method")
+class ReadBufferTest(unittest.TestCase):
+
+    def test_array(self):
+        import array
+        self.assertEqual(
+            codecs.readbuffer_encode(array.array("c", "spam")),
+            ("spam", 4)
+        )
+
+    def test_empty(self):
+        self.assertEqual(codecs.readbuffer_encode(""), ("", 0))
+
+    def test_bad_args(self):
+        self.assertRaises(TypeError, codecs.readbuffer_encode)
+        self.assertRaises(TypeError, codecs.readbuffer_encode, 42)
+
+@unittest.skipIf(test_support.is_jython, "FIXME: Jython has no _codecs.charbuffer_encode method")
+class CharBufferTest(unittest.TestCase):
+
+    def test_string(self):
+        self.assertEqual(codecs.charbuffer_encode("spam"), ("spam", 4))
+
+    def test_empty(self):
+        self.assertEqual(codecs.charbuffer_encode(""), ("", 0))
+
+    def test_bad_args(self):
+        self.assertRaises(TypeError, codecs.charbuffer_encode)
+        self.assertRaises(TypeError, codecs.charbuffer_encode, 42)
+
+class UTF8SigTest(ReadTest):
+    encoding = "utf-8-sig"
+
+    def test_partial(self):
+        self.check_partial(
+            u"\ufeff\x00\xff\u07ff\u0800\uffff",
+            [
+                u"",
+                u"",
+                u"", # First BOM has been read and skipped
+                u"",
+                u"",
+                u"\ufeff", # Second BOM has been read and emitted
+                u"\ufeff\x00", # "\x00" read and emitted
+                u"\ufeff\x00", # First byte of encoded u"\xff" read
+                u"\ufeff\x00\xff", # Second byte of encoded u"\xff" read
+                u"\ufeff\x00\xff", # First byte of encoded u"\u07ff" read
+                u"\ufeff\x00\xff\u07ff", # Second byte of encoded u"\u07ff" read
+                u"\ufeff\x00\xff\u07ff",
+                u"\ufeff\x00\xff\u07ff",
+                u"\ufeff\x00\xff\u07ff\u0800",
+                u"\ufeff\x00\xff\u07ff\u0800",
+                u"\ufeff\x00\xff\u07ff\u0800",
+                u"\ufeff\x00\xff\u07ff\u0800\uffff",
+            ]
+        )
+
+    def test_bug1601501(self):
+        # SF bug #1601501: check that the codec works with a buffer
+        unicode("\xef\xbb\xbf", "utf-8-sig")
+
+    def test_bom(self):
+        d = codecs.getincrementaldecoder("utf-8-sig")()
+        s = u"spam"
+        self.assertEqual(d.decode(s.encode("utf-8-sig")), s)
+
+    def test_stream_bom(self):
+        unistring = u"ABC\u00A1\u2200XYZ"
+        bytestring = codecs.BOM_UTF8 + "ABC\xC2\xA1\xE2\x88\x80XYZ"
+
+        reader = codecs.getreader("utf-8-sig")
+        for sizehint in [None] + range(1, 11) + \
+                        [64, 128, 256, 512, 1024]:
+            istream = reader(StringIO.StringIO(bytestring))
+            ostream = StringIO.StringIO()
+            while 1:
+                if sizehint is not None:
+                    data = istream.read(sizehint)
+                else:
+                    data = istream.read()
+
+                if not data:
+                    break
+                ostream.write(data)
+
+            got = ostream.getvalue()
+            self.assertEqual(got, unistring)
+
+    def test_stream_bare(self):
+        unistring = u"ABC\u00A1\u2200XYZ"
+        bytestring = "ABC\xC2\xA1\xE2\x88\x80XYZ"
+
+        reader = codecs.getreader("utf-8-sig")
+        for sizehint in [None] + range(1, 11) + \
+                        [64, 128, 256, 512, 1024]:
+            istream = reader(StringIO.StringIO(bytestring))
+            ostream = StringIO.StringIO()
+            while 1:
+                if sizehint is not None:
+                    data = istream.read(sizehint)
+                else:
+                    data = istream.read()
+
+                if not data:
+                    break
+                ostream.write(data)
+
+            got = ostream.getvalue()
+            self.assertEqual(got, unistring)
 
 class EscapeDecodeTest(unittest.TestCase):
-    def test_empty_escape_decode(self):
-        self.assertEquals(codecs.escape_decode(""), ("", 0))
+    def test_empty(self):
+        self.assertEqual(codecs.escape_decode(""), ("", 0))
 
 class RecodingTest(unittest.TestCase):
     def test_recoding(self):
      u"\u0056\u0069\u1EC7\u0074",
      "TisaohkhngthchnitingVit-kjcr8268qyxafd2f1b9g"),
 
-
     #(L) 3<nen>B<gumi><kinpachi><sensei>
     (u"\u0033\u5E74\u0042\u7D44\u91D1\u516B\u5148\u751F",
      "3B-ww4c5e180e575a65lsy2b"),
             # code produces only lower case. Converting just puny to
             # lower is also insufficient, since some of the input characters
             # are upper case.
-            self.assertEquals(uni.encode("punycode").lower(), puny.lower())
+            self.assertEqual(uni.encode("punycode").lower(), puny.lower())
 
     def test_decode(self):
         for uni, puny in punycode_testcases:
-            self.assertEquals(uni, puny.decode("punycode"))
+            self.assertEqual(uni, puny.decode("punycode"))
+
+@unittest.skipIf(test_support.is_jython, "FIXME: equates to UTF-32BE in Jython")
+class UnicodeInternalTest(unittest.TestCase):
+    def test_bug1251300(self):
+        # Decoding with unicode_internal used to not correctly handle "code
+        # points" above 0x10ffff on UCS-4 builds.
+        if sys.maxunicode > 0xffff:
+            ok = [
+                ("\x00\x10\xff\xff", u"\U0010ffff"),
+                ("\x00\x00\x01\x01", u"\U00000101"),
+                ("", u""),
+            ]
+            not_ok = [
+                "\x7f\xff\xff\xff",
+                "\x80\x00\x00\x00",
+                "\x81\x00\x00\x00",
+                "\x00",
+                "\x00\x00\x00\x00\x00",
+            ]
+            for internal, uni in ok:
+                if sys.byteorder == "little":
+                    internal = "".join(reversed(internal))
+                self.assertEqual(uni, internal.decode("unicode_internal"))
+            for internal in not_ok:
+                if sys.byteorder == "little":
+                    internal = "".join(reversed(internal))
+                self.assertRaises(UnicodeDecodeError, internal.decode,
+                    "unicode_internal")
+
+    def test_decode_error_attributes(self):
+        if sys.maxunicode > 0xffff:
+            try:
+                "\x00\x00\x00\x00\x00\x11\x11\x00".decode("unicode_internal")
+            except UnicodeDecodeError, ex:
+                self.assertEqual("unicode_internal", ex.encoding)
+                self.assertEqual("\x00\x00\x00\x00\x00\x11\x11\x00", ex.object)
+                self.assertEqual(4, ex.start)
+                self.assertEqual(8, ex.end)
+            else:
+                self.fail("UnicodeDecodeError not raised")
+
+    def test_decode_callback(self):
+        if sys.maxunicode > 0xffff:
+            codecs.register_error("UnicodeInternalTest", codecs.ignore_errors)
+            decoder = codecs.getdecoder("unicode_internal")
+            ab = u"ab".encode("unicode_internal")
+            ignored = decoder("%s\x22\x22\x22\x22%s" % (ab[:4], ab[4:]),
+                "UnicodeInternalTest")
+            self.assertEqual((u"ab", 12), ignored)
+
+    def test_encode_length(self):
+        # Issue 3739
+        encoder = codecs.getencoder("unicode_internal")
+        self.assertEqual(encoder(u"a")[1], 1)
+        self.assertEqual(encoder(u"\xe9\u0142")[1], 2)
+
+        encoder = codecs.getencoder("string-escape")
+        self.assertEqual(encoder(r'\x00')[1], 4)
 
 # From http://www.gnu.org/software/libidn/draft-josefsson-idn-test-vectors.html
 nameprep_tests = [
     ]
 
 
+@unittest.skipIf(test_support.is_jython, "FIXME: incomplete unicodedata module")
 class NameprepTest(unittest.TestCase):
     def test_nameprep(self):
         from encodings.idna import nameprep
             else:
                 prepped = unicode(prepped, "utf-8")
                 try:
-                    self.assertEquals(nameprep(orig), prepped)
+                    self.assertEqual(nameprep(orig), prepped)
                 except Exception,e:
                     raise test_support.TestFailed("Test 3.%d: %s" % (pos+1, str(e)))
 
+@unittest.skipIf(test_support.is_jython, "FIXME: Jython issue 2000 missing support for IDNA")
+class IDNACodecTest(unittest.TestCase):
+    def test_builtin_decode(self):
+        self.assertEqual(unicode("python.org", "idna"), u"python.org")
+        self.assertEqual(unicode("python.org.", "idna"), u"python.org.")
+        self.assertEqual(unicode("xn--pythn-mua.org", "idna"), u"pyth\xf6n.org")
+        self.assertEqual(unicode("xn--pythn-mua.org.", "idna"), u"pyth\xf6n.org.")
+
+    def test_builtin_encode(self):
+        self.assertEqual(u"python.org".encode("idna"), "python.org")
+        self.assertEqual("python.org.".encode("idna"), "python.org.")
+        self.assertEqual(u"pyth\xf6n.org".encode("idna"), "xn--pythn-mua.org")
+        self.assertEqual(u"pyth\xf6n.org.".encode("idna"), "xn--pythn-mua.org.")
+
+    def test_stream(self):
+        import StringIO
+        r = codecs.getreader("idna")(StringIO.StringIO("abc"))
+        r.read(3)
+        self.assertEqual(r.read(), u"")
+
+    def test_incremental_decode(self):
+        self.assertEqual(
+            "".join(codecs.iterdecode("python.org", "idna")),
+            u"python.org"
+        )
+        self.assertEqual(
+            "".join(codecs.iterdecode("python.org.", "idna")),
+            u"python.org."
+        )
+        self.assertEqual(
+            "".join(codecs.iterdecode("xn--pythn-mua.org.", "idna")),
+            u"pyth\xf6n.org."
+        )
+        self.assertEqual(
+            "".join(codecs.iterdecode("xn--pythn-mua.org.", "idna")),
+            u"pyth\xf6n.org."
+        )
+
+        decoder = codecs.getincrementaldecoder("idna")()
+        self.assertEqual(decoder.decode("xn--xam", ), u"")
+        self.assertEqual(decoder.decode("ple-9ta.o", ), u"\xe4xample.")
+        self.assertEqual(decoder.decode(u"rg"), u"")
+        self.assertEqual(decoder.decode(u"", True), u"org")
+
+        decoder.reset()
+        self.assertEqual(decoder.decode("xn--xam", ), u"")
+        self.assertEqual(decoder.decode("ple-9ta.o", ), u"\xe4xample.")
+        self.assertEqual(decoder.decode("rg."), u"org.")
+        self.assertEqual(decoder.decode("", True), u"")
+
+    def test_incremental_encode(self):
+        self.assertEqual(
+            "".join(codecs.iterencode(u"python.org", "idna")),
+            "python.org"
+        )
+        self.assertEqual(
+            "".join(codecs.iterencode(u"python.org.", "idna")),
+            "python.org."
+        )
+        self.assertEqual(
+            "".join(codecs.iterencode(u"pyth\xf6n.org.", "idna")),
+            "xn--pythn-mua.org."
+        )
+        self.assertEqual(
+            "".join(codecs.iterencode(u"pyth\xf6n.org.", "idna")),
+            "xn--pythn-mua.org."
+        )
+
+        encoder = codecs.getincrementalencoder("idna")()
+        self.assertEqual(encoder.encode(u"\xe4x"), "")
+        self.assertEqual(encoder.encode(u"ample.org"), "xn--xample-9ta.")
+        self.assertEqual(encoder.encode(u"", True), "org")
+
+        encoder.reset()
+        self.assertEqual(encoder.encode(u"\xe4x"), "")
+        self.assertEqual(encoder.encode(u"ample.org."), "xn--xample-9ta.org.")
+        self.assertEqual(encoder.encode(u"", True), "")
+
+class CodecsModuleTest(unittest.TestCase):
+
+    @unittest.skipIf(test_support.is_jython, "FIXME: _codecs.decode not implemented")
+    def test_decode(self):
+        self.assertEqual(codecs.decode('\xe4\xf6\xfc', 'latin-1'),
+                          u'\xe4\xf6\xfc')
+        self.assertRaises(TypeError, codecs.decode)
+        self.assertEqual(codecs.decode('abc'), u'abc')
+        self.assertRaises(UnicodeDecodeError, codecs.decode, '\xff', 'ascii')
+
+    @unittest.skipIf(test_support.is_jython, "FIXME: _codecs.encode not implemented")
+    def test_encode(self):
+        self.assertEqual(codecs.encode(u'\xe4\xf6\xfc', 'latin-1'),
+                          '\xe4\xf6\xfc')
+        self.assertRaises(TypeError, codecs.encode)
+        self.assertRaises(LookupError, codecs.encode, "foo", "__spam__")
+        self.assertEqual(codecs.encode(u'abc'), 'abc')
+        self.assertRaises(UnicodeEncodeError, codecs.encode, u'\xffff', 'ascii')
+
+    def test_register(self):
+        self.assertRaises(TypeError, codecs.register)
+        self.assertRaises(TypeError, codecs.register, 42)
+
+    def test_lookup(self):
+        self.assertRaises(TypeError, codecs.lookup)
+        self.assertRaises(LookupError, codecs.lookup, "__spam__")
+        self.assertRaises(LookupError, codecs.lookup, " ")
+
+    def test_getencoder(self):
+        self.assertRaises(TypeError, codecs.getencoder)
+        self.assertRaises(LookupError, codecs.getencoder, "__spam__")
+
+    def test_getdecoder(self):
+        self.assertRaises(TypeError, codecs.getdecoder)
+        self.assertRaises(LookupError, codecs.getdecoder, "__spam__")
+
+    def test_getreader(self):
+        self.assertRaises(TypeError, codecs.getreader)
+        self.assertRaises(LookupError, codecs.getreader, "__spam__")
+
+    def test_getwriter(self):
+        self.assertRaises(TypeError, codecs.getwriter)
+        self.assertRaises(LookupError, codecs.getwriter, "__spam__")
+
+    def test_lookup_issue1813(self):
+        # Issue #1813: under Turkish locales, lookup of some codecs failed
+        # because 'I' is lowercased as a dotless "i"
+        oldlocale = locale.getlocale(locale.LC_CTYPE)
+        self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale)
+        try:
+            locale.setlocale(locale.LC_CTYPE, 'tr_TR')
+        except locale.Error:
+            # Unsupported locale on this system
+            self.skipTest('test needs Turkish locale')
+        c = codecs.lookup('ASCII')
+        self.assertEqual(c.name, 'ascii')
+
+class StreamReaderTest(unittest.TestCase):
+
+    def setUp(self):
+        self.reader = codecs.getreader('utf-8')
+        self.stream = StringIO.StringIO('\xed\x95\x9c\n\xea\xb8\x80')
+
+    def test_readlines(self):
+        f = self.reader(self.stream)
+        self.assertEqual(f.readlines(), [u'\ud55c\n', u'\uae00'])
+
+class EncodedFileTest(unittest.TestCase):
+
+    def test_basic(self):
+        f = StringIO.StringIO('\xed\x95\x9c\n\xea\xb8\x80')
+        ef = codecs.EncodedFile(f, 'utf-16-le', 'utf-8')
+        self.assertEqual(ef.read(), '\\\xd5\n\x00\x00\xae')
+
+        f = StringIO.StringIO()
+        ef = codecs.EncodedFile(f, 'utf-8', 'latin1')
+        ef.write('\xc3\xbc')
+        self.assertEqual(f.getvalue(), '\xfc')
+
+class Str2StrTest(unittest.TestCase):
+
+    def test_read(self):
+        sin = "\x80".encode("base64_codec")
+        reader = codecs.getreader("base64_codec")(StringIO.StringIO(sin))
+        sout = reader.read()
+        self.assertEqual(sout, "\x80")
+        self.assertIsInstance(sout, str)
+
+    def test_readline(self):
+        sin = "\x80".encode("base64_codec")
+        reader = codecs.getreader("base64_codec")(StringIO.StringIO(sin))
+        sout = reader.readline()
+        self.assertEqual(sout, "\x80")
+        self.assertIsInstance(sout, str)
+
+all_unicode_encodings = [
+    "ascii",
+    "base64_codec",
+# FIXME: Jython issue 1066:    "big5",
+# FIXME: Jython issue 1066:    "big5hkscs",
+    "charmap",
+    "cp037",
+    "cp1006",
+    "cp1026",
+    "cp1140",
+    "cp1250",
+    "cp1251",
+    "cp1252",
+    "cp1253",
+    "cp1254",
+    "cp1255",
+    "cp1256",
+    "cp1257",
+    "cp1258",
+    "cp424",
+    "cp437",
+    "cp500",
+    "cp720",
+    "cp737",
+    "cp775",
+    "cp850",
+    "cp852",
+    "cp855",
+    "cp856",
+    "cp857",
+    "cp858",
+    "cp860",
+    "cp861",
+    "cp862",
+    "cp863",
+    "cp864",
+    "cp865",
+    "cp866",
+    "cp869",
+    "cp874",
+    "cp875",
+# FIXME: Jython issue 1066:    "cp932",
+# FIXME: Jython issue 1066:    "cp949",
+# FIXME: Jython issue 1066:    "cp950",
+# FIXME: Jython issue 1066:    "euc_jis_2004",
+# FIXME: Jython issue 1066:    'euc_jisx0213',
+# FIXME: Jython issue 1066:    'euc_jp',
+# FIXME: Jython issue 1066:    'euc_kr',
+# FIXME: Jython issue 1066:    'gb18030',
+# FIXME: Jython issue 1066:    'gb2312',
+# FIXME: Jython issue 1066:    'gbk',
+    "hex_codec",
+    "hp_roman8",
+# FIXME: Jython issue 1066:    'hz',
+# FIXME: Jython issue 1066:    "idna",
+# FIXME: Jython issue 1066:    'iso2022_jp',
+# FIXME: Jython issue 1066:    'iso2022_jp_1',
+# FIXME: Jython issue 1066:    'iso2022_jp_2',
+# FIXME: Jython issue 1066:    'iso2022_jp_2004',
+# FIXME: Jython issue 1066:    'iso2022_jp_3',
+# FIXME: Jython issue 1066:    'iso2022_jp_ext',
+# FIXME: Jython issue 1066:    'iso2022_kr',
+    "iso8859_1",
+    "iso8859_10",
+    "iso8859_11",
+    "iso8859_13",
+    "iso8859_14",
+    "iso8859_15",
+    "iso8859_16",
+    "iso8859_2",
+    "iso8859_3",
+    "iso8859_4",
+    "iso8859_5",
+    "iso8859_6",
+    "iso8859_7",
+    "iso8859_8",
+    "iso8859_9",
+# FIXME: Jython issue 1066:    'johab',
+    "koi8_r",
+    "koi8_u",
+    "latin_1",
+    "mac_cyrillic",
+    "mac_greek",
+    "mac_iceland",
+    "mac_latin2",
+    "mac_roman",
+    "mac_turkish",
+    "palmos",
+    "ptcp154",
+    "punycode",
+    "raw_unicode_escape",
+    "rot_13",
+# FIXME: Jython issue 1066:    'shift_jis',
+# FIXME: Jython issue 1066:    'shift_jis_2004',
+# FIXME: Jython issue 1066:    'shift_jisx0213',
+    "tis_620",
+    "unicode_escape",
+    "unicode_internal",
+    "utf_16",
+    "utf_16_be",
+    "utf_16_le",
+    "utf_7",
+    "utf_8",
+]
+
+if hasattr(codecs, "mbcs_encode"):
+    all_unicode_encodings.append("mbcs")
+
+# The following encodings work only with str, not unicode
+all_string_encodings = [
+    "quopri_codec",
+    "string_escape",
+    "uu_codec",
+]
+
+# The following encoding is not tested, because it's not supposed
+# to work:
+#    "undefined"
+
+# The following encodings don't work in stateful mode
+broken_unicode_with_streams = [
+    "base64_codec",
+    "hex_codec",
+    "punycode",
+    "unicode_internal"
+]
+broken_incremental_coders = broken_unicode_with_streams[:]
+
+# The following encodings only support "strict" mode
+only_strict_mode = [
+    "idna",
+    "zlib_codec",
+    "bz2_codec",
+]
+
+try:
+    import bz2
+except ImportError:
+    pass
+else:
+    all_unicode_encodings.append("bz2_codec")
+    broken_unicode_with_streams.append("bz2_codec")
+
+try:
+    import zlib
+except ImportError:
+    pass
+else:
+    all_unicode_encodings.append("zlib_codec")
+    broken_unicode_with_streams.append("zlib_codec")
+
+class BasicUnicodeTest(unittest.TestCase):
+
+    @unittest.skipIf(test_support.is_jython, "_testcapi module not present in Jython")
+    def test_basics(self):
+        s = u"abc123" # all codecs should be able to encode these
+        for encoding in all_unicode_encodings:
+            name = codecs.lookup(encoding).name
+            if encoding.endswith("_codec"):
+                name += "_codec"
+            elif encoding == "latin_1":
+                name = "latin_1"
+            self.assertEqual(encoding.replace("_", "-"), name.replace("_", "-"))
+            (bytes, size) = codecs.getencoder(encoding)(s)
+            self.assertEqual(size, len(s), "%r != %r (encoding=%r)" % (size, len(s), encoding))
+            (chars, size) = codecs.getdecoder(encoding)(bytes)
+            self.assertEqual(chars, s, "%r != %r (encoding=%r)" % (chars, s, encoding))
+
+            if encoding not in broken_unicode_with_streams:
+                # check stream reader/writer
+                q = Queue()
+                writer = codecs.getwriter(encoding)(q)
+                encodedresult = ""
+                for c in s:
+                    writer.write(c)
+                    encodedresult += q.read()
+                q = Queue()
+                reader = codecs.getreader(encoding)(q)
+                decodedresult = u""
+                for c in encodedresult:
+                    q.write(c)
+                    decodedresult += reader.read()
+                self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding))
+
+            if encoding not in broken_incremental_coders:
+                # check incremental decoder/encoder (fetched via the Python
+                # and C API) and iterencode()/iterdecode()
+                try:
+                    encoder = codecs.getincrementalencoder(encoding)()
+                    cencoder = _testcapi.codec_incrementalencoder(encoding)
+                except LookupError: # no IncrementalEncoder
+                    pass
+                else:
+                    # check incremental decoder/encoder
+                    encodedresult = ""
+                    for c in s:
+                        encodedresult += encoder.encode(c)
+                    encodedresult += encoder.encode(u"", True)
+                    decoder = codecs.getincrementaldecoder(encoding)()
+                    decodedresult = u""
+                    for c in encodedresult:
+                        decodedresult += decoder.decode(c)
+                    decodedresult += decoder.decode("", True)
+                    self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding))
+
+                    # check C API
+                    encodedresult = ""
+                    for c in s:
+                        encodedresult += cencoder.encode(c)
+                    encodedresult += cencoder.encode(u"", True)
+                    cdecoder = _testcapi.codec_incrementaldecoder(encoding)
+                    decodedresult = u""
+                    for c in encodedresult:
+                        decodedresult += cdecoder.decode(c)
+                    decodedresult += cdecoder.decode("", True)
+                    self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding))
+
+                    # check iterencode()/iterdecode()
+                    result = u"".join(codecs.iterdecode(codecs.iterencode(s, encoding), encoding))
+                    self.assertEqual(result, s, "%r != %r (encoding=%r)" % (result, s, encoding))
+
+                    # check iterencode()/iterdecode() with empty string
+                    result = u"".join(codecs.iterdecode(codecs.iterencode(u"", encoding), encoding))
+                    self.assertEqual(result, u"")
+
+                if encoding not in only_strict_mode:
+                    # check incremental decoder/encoder with errors argument
+                    try:
+                        encoder = codecs.getincrementalencoder(encoding)("ignore")
+                        cencoder = _testcapi.codec_incrementalencoder(encoding, "ignore")
+                    except LookupError: # no IncrementalEncoder
+                        pass
+                    else:
+                        encodedresult = "".join(encoder.encode(c) for c in s)
+                        decoder = codecs.getincrementaldecoder(encoding)("ignore")
+                        decodedresult = u"".join(decoder.decode(c) for c in encodedresult)
+                        self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding))
+
+                        encodedresult = "".join(cencoder.encode(c) for c in s)
+                        cdecoder = _testcapi.codec_incrementaldecoder(encoding, "ignore")
+                        decodedresult = u"".join(cdecoder.decode(c) for c in encodedresult)
+                        self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding))
+
+    def test_seek(self):
+        # all codecs should be able to encode these
+        s = u"%s\n%s\n" % (100*u"abc123", 100*u"def456")
+        for encoding in all_unicode_encodings:
+            if encoding == "idna": # FIXME: See SF bug #1163178
+                continue
+            if encoding in broken_unicode_with_streams:
+                continue
+            reader = codecs.getreader(encoding)(StringIO.StringIO(s.encode(encoding)))
+            for t in xrange(5):
+                # Test that calling seek resets the internal codec state and buffers
+                reader.seek(0, 0)
+                line = reader.readline()
+                self.assertEqual(s[:len(line)], line)
+
+    def test_bad_decode_args(self):
+        for encoding in all_unicode_encodings:
+            decoder = codecs.getdecoder(encoding)
+            self.assertRaises(TypeError, decoder)
+            if encoding not in ("idna", "punycode"):
+                self.assertRaises(TypeError, decoder, 42)
+
+    def test_bad_encode_args(self):
+        for encoding in all_unicode_encodings:
+            encoder = codecs.getencoder(encoding)
+            self.assertRaises(TypeError, encoder)
+
+    def test_encoding_map_type_initialized(self):
+        from encodings import cp1140
+        # This used to crash, we are only verifying there's no crash.
+        table_type = type(cp1140.encoding_table)
+        self.assertEqual(table_type, table_type)
+
+class BasicStrTest(unittest.TestCase):
+    def test_basics(self):
+        s = "abc123"
+        for encoding in all_string_encodings:
+            (bytes, size) = codecs.getencoder(encoding)(s)
+            self.assertEqual(size, len(s))
+            (chars, size) = codecs.getdecoder(encoding)(bytes)
+            self.assertEqual(chars, s, "%r != %r (encoding=%r)" % (chars, s, encoding))
+
+class CharmapTest(unittest.TestCase):
+    def test_decode_with_string_map(self):
+        self.assertEqual(
+            codecs.charmap_decode("\x00\x01\x02", "strict", u"abc"),
+            (u"abc", 3)
+        )
+
+        self.assertEqual(
+            codecs.charmap_decode("\x00\x01\x02", "replace", u"ab"),
+            (u"ab\ufffd", 3)
+        )
+
+        self.assertEqual(
+            codecs.charmap_decode("\x00\x01\x02", "replace", u"ab\ufffe"),
+            (u"ab\ufffd", 3)
+        )
+
+        self.assertEqual(
+            codecs.charmap_decode("\x00\x01\x02", "ignore", u"ab"),
+            (u"ab", 3)
+        )
+
+        self.assertEqual(
+            codecs.charmap_decode("\x00\x01\x02", "ignore", u"ab\ufffe"),
+            (u"ab", 3)
+        )
+
+        allbytes = "".join(chr(i) for i in xrange(256))
+        self.assertEqual(
+            codecs.charmap_decode(allbytes, "ignore", u""),
+            (u"", len(allbytes))
+        )
+
+class WithStmtTest(unittest.TestCase):
+    def test_encodedfile(self):
+        f = StringIO.StringIO("\xc3\xbc")
+        with codecs.EncodedFile(f, "latin-1", "utf-8") as ef:
+            self.assertEqual(ef.read(), "\xfc")
+
+    def test_streamreaderwriter(self):
+        f = StringIO.StringIO("\xc3\xbc")
+        info = codecs.lookup("utf-8")
+        with codecs.StreamReaderWriter(f, info.streamreader,
+                                       info.streamwriter, 'strict') as srw:
+            self.assertEqual(srw.read(), u"\xfc")
+
+
+class BomTest(unittest.TestCase):
+    def test_seek0(self):
+        data = u"1234567890"
+        tests = ("utf-16",
+                 "utf-16-le",
+                 "utf-16-be",
+                 # FIXME: Jython does not support:"utf-32",
+                 # FIXME: Jython does not support:"utf-32-le",
+                 # FIXME: Jython does not support:"utf-32-be",
+                 )
+        self.addCleanup(test_support.unlink, test_support.TESTFN)
+        for encoding in tests:
+            # Check if the BOM is written only once
+            with codecs.open(test_support.TESTFN, 'w+', encoding=encoding) as f:
+                f.write(data)
+                f.write(data)
+                f.seek(0)
+                self.assertEqual(f.read(), data * 2)
+                f.seek(0)
+                self.assertEqual(f.read(), data * 2)
+
+            # Check that the BOM is written after a seek(0)
+            with codecs.open(test_support.TESTFN, 'w+', encoding=encoding) as f:
+                f.write(data[0])
+                self.assertNotEqual(f.tell(), 0)
+                f.seek(0)
+                f.write(data)
+                f.seek(0)
+                self.assertEqual(f.read(), data)
+
+            # (StreamWriter) Check that the BOM is written after a seek(0)
+            with codecs.open(test_support.TESTFN, 'w+', encoding=encoding) as f:
+                f.writer.write(data[0])
+                self.assertNotEqual(f.writer.tell(), 0)
+                f.writer.seek(0)
+                f.writer.write(data)
+                f.seek(0)
+                self.assertEqual(f.read(), data)
+
+            # Check that the BOM is not written after a seek() at a position
+            # different than the start
+            with codecs.open(test_support.TESTFN, 'w+', encoding=encoding) as f:
+                f.write(data)
+                f.seek(f.tell())
+                f.write(data)
+                f.seek(0)
+                self.assertEqual(f.read(), data * 2)
+
+            # (StreamWriter) Check that the BOM is not written after a seek()
+            # at a position different than the start
+            with codecs.open(test_support.TESTFN, 'w+', encoding=encoding) as f:
+                f.writer.write(data)
+                f.writer.seek(f.writer.tell())
+                f.writer.write(data)
+                f.seek(0)
+                self.assertEqual(f.read(), data * 2)
+
+
 def test_main():
     test_support.run_unittest(
+        UTF32Test,
+        UTF32LETest,
+        UTF32BETest,
         UTF16Test,
+        UTF16LETest,
+        UTF16BETest,
+        UTF8Test,
+        UTF8SigTest,
+        UTF7Test,
+        UTF16ExTest,
+        ReadBufferTest,
+        CharBufferTest,
         EscapeDecodeTest,
         RecodingTest,
         PunycodeTest,
-# Jython transition 2.3
-# Missing the stringprep module.  http://jython.org/bugs/1758320
-#        NameprepTest
+        UnicodeInternalTest,
+        NameprepTest,
+        IDNACodecTest,
+        CodecsModuleTest,
+        StreamReaderTest,
+        EncodedFileTest,
+        Str2StrTest,
+        BasicUnicodeTest,
+        BasicStrTest,
+        CharmapTest,
+        WithStmtTest,
+        BomTest,
     )
 
 

File Lib/test/test_unicode.py

 
         self.assertRaises(TypeError, unicode, 42, 42, 42)
 
-    @unittest.skip("FIXME: broken")
     def test_codecs_utf7(self):
         utfTests = [
             (u'A\u2262\u0391.', 'A+ImIDkQ.'),             # RFC2152 example
         for (x, y) in utfTests:
             self.assertEqual(x.encode('utf-7'), y)
 
-        # surrogates not supported
+        # Lone/misordered surrogates are an error
         self.assertRaises(UnicodeError, unicode, '+3ADYAA-', 'utf-7')
 
-        self.assertEqual(unicode('+3ADYAA-', 'utf-7', 'replace'), u'\ufffd')
+        # Jython (and some CPython versions): two misplaced surrogates => two replacements
+        self.assertEqual(unicode('+3ADYAA-', 'utf-7', 'replace'), u'\ufffd\ufffd')
+        # self.assertEqual(unicode('+3ADYAA-', 'utf-7', 'replace'), u'\ufffd')
 
     def test_codecs_utf8(self):
         self.assertEqual(u''.encode('utf-8'), '')
         self.assertEqual(u'\u20ac'.encode('utf-8'), '\xe2\x82\xac')
+        # Jython will not compile Unicode literals with surrogate units
         #self.assertEqual(u'\ud800\udc02'.encode('utf-8'), '\xf0\x90\x80\x82')
         #self.assertEqual(u'\ud84d\udc56'.encode('utf-8'), '\xf0\xa3\x91\x96')
         #self.assertEqual(u'\ud800'.encode('utf-8'), '\xed\xa0\x80')
         # * strict decoding testing for all of the
         #   UTF8_ERROR cases in PyUnicode_DecodeUTF8
 
+    @unittest.skipIf(test_support.is_jython, "IDNA codec missing in Jython (issue 1153)")
     def test_codecs_idna(self):
         # Test whether trailing dot is preserved
         self.assertEqual(u"www.python.org.".encode("idna"), "www.python.org.")
         # Error handling (PyUnicode_EncodeDecimal())
         self.assertRaises(UnicodeError, int, u"\u0200")
 
-    @unittest.skip("FIXME: broken")
     def test_codecs(self):
         # Encoding
         self.assertEqual(u'hello'.encode('ascii'), 'hello')
         self.assertEqual(x, y)
 
 def test_main():
-    if test_support.is_jython:
-        # http://bugs.jython.org/issue1153
-        del UnicodeTest.test_codecs_idna
     test_support.run_unittest(UnicodeTest)
 
 if __name__ == "__main__":

File src/org/python/core/codecs.java

 /*
- * Copyright 2000 Finn Bock
+ * Copyright (c)2013 Jython Developers. Original Java version copyright 2000 Finn Bock.
  *
- * This program contains material copyrighted by:
- * Copyright (c) Corporation for National Research Initiatives.
- * Originally written by Marc-Andre Lemburg (mal@lemburg.com).
+ * This program contains material copyrighted by: Copyright (c) Corporation for National Research
+ * Initiatives. Originally written by Marc-Andre Lemburg (mal@lemburg.com).
  */
 package org.python.core;
 
 import java.nio.charset.Charset;
-
 import java.util.ArrayList;
 import java.util.Iterator;
 
 import org.python.core.util.StringUtil;
 
 /**
- * Contains the implementation of the builtin codecs.
+ * This class implements the codec registry and utility methods supporting codecs, such as those
+ * providing the standard replacement strategies ("ignore", "backslashreplace", etc.). The _codecs
+ * module relies heavily on apparatus implemented here, and therefore so does the Python
+ * <code>codecs</code> module (in <code>Lib/codecs.py</code>). It corresponds approximately to
+ * CPython's <code>Python/codecs.c</code>.
+ * <p>
+ * The class also contains the inner methods of the standard Unicode codecs, available for
+ * transcoding of text at the Java level. These also are exposed through the <code>_codecs</code>
+ * module. In CPython, the implementation are found in <code>Objects/unicodeobject.c</code>.
+ *
  * @since Jython 2.0
  */
 public class codecs {
         }
         PyObject handler = errorHandlers.__finditem__(handlerName.intern());
         if (handler == null) {
-            throw new PyException(Py.LookupError,
-                    "unknown error handler name '" + handlerName + "'");
+            throw new PyException(Py.LookupError, "unknown error handler name '" + handlerName
+                    + "'");
         }
         return handler;
     }
 
         if (searchPath.__len__() == 0) {
             throw new PyException(Py.LookupError,
-                "no codec search functions registered: can't find encoding '" + encoding + "'");
+                    "no codec search functions registered: can't find encoding '" + encoding + "'");
         }
 
         for (PyObject func : searchPath.asIterable()) {
     private static String normalizestring(String string) {
         return string.toLowerCase().replace(' ', '-');
     }
+
     private static boolean import_encodings_called;
 
     private static void import_encodings() {
                 // If we couldn't find an encoding, see if we have a builtin
                 if (encoding.equals("utf-8")) {
                     return wrapDecodeResult(PyUnicode_DecodeUTF8(v.toString(), errors));
-                } else if(encoding.equals("utf-7")) {
+                } else if (encoding.equals("utf-7")) {
                     return wrapDecodeResult(PyUnicode_DecodeUTF7(v.toString(), errors));
-                } else if(encoding.equals("latin-1")) {
+                } else if (encoding.equals("latin-1")) {
                     return wrapDecodeResult(PyUnicode_DecodeLatin1(v.toString(), v.__len__(),
-                        errors));
+                            errors));
                 }
             }
             throw ex;
         return new PyUnicode(result, true);
     }
 
-    public static String encode(PyString v, String encoding,
-            String errors) {
+    public static String encode(PyString v, String encoding, String errors) {
         if (encoding == null) {
             encoding = getDefaultEncoding();
         } else {
             errors = errors.intern();
         }
 
-        /* Shortcuts for common default encodings.  latin-1 must not use the
-         * lookup registry for the encodings module to work correctly */
+        /*
+         * Shortcuts for common default encodings. latin-1 must not use the lookup registry for the
+         * encodings module to work correctly
+         */
         if (encoding.equals("latin-1")) {
             return PyUnicode_EncodeLatin1(v.toString(), v.__len__(), errors);
         } else if (encoding.equals("ascii")) {
                 // If we couldn't find an encoding, see if we have a builtin
                 if (encoding.equals("utf-8")) {
                     return PyUnicode_EncodeUTF8(v.toString(), errors);
-                } else if(encoding.equals("utf-7")) {
+                } else if (encoding.equals("utf-7")) {
                     return codecs.PyUnicode_EncodeUTF7(v.toString(), false, false, errors);
                 }
             }
     }
 
     private static boolean isUnicodeError(PyObject exc) {
-        return Py.isInstance(exc, Py.UnicodeDecodeError) ||
-                Py.isInstance(exc, Py.UnicodeEncodeError) ||
-                Py.isInstance(exc, Py.UnicodeTranslateError);
+        return Py.isInstance(exc, Py.UnicodeDecodeError)
+                || Py.isInstance(exc, Py.UnicodeEncodeError)
+                || Py.isInstance(exc, Py.UnicodeTranslateError);
     }
 
     public static PyObject replace_errors(PyObject[] args, String[] kws) {
             return new PyTuple(new PyUnicode("?"), Py.newInteger(end));
         } else if (Py.isInstance(exc, Py.UnicodeDecodeError)) {
             int end = exceptions.getEnd(exc, false);
-            return new PyTuple(new PyUnicode(Py_UNICODE_REPLACEMENT_CHARACTER),
-                               Py.newInteger(end));
+            return new PyTuple(new PyUnicode(Py_UNICODE_REPLACEMENT_CHARACTER), Py.newInteger(end));
         } else if (Py.isInstance(exc, Py.UnicodeTranslateError)) {
             int end = exceptions.getEnd(exc, true);
-            return new PyTuple(new PyUnicode(Py_UNICODE_REPLACEMENT_CHARACTER),
-                               Py.newInteger(end));
+            return new PyTuple(new PyUnicode(Py_UNICODE_REPLACEMENT_CHARACTER), Py.newInteger(end));
         }
         throw wrong_exception_type(exc);
     }
         if (!Py.isInstance(exc, Py.UnicodeEncodeError)) {
             throw wrong_exception_type(exc);
         }
-        int start = ((PyInteger) exc.__getattr__("start")).getValue();
-        int end = ((PyInteger) exc.__getattr__("end")).getValue();
+        int start = ((PyInteger)exc.__getattr__("start")).getValue();
+        int end = ((PyInteger)exc.__getattr__("end")).getValue();
         String object = exc.__getattr__("object").toString();
         StringBuilder replacement = new StringBuilder();
         xmlcharrefreplace_internal(start, end, object, replacement);
         return replacement;
     }
 
-    private static void xmlcharrefreplace_internal(int start, int end, String object, StringBuilder replacement) {
+    private static void xmlcharrefreplace_internal(int start, int end, String object,
+            StringBuilder replacement) {
         for (int i = start; i < end; i++) {
             replacement.append("&#");
             char cur = object.charAt(i);
                 base = 1000000;
             }
             while (digits-- > 0) {
-                replacement.append((char) ('0' + cur / base));
+                replacement.append((char)('0' + cur / base));
                 cur %= base;
                 base /= 10;
             }
     private static PyException wrong_exception_type(PyObject exc) {
         PyObject excClass = exc.__getattr__("__class__");
         PyObject className = excClass.__getattr__("__name__");
-        return new PyException(Py.TypeError, "Don't know how to handle " + className + " in error callback");
+        return new PyException(Py.TypeError, "Don't know how to handle " + className
+                + " in error callback");
     }
-    static char hexdigits[] = {
+
+    static char hexdigits[] = {//@formatter:off
         '0', '1', '2', '3', '4', '5', '6', '7',
         '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
-    };
+    }; //@formatter:on
 
     public static PyObject backslashreplace_errors(PyObject[] args, String[] kws) {
         ArgParser ap = new ArgParser("backslashreplace_errors", args, kws, "exc");
         if (!Py.isInstance(exc, Py.UnicodeEncodeError)) {
             throw wrong_exception_type(exc);
         }
-        int start = ((PyInteger) exc.__getattr__("start")).getValue();
-        int end = ((PyInteger) exc.__getattr__("end")).getValue();
+        int start = ((PyInteger)exc.__getattr__("start")).getValue();
+        int end = ((PyInteger)exc.__getattr__("end")).getValue();
         String object = exc.__getattr__("object").toString();
         StringBuilder replacement = new StringBuilder();
         backslashreplace_internal(start, end, object, replacement);
         return replacement;
     }
 
-    private static void backslashreplace_internal(int start, int end, String object, StringBuilder replacement) {
-        for (Iterator<Integer> iter = new StringSubsequenceIterator(object, start, end, 1); iter.hasNext();) {
+    private static void backslashreplace_internal(int start, int end, String object,
+            StringBuilder replacement) {
+        for (Iterator<Integer> iter = new StringSubsequenceIterator(object, start, end, 1); iter
+                .hasNext();) {
             int c = iter.next();
             replacement.append('\\');
             if (c >= 0x00010000) {
             searchPath = new PyList();
             searchCache = new PyStringMap();
             errorHandlers = new PyStringMap();
-            String[] builtinErrorHandlers = new String[]{"strict",
-                IGNORE,
-                REPLACE,
-                XMLCHARREFREPLACE,
-                BACKSLASHREPLACE
-            };
+            String[] builtinErrorHandlers =
+                    new String[] {"strict", IGNORE, REPLACE, XMLCHARREFREPLACE, BACKSLASHREPLACE};
             for (String builtinErrorHandler : builtinErrorHandlers) {
-                register_error(builtinErrorHandler, Py.newJavaFunc(codecs.class,
-                        builtinErrorHandler + "_errors"));
+                register_error(builtinErrorHandler,
+                        Py.newJavaFunc(codecs.class, builtinErrorHandler + "_errors"));
             }
             import_encodings();
         }
     }
+
     /* --- UTF-7 Codec -------------------------------------------------------- */
 
-    /* see RFC2152 for details */
-    public static char utf7_special[] = {
-        /*
-         * indicate whether a UTF-7 character is special i.e. cannot be directly
-         * encoded: 0 - not special 1 - special 2 - whitespace (optional) 3 -
-         * RFC2152 Set O (optional)
-         */
-        1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 2, 1, 1,
-        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
-        2, 3, 3, 3, 3, 3, 3, 0, 0, 0, 3, 1, 0, 0, 0, 1,
-        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 0,
-        3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 1, 3, 3, 3,
-        3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 1, 1
-    ,
+    /*
+     * This codec was converted to Java from the CPython v2.7.3 final. See RFC2152 for details of
+     * the encoding scheme. We encode conservatively and decode liberally.
+     */
 
+    /* //@formatter:off
+     * The UTF-7 encoder treats ASCII characters differently according to whether they are Set D,
+     * Set O, Whitespace, or special (i.e. none of the above). See RFC2152. This array identifies
+     * these different sets:
+     * 0 : "Set D"
+     *     alphanumeric and '(),-./:?
+     * 1 : "Set O"
+     *     !"#$%&*;<=>@[]^_`{|}
+     * 2 : "whitespace"
+     *     ht nl cr sp
+     * 3 : special (must be base64 encoded)
+     *     everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
+     */
+    private static final byte[] utf7_category = {
+    /* nul soh stx etx eot enq ack bel bs  ht  nl  vt  np  cr  so  si  */
+        3,  3,  3,  3,  3,  3,  3,  3,  3,  2,  2,  3,  3,  2,  3,  3,
+    /* dle dc1 dc2 dc3 dc4 nak syn etb can em  sub esc fs  gs  rs  us  */
+        3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,
+    /* sp   !   "   #   $   %   &   '   (   )   *   +   ,   -   .   /  */
+        2,  1,  1,  1,  1,  1,  1,  0,  0,  0,  1,  3,  0,  0,  0,  0,
+    /*  0   1   2   3   4   5   6   7   8   9   :   ;   <   =   >   ?  */
+        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  0,
+    /*  @   A   B   C   D   E   F   G   H   I   J   K   L   M   N   O  */
+        1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+    /*  P   Q   R   S   T   U   V   W   X   Y   Z   [   \   ]   ^   _  */
+        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  3,  1,  1,  1,
+    /*  `   a   b   c   d   e   f   g   h   i   j   k   l   m   n   o  */
+        1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+    /*  p   q   r   s   t   u   v   w   x   y   z   {   |   }   ~  del */
+        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  3,  3,
+    };//@formatter:on
 
-           };
+    /**
+     * Determine whether this character should be encoded as itself. The answer depends on whether
+     * we are encoding set O (optional special characters) as itself, and also on whether we are
+     * encoding whitespace as itself. RFC2152 makes it clear that the answers to these questions
+     * vary between applications, so this code needs to be flexible.
+     *
+     * @param c code point of the character
+     * @param directO true if characters in "set O" may be encoded as themselves
+     * @param directWS true if whitespace characters may be encoded as themselves
+     * @return
+     */
+    private static boolean ENCODE_DIRECT(int c, boolean directO, boolean directWS) {
 
-    private static boolean SPECIAL(char c, boolean encodeO, boolean encodeWS){
-    return (c>127 || utf7_special[(c)] == 1) ||
-                (encodeWS && (utf7_special[(c)] == 2)) ||
-                (encodeO && (utf7_special[(c)] == 3));
+        if (c >= 128 || c < 0) {
+            return false;   // Character not in table is always special
+        } else {
+            switch (utf7_category[c]) {
+                case 0:     // This is a regular character
+                    return true;
+                case 1:     // This is a whilespace character
+                    return directWS;
+                case 2:     // This is an optional special character
+                    return directO;
+                default:    // This is always a special character (including '+')
+                    return false;
+            }
+        }
     }
-    private static final String B64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
 
-    private static char B64(int n) {
+    /** Look-up for the Base64 encoded byte [0..0x3f] */
+    private static final String B64_CHARS =
+            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+    /** What is the Base64 encoded byte for (the bottom 6 bits of) n? */
+    private static char TO_BASE64(int n) {
         return B64_CHARS.charAt(n & 0x3f);
     }
 
-    private static boolean B64CHAR(char c) {
-        return B64_CHARS.indexOf(c) != -1;
+    /**
+     * Is c the code point of a Base64 character? And if so, what is the 6-bit quantity to be
+     * decodec from c? Return the 6-bit equivalent of c in a Base64 segment, -1 if it cannot be used
+     * in a Base64 segment, and -2 for the special case of '-' ending the segment.
+     */
+    private static int FROM_BASE64(int c) {
+        return (c >= 128) ? -1 : BASE64_VALUE[c];
     }
 
-    private static int UB64(char c) {
-        return ((c) == '+' ? 62 : (c) == '/' ? 63 : (c) >= 'a' ? (c) - 71 : (c) >= 'A' ? (c) - 65 : (c) + 4);
+    /**
+     * Look-up table to convert ASCII byte to 6-bit Base64 value, -1 if not Base64, and -2 if
+     * special terminator '-'.
+     */
+    private static final byte[] BASE64_VALUE = {//@formatter:off
+    // nul soh stx etx eot enq ack bel  bs  ht  nl  vt  np  cr  so  si
+        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+    // dle dc1 dc2 dc3 dc4 nak syn etb can  em sub esc  fs  gs  rs  us
+        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+    //  sp   !   "   #   $   %   &   '   (   )   *   +   ,   -   .   /
+        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -2, -1, 63,
+    //   0   1   2   3   4   5   6   7   8   9   :   ;   <   =   >   ?
+        52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
+    //   @   A   B   C   D   E   F   G   H   I   J   K   L   M   N   O
+        -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
+    //   P   Q   R   S   T   U   V   W   X   Y   Z   [   \   ]   ^   _
+        15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
+    //   `   a   b   c   d   e   f   g   h   i   j   k   l   m   n   o
+        -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
+    //   p   q   r   s   t   u   v   w   x   y   z   {   |   }   ~ del
+        41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
+    };//@formatter:on
+
+    /**
+     * Enumeration of the error causes during decoding of the Base64 segment of UTF-7
+     */
+    static enum UTF7Error {
+        NONE("No error"),                                               // No error
+        PADDING("non-zero padding bits in shift sequence"),             // Error when at end
+        PARTIAL("partial character in shift sequence"),                 // Error when at end
+        TRUNCATED("second surrogate missing at end of shift sequence"), // Error when at end
+        MISSING("second surrogate missing"),  // Lead surrogate followed by another, or BMP
+        TRAIL("unexpected second surrogate"); // Trail surrogate not preceded by lead
+
+        /** Suitable error message */
+        final String msg;
+
+        private UTF7Error(String msg) {
+            this.msg = msg;
+        }
     }
 
-    // note that we follow CPython 2.5 exactly here - it does not support surrogates,
-    // but has to process as-if they are there for replacement purposes
-    // fortunately no one really cares about utf-7
-    public static String PyUnicode_DecodeUTF7(String str, String errors) {
-        int s = 0;
-        int e = str.length();
-        boolean inShift = false;
-        int bitsInCharsleft = 0;
-        long charsleft = 0;
-        boolean surrogate = false;
-        StringBuilder unicode = new StringBuilder(e);
-        while (s < e) {
-            // restart:
-            char ch = str.charAt(s);
-            if (inShift) {
-                if ((ch == '-') || !B64CHAR(ch)) {
-                    inShift = false;
-                    s++;
-                    while (bitsInCharsleft >= 16) {
-                        bitsInCharsleft -= 16;
-                        char outCh = (char) ((charsleft >> bitsInCharsleft) & 0xffff);
-                        if (surrogate) {
-                            s = codecs.insertReplacementAndGetResume(unicode,
-                                    errors,
-                                    "utf-7",
-                                    str,
-                                    s,
-                                    s + 1,
-                                    "code pairs are not supported");
-                            surrogate = false;
-                        } else if (0xDC00 <= outCh && outCh <= 0xDFFF) {
-                            surrogate = true;
-                        } else {
-                            unicode.append(outCh);
+    /**
+     * Decode (perhaps partially) a sequence of bytes representing the UTF-7 encoded form of a
+     * Unicode string and return the (Jython internal representation of) the unicode object, and
+     * amount of input consumed. The only state we preserve is our read position, i.e. how many
+     * characters we have consumed. So if the input ends part way through a Base64 sequence the data
+     * reported as consumed is only that up to and not including the Base64 start marker ('+').
+     * Performance will be poor (quadratic cost) on runs of Base64 data long enough to exceed the
+     * input quantum in incremental decoding. The retruned Java String is a UTF-16 representation of
+     * the Unicode result, in line with Java conventions. Unicode characters above the BMP are
+     * represented as surrogate pairs.
+     *
+     * @param bytes input represented as String (Jython PyString convention)
+     * @param errors error policy name (e.g. "ignore", "replace")
+     * @param consumed returns number of bytes consumed in element 0, or is null if a "final" call
+     * @return unicode result (as UTF-16 Java String)
+     */
+    public static String PyUnicode_DecodeUTF7Stateful(String bytes, String errors, int[] consumed) {
+        int s;                      // Index in the input bytes
+        boolean inBase64 = false;   // Whether s is currently in a Base64 segment
+        long base64buffer = 0;      // Stored bits buffer during Base64 decoding
+        int base64bits = 0;         // Number of valid bits buffered during Base64 decoding
+        int startInBytes = 0;       // Place in input bytes where most recent Base64 segment begins
+        int syncInBytes = 0;        // Place in input bytes where stored bits buffer last empty
+        int startInUnicode = 0;     // Place in output unicode where most recent Base64 segment begins
+
+        int size = bytes.length();
+        StringBuilder unicode = new StringBuilder(size);
+
+        for (s = 0; s < size; s++) { // In error cases s may skip forwards in bytes
+
+            // Next byte to process
+            int b = bytes.charAt(s);
+
+            if (b >= 128) {
+                // The input was supposed to be 7-bit clean
+                s = insertReplacementAndGetResume(unicode, errors, "utf-7", //
+                        bytes, s, s + 1, "unexpected special character") - 1;
+
+            } else if (inBase64) {
+                // We are currently processing a Base64 section
+
+                if (base64bits == 0) {
+                    // Mark this point as latest easy error recovery point (bits buffer empty)
+                    syncInBytes = s;
+                }
+
+                int sixBits = FROM_BASE64(b);   // returns -ve if not Base64
+                if (sixBits >= 0) {
+                    // And we continue processing a Base64 section
+                    base64buffer = (base64buffer << 6) | sixBits;
+                    base64bits += 6;
+
+                    if (base64bits >= 32) {
+                        // We have enough bits for a code point
+                        base64bits = emitCodePoints(unicode, base64buffer, base64bits);
+
+                        if (base64bits >= 32) {
+                            // We stopped prematurely. Why?
+                            UTF7Error error = emitCodePointsDiagnosis(base64buffer, base64bits);
+                            // Difficult to know exactly what input characters to blame
+                            s = insertReplacementAndGetResume(unicode, errors, "utf-7", //
+                                    bytes, syncInBytes, s + 1, error.msg) - 1;
+                            // Discard one UTF-16 output and hope for the best
+                            base64bits -= 16;
                         }
+
                     }
-                    if (bitsInCharsleft >= 6) {
+
+                } else {
+                    // We are now leaving a Base64 section
+                    inBase64 = false;
+
+                    // We should have a whole number of code points and < 6 bits zero padding
+                    if (base64bits > 0) {
+                        // Try to emit them all
+                        base64bits = emitCodePoints(unicode, base64buffer, base64bits);
+                        // Now check for errors
+                        UTF7Error error = emitCodePointsDiagnosis(base64buffer, base64bits);
+                        if (error != UTF7Error.NONE) {
+                            // Difficult to know exactly what input characters to blame
+                            s = insertReplacementAndGetResume(unicode, errors, "utf-7", //
+                                    bytes, s, s + 1, error.msg) - 1;
+                        }
+                        // We are, in any case, discarding whatever is in the buffer
+                        base64bits = 0;
+                    }
+
+                    if (b == '-') {
                         /*
-                         * The shift sequence has a partial character in it. If
-                         * bitsleft < 6 then we could just classify it as
-                         * padding but that is not the case here
+                         * '-' signals the end of Base64. The byte is is simply absorbed, but in the
+                         * special case where it is the first byte of the Base64 segment, the
+                         * zero-length segment '+-' actually encodes "+".
                          */
-                        s = insertReplacementAndGetResume(unicode,
-                                errors,
-                                "utf-7",
-                                str,
-                                s,
-                                s + 1,
-                                "partial character in shift sequence");
-                    }
-                    /*
-                     * According to RFC2152 the remaining bits should be zero.
-                     * We choose to signal an error/insert a replacement
-                     * character here so indicate the potential of a misencoded
-                     * character.
-                     */
-                    if (bitsInCharsleft > 0 && ((charsleft << 5 - bitsInCharsleft) & 0x1f) > 0) {
-                        s = insertReplacementAndGetResume(unicode,
-                                errors,
-                                "utf-7",
-                                str,
-                                s,
-                                s + 1,
-                                "non-zero padding bits in shift sequence");
-                    }
-                    if (ch == '-') {
-                        if ((s < e) && (str.charAt(s) == '-')) {
-                            unicode.append('-');
-                            inShift = true;
+                        if (s == startInBytes + 1) {
+                            unicode.append('+');
                         }
-                    } else if (SPECIAL(ch, false, false)) {
-                        s = insertReplacementAndGetResume(unicode,
-                                errors,
-                                "utf-7",
-                                str,
-                                s,
-                                s + 1,
-                                "unexpected special character");
                     } else {
-                        unicode.append(ch);
-                    }
-                } else {
-                    charsleft = (charsleft << 6) | UB64(ch);
-                    bitsInCharsleft += 6;
-                    s++;
-                    while (bitsInCharsleft >= 16) {
-                        bitsInCharsleft -= 16;
-                        char outCh = (char) ((charsleft >> bitsInCharsleft) & 0xffff);
-                        if (surrogate) {
-                            s = codecs.insertReplacementAndGetResume(unicode,
-                                    errors,
-                                    "utf-7",
-                                    str,
-                                    s,
-                                    s + 1,
-                                    "code pairs are not supported");
-                        } else if (0xDC00 <= outCh && outCh <= 0xDFFF) {
-                            surrogate = true;
-                        } else {
-                            unicode.append(outCh);
-                        }
+                        /*
+                         * This b is a US-ASCII byte for some character.
+                         */
+                        unicode.appendCodePoint(b);
                     }
                 }
-            } else if (ch == '+') {
-                s++;
-                if (s < e && str.charAt(s) == '-') {
-                    s++;
-                    unicode.append('+');
-                } else {
-                    inShift = true;
-                    bitsInCharsleft = 0;
-                }
-            } else if (SPECIAL(ch, false, false)) {
-                s = insertReplacementAndGetResume(unicode,
-                        errors,
-                        "utf-7",
-                        str,
-                        s,
-                        s + 1,
-                        "unexpected special character");
+
+            } else if (b == '+') {
+                /*
+                 * We are not currently processing a Base64 section, but this starts one. Remember
+                 * where it starts, in the input bytes and the output unicode so that, if we hit the
+                 * end of input before it ends, we can leave it unprocessed for next time.
+                 */
+                startInBytes = s;
+                startInUnicode = unicode.length();
+
+                // Initialise the Base64 decoder
+                base64bits = 0;
+                inBase64 = true;
+
             } else {
-                unicode.append(ch);
-                s++;
-            }
-            if (inShift && s == e) {