test_source_encoding.py 5.1 KB
Newer Older
Benjamin Peterson's avatar
Benjamin Peterson committed
1
# -*- coding: koi8-r -*-
2 3

import unittest
4
from test.support import TESTFN, unlink, unload
5 6 7
import importlib
import os
import sys
Martin v. Löwis's avatar
Martin v. Löwis committed
8
import subprocess
9

10
class SourceEncodingTest(unittest.TestCase):
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

    def test_pep263(self):
        self.assertEqual(
            "".encode("utf-8"),
            b'\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd'
        )
        self.assertEqual(
            "\".encode("utf-8"),
            b'\\\xd0\x9f'
        )

    def test_compilestring(self):
        # see #1882
        c = compile(b"\n# coding: utf-8\nu = '\xc3\xb3'\n", "dummy", "exec")
        d = {}
        exec(c, d)
        self.assertEqual(d['u'], '\xf3')

    def test_issue2301(self):
        try:
            compile(b"# coding: cp932\nprint '\x94\x4e'", "dummy", "exec")
        except SyntaxError as v:
33
            self.assertEqual(v.text, "print '\u5e74'\n")
34 35 36
        else:
            self.fail()

37 38 39 40
    def test_issue4626(self):
        c = compile("# coding=latin-1\n\u00c6 = '\u00c6'", "dummy", "exec")
        d = {}
        exec(c, d)
41
        self.assertEqual(d['\xc6'], '\xc6')
42

43 44 45 46 47 48 49 50
    def test_issue3297(self):
        c = compile("a, b = '\U0001010F', '\\U0001010F'", "dummy", "exec")
        d = {}
        exec(c, d)
        self.assertEqual(d['a'], d['b'])
        self.assertEqual(len(d['a']), len(d['b']))
        self.assertEqual(ascii(d['a']), ascii(d['b']))

51 52 53 54 55 56 57 58 59 60 61
    def test_issue7820(self):
        # Ensure that check_bom() restores all bytes in the right order if
        # check_bom() fails in pydebug mode: a buffer starts with the first
        # byte of a valid BOM, but next bytes are different

        # one byte in common with the UTF-16-LE BOM
        self.assertRaises(SyntaxError, eval, b'\xff\x20')

        # two bytes in common with the UTF-8 BOM
        self.assertRaises(SyntaxError, eval, b'\xef\xbb\x20')

Martin v. Löwis's avatar
Martin v. Löwis committed
62
    def test_20731(self):
Martin v. Löwis's avatar
Martin v. Löwis committed
63
        sub = subprocess.Popen([sys.executable,
Martin v. Löwis's avatar
Martin v. Löwis committed
64 65 66 67
                        os.path.join(os.path.dirname(__file__),
                                     'coding20731.py')],
                        stderr=subprocess.PIPE)
        err = sub.communicate()[1]
Benjamin Peterson's avatar
Benjamin Peterson committed
68 69
        self.assertEqual(sub.returncode, 0)
        self.assertNotIn(b'SyntaxError', err)
Martin v. Löwis's avatar
Martin v. Löwis committed
70

71 72 73 74
    def test_error_message(self):
        compile(b'# -*- coding: iso-8859-15 -*-\n', 'dummy', 'exec')
        compile(b'\xef\xbb\xbf\n', 'dummy', 'exec')
        compile(b'\xef\xbb\xbf# -*- coding: utf-8 -*-\n', 'dummy', 'exec')
75
        with self.assertRaisesRegex(SyntaxError, 'fake'):
76
            compile(b'# -*- coding: fake -*-\n', 'dummy', 'exec')
77
        with self.assertRaisesRegex(SyntaxError, 'iso-8859-15'):
78 79
            compile(b'\xef\xbb\xbf# -*- coding: iso-8859-15 -*-\n',
                    'dummy', 'exec')
80
        with self.assertRaisesRegex(SyntaxError, 'BOM'):
81 82
            compile(b'\xef\xbb\xbf# -*- coding: iso-8859-15 -*-\n',
                    'dummy', 'exec')
83
        with self.assertRaisesRegex(SyntaxError, 'fake'):
84
            compile(b'\xef\xbb\xbf# -*- coding: fake -*-\n', 'dummy', 'exec')
85
        with self.assertRaisesRegex(SyntaxError, 'BOM'):
86
            compile(b'\xef\xbb\xbf# -*- coding: fake -*-\n', 'dummy', 'exec')
87 88 89

    def test_bad_coding(self):
        module_name = 'bad_coding'
90 91 92 93 94 95 96
        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):
97 98 99 100
        self.assertRaises(SyntaxError, __import__, 'test.' + module_name)

        path = os.path.dirname(__file__)
        filename = os.path.join(path, module_name + '.py')
101 102
        with open(filename, "rb") as fp:
            bytes = fp.read()
103
        self.assertRaises(SyntaxError, compile, bytes, filename, 'exec')
104

105 106
    def test_exec_valid_coding(self):
        d = {}
107 108
        exec(b'# coding: cp949\na = "\xaa\xa7"\n', d)
        self.assertEqual(d['a'], '\u3047')
109

110 111 112
    def test_file_parse(self):
        # issue1134: all encodings outside latin-1 and utf-8 fail on
        # multiline strings and long lines (>512 columns)
113
        unload(TESTFN)
114
        filename = TESTFN + ".py"
115 116
        f = open(filename, "w", encoding="cp1252")
        sys.path.insert(0, os.curdir)
117
        try:
118 119 120 121 122
            with f:
                f.write("# -*- coding: cp1252 -*-\n")
                f.write("'''A short string\n")
                f.write("'''\n")
                f.write("'A very long string %s'\n" % ("X" * 1000))
123

124
            importlib.invalidate_caches()
125
            __import__(TESTFN)
126
        finally:
127
            del sys.path[0]
128 129
            unlink(filename)
            unlink(filename + "c")
130
            unlink(filename + "o")
131
            unload(TESTFN)
132

Benjamin Peterson's avatar
Benjamin Peterson committed
133 134 135
    def test_error_from_string(self):
        # See http://bugs.python.org/issue6289
        input = "# coding: ascii\n\N{SNOWMAN}".encode('utf-8')
136
        with self.assertRaises(SyntaxError) as c:
Benjamin Peterson's avatar
Benjamin Peterson committed
137
            compile(input, "<string>", "exec")
138 139
        expected = "'ascii' codec can't decode byte 0xe2 in position 16: " \
                   "ordinal not in range(128)"
140 141
        self.assertTrue(c.exception.args[0].startswith(expected),
                        msg=c.exception.args[0])
142

Benjamin Peterson's avatar
Benjamin Peterson committed
143

144
if __name__ == "__main__":
145
    unittest.main()