test_codecs.py 56 KB
Newer Older
1
from test import support
2
import unittest
3
import codecs
4
import sys, _testcapi, io
5

6 7 8 9
class Queue(object):
    """
    queue: write bytes at one end, read bytes from the other end
    """
10 11
    def __init__(self, buffer):
        self._buffer = buffer
12 13 14 15 16 17 18

    def write(self, chars):
        self._buffer += chars

    def read(self, size=-1):
        if size<0:
            s = self._buffer
19
            self._buffer = self._buffer[:0] # make empty
20 21 22 23 24 25
            return s
        else:
            s = self._buffer[:size]
            self._buffer = self._buffer[size:]
            return s

26 27
class MixInCheckStateHandling:
    def check_state_handling_decode(self, encoding, u, s):
28
        for i in range(len(s)+1):
29 30 31
            d = codecs.getincrementaldecoder(encoding)()
            part1 = d.decode(s[:i])
            state = d.getstate()
32
            self.assertTrue(isinstance(state[1], int))
33 34 35 36 37 38
            # Check that the condition stated in the documentation for
            # IncrementalDecoder.getstate() holds
            if not state[1]:
                # reset decoder to the default state without anything buffered
                d.setstate((state[0][:0], 0))
                # Feeding the previous input may not produce any output
39
                self.assertTrue(not d.decode(state[0]))
40 41 42 43 44 45 46 47 48 49
                # The decoder must return to the same state
                self.assertEqual(state, d.getstate())
            # Create a new decoder and set it to the state
            # we extracted from the old one
            d = codecs.getincrementaldecoder(encoding)()
            d.setstate(state)
            part2 = d.decode(s[i:], True)
            self.assertEqual(u, part1+part2)

    def check_state_handling_encode(self, encoding, u, s):
50
        for i in range(len(u)+1):
51 52 53 54 55 56 57 58 59
            d = codecs.getincrementalencoder(encoding)()
            part1 = d.encode(u[:i])
            state = d.getstate()
            d = codecs.getincrementalencoder(encoding)()
            d.setstate(state)
            part2 = d.encode(u[i:], True)
            self.assertEqual(s, part1+part2)

class ReadTest(unittest.TestCase, MixInCheckStateHandling):
60
    def check_partial(self, input, partialresults):
61
        # get a StreamReader for the encoding and feed the bytestring version
62
        # of input to the reader byte by byte. Read everything available from
63 64
        # the StreamReader and check that the results equal the appropriate
        # entries from partialresults.
65
        q = Queue(b"")
66
        r = codecs.getreader(self.encoding)(q)
67
        result = ""
68
        for (c, partialresult) in zip(input.encode(self.encoding), partialresults):
69
            q.write(bytes([c]))
70 71 72
            result += r.read()
            self.assertEqual(result, partialresult)
        # check that there's nothing left in the buffers
73
        self.assertEqual(r.read(), "")
74
        self.assertEqual(r.bytebuffer, b"")
75
        self.assertEqual(r.charbuffer, "")
76

77 78
        # do the check again, this time using a incremental decoder
        d = codecs.getincrementaldecoder(self.encoding)()
79
        result = ""
80
        for (c, partialresult) in zip(input.encode(self.encoding), partialresults):
81
            result += d.decode(bytes([c]))
82 83
            self.assertEqual(result, partialresult)
        # check that there's nothing left in the buffers
84 85
        self.assertEqual(d.decode(b"", True), "")
        self.assertEqual(d.buffer, b"")
86

87
        # Check whether the reset method works properly
88
        d.reset()
89
        result = ""
90
        for (c, partialresult) in zip(input.encode(self.encoding), partialresults):
91
            result += d.decode(bytes([c]))
92 93
            self.assertEqual(result, partialresult)
        # check that there's nothing left in the buffers
94 95
        self.assertEqual(d.decode(b"", True), "")
        self.assertEqual(d.buffer, b"")
96 97 98 99 100

        # check iterdecode()
        encoded = input.encode(self.encoding)
        self.assertEqual(
            input,
101
            "".join(codecs.iterdecode([bytes([c]) for c in encoded], self.encoding))
102 103
        )

104 105
    def test_readline(self):
        def getreader(input):
106
            stream = io.BytesIO(input.encode(self.encoding))
107 108
            return codecs.getreader(self.encoding)(stream)

109
        def readalllines(input, keepends=True, size=None):
110 111 112
            reader = getreader(input)
            lines = []
            while True:
113
                line = reader.readline(size=size, keepends=keepends)
114 115 116
                if not line:
                    break
                lines.append(line)
117
            return "|".join(lines)
118

119 120 121
        s = "foo\nbar\r\nbaz\rspam\u2028eggs"
        sexpected = "foo\n|bar\r\n|baz\r|spam\u2028|eggs"
        sexpectednoends = "foo|bar|baz|spam|eggs"
122 123 124 125
        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)
126 127 128 129

        # Test long lines (multiple calls to read() in readline())
        vw = []
        vwo = []
130 131 132
        for (i, lineend) in enumerate("\n \r\n \r \u2028".split()):
            vw.append((i*200)*"\3042" + lineend)
            vwo.append((i*200)*"\3042")
133 134 135 136 137
        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
138
        for size in range(80):
139 140
            for lineend in "\n \r\n \r \u2028".split():
                s = 10*(size*"a" + lineend + "xxx\n")
141
                reader = getreader(s)
142
                for i in range(10):
143 144
                    self.assertEqual(
                        reader.readline(keepends=True),
145
                        size*"a" + lineend,
146 147
                    )
                reader = getreader(s)
148
                for i in range(10):
149 150
                    self.assertEqual(
                        reader.readline(keepends=False),
151
                        size*"a",
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
                    )

    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',
        ]
218
        stream = io.BytesIO("".join(s).encode(self.encoding))
219 220 221
        reader = codecs.getreader(self.encoding)(stream)
        for (i, line) in enumerate(reader):
            self.assertEqual(line, s[i])
222 223

    def test_readlinequeue(self):
224
        q = Queue(b"")
225 226 227 228
        writer = codecs.getwriter(self.encoding)(q)
        reader = codecs.getreader(self.encoding)(q)

        # No lineends
229 230 231 232 233 234 235 236
        writer.write("foo\r")
        self.assertEqual(reader.readline(keepends=False), "foo")
        writer.write("\nbar\r")
        self.assertEqual(reader.readline(keepends=False), "")
        self.assertEqual(reader.readline(keepends=False), "bar")
        writer.write("baz")
        self.assertEqual(reader.readline(keepends=False), "baz")
        self.assertEqual(reader.readline(keepends=False), "")
237 238

        # Lineends
239 240 241 242 243 244 245 246 247 248
        writer.write("foo\r")
        self.assertEqual(reader.readline(keepends=True), "foo\r")
        writer.write("\nbar\r")
        self.assertEqual(reader.readline(keepends=True), "\n")
        self.assertEqual(reader.readline(keepends=True), "bar\r")
        writer.write("baz")
        self.assertEqual(reader.readline(keepends=True), "baz")
        self.assertEqual(reader.readline(keepends=True), "")
        writer.write("foo\r\n")
        self.assertEqual(reader.readline(keepends=True), "foo\r\n")
249

250
    def test_bug1098990_a(self):
251 252 253
        s1 = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy\r\n"
        s2 = "offending line: ladfj askldfj klasdj fskla dfzaskdj fasklfj laskd fjasklfzzzzaa%whereisthis!!!\r\n"
        s3 = "next line.\r\n"
254 255

        s = (s1+s2+s3).encode(self.encoding)
256
        stream = io.BytesIO(s)
257 258 259 260
        reader = codecs.getreader(self.encoding)(stream)
        self.assertEqual(reader.readline(), s1)
        self.assertEqual(reader.readline(), s2)
        self.assertEqual(reader.readline(), s3)
261
        self.assertEqual(reader.readline(), "")
262 263

    def test_bug1098990_b(self):
264 265 266 267 268
        s1 = "aaaaaaaaaaaaaaaaaaaaaaaa\r\n"
        s2 = "bbbbbbbbbbbbbbbbbbbbbbbb\r\n"
        s3 = "stillokay:bbbbxx\r\n"
        s4 = "broken!!!!badbad\r\n"
        s5 = "againokay.\r\n"
269 270

        s = (s1+s2+s3+s4+s5).encode(self.encoding)
271
        stream = io.BytesIO(s)
272 273 274 275 276 277
        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)
278
        self.assertEqual(reader.readline(), "")
279

280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
class UTF32Test(ReadTest):
    encoding = "utf-32"

    spamle = (b'\xff\xfe\x00\x00'
              b's\x00\x00\x00p\x00\x00\x00a\x00\x00\x00m\x00\x00\x00'
              b's\x00\x00\x00p\x00\x00\x00a\x00\x00\x00m\x00\x00\x00')
    spambe = (b'\x00\x00\xfe\xff'
              b'\x00\x00\x00s\x00\x00\x00p\x00\x00\x00a\x00\x00\x00m'
              b'\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 = io.BytesIO()
        f = writer(s)
        f.write("spam")
        f.write("spam")
        d = s.getvalue()
        # check whether there is exactly one BOM in it
299
        self.assertTrue(d == self.spamle or d == self.spambe)
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
        # try to read it back
        s = io.BytesIO(d)
        f = reader(s)
        self.assertEquals(f.read(), "spamspam")

    def test_badbom(self):
        s = io.BytesIO(4*b"\xff")
        f = codecs.getreader(self.encoding)(s)
        self.assertRaises(UnicodeError, f.read)

        s = io.BytesIO(8*b"\xff")
        f = codecs.getreader(self.encoding)(s)
        self.assertRaises(UnicodeError, f.read)

    def test_partial(self):
        self.check_partial(
            "\x00\xff\u0100\uffff",
            [
                "", # first byte of BOM read
                "", # second byte of BOM read
                "", # third byte of BOM read
                "", # fourth byte of BOM read => byteorder known
                "",
                "",
                "",
                "\x00",
                "\x00",
                "\x00",
                "\x00",
                "\x00\xff",
                "\x00\xff",
                "\x00\xff",
                "\x00\xff",
                "\x00\xff\u0100",
                "\x00\xff\u0100",
                "\x00\xff\u0100",
                "\x00\xff\u0100",
                "\x00\xff\u0100\uffff",
            ]
        )

    def test_errors(self):
        self.assertRaises(UnicodeDecodeError, codecs.utf_32_decode,
                          b"\xff", "strict", True)

    def test_decoder_state(self):
        self.check_state_handling_decode(self.encoding,
                                         "spamspam", self.spamle)
        self.check_state_handling_decode(self.encoding,
                                         "spamspam", self.spambe)

class UTF32LETest(ReadTest):
    encoding = "utf-32-le"

    def test_partial(self):
        self.check_partial(
            "\x00\xff\u0100\uffff",
            [
                "",
                "",
                "",
                "\x00",
                "\x00",
                "\x00",
                "\x00",
                "\x00\xff",
                "\x00\xff",
                "\x00\xff",
                "\x00\xff",
                "\x00\xff\u0100",
                "\x00\xff\u0100",
                "\x00\xff\u0100",
                "\x00\xff\u0100",
                "\x00\xff\u0100\uffff",
            ]
        )

    def test_simple(self):
        self.assertEqual("\U00010203".encode(self.encoding), b"\x03\x02\x01\x00")

    def test_errors(self):
        self.assertRaises(UnicodeDecodeError, codecs.utf_32_le_decode,
                          b"\xff", "strict", True)

class UTF32BETest(ReadTest):
    encoding = "utf-32-be"

    def test_partial(self):
        self.check_partial(
            "\x00\xff\u0100\uffff",
            [
                "",
                "",
                "",
                "\x00",
                "\x00",
                "\x00",
                "\x00",
                "\x00\xff",
                "\x00\xff",
                "\x00\xff",
                "\x00\xff",
                "\x00\xff\u0100",
                "\x00\xff\u0100",
                "\x00\xff\u0100",
                "\x00\xff\u0100",
                "\x00\xff\u0100\uffff",
            ]
        )

    def test_simple(self):
        self.assertEqual("\U00010203".encode(self.encoding), b"\x00\x01\x02\x03")

    def test_errors(self):
        self.assertRaises(UnicodeDecodeError, codecs.utf_32_be_decode,
                          b"\xff", "strict", True)

417 418
class UTF16Test(ReadTest):
    encoding = "utf-16"
419

420 421
    spamle = b'\xff\xfes\x00p\x00a\x00m\x00s\x00p\x00a\x00m\x00'
    spambe = b'\xfe\xff\x00s\x00p\x00a\x00m\x00s\x00p\x00a\x00m'
422 423

    def test_only_one_bom(self):
424
        _,_,reader,writer = codecs.lookup(self.encoding)
425
        # encode some stream
426
        s = io.BytesIO()
427
        f = writer(s)
428 429
        f.write("spam")
        f.write("spam")
430 431
        d = s.getvalue()
        # check whether there is exactly one BOM in it
432
        self.assertTrue(d == self.spamle or d == self.spambe)
433
        # try to read it back
434
        s = io.BytesIO(d)
435
        f = reader(s)
436
        self.assertEquals(f.read(), "spamspam")
437

438
    def test_badbom(self):
439
        s = io.BytesIO(b"\xff\xff")
440
        f = codecs.getreader(self.encoding)(s)
441 442
        self.assertRaises(UnicodeError, f.read)

443
        s = io.BytesIO(b"\xff\xff\xff\xff")
444
        f = codecs.getreader(self.encoding)(s)
445 446
        self.assertRaises(UnicodeError, f.read)

447 448
    def test_partial(self):
        self.check_partial(
449
            "\x00\xff\u0100\uffff",
450
            [
451 452 453 454 455 456 457 458 459 460
                "", # first byte of BOM read
                "", # second byte of BOM read => byteorder known
                "",
                "\x00",
                "\x00",
                "\x00\xff",
                "\x00\xff",
                "\x00\xff\u0100",
                "\x00\xff\u0100",
                "\x00\xff\u0100\uffff",
461 462 463
            ]
        )

464
    def test_errors(self):
465
        self.assertRaises(UnicodeDecodeError, codecs.utf_16_decode,
466
                          b"\xff", "strict", True)
467 468 469

    def test_decoder_state(self):
        self.check_state_handling_decode(self.encoding,
470
                                         "spamspam", self.spamle)
471
        self.check_state_handling_decode(self.encoding,
472
                                         "spamspam", self.spambe)
473

474 475
class UTF16LETest(ReadTest):
    encoding = "utf-16-le"
476 477 478

    def test_partial(self):
        self.check_partial(
479
            "\x00\xff\u0100\uffff",
480
            [
481 482 483 484 485 486 487 488
                "",
                "\x00",
                "\x00",
                "\x00\xff",
                "\x00\xff",
                "\x00\xff\u0100",
                "\x00\xff\u0100",
                "\x00\xff\u0100\uffff",
489 490 491
            ]
        )

492
    def test_errors(self):
493
        self.assertRaises(UnicodeDecodeError, codecs.utf_16_le_decode,
494
                          b"\xff", "strict", True)
495

496 497
class UTF16BETest(ReadTest):
    encoding = "utf-16-be"
498 499 500

    def test_partial(self):
        self.check_partial(
501
            "\x00\xff\u0100\uffff",
502
            [
503 504 505 506 507 508 509 510
                "",
                "\x00",
                "\x00",
                "\x00\xff",
                "\x00\xff",
                "\x00\xff\u0100",
                "\x00\xff\u0100",
                "\x00\xff\u0100\uffff",
511 512 513
            ]
        )

514
    def test_errors(self):
515
        self.assertRaises(UnicodeDecodeError, codecs.utf_16_be_decode,
516
                          b"\xff", "strict", True)
517

518 519
class UTF8Test(ReadTest):
    encoding = "utf-8"
520 521 522

    def test_partial(self):
        self.check_partial(
523
            "\x00\xff\u07ff\u0800\uffff",
524
            [
525 526 527 528 529 530 531 532 533 534 535
                "\x00",
                "\x00",
                "\x00\xff",
                "\x00\xff",
                "\x00\xff\u07ff",
                "\x00\xff\u07ff",
                "\x00\xff\u07ff",
                "\x00\xff\u07ff\u0800",
                "\x00\xff\u07ff\u0800",
                "\x00\xff\u07ff\u0800",
                "\x00\xff\u07ff\u0800\uffff",
536 537 538
            ]
        )

539
    def test_decoder_state(self):
540
        u = "\x00\x7f\x80\xff\u0100\u07ff\u0800\uffff\U0010ffff"
541 542 543
        self.check_state_handling_decode(self.encoding,
                                         u, u.encode(self.encoding))

544 545 546 547
    def test_lone_surrogates(self):
        self.assertRaises(UnicodeEncodeError, "\ud800".encode, "utf-8")
        self.assertRaises(UnicodeDecodeError, b"\xed\xa0\x80".decode, "utf-8")

548 549
    def test_surrogatepass_handler(self):
        self.assertEquals("abc\ud800def".encode("utf-8", "surrogatepass"),
550
                          b"abc\xed\xa0\x80def")
551
        self.assertEquals(b"abc\xed\xa0\x80def".decode("utf-8", "surrogatepass"),
552
                          "abc\ud800def")
553
        self.assertTrue(codecs.lookup_error("surrogatepass"))
554

555 556 557
class UTF7Test(ReadTest):
    encoding = "utf-7"

558 559 560 561 562 563 564 565 566 567 568
    def test_partial(self):
        self.check_partial(
            "a+-b",
            [
                "a",
                "a",
                "a+",
                "a+-",
                "a+-b",
            ]
        )
569 570 571 572

class UTF16ExTest(unittest.TestCase):

    def test_errors(self):
573
        self.assertRaises(UnicodeDecodeError, codecs.utf_16_ex_decode, b"\xff", "strict", 0, True)
574 575 576 577 578 579 580 581 582

    def test_bad_args(self):
        self.assertRaises(TypeError, codecs.utf_16_ex_decode)

class ReadBufferTest(unittest.TestCase):

    def test_array(self):
        import array
        self.assertEqual(
583
            codecs.readbuffer_encode(array.array("b", b"spam")),
584
            (b"spam", 4)
585 586 587
        )

    def test_empty(self):
588
        self.assertEqual(codecs.readbuffer_encode(""), (b"", 0))
589 590 591 592 593 594 595 596

    def test_bad_args(self):
        self.assertRaises(TypeError, codecs.readbuffer_encode)
        self.assertRaises(TypeError, codecs.readbuffer_encode, 42)

class CharBufferTest(unittest.TestCase):

    def test_string(self):
597
        self.assertEqual(codecs.charbuffer_encode(b"spam"), (b"spam", 4))
598 599

    def test_empty(self):
600
        self.assertEqual(codecs.charbuffer_encode(b""), (b"", 0))
601 602 603 604 605

    def test_bad_args(self):
        self.assertRaises(TypeError, codecs.charbuffer_encode)
        self.assertRaises(TypeError, codecs.charbuffer_encode, 42)

606 607 608 609 610
class UTF8SigTest(ReadTest):
    encoding = "utf-8-sig"

    def test_partial(self):
        self.check_partial(
611
            "\ufeff\x00\xff\u07ff\u0800\uffff",
612
            [
613 614 615 616 617 618 619
                "",
                "",
                "", # First BOM has been read and skipped
                "",
                "",
                "\ufeff", # Second BOM has been read and emitted
                "\ufeff\x00", # "\x00" read and emitted
620 621 622 623
                "\ufeff\x00", # First byte of encoded "\xff" read
                "\ufeff\x00\xff", # Second byte of encoded "\xff" read
                "\ufeff\x00\xff", # First byte of encoded "\u07ff" read
                "\ufeff\x00\xff\u07ff", # Second byte of encoded "\u07ff" read
624 625 626 627 628 629
                "\ufeff\x00\xff\u07ff",
                "\ufeff\x00\xff\u07ff",
                "\ufeff\x00\xff\u07ff\u0800",
                "\ufeff\x00\xff\u07ff\u0800",
                "\ufeff\x00\xff\u07ff\u0800",
                "\ufeff\x00\xff\u07ff\u0800\uffff",
630 631 632
            ]
        )

633 634
    def test_bug1601501(self):
        # SF bug #1601501: check that the codec works with a buffer
635
        self.assertEquals(str(b"\xef\xbb\xbf", "utf-8-sig"), "")
636

637 638
    def test_bom(self):
        d = codecs.getincrementaldecoder("utf-8-sig")()
639
        s = "spam"
640 641
        self.assertEqual(d.decode(s.encode("utf-8-sig")), s)

642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
    def test_stream_bom(self):
        unistring = "ABC\u00A1\u2200XYZ"
        bytestring = codecs.BOM_UTF8 + b"ABC\xC2\xA1\xE2\x88\x80XYZ"

        reader = codecs.getreader("utf-8-sig")
        for sizehint in [None] + list(range(1, 11)) + \
                        [64, 128, 256, 512, 1024]:
            istream = reader(io.BytesIO(bytestring))
            ostream = io.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 = "ABC\u00A1\u2200XYZ"
        bytestring = b"ABC\xC2\xA1\xE2\x88\x80XYZ"

        reader = codecs.getreader("utf-8-sig")
        for sizehint in [None] + list(range(1, 11)) + \
                        [64, 128, 256, 512, 1024]:
            istream = reader(io.BytesIO(bytestring))
            ostream = io.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(self):
        self.assertEquals(codecs.escape_decode(""), ("", 0))
689

690 691
class RecodingTest(unittest.TestCase):
    def test_recoding(self):
692
        f = io.BytesIO()
693
        f2 = codecs.EncodedFile(f, "unicode_internal", "utf-8")
694
        f2.write("a")
695 696 697
        f2.close()
        # Python used to crash on this at exit because of a refcount
        # bug in _codecsmodule.c
698

699 700 701
# From RFC 3492
punycode_testcases = [
    # A Arabic (Egyptian):
702 703
    ("\u0644\u064A\u0647\u0645\u0627\u0628\u062A\u0643\u0644"
     "\u0645\u0648\u0634\u0639\u0631\u0628\u064A\u061F",
704
     b"egbpdaj6bu4bxfgehfvwxn"),
705
    # B Chinese (simplified):
706
    ("\u4ED6\u4EEC\u4E3A\u4EC0\u4E48\u4E0D\u8BF4\u4E2D\u6587",
707
     b"ihqwcrb4cv8a8dqg056pqjye"),
708
    # C Chinese (traditional):
709
    ("\u4ED6\u5011\u7232\u4EC0\u9EBD\u4E0D\u8AAA\u4E2D\u6587",
710
     b"ihqwctvzc91f659drss3x8bo0yb"),
711
    # D Czech: Pro<ccaron>prost<ecaron>nemluv<iacute><ccaron>esky
712 713 714
    ("\u0050\u0072\u006F\u010D\u0070\u0072\u006F\u0073\u0074"
     "\u011B\u006E\u0065\u006D\u006C\u0075\u0076\u00ED\u010D"
     "\u0065\u0073\u006B\u0079",
715
     b"Proprostnemluvesky-uyb24dma41a"),
716
    # E Hebrew:
717 718 719
    ("\u05DC\u05DE\u05D4\u05D4\u05DD\u05E4\u05E9\u05D5\u05D8"
     "\u05DC\u05D0\u05DE\u05D3\u05D1\u05E8\u05D9\u05DD\u05E2"
     "\u05D1\u05E8\u05D9\u05EA",
720
     b"4dbcagdahymbxekheh6e0a7fei0b"),
721
    # F Hindi (Devanagari):
722
    ("\u092F\u0939\u0932\u094B\u0917\u0939\u093F\u0928\u094D"
723 724 725 726
     "\u0926\u0940\u0915\u094D\u092F\u094B\u0902\u0928\u0939"
     "\u0940\u0902\u092C\u094B\u0932\u0938\u0915\u0924\u0947"
     "\u0939\u0948\u0902",
     b"i1baa7eci9glrd9b2ae1bj0hfcgg6iyaf8o0a1dig0cd"),
727 728

    #(G) Japanese (kanji and hiragana):
729
    ("\u306A\u305C\u307F\u3093\u306A\u65E5\u672C\u8A9E\u3092"
730 731
     "\u8A71\u3057\u3066\u304F\u308C\u306A\u3044\u306E\u304B",
     b"n8jok5ay5dzabd5bym9f0cm5685rrjetr6pdxa"),
732 733

    # (H) Korean (Hangul syllables):
734 735 736
    ("\uC138\uACC4\uC758\uBAA8\uB4E0\uC0AC\uB78C\uB4E4\uC774"
     "\uD55C\uAD6D\uC5B4\uB97C\uC774\uD574\uD55C\uB2E4\uBA74"
     "\uC5BC\uB9C8\uB098\uC88B\uC744\uAE4C",
737 738
     b"989aomsvi5e83db1d2a355cv1e0vak1dwrv93d5xbh15a0dt30a5j"
     b"psd879ccm6fea98c"),
739 740

    # (I) Russian (Cyrillic):
741 742 743 744
    ("\u043F\u043E\u0447\u0435\u043C\u0443\u0436\u0435\u043E"
     "\u043D\u0438\u043D\u0435\u0433\u043E\u0432\u043E\u0440"
     "\u044F\u0442\u043F\u043E\u0440\u0443\u0441\u0441\u043A"
     "\u0438",
745
     b"b1abfaaepdrnnbgefbaDotcwatmq2g4l"),
746 747

    # (J) Spanish: Porqu<eacute>nopuedensimplementehablarenEspa<ntilde>ol
748 749 750 751 752
    ("\u0050\u006F\u0072\u0071\u0075\u00E9\u006E\u006F\u0070"
     "\u0075\u0065\u0064\u0065\u006E\u0073\u0069\u006D\u0070"
     "\u006C\u0065\u006D\u0065\u006E\u0074\u0065\u0068\u0061"
     "\u0062\u006C\u0061\u0072\u0065\u006E\u0045\u0073\u0070"
     "\u0061\u00F1\u006F\u006C",
753
     b"PorqunopuedensimplementehablarenEspaol-fmd56a"),
754 755 756 757

    # (K) Vietnamese:
    #  T<adotbelow>isaoh<odotbelow>kh<ocirc>ngth<ecirchookabove>ch\
    #   <ihookabove>n<oacute>iti<ecircacute>ngVi<ecircdotbelow>t
758 759 760 761
    ("\u0054\u1EA1\u0069\u0073\u0061\u006F\u0068\u1ECD\u006B"
     "\u0068\u00F4\u006E\u0067\u0074\u0068\u1EC3\u0063\u0068"
     "\u1EC9\u006E\u00F3\u0069\u0074\u0069\u1EBF\u006E\u0067"
     "\u0056\u0069\u1EC7\u0074",
762
     b"TisaohkhngthchnitingVit-kjcr8268qyxafd2f1b9g"),
763 764

    #(L) 3<nen>B<gumi><kinpachi><sensei>
765
    ("\u0033\u5E74\u0042\u7D44\u91D1\u516B\u5148\u751F",
766
     b"3B-ww4c5e180e575a65lsy2b"),
Tim Peters's avatar
Tim Peters committed
767

768
    # (M) <amuro><namie>-with-SUPER-MONKEYS
769 770 771
    ("\u5B89\u5BA4\u5948\u7F8E\u6075\u002D\u0077\u0069\u0074"
     "\u0068\u002D\u0053\u0055\u0050\u0045\u0052\u002D\u004D"
     "\u004F\u004E\u004B\u0045\u0059\u0053",
772
     b"-with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n"),
773 774

    # (N) Hello-Another-Way-<sorezore><no><basho>
775 776 777
    ("\u0048\u0065\u006C\u006C\u006F\u002D\u0041\u006E\u006F"
     "\u0074\u0068\u0065\u0072\u002D\u0057\u0061\u0079\u002D"
     "\u305D\u308C\u305E\u308C\u306E\u5834\u6240",
778
     b"Hello-Another-Way--fc4qua05auwb3674vfr0b"),
779 780

    # (O) <hitotsu><yane><no><shita>2
781
    ("\u3072\u3068\u3064\u5C4B\u6839\u306E\u4E0B\u0032",
782
     b"2-u9tlzr9756bt3uc0v"),
783 784

    # (P) Maji<de>Koi<suru>5<byou><mae>
785 786
    ("\u004D\u0061\u006A\u0069\u3067\u004B\u006F\u0069\u3059"
     "\u308B\u0035\u79D2\u524D",
787
     b"MajiKoi5-783gue6qz075azm5e"),
788 789

     # (Q) <pafii>de<runba>
790
    ("\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0",
791
     b"de-jg4avhby1noc0d"),
792 793

    # (R) <sono><supiido><de>
794
    ("\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067",
795
     b"d9juau41awczczp"),
796 797

    # (S) -> $1.00 <-
798 799
    ("\u002D\u003E\u0020\u0024\u0031\u002E\u0030\u0030\u0020"
     "\u003C\u002D",
800
     b"-> $1.00 <--")
801 802 803 804
    ]

for i in punycode_testcases:
    if len(i)!=2:
805
        print(repr(i))
806 807 808 809 810 811 812 813 814

class PunycodeTest(unittest.TestCase):
    def test_encode(self):
        for uni, puny in punycode_testcases:
            # Need to convert both strings to lower case, since
            # some of the extended encodings use upper case, but our
            # code produces only lower case. Converting just puny to
            # lower is also insufficient, since some of the input characters
            # are upper case.
815 816 817 818
            self.assertEquals(
                str(uni.encode("punycode"), "ascii").lower(),
                str(puny, "ascii").lower()
            )
819 820 821 822

    def test_decode(self):
        for uni, puny in punycode_testcases:
            self.assertEquals(uni, puny.decode("punycode"))
823 824
            puny = puny.decode("ascii").encode("ascii")
            self.assertEquals(uni, puny.decode("punycode"))
825

826 827 828 829 830 831
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 = [
832 833 834
                (b"\x00\x10\xff\xff", "\U0010ffff"),
                (b"\x00\x00\x01\x01", "\U00000101"),
                (b"", ""),
835 836
            ]
            not_ok = [
837 838 839 840 841
                b"\x7f\xff\xff\xff",
                b"\x80\x00\x00\x00",
                b"\x81\x00\x00\x00",
                b"\x00",
                b"\x00\x00\x00\x00\x00",
842 843 844
            ]
            for internal, uni in ok:
                if sys.byteorder == "little":
845
                    internal = bytes(reversed(internal))
846 847 848
                self.assertEquals(uni, internal.decode("unicode_internal"))
            for internal in not_ok:
                if sys.byteorder == "little":
849
                    internal = bytes(reversed(internal))
850 851 852 853 854 855
                self.assertRaises(UnicodeDecodeError, internal.decode,
                    "unicode_internal")

    def test_decode_error_attributes(self):
        if sys.maxunicode > 0xffff:
            try:
856
                b"\x00\x00\x00\x00\x00\x11\x11\x00".decode("unicode_internal")
857
            except UnicodeDecodeError as ex:
858
                self.assertEquals("unicode_internal", ex.encoding)
859
                self.assertEquals(b"\x00\x00\x00\x00\x00\x11\x11\x00", ex.object)
860 861 862 863 864 865 866 867 868
                self.assertEquals(4, ex.start)
                self.assertEquals(8, ex.end)
            else:
                self.fail()

    def test_decode_callback(self):
        if sys.maxunicode > 0xffff:
            codecs.register_error("UnicodeInternalTest", codecs.ignore_errors)
            decoder = codecs.getdecoder("unicode_internal")
869
            ab = "ab".encode("unicode_internal").decode()
870 871 872
            ignored = decoder(bytes("%s\x22\x22\x22\x22%s" % (ab[:4], ab[4:]),
                                    "ascii"),
                              "UnicodeInternalTest")
873
            self.assertEquals(("ab", 12), ignored)
874

875 876 877 878 879 880
    def test_encode_length(self):
        # Issue 3739
        encoder = codecs.getencoder("unicode_internal")
        self.assertEquals(encoder("a")[1], 1)
        self.assertEquals(encoder("\xe9\u0142")[1], 2)

881 882 883
# From http://www.gnu.org/software/libidn/draft-josefsson-idn-test-vectors.html
nameprep_tests = [
    # 3.1 Map to nothing.
884 885 886 887
    (b'foo\xc2\xad\xcd\x8f\xe1\xa0\x86\xe1\xa0\x8bbar'
     b'\xe2\x80\x8b\xe2\x81\xa0baz\xef\xb8\x80\xef\xb8\x88\xef'
     b'\xb8\x8f\xef\xbb\xbf',
     b'foobarbaz'),
888
    # 3.2 Case folding ASCII U+0043 U+0041 U+0046 U+0045.
889 890
    (b'CAFE',
     b'cafe'),
891 892
    # 3.3 Case folding 8bit U+00DF (german sharp s).
    # The original test case is bogus; it says \xc3\xdf
893 894
    (b'\xc3\x9f',
     b'ss'),
895
    # 3.4 Case folding U+0130 (turkish capital I with dot).
896 897
    (b'\xc4\xb0',
     b'i\xcc\x87'),
898
    # 3.5 Case folding multibyte U+0143 U+037A.
899 900
    (b'\xc5\x83\xcd\xba',
     b'\xc5\x84 \xce\xb9'),
901 902 903 904 905 906
    # 3.6 Case folding U+2121 U+33C6 U+1D7BB.
    # XXX: skip this as it fails in UCS-2 mode
    #('\xe2\x84\xa1\xe3\x8f\x86\xf0\x9d\x9e\xbb',
    # 'telc\xe2\x88\x95kg\xcf\x83'),
    (None, None),
    # 3.7 Normalization of U+006a U+030c U+00A0 U+00AA.
907 908
    (b'j\xcc\x8c\xc2\xa0\xc2\xaa',
     b'\xc7\xb0 a'),
909
    # 3.8 Case folding U+1FB7 and normalization.
910 911
    (b'\xe1\xbe\xb7',
     b'\xe1\xbe\xb6\xce\xb9'),
912 913
    # 3.9 Self-reverting case folding U+01F0 and normalization.
    # The original test case is bogus, it says `\xc7\xf0'
914 915
    (b'\xc7\xb0',
     b'\xc7\xb0'),
916
    # 3.10 Self-reverting case folding U+0390 and normalization.
917 918
    (b'\xce\x90',
     b'\xce\x90'),
919
    # 3.11 Self-reverting case folding U+03B0 and normalization.
920 921
    (b'\xce\xb0',
     b'\xce\xb0'),
922
    # 3.12 Self-reverting case folding U+1E96 and normalization.
923 924
    (b'\xe1\xba\x96',
     b'\xe1\xba\x96'),
925
    # 3.13 Self-reverting case folding U+1F56 and normalization.
926 927
    (b'\xe1\xbd\x96',
     b'\xe1\xbd\x96'),
928
    # 3.14 ASCII space character U+0020.
929 930
    (b' ',
     b' '),
931
    # 3.15 Non-ASCII 8bit space character U+00A0.
932 933
    (b'\xc2\xa0',
     b' '),
934
    # 3.16 Non-ASCII multibyte space character U+1680.
935
    (b'\xe1\x9a\x80',
936 937
     None),
    # 3.17 Non-ASCII multibyte space character U+2000.
938 939
    (b'\xe2\x80\x80',
     b' '),
940
    # 3.18 Zero Width Space U+200b.
941 942
    (b'\xe2\x80\x8b',
     b''),
943
    # 3.19 Non-ASCII multibyte space character U+3000.
944 945
    (b'\xe3\x80\x80',
     b' '),
946
    # 3.20 ASCII control characters U+0010 U+007F.
947 948
    (b'\x10\x7f',
     b'\x10\x7f'),
949
    # 3.21 Non-ASCII 8bit control character U+0085.
950
    (b'\xc2\x85',
951 952
     None),
    # 3.22 Non-ASCII multibyte control character U+180E.
953
    (b'\xe1\xa0\x8e',
954 955
     None),
    # 3.23 Zero Width No-Break Space U+FEFF.
956 957
    (b'\xef\xbb\xbf',
     b''),
958
    # 3.24 Non-ASCII control character U+1D175.
959
    (b'\xf0\x9d\x85\xb5',
960 961
     None),
    # 3.25 Plane 0 private use character U+F123.
962
    (b'\xef\x84\xa3',
963 964
     None),
    # 3.26 Plane 15 private use character U+F1234.
965
    (b'\xf3\xb1\x88\xb4',
966 967
     None),
    # 3.27 Plane 16 private use character U+10F234.
968
    (b'\xf4\x8f\x88\xb4',
969 970
     None),
    # 3.28 Non-character code point U+8FFFE.
971
    (b'\xf2\x8f\xbf\xbe',
972 973
     None),
    # 3.29 Non-character code point U+10FFFF.
974
    (b'\xf4\x8f\xbf\xbf',
975 976
     None),
    # 3.30 Surrogate code U+DF42.
977
    (b'\xed\xbd\x82',
978 979
     None),
    # 3.31 Non-plain text character U+FFFD.
980
    (b'\xef\xbf\xbd',
981 982
     None),
    # 3.32 Ideographic description character U+2FF5.
983
    (b'\xe2\xbf\xb5',
984 985
     None),
    # 3.33 Display property character U+0341.
986 987
    (b'\xcd\x81',
     b'\xcc\x81'),
988
    # 3.34 Left-to-right mark U+200E.
989
    (b'\xe2\x80\x8e',
990 991
     None),
    # 3.35 Deprecated U+202A.
992
    (b'\xe2\x80\xaa',
993 994
     None),
    # 3.36 Language tagging character U+E0001.
995
    (b'\xf3\xa0\x80\x81',
996 997
     None),
    # 3.37 Language tagging character U+E0042.
998
    (b'\xf3\xa0\x81\x82',
999 1000
     None),
    # 3.38 Bidi: RandALCat character U+05BE and LCat characters.
1001
    (b'foo\xd6\xbebar',
1002 1003
     None),
    # 3.39 Bidi: RandALCat character U+FD50 and LCat characters.
1004
    (b'foo\xef\xb5\x90bar',
1005 1006
     None),
    # 3.40 Bidi: RandALCat character U+FB38 and LCat characters.
1007 1008
    (b'foo\xef\xb9\xb6bar',
     b'foo \xd9\x8ebar'),
1009
    # 3.41 Bidi: RandALCat without trailing RandALCat U+0627 U+0031.
1010
    (b'\xd8\xa71',
1011 1012
     None),
    # 3.42 Bidi: RandALCat character U+0627 U+0031 U+0628.
1013 1014
    (b'\xd8\xa71\xd8\xa8',
     b'\xd8\xa71\xd8\xa8'),
1015
    # 3.43 Unassigned code point U+E0002.
1016
    # Skip this test as we allow unassigned
1017
    #(b'\xf3\xa0\x80\x82',
1018 1019
    # None),
    (None, None),
1020 1021
    # 3.44 Larger test (shrinking).
    # Original test case reads \xc3\xdf
1022 1023 1024
    (b'X\xc2\xad\xc3\x9f\xc4\xb0\xe2\x84\xa1j\xcc\x8c\xc2\xa0\xc2'
     b'\xaa\xce\xb0\xe2\x80\x80',
     b'xssi\xcc\x87tel\xc7\xb0 a\xce\xb0 '),
1025 1026
    # 3.45 Larger test (expanding).
    # Original test case reads \xc3\x9f
1027 1028 1029 1030 1031
    (b'X\xc3\x9f\xe3\x8c\x96\xc4\xb0\xe2\x84\xa1\xe2\x92\x9f\xe3\x8c'
     b'\x80',
     b'xss\xe3\x82\xad\xe3\x83\xad\xe3\x83\xa1\xe3\x83\xbc\xe3'
     b'\x83\x88\xe3\x83\xabi\xcc\x87tel\x28d\x29\xe3\x82'
     b'\xa2\xe3\x83\x91\xe3\x83\xbc\xe3\x83\x88')
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
    ]


class NameprepTest(unittest.TestCase):
    def test_nameprep(self):
        from encodings.idna import nameprep
        for pos, (orig, prepped) in enumerate(nameprep_tests):
            if orig is None:
                # Skipped
                continue
            # The Unicode strings are given in UTF-8
1043
            orig = str(orig, "utf-8", "surrogatepass")
1044 1045 1046 1047
            if prepped is None:
                # Input contains prohibited characters
                self.assertRaises(UnicodeError, nameprep, orig)
            else:
1048
                prepped = str(prepped, "utf-8", "surrogatepass")
1049 1050
                try:
                    self.assertEquals(nameprep(orig), prepped)
1051
                except Exception as e:
1052
                    raise support.TestFailed("Test 3.%d: %s" % (pos+1, str(e)))
1053

1054 1055
class IDNACodecTest(unittest.TestCase):
    def test_builtin_decode(self):
1056 1057 1058 1059
        self.assertEquals(str(b"python.org", "idna"), "python.org")
        self.assertEquals(str(b"python.org.", "idna"), "python.org.")
        self.assertEquals(str(b"xn--pythn-mua.org", "idna"), "pyth\xf6n.org")
        self.assertEquals(str(b"xn--pythn-mua.org.", "idna"), "pyth\xf6n.org.")
1060 1061

    def test_builtin_encode(self):
1062 1063 1064 1065
        self.assertEquals("python.org".encode("idna"), b"python.org")
        self.assertEquals("python.org.".encode("idna"), b"python.org.")
        self.assertEquals("pyth\xf6n.org".encode("idna"), b"xn--pythn-mua.org")
        self.assertEquals("pyth\xf6n.org.".encode("idna"), b"xn--pythn-mua.org.")
1066

1067
    def test_stream(self):
1068
        r = codecs.getreader("idna")(io.BytesIO(b"abc"))
1069
        r.read(3)
1070
        self.assertEquals(r.read(), "")
1071

1072 1073
    def test_incremental_decode(self):
        self.assertEquals(
1074
            "".join(codecs.iterdecode((bytes([c]) for c in b"python.org"), "idna")),
1075
            "python.org"
1076 1077
        )
        self.assertEquals(
1078
            "".join(codecs.iterdecode((bytes([c]) for c in b"python.org."), "idna")),
1079
            "python.org."
1080 1081
        )
        self.assertEquals(
1082
            "".join(codecs.iterdecode((bytes([c]) for c in b"xn--pythn-mua.org."), "idna")),
1083
            "pyth\xf6n.org."
1084 1085
        )
        self.assertEquals(
1086
            "".join(codecs.iterdecode((bytes([c]) for c in b"xn--pythn-mua.org."), "idna")),
1087
            "pyth\xf6n.org."
1088 1089 1090
        )

        decoder = codecs.getincrementaldecoder("idna")()
1091 1092 1093 1094
        self.assertEquals(decoder.decode(b"xn--xam", ), "")
        self.assertEquals(decoder.decode(b"ple-9ta.o", ), "\xe4xample.")
        self.assertEquals(decoder.decode(b"rg"), "")
        self.assertEquals(decoder.decode(b"", True), "org")
1095 1096

        decoder.reset()
1097 1098 1099 1100
        self.assertEquals(decoder.decode(b"xn--xam", ), "")
        self.assertEquals(decoder.decode(b"ple-9ta.o", ), "\xe4xample.")
        self.assertEquals(decoder.decode(b"rg."), "org.")
        self.assertEquals(decoder.decode(b"", True), "")
1101 1102 1103

    def test_incremental_encode(self):
        self.assertEquals(
1104 1105
            b"".join(codecs.iterencode("python.org", "idna")),
            b"python.org"
1106 1107
        )
        self.assertEquals(
1108 1109
            b"".join(codecs.iterencode("python.org.", "idna")),
            b"python.org."
1110 1111
        )
        self.assertEquals(
1112 1113
            b"".join(codecs.iterencode("pyth\xf6n.org.", "idna")),
            b"xn--pythn-mua.org."
1114 1115
        )
        self.assertEquals(
1116 1117
            b"".join(codecs.iterencode("pyth\xf6n.org.", "idna")),
            b"xn--pythn-mua.org."
1118 1119 1120
        )

        encoder = codecs.getincrementalencoder("idna")()
1121 1122 1123
        self.assertEquals(encoder.encode("\xe4x"), b"")
        self.assertEquals(encoder.encode("ample.org"), b"xn--xample-9ta.")
        self.assertEquals(encoder.encode("", True), b"org")
1124 1125

        encoder.reset()
1126 1127 1128
        self.assertEquals(encoder.encode("\xe4x"), b"")
        self.assertEquals(encoder.encode("ample.org."), b"xn--xample-9ta.org.")
        self.assertEquals(encoder.encode("", True), b"")
1129

1130 1131 1132
class CodecsModuleTest(unittest.TestCase):

    def test_decode(self):
1133
        self.assertEquals(codecs.decode(b'\xe4\xf6\xfc', 'latin-1'),
1134
                          '\xe4\xf6\xfc')
1135
        self.assertRaises(TypeError, codecs.decode)
1136 1137
        self.assertEquals(codecs.decode(b'abc'), 'abc')
        self.assertRaises(UnicodeDecodeError, codecs.decode, b'\xff', 'ascii')
1138

1139
    def test_encode(self):
1140
        self.assertEquals(codecs.encode('\xe4\xf6\xfc', 'latin-1'),
1141
                          b'\xe4\xf6\xfc')
1142
        self.assertRaises(TypeError, codecs.encode)
1143
        self.assertRaises(LookupError, codecs.encode, "foo", "__spam__")
1144
        self.assertEquals(codecs.encode('abc'), b'abc')
1145
        self.assertRaises(UnicodeEncodeError, codecs.encode, '\xffff', 'ascii')
1146 1147 1148

    def test_register(self):
        self.assertRaises(TypeError, codecs.register)
1149
        self.assertRaises(TypeError, codecs.register, 42)
1150 1151 1152 1153

    def test_lookup(self):
        self.assertRaises(TypeError, codecs.lookup)
        self.assertRaises(LookupError, codecs.lookup, "__spam__")
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
        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__")
1171

1172 1173 1174 1175
class StreamReaderTest(unittest.TestCase):

    def setUp(self):
        self.reader = codecs.getreader('utf-8')
1176
        self.stream = io.BytesIO(b'\xed\x95\x9c\n\xea\xb8\x80')
1177 1178 1179

    def test_readlines(self):
        f = self.reader(self.stream)
1180
        self.assertEquals(f.readlines(), ['\ud55c\n', '\uae00'])
1181

1182 1183 1184
class EncodedFileTest(unittest.TestCase):

    def test_basic(self):
1185
        f = io.BytesIO(b'\xed\x95\x9c\n\xea\xb8\x80')
1186
        ef = codecs.EncodedFile(f, 'utf-16-le', 'utf-8')
1187
        self.assertEquals(ef.read(), b'\\\xd5\n\x00\x00\xae')
1188

1189
        f = io.BytesIO()
1190
        ef = codecs.EncodedFile(f, 'utf-8', 'latin1')
1191 1192
        ef.write(b'\xc3\xbc')
        self.assertEquals(f.getvalue(), b'\xfc')
1193

1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
all_unicode_encodings = [
    "ascii",
    "big5",
    "big5hkscs",
    "charmap",
    "cp037",
    "cp1006",
    "cp1026",
    "cp1140",
    "cp1250",
    "cp1251",
    "cp1252",
    "cp1253",
    "cp1254",
    "cp1255",
    "cp1256",
    "cp1257",
    "cp1258",
    "cp424",
    "cp437",
    "cp500",
    "cp737",
    "cp775",
    "cp850",
    "cp852",
    "cp855",
    "cp856",
    "cp857",
    "cp860",
    "cp861",
    "cp862",
    "cp863",
    "cp864",
    "cp865",
    "cp866",
    "cp869",
    "cp874",
    "cp875",
    "cp932",
    "cp949",
    "cp950",
    "euc_jis_2004",
    "euc_jisx0213",
    "euc_jp",
    "euc_kr",
    "gb18030",
    "gb2312",
    "gbk",
    "hp_roman8",
    "hz",
    "idna",
    "iso2022_jp",
    "iso2022_jp_1",
    "iso2022_jp_2",
    "iso2022_jp_2004",
    "iso2022_jp_3",
    "iso2022_jp_ext",
    "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",
    "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",
    "shift_jis",
    "shift_jis_2004",
    "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 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 = [
    "punycode",
    "unicode_internal"
]
1306 1307 1308
broken_incremental_coders = broken_unicode_with_streams + [
    "idna",
]
1309 1310 1311 1312 1313

# The following encodings only support "strict" mode
only_strict_mode = [
    "idna",
]
1314

1315
class BasicUnicodeTest(unittest.TestCase, MixInCheckStateHandling):
1316
    def test_basics(self):
1317
        s = "abc123" # all codecs should be able to encode these
1318
        for encoding in all_unicode_encodings:
1319 1320 1321 1322 1323 1324
            name = codecs.lookup(encoding).name
            if encoding.endswith("_codec"):
                name += "_codec"
            elif encoding == "latin_1":
                name = "latin_1"
            self.assertEqual(encoding.replace("_", "-"), name.replace("_", "-"))
1325
            (b, size) = codecs.getencoder(encoding)(s)
1326
            self.assertEqual(size, len(s), "%r != %r (encoding=%r)" % (size, len(s), encoding))
1327
            (chars, size) = codecs.getdecoder(encoding)(b)
1328 1329 1330 1331
            self.assertEqual(chars, s, "%r != %r (encoding=%r)" % (chars, s, encoding))

            if encoding not in broken_unicode_with_streams:
                # check stream reader/writer
1332
                q = Queue(b"")
1333
                writer = codecs.getwriter(encoding)(q)
1334
                encodedresult = b""
1335 1336
                for c in s:
                    writer.write(c)
1337
                    chunk = q.read()
1338
                    self.assertTrue(type(chunk) is bytes, type(chunk))
1339
                    encodedresult += chunk
1340
                q = Queue(b"")
1341
                reader = codecs.getreader(encoding)(q)
1342
                decodedresult = ""
1343
                for c in encodedresult:
1344
                    q.write(bytes([c]))
1345 1346 1347
                    decodedresult += reader.read()
                self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding))

1348
            if encoding not in broken_incremental_coders:
1349 1350
                # check incremental decoder/encoder (fetched via the Python
                # and C API) and iterencode()/iterdecode()
1351 1352
                try:
                    encoder = codecs.getincrementalencoder(encoding)()
1353
                    cencoder = _testcapi.codec_incrementalencoder(encoding)
1354 1355 1356 1357
                except LookupError: # no IncrementalEncoder
                    pass
                else:
                    # check incremental decoder/encoder
1358
                    encodedresult = b""
1359 1360
                    for c in s:
                        encodedresult += encoder.encode(c)
1361
                    encodedresult += encoder.encode("", True)
1362
                    decoder = codecs.getincrementaldecoder(encoding)()
1363
                    decodedresult = ""
1364
                    for c in encodedresult:
1365
                        decodedresult += decoder.decode(bytes([c]))
1366
                    decodedresult += decoder.decode(b"", True)
1367 1368 1369
                    self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding))

                    # check C API
1370
                    encodedresult = b""
1371 1372
                    for c in s:
                        encodedresult += cencoder.encode(c)
1373
                    encodedresult += cencoder.encode("", True)
1374
                    cdecoder = _testcapi.codec_incrementaldecoder(encoding)
1375
                    decodedresult = ""
1376
                    for c in encodedresult:
1377
                        decodedresult += cdecoder.decode(bytes([c]))
1378
                    decodedresult += cdecoder.decode(b"", True)
1379 1380 1381
                    self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding))

                    # check iterencode()/iterdecode()
1382
                    result = "".join(codecs.iterdecode(codecs.iterencode(s, encoding), encoding))
1383 1384 1385
                    self.assertEqual(result, s, "%r != %r (encoding=%r)" % (result, s, encoding))

                    # check iterencode()/iterdecode() with empty string
1386 1387
                    result = "".join(codecs.iterdecode(codecs.iterencode("", encoding), encoding))
                    self.assertEqual(result, "")
1388

1389 1390 1391 1392 1393 1394 1395 1396
                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:
1397
                        encodedresult = b"".join(encoder.encode(c) for c in s)
1398
                        decoder = codecs.getincrementaldecoder(encoding)("ignore")
1399
                        decodedresult = "".join(decoder.decode(bytes([c])) for c in encodedresult)
1400 1401
                        self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding))

1402
                        encodedresult = b"".join(cencoder.encode(c) for c in s)
1403
                        cdecoder = _testcapi.codec_incrementaldecoder(encoding, "ignore")
1404
                        decodedresult = "".join(cdecoder.decode(bytes([c])) for c in encodedresult)
1405 1406
                        self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding))

1407 1408
    def test_seek(self):
        # all codecs should be able to encode these
1409
        s = "%s\n%s\n" % (100*"abc123", 100*"def456")
1410 1411 1412 1413 1414
        for encoding in all_unicode_encodings:
            if encoding == "idna": # FIXME: See SF bug #1163178
                continue
            if encoding in broken_unicode_with_streams:
                continue
1415
            reader = codecs.getreader(encoding)(io.BytesIO(s.encode(encoding)))
1416
            for t in range(5):
1417 1418
                # Test that calling seek resets the internal codec state and buffers
                reader.seek(0, 0)
1419 1420
                data = reader.read()
                self.assertEqual(s, data)
1421

1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
    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)

1434 1435 1436 1437 1438 1439
    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)

1440 1441
    def test_decoder_state(self):
        # Check that getstate() and setstate() handle the state properly
1442
        u = "abc123"
1443 1444 1445 1446 1447
        for encoding in all_unicode_encodings:
            if encoding not in broken_incremental_coders:
                self.check_state_handling_decode(encoding, u, u.encode(encoding))
                self.check_state_handling_encode(encoding, u, u.encode(encoding))

1448 1449 1450
class CharmapTest(unittest.TestCase):
    def test_decode_with_string_map(self):
        self.assertEquals(
1451
            codecs.charmap_decode(b"\x00\x01\x02", "strict", "abc"),
1452
            ("abc", 3)
1453 1454 1455
        )

        self.assertEquals(
1456
            codecs.charmap_decode(b"\x00\x01\x02", "replace", "ab"),
1457
            ("ab\ufffd", 3)
1458 1459 1460
        )

        self.assertEquals(
1461
            codecs.charmap_decode(b"\x00\x01\x02", "replace", "ab\ufffe"),
1462
            ("ab\ufffd", 3)
1463 1464 1465
        )

        self.assertEquals(
1466
            codecs.charmap_decode(b"\x00\x01\x02", "ignore", "ab"),
1467
            ("ab", 3)
1468 1469 1470
        )

        self.assertEquals(
1471
            codecs.charmap_decode(b"\x00\x01\x02", "ignore", "ab\ufffe"),
1472
            ("ab", 3)
1473 1474
        )

1475
        allbytes = bytes(range(256))
1476
        self.assertEquals(
1477 1478
            codecs.charmap_decode(allbytes, "ignore", ""),
            ("", len(allbytes))
1479 1480
        )

1481 1482
class WithStmtTest(unittest.TestCase):
    def test_encodedfile(self):
1483
        f = io.BytesIO(b"\xc3\xbc")
1484
        with codecs.EncodedFile(f, "latin-1", "utf-8") as ef:
1485
            self.assertEquals(ef.read(), b"\xfc")
1486 1487

    def test_streamreaderwriter(self):
1488
        f = io.BytesIO(b"\xc3\xbc")
1489 1490 1491
        info = codecs.lookup("utf-8")
        with codecs.StreamReaderWriter(f, info.streamreader,
                                       info.streamwriter, 'strict') as srw:
1492
            self.assertEquals(srw.read(), "\xfc")
1493

1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
class TypesTest(unittest.TestCase):
    def test_decode_unicode(self):
        # Most decoders don't accept unicode input
        decoders = [
            codecs.utf_7_decode,
            codecs.utf_8_decode,
            codecs.utf_16_le_decode,
            codecs.utf_16_be_decode,
            codecs.utf_16_ex_decode,
            codecs.utf_32_decode,
            codecs.utf_32_le_decode,
            codecs.utf_32_be_decode,
            codecs.utf_32_ex_decode,
            codecs.latin_1_decode,
            codecs.ascii_decode,
            codecs.charmap_decode,
        ]
        if hasattr(codecs, "mbcs_decode"):
            decoders.append(codecs.mbcs_decode)
        for decoder in decoders:
            self.assertRaises(TypeError, decoder, "xxx")

    def test_unicode_escape(self):
        # Escape-decoding an unicode string is supported ang gives the same
        # result as decoding the equivalent ASCII bytes string.
        self.assertEquals(codecs.unicode_escape_decode(r"\u1234"), ("\u1234", 6))
        self.assertEquals(codecs.unicode_escape_decode(br"\u1234"), ("\u1234", 6))
        self.assertEquals(codecs.raw_unicode_escape_decode(r"\u1234"), ("\u1234", 6))
        self.assertEquals(codecs.raw_unicode_escape_decode(br"\u1234"), ("\u1234", 6))

1524
class SurrogateEscapeTest(unittest.TestCase):
1525 1526 1527

    def test_utf8(self):
        # Bad byte
1528
        self.assertEqual(b"foo\x80bar".decode("utf-8", "surrogateescape"),
1529
                         "foo\udc80bar")
1530
        self.assertEqual("foo\udc80bar".encode("utf-8", "surrogateescape"),
1531 1532
                         b"foo\x80bar")
        # bad-utf-8 encoded surrogate
1533
        self.assertEqual(b"\xed\xb0\x80".decode("utf-8", "surrogateescape"),
1534
                         "\udced\udcb0\udc80")
1535
        self.assertEqual("\udced\udcb0\udc80".encode("utf-8", "surrogateescape"),
1536 1537 1538 1539
                         b"\xed\xb0\x80")

    def test_ascii(self):
        # bad byte
1540
        self.assertEqual(b"foo\x80bar".decode("ascii", "surrogateescape"),
1541
                         "foo\udc80bar")
1542
        self.assertEqual("foo\udc80bar".encode("ascii", "surrogateescape"),
1543 1544 1545 1546
                         b"foo\x80bar")

    def test_charmap(self):
        # bad byte: \xa5 is unmapped in iso-8859-3
1547
        self.assertEqual(b"foo\xa5bar".decode("iso-8859-3", "surrogateescape"),
1548
                         "foo\udca5bar")
1549
        self.assertEqual("foo\udca5bar".encode("iso-8859-3", "surrogateescape"),
1550 1551
                         b"foo\xa5bar")

1552 1553 1554 1555 1556
    def test_latin1(self):
        # Issue6373
        self.assertEqual("\udce4\udceb\udcef\udcf6\udcfc".encode("latin1", "surrogateescape"),
                         b"\xe4\xeb\xef\xf6\xfc")

1557

1558
def test_main():
1559
    support.run_unittest(
1560 1561 1562
        UTF32Test,
        UTF32LETest,
        UTF32BETest,
1563
        UTF16Test,
1564 1565 1566
        UTF16LETest,
        UTF16BETest,
        UTF8Test,
1567
        UTF8SigTest,
1568 1569 1570 1571
        UTF7Test,
        UTF16ExTest,
        ReadBufferTest,
        CharBufferTest,
1572 1573
        RecodingTest,
        PunycodeTest,
1574
        UnicodeInternalTest,
1575
        NameprepTest,
1576
        IDNACodecTest,
1577
        CodecsModuleTest,
1578
        StreamReaderTest,
1579
        EncodedFileTest,
1580
        BasicUnicodeTest,
1581 1582
        CharmapTest,
        WithStmtTest,
1583
        TypesTest,
1584
        SurrogateEscapeTest,
1585
    )
1586 1587 1588 1589


if __name__ == "__main__":
    test_main()