test_coding.py 2.04 KB
Newer Older
1

2
import test.support, unittest
3
from test.support import TESTFN, unlink, unload
4
import os, sys
5 6 7 8

class CodingTest(unittest.TestCase):
    def test_bad_coding(self):
        module_name = 'bad_coding'
9 10 11 12 13 14 15
        self.verify_bad_module(module_name)

    def test_bad_coding2(self):
        module_name = 'bad_coding2'
        self.verify_bad_module(module_name)

    def verify_bad_module(self, module_name):
16 17 18 19
        self.assertRaises(SyntaxError, __import__, 'test.' + module_name)

        path = os.path.dirname(__file__)
        filename = os.path.join(path, module_name + '.py')
20 21
        with open(filename, "rb") as fp:
            bytes = fp.read()
22
        self.assertRaises(SyntaxError, compile, bytes, filename, 'exec')
23

24 25 26 27 28
    def test_exec_valid_coding(self):
        d = {}
        exec('# coding: cp949\na = 5\n', d)
        self.assertEqual(d['a'], 5)

29 30 31
    def test_file_parse(self):
        # issue1134: all encodings outside latin-1 and utf-8 fail on
        # multiline strings and long lines (>512 columns)
32 33
        unload(TESTFN)
        sys.path.insert(0, os.curdir)
34
        filename = TESTFN + ".py"
35 36 37 38 39 40 41 42
        f = open(filename, "w")
        try:
            f.write("# -*- coding: cp1252 -*-\n")
            f.write("'''A short string\n")
            f.write("'''\n")
            f.write("'A very long string %s'\n" % ("X" * 1000))
            f.close()

43
            __import__(TESTFN)
44 45
        finally:
            f.close()
46 47 48 49
            unlink(filename)
            unlink(filename + "c")
            unload(TESTFN)
            del sys.path[0]
50

Benjamin Peterson's avatar
Benjamin Peterson committed
51 52 53
    def test_error_from_string(self):
        # See http://bugs.python.org/issue6289
        input = "# coding: ascii\n\N{SNOWMAN}".encode('utf-8')
54
        with self.assertRaises(SyntaxError) as c:
Benjamin Peterson's avatar
Benjamin Peterson committed
55
            compile(input, "<string>", "exec")
56 57 58 59
        expected = "'ascii' codec can't decode byte 0xe2 in position 16: " \
                   "ordinal not in range(128)"
        self.assertTrue(c.exception.args[0].startswith(expected))

Benjamin Peterson's avatar
Benjamin Peterson committed
60

61
def test_main():
62
    test.support.run_unittest(CodingTest)
63 64 65

if __name__ == "__main__":
    test_main()