1
from importlib import _bootstrap
2
from . import util as source_util
7
# Because sys.path gets essentially blanked, need to have unicodedata already
8
# imported for the parser to use.
13
CODING_RE = re.compile(r'coding[:=]\s*([-\w.]+)')
16
class EncodingTest(unittest.TestCase):
18
"""PEP 3120 makes UTF-8 the default encoding for source code
21
PEP 263 specifies how that can change on a per-file basis. Either the first
22
or second line can contain the encoding line [encoding first line]
23
encoding second line]. If the file has the BOM marker it is considered UTF-8
24
implicitly [BOM]. If any encoding is specified it must be UTF-8, else it is
25
an error [BOM and utf-8][BOM conflict].
31
source_line = "{0} = '{1}'\n".format(variable, character)
34
def run_test(self, source):
35
with source_util.create_modules(self.module_name) as mapping:
36
with open(mapping[self.module_name], 'wb')as file:
38
loader = _bootstrap._PyPycFileLoader(self.module_name,
39
mapping[self.module_name], False)
40
return loader.load_module(self.module_name)
42
def create_source(self, encoding):
43
encoding_line = "# coding={0}".format(encoding)
44
assert CODING_RE.search(encoding_line)
45
source_lines = [encoding_line.encode('utf-8')]
46
source_lines.append(self.source_line.encode(encoding))
47
return b'\n'.join(source_lines)
49
def test_non_obvious_encoding(self):
50
# Make sure that an encoding that has never been a standard one for
52
encoding_line = "# coding=koi8-r"
53
assert CODING_RE.search(encoding_line)
54
source = "{0}\na=42\n".format(encoding_line).encode("koi8-r")
58
def test_default_encoding(self):
59
self.run_test(self.source_line.encode('utf-8'))
61
# [encoding first line]
62
def test_encoding_on_first_line(self):
64
source = self.create_source(encoding)
67
# [encoding second line]
68
def test_encoding_on_second_line(self):
69
source = b"#/usr/bin/python\n" + self.create_source('Latin-1')
74
self.run_test(codecs.BOM_UTF8 + self.source_line.encode('utf-8'))
77
def test_bom_and_utf_8(self):
78
source = codecs.BOM_UTF8 + self.create_source('utf-8')
82
def test_bom_conflict(self):
83
source = codecs.BOM_UTF8 + self.create_source('latin-1')
84
self.assertRaises(SyntaxError, self.run_test, source)
87
class LineEndingTest(unittest.TestCase):
89
r"""Source written with the three types of line endings (\n, \r\n, \r)
90
need to be readable [cr][crlf][lf]."""
92
def run_test(self, line_ending):
94
source_lines = [b"a = 42", b"b = -13", b'']
95
source = line_ending.join(source_lines)
96
with source_util.create_modules(module_name) as mapping:
97
with open(mapping[module_name], 'wb') as file:
99
loader = _bootstrap._PyPycFileLoader(module_name,
100
mapping[module_name], False)
101
return loader.load_module(module_name)
109
self.run_test(b'\r\n')
117
from test.support import run_unittest
118
run_unittest(EncodingTest, LineEndingTest)
121
if __name__ == '__main__':