Debian Codegraph @

Lib/test/test_source_encoding.py

raw
1 # -*- coding: utf-8 -*-
2
3 import unittest
4 from test.support import script_helper, captured_stdout, requires_subprocess, requires_resource
5 from test.support.os_helper import TESTFN, unlink, rmtree
6 from test.support.import_helper import unload
7 import importlib
8 import os
9 import sys
10 import subprocess
11 import tempfile
12
13 class MiscSourceEncodingTest(unittest.TestCase):
14
15 def test_import_encoded_module(self):
16 from test.encoded_modules import test_strings
17 # Make sure we're actually testing something
18 self.assertGreaterEqual(len(test_strings), 1)
19 for modname, encoding, teststr in test_strings:
20 mod = importlib.import_module('test.encoded_modules.'
21 'module_' + modname)
22 self.assertEqual(teststr, mod.test)
23
24 def test_compilestring(self):
25 # see #1882
26 c = compile(b"\n# coding: utf-8\nu = '\xc3\xb3'\n", "dummy", "exec")
27 d = {}
28 exec(c, d)
29 self.assertEqual(d['u'], '\xf3')
30
31 def test_issue2301(self):
32 try:
33 compile(b"# coding: cp932\nprint '\x94\x4e'", "dummy", "exec")
34 except SyntaxError as v:
35 self.assertEqual(v.text.rstrip('\n'), "print '\u5e74'")
36 else:
37 self.fail()
38
39 def test_issue4626(self):
40 c = compile("# coding=latin-1\n\u00c6 = '\u00c6'", "dummy", "exec")
41 d = {}
42 exec(c, d)
43 self.assertEqual(d['\xc6'], '\xc6')
44
45 def test_issue3297(self):
46 c = compile("a, b = '\U0001010F', '\\U0001010F'", "dummy", "exec")
47 d = {}
48 exec(c, d)
49 self.assertEqual(d['a'], d['b'])
50 self.assertEqual(len(d['a']), len(d['b']))
51 self.assertEqual(ascii(d['a']), ascii(d['b']))
52
53 def test_issue7820(self):
54 # Ensure that check_bom() restores all bytes in the right order if
55 # check_bom() fails in pydebug mode: a buffer starts with the first
56 # byte of a valid BOM, but next bytes are different
57
58 # one byte in common with the UTF-16-LE BOM
59 self.assertRaises(SyntaxError, eval, b'\xff\x20')
60
61 # one byte in common with the UTF-8 BOM
62 self.assertRaises(SyntaxError, eval, b'\xef\x20')
63
64 # two bytes in common with the UTF-8 BOM
65 self.assertRaises(SyntaxError, eval, b'\xef\xbb\x20')
66
67 @requires_subprocess()
68 def test_20731(self):
69 sub = subprocess.Popen([sys.executable,
70 os.path.join(os.path.dirname(__file__),
71 'tokenizedata',
72 'coding20731.py')],
73 stderr=subprocess.PIPE)
74 err = sub.communicate()[1]
75 self.assertEqual(sub.returncode, 0)
76 self.assertNotIn(b'SyntaxError', err)
77
78 def test_error_message(self):
79 compile(b'# -*- coding: iso-8859-15 -*-\n', 'dummy', 'exec')
80 compile(b'\xef\xbb\xbf\n', 'dummy', 'exec')
81 compile(b'\xef\xbb\xbf# -*- coding: utf-8 -*-\n', 'dummy', 'exec')
82 with self.assertRaisesRegex(SyntaxError, 'fake'):
83 compile(b'# -*- coding: fake -*-\n', 'dummy', 'exec')
84 with self.assertRaisesRegex(SyntaxError, 'iso-8859-15'):
85 compile(b'\xef\xbb\xbf# -*- coding: iso-8859-15 -*-\n',
86 'dummy', 'exec')
87 with self.assertRaisesRegex(SyntaxError, 'BOM'):
88 compile(b'\xef\xbb\xbf# -*- coding: iso-8859-15 -*-\n',
89 'dummy', 'exec')
90 with self.assertRaisesRegex(SyntaxError, 'fake'):
91 compile(b'\xef\xbb\xbf# -*- coding: fake -*-\n', 'dummy', 'exec')
92 with self.assertRaisesRegex(SyntaxError, 'BOM'):
93 compile(b'\xef\xbb\xbf# -*- coding: fake -*-\n', 'dummy', 'exec')
94
95 def test_bad_coding(self):
96 module_name = 'bad_coding'
97 self.verify_bad_module(module_name)
98
99 def test_bad_coding2(self):
100 module_name = 'bad_coding2'
101 self.verify_bad_module(module_name)
102
103 def verify_bad_module(self, module_name):
104 self.assertRaises(SyntaxError, __import__, 'test.tokenizedata.' + module_name)
105
106 path = os.path.dirname(__file__)
107 filename = os.path.join(path, 'tokenizedata', module_name + '.py')
108 with open(filename, "rb") as fp:
109 bytes = fp.read()
110 self.assertRaises(SyntaxError, compile, bytes, filename, 'exec')
111
112 def test_exec_valid_coding(self):
113 d = {}
114 exec(b'# coding: cp949\na = "\xaa\xa7"\n', d)
115 self.assertEqual(d['a'], '\u3047')
116
117 def test_file_parse(self):
118 # issue1134: all encodings outside latin-1 and utf-8 fail on
119 # multiline strings and long lines (>512 columns)
120 unload(TESTFN)
121 filename = TESTFN + ".py"
122 f = open(filename, "w", encoding="cp1252")
123 sys.path.insert(0, os.curdir)
124 try:
125 with f:
126 f.write("# -*- coding: cp1252 -*-\n")
127 f.write("'''A short string\n")
128 f.write("'''\n")
129 f.write("'A very long string %s'\n" % ("X" * 1000))
130
131 importlib.invalidate_caches()
132 __import__(TESTFN)
133 finally:
134 del sys.path[0]
135 unlink(filename)
136 unlink(filename + "c")
137 unlink(filename + "o")
138 unload(TESTFN)
139 rmtree('__pycache__')
140
141 def test_error_from_string(self):
142 # See http://bugs.python.org/issue6289
143 input = "# coding: ascii\n\N{SNOWMAN}".encode('utf-8')
144 with self.assertRaises(SyntaxError) as c:
145 compile(input, "<string>", "exec")
146 expected = "'ascii' codec can't decode byte 0xe2 in position 16: " \
147 "ordinal not in range(128)"
148 self.assertTrue(c.exception.args[0].startswith(expected),
149 msg=c.exception.args[0])
150
151 def test_file_parse_error_multiline(self):
152 # gh96611:
153 with open(TESTFN, "wb") as fd:
154 fd.write(b'print("""\n\xb1""")\n')
155
156 try:
157 retcode, stdout, stderr = script_helper.assert_python_failure(TESTFN)
158
159 self.assertGreater(retcode, 0)
160 self.assertIn(b"Non-UTF-8 code starting with '\\xb1'", stderr)
161 finally:
162 os.unlink(TESTFN)
163
164 def test_tokenizer_fstring_warning_in_first_line(self):
165 source = "0b1and 2"
166 with open(TESTFN, "w") as fd:
167 fd.write("{}".format(source))
168 try:
169 retcode, stdout, stderr = script_helper.assert_python_ok(TESTFN)
170 self.assertIn(b"SyntaxWarning: invalid binary litera", stderr)
171 self.assertEqual(stderr.count(source.encode()), 1)
172 finally:
173 os.unlink(TESTFN)
174
175
176 BUFSIZ = 2**13
177
178 class AbstractSourceEncodingTest:
179
180 def test_default_coding(self):
181 src = (b'print(ascii("\xc3\xa4"))\n')
182 self.check_script_output(src, br"'\xe4'")
183
184 def test_first_coding_line(self):
185 src = (b'#coding:iso8859-15\n'
186 b'print(ascii("\xc3\xa4"))\n')
187 self.check_script_output(src, br"'\xc3\u20ac'")
188
189 def test_second_coding_line(self):
190 src = (b'#!/usr/bin/python\n'
191 b'#coding:iso8859-15\n'
192 b'print(ascii("\xc3\xa4"))\n')
193 self.check_script_output(src, br"'\xc3\u20ac'")
194
195 def test_second_coding_line_empty_first_line(self):
196 src = (b'\n'
197 b'#coding:iso8859-15\n'
198 b'print(ascii("\xc3\xa4"))\n')
199 self.check_script_output(src, br"'\xc3\u20ac'")
200
201 def test_third_coding_line(self):
202 # Only first two lines are tested for a magic comment.
203 src = (b'#!/usr/bin/python\n'
204 b'#\n'
205 b'#coding:iso8859-15\n'
206 b'print(ascii("\xc3\xa4"))\n')
207 self.check_script_output(src, br"'\xe4'")
208
209 def test_double_coding_line(self):
210 # If the first line matches the second line is ignored.
211 src = (b'#coding:iso8859-15\n'
212 b'#coding:latin1\n'
213 b'print(ascii("\xc3\xa4"))\n')
214 self.check_script_output(src, br"'\xc3\u20ac'")
215
216 def test_double_coding_same_line(self):
217 src = (b'#coding:iso8859-15 coding:latin1\n'
218 b'print(ascii("\xc3\xa4"))\n')
219 self.check_script_output(src, br"'\xc3\u20ac'")
220
221 def test_double_coding_utf8(self):
222 src = (b'#coding:utf-8\n'
223 b'#coding:latin1\n'
224 b'print(ascii("\xc3\xa4"))\n')
225 self.check_script_output(src, br"'\xe4'")
226
227 def test_long_first_coding_line(self):
228 src = (b'#' + b' '*BUFSIZ + b'coding:iso8859-15\n'
229 b'print(ascii("\xc3\xa4"))\n')
230 self.check_script_output(src, br"'\xc3\u20ac'")
231
232 def test_long_second_coding_line(self):
233 src = (b'#!/usr/bin/python\n'
234 b'#' + b' '*BUFSIZ + b'coding:iso8859-15\n'
235 b'print(ascii("\xc3\xa4"))\n')
236 self.check_script_output(src, br"'\xc3\u20ac'")
237
238 def test_long_coding_line(self):
239 src = (b'#coding:iso-8859-15' + b' '*BUFSIZ + b'\n'
240 b'print(ascii("\xc3\xa4"))\n')
241 self.check_script_output(src, br"'\xc3\u20ac'")
242
243 def test_long_coding_name(self):
244 src = (b'#coding:iso-8859-1-' + b'x'*BUFSIZ + b'\n'
245 b'print(ascii("\xc3\xa4"))\n')
246 self.check_script_output(src, br"'\xc3\xa4'")
247
248 def test_long_first_utf8_line(self):
249 src = b'#' + b'\xc3\xa4'*(BUFSIZ//2) + b'\n'
250 self.check_script_output(src, b'')
251 src = b'# ' + b'\xc3\xa4'*(BUFSIZ//2) + b'\n'
252 self.check_script_output(src, b'')
253
254 def test_long_second_utf8_line(self):
255 src = b'\n#' + b'\xc3\xa4'*(BUFSIZ//2) + b'\n'
256 self.check_script_output(src, b'')
257 src = b'\n# ' + b'\xc3\xa4'*(BUFSIZ//2) + b'\n'
258 self.check_script_output(src, b'')
259
260 def test_first_non_utf8_coding_line(self):
261 src = (b'#coding:iso-8859-15 \xa4\n'
262 b'print(ascii("\xc3\xa4"))\n')
263 self.check_script_output(src, br"'\xc3\u20ac'")
264
265 def test_second_non_utf8_coding_line(self):
266 src = (b'#!/usr/bin/python\n'
267 b'#coding:iso-8859-15 \xa4\n'
268 b'print(ascii("\xc3\xa4"))\n')
269 self.check_script_output(src, br"'\xc3\u20ac'")
270
271 def test_utf8_bom(self):
272 src = (b'\xef\xbb\xbfprint(ascii("\xc3\xa4"))\n')
273 self.check_script_output(src, br"'\xe4'")
274
275 def test_utf8_bom_utf8_comments(self):
276 src = (b'\xef\xbb\xbf#\xc3\xa4\n'
277 b'#\xc3\xa4\n'
278 b'print(ascii("\xc3\xa4"))\n')
279 self.check_script_output(src, br"'\xe4'")
280
281 def test_utf8_bom_and_utf8_coding_line(self):
282 src = (b'\xef\xbb\xbf#coding:utf-8\n'
283 b'print(ascii("\xc3\xa4"))\n')
284 self.check_script_output(src, br"'\xe4'")
285
286 def test_utf8_non_utf8_comment_line_error(self):
287 src = (b'#coding: utf8\n'
288 b'#\n'
289 b'#\xa4\n'
290 b'raise RuntimeError\n')
291 self.check_script_error(src,
292 br"'utf-8' codec can't decode byte|"
293 br"encoding problem: utf8")
294
295 def test_crlf(self):
296 src = (b'print(ascii("""\r\n"""))\n')
297 self.check_script_output(src, br"'\n'")
298
299 def test_crcrlf(self):
300 src = (b'print(ascii("""\r\r\n"""))\n')
301 self.check_script_output(src, br"'\n\n'")
302
303 def test_crcrcrlf(self):
304 src = (b'print(ascii("""\r\r\r\n"""))\n')
305 self.check_script_output(src, br"'\n\n\n'")
306
307 def test_crcrcrlf2(self):
308 src = (b'#coding:iso-8859-1\n'
309 b'print(ascii("""\r\r\r\n"""))\n')
310 self.check_script_output(src, br"'\n\n\n'")
311
312 def test_nul_in_first_coding_line(self):
313 src = (b'#coding:iso8859-15\x00\n'
314 b'\n'
315 b'\n'
316 b'raise RuntimeError\n')
317 self.check_script_error(src, br"source code (string )?cannot contain null bytes")
318
319 def test_nul_in_second_coding_line(self):
320 src = (b'#!/usr/bin/python\n'
321 b'#coding:iso8859-15\x00\n'
322 b'\n'
323 b'raise RuntimeError\n')
324 self.check_script_error(src, br"source code (string )?cannot contain null bytes")
325
326
327 class UTF8ValidatorTest(unittest.TestCase):
328 @unittest.skipIf(not sys.platform.startswith("linux"),
329 "Too slow to run on non-Linux platforms")
330 @requires_resource('cpu')
331 def test_invalid_utf8(self):
332 # This is a port of test_utf8_decode_invalid_sequences in
333 # test_unicode.py to exercise the separate utf8 validator in
334 # Parser/tokenizer/helpers.c used when reading source files.
335
336 # That file is written using low-level C file I/O, so the only way to
337 # test it is to write actual files to disk.
338
339 # Each example is put inside a string at the top of the file so
340 # it's an otherwise valid Python source file. Put some newlines
341 # beforehand so we can assert that the error is reported on the
342 # correct line.
343 template = b'\n\n\n"%s"\n'
344
345 fn = TESTFN
346 self.addCleanup(unlink, fn)
347
348 def check(content):
349 with open(fn, 'wb') as fp:
350 fp.write(template % content)
351 rc, stdout, stderr = script_helper.assert_python_failure(fn)
352 # We want to assert that the python subprocess failed gracefully,
353 # not via a signal.
354 self.assertGreaterEqual(rc, 1)
355 self.assertIn(b"Non-UTF-8 code starting with", stderr)
356 self.assertIn(b"on line 4", stderr)
357
358 # continuation bytes in a sequence of 2, 3, or 4 bytes
359 continuation_bytes = [bytes([x]) for x in range(0x80, 0xC0)]
360 # start bytes of a 2-byte sequence equivalent to code points < 0x7F
361 invalid_2B_seq_start_bytes = [bytes([x]) for x in range(0xC0, 0xC2)]
362 # start bytes of a 4-byte sequence equivalent to code points > 0x10FFFF
363 invalid_4B_seq_start_bytes = [bytes([x]) for x in range(0xF5, 0xF8)]
364 invalid_start_bytes = (
365 continuation_bytes + invalid_2B_seq_start_bytes +
366 invalid_4B_seq_start_bytes + [bytes([x]) for x in range(0xF7, 0x100)]
367 )
368
369 for byte in invalid_start_bytes:
370 check(byte)
371
372 for sb in invalid_2B_seq_start_bytes:
373 for cb in continuation_bytes:
374 check(sb + cb)
375
376 for sb in invalid_4B_seq_start_bytes:
377 for cb1 in continuation_bytes[:3]:
378 for cb3 in continuation_bytes[:3]:
379 check(sb+cb1+b'\x80'+cb3)
380
381 for cb in [bytes([x]) for x in range(0x80, 0xA0)]:
382 check(b'\xE0'+cb+b'\x80')
383 check(b'\xE0'+cb+b'\xBF')
384 # surrogates
385 for cb in [bytes([x]) for x in range(0xA0, 0xC0)]:
386 check(b'\xED'+cb+b'\x80')
387 check(b'\xED'+cb+b'\xBF')
388 for cb in [bytes([x]) for x in range(0x80, 0x90)]:
389 check(b'\xF0'+cb+b'\x80\x80')
390 check(b'\xF0'+cb+b'\xBF\xBF')
391 for cb in [bytes([x]) for x in range(0x90, 0xC0)]:
392 check(b'\xF4'+cb+b'\x80\x80')
393 check(b'\xF4'+cb+b'\xBF\xBF')
394
395
396 class BytesSourceEncodingTest(AbstractSourceEncodingTest, unittest.TestCase):
397
398 def check_script_output(self, src, expected):
399 with captured_stdout() as stdout:
400 exec(src)
401 out = stdout.getvalue().encode('latin1')
402 self.assertEqual(out.rstrip(), expected)
403
404 def check_script_error(self, src, expected):
405 with self.assertRaisesRegex(SyntaxError, expected.decode()) as cm:
406 exec(src)
407
408
409 class FileSourceEncodingTest(AbstractSourceEncodingTest, unittest.TestCase):
410
411 def check_script_output(self, src, expected):
412 with tempfile.TemporaryDirectory() as tmpd:
413 fn = os.path.join(tmpd, 'test.py')
414 with open(fn, 'wb') as fp:
415 fp.write(src)
416 res = script_helper.assert_python_ok(fn)
417 self.assertEqual(res.out.rstrip(), expected)
418
419 def check_script_error(self, src, expected):
420 with tempfile.TemporaryDirectory() as tmpd:
421 fn = os.path.join(tmpd, 'test.py')
422 with open(fn, 'wb') as fp:
423 fp.write(src)
424 res = script_helper.assert_python_failure(fn)
425 self.assertRegex(res.err.rstrip().splitlines()[-1], b'SyntaxError.*?' + expected)
426
427
428 if __name__ == "__main__":
429 unittest.main()