test_source_encoding.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. # -*- coding: koi8-r -*-
  2. import unittest
  3. from test.support import script_helper, captured_stdout, requires_subprocess
  4. from test.support.os_helper import TESTFN, unlink, rmtree
  5. from test.support.import_helper import unload
  6. import importlib
  7. import os
  8. import sys
  9. import subprocess
  10. import tempfile
  11. class MiscSourceEncodingTest(unittest.TestCase):
  12. def test_pep263(self):
  13. self.assertEqual(
  14. "ðÉÔÏÎ".encode("utf-8"),
  15. b'\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd'
  16. )
  17. self.assertEqual(
  18. "\ð".encode("utf-8"),
  19. b'\\\xd0\x9f'
  20. )
  21. def test_compilestring(self):
  22. # see #1882
  23. c = compile(b"\n# coding: utf-8\nu = '\xc3\xb3'\n", "dummy", "exec")
  24. d = {}
  25. exec(c, d)
  26. self.assertEqual(d['u'], '\xf3')
  27. def test_issue2301(self):
  28. try:
  29. compile(b"# coding: cp932\nprint '\x94\x4e'", "dummy", "exec")
  30. except SyntaxError as v:
  31. self.assertEqual(v.text.rstrip('\n'), "print '\u5e74'")
  32. else:
  33. self.fail()
  34. def test_issue4626(self):
  35. c = compile("# coding=latin-1\n\u00c6 = '\u00c6'", "dummy", "exec")
  36. d = {}
  37. exec(c, d)
  38. self.assertEqual(d['\xc6'], '\xc6')
  39. def test_issue3297(self):
  40. c = compile("a, b = '\U0001010F', '\\U0001010F'", "dummy", "exec")
  41. d = {}
  42. exec(c, d)
  43. self.assertEqual(d['a'], d['b'])
  44. self.assertEqual(len(d['a']), len(d['b']))
  45. self.assertEqual(ascii(d['a']), ascii(d['b']))
  46. def test_issue7820(self):
  47. # Ensure that check_bom() restores all bytes in the right order if
  48. # check_bom() fails in pydebug mode: a buffer starts with the first
  49. # byte of a valid BOM, but next bytes are different
  50. # one byte in common with the UTF-16-LE BOM
  51. self.assertRaises(SyntaxError, eval, b'\xff\x20')
  52. # one byte in common with the UTF-8 BOM
  53. self.assertRaises(SyntaxError, eval, b'\xef\x20')
  54. # two bytes in common with the UTF-8 BOM
  55. self.assertRaises(SyntaxError, eval, b'\xef\xbb\x20')
  56. @requires_subprocess()
  57. def test_20731(self):
  58. sub = subprocess.Popen([sys.executable,
  59. os.path.join(os.path.dirname(__file__),
  60. 'coding20731.py')],
  61. stderr=subprocess.PIPE)
  62. err = sub.communicate()[1]
  63. self.assertEqual(sub.returncode, 0)
  64. self.assertNotIn(b'SyntaxError', err)
  65. def test_error_message(self):
  66. compile(b'# -*- coding: iso-8859-15 -*-\n', 'dummy', 'exec')
  67. compile(b'\xef\xbb\xbf\n', 'dummy', 'exec')
  68. compile(b'\xef\xbb\xbf# -*- coding: utf-8 -*-\n', 'dummy', 'exec')
  69. with self.assertRaisesRegex(SyntaxError, 'fake'):
  70. compile(b'# -*- coding: fake -*-\n', 'dummy', 'exec')
  71. with self.assertRaisesRegex(SyntaxError, 'iso-8859-15'):
  72. compile(b'\xef\xbb\xbf# -*- coding: iso-8859-15 -*-\n',
  73. 'dummy', 'exec')
  74. with self.assertRaisesRegex(SyntaxError, 'BOM'):
  75. compile(b'\xef\xbb\xbf# -*- coding: iso-8859-15 -*-\n',
  76. 'dummy', 'exec')
  77. with self.assertRaisesRegex(SyntaxError, 'fake'):
  78. compile(b'\xef\xbb\xbf# -*- coding: fake -*-\n', 'dummy', 'exec')
  79. with self.assertRaisesRegex(SyntaxError, 'BOM'):
  80. compile(b'\xef\xbb\xbf# -*- coding: fake -*-\n', 'dummy', 'exec')
  81. def test_bad_coding(self):
  82. module_name = 'bad_coding'
  83. self.verify_bad_module(module_name)
  84. def test_bad_coding2(self):
  85. module_name = 'bad_coding2'
  86. self.verify_bad_module(module_name)
  87. def verify_bad_module(self, module_name):
  88. self.assertRaises(SyntaxError, __import__, 'test.' + module_name)
  89. path = os.path.dirname(__file__)
  90. filename = os.path.join(path, module_name + '.py')
  91. with open(filename, "rb") as fp:
  92. bytes = fp.read()
  93. self.assertRaises(SyntaxError, compile, bytes, filename, 'exec')
  94. def test_exec_valid_coding(self):
  95. d = {}
  96. exec(b'# coding: cp949\na = "\xaa\xa7"\n', d)
  97. self.assertEqual(d['a'], '\u3047')
  98. def test_file_parse(self):
  99. # issue1134: all encodings outside latin-1 and utf-8 fail on
  100. # multiline strings and long lines (>512 columns)
  101. unload(TESTFN)
  102. filename = TESTFN + ".py"
  103. f = open(filename, "w", encoding="cp1252")
  104. sys.path.insert(0, os.curdir)
  105. try:
  106. with f:
  107. f.write("# -*- coding: cp1252 -*-\n")
  108. f.write("'''A short string\n")
  109. f.write("'''\n")
  110. f.write("'A very long string %s'\n" % ("X" * 1000))
  111. importlib.invalidate_caches()
  112. __import__(TESTFN)
  113. finally:
  114. del sys.path[0]
  115. unlink(filename)
  116. unlink(filename + "c")
  117. unlink(filename + "o")
  118. unload(TESTFN)
  119. rmtree('__pycache__')
  120. def test_error_from_string(self):
  121. # See http://bugs.python.org/issue6289
  122. input = "# coding: ascii\n\N{SNOWMAN}".encode('utf-8')
  123. with self.assertRaises(SyntaxError) as c:
  124. compile(input, "<string>", "exec")
  125. expected = "'ascii' codec can't decode byte 0xe2 in position 16: " \
  126. "ordinal not in range(128)"
  127. self.assertTrue(c.exception.args[0].startswith(expected),
  128. msg=c.exception.args[0])
  129. def test_file_parse_error_multiline(self):
  130. # gh96611:
  131. with open(TESTFN, "wb") as fd:
  132. fd.write(b'print("""\n\xb1""")\n')
  133. try:
  134. retcode, stdout, stderr = script_helper.assert_python_failure(TESTFN)
  135. self.assertGreater(retcode, 0)
  136. self.assertIn(b"Non-UTF-8 code starting with '\\xb1'", stderr)
  137. finally:
  138. os.unlink(TESTFN)
  139. def test_tokenizer_fstring_warning_in_first_line(self):
  140. source = "0b1and 2"
  141. with open(TESTFN, "w") as fd:
  142. fd.write("{}".format(source))
  143. try:
  144. retcode, stdout, stderr = script_helper.assert_python_ok(TESTFN)
  145. self.assertIn(b"SyntaxWarning: invalid binary litera", stderr)
  146. self.assertEqual(stderr.count(source.encode()), 1)
  147. finally:
  148. os.unlink(TESTFN)
  149. class AbstractSourceEncodingTest:
  150. def test_default_coding(self):
  151. src = (b'print(ascii("\xc3\xa4"))\n')
  152. self.check_script_output(src, br"'\xe4'")
  153. def test_first_coding_line(self):
  154. src = (b'#coding:iso8859-15\n'
  155. b'print(ascii("\xc3\xa4"))\n')
  156. self.check_script_output(src, br"'\xc3\u20ac'")
  157. def test_second_coding_line(self):
  158. src = (b'#\n'
  159. b'#coding:iso8859-15\n'
  160. b'print(ascii("\xc3\xa4"))\n')
  161. self.check_script_output(src, br"'\xc3\u20ac'")
  162. def test_third_coding_line(self):
  163. # Only first two lines are tested for a magic comment.
  164. src = (b'#\n'
  165. b'#\n'
  166. b'#coding:iso8859-15\n'
  167. b'print(ascii("\xc3\xa4"))\n')
  168. self.check_script_output(src, br"'\xe4'")
  169. def test_double_coding_line(self):
  170. # If the first line matches the second line is ignored.
  171. src = (b'#coding:iso8859-15\n'
  172. b'#coding:latin1\n'
  173. b'print(ascii("\xc3\xa4"))\n')
  174. self.check_script_output(src, br"'\xc3\u20ac'")
  175. def test_double_coding_same_line(self):
  176. src = (b'#coding:iso8859-15 coding:latin1\n'
  177. b'print(ascii("\xc3\xa4"))\n')
  178. self.check_script_output(src, br"'\xc3\u20ac'")
  179. def test_first_non_utf8_coding_line(self):
  180. src = (b'#coding:iso-8859-15 \xa4\n'
  181. b'print(ascii("\xc3\xa4"))\n')
  182. self.check_script_output(src, br"'\xc3\u20ac'")
  183. def test_second_non_utf8_coding_line(self):
  184. src = (b'\n'
  185. b'#coding:iso-8859-15 \xa4\n'
  186. b'print(ascii("\xc3\xa4"))\n')
  187. self.check_script_output(src, br"'\xc3\u20ac'")
  188. def test_utf8_bom(self):
  189. src = (b'\xef\xbb\xbfprint(ascii("\xc3\xa4"))\n')
  190. self.check_script_output(src, br"'\xe4'")
  191. def test_utf8_bom_and_utf8_coding_line(self):
  192. src = (b'\xef\xbb\xbf#coding:utf-8\n'
  193. b'print(ascii("\xc3\xa4"))\n')
  194. self.check_script_output(src, br"'\xe4'")
  195. def test_crlf(self):
  196. src = (b'print(ascii("""\r\n"""))\n')
  197. out = self.check_script_output(src, br"'\n'")
  198. def test_crcrlf(self):
  199. src = (b'print(ascii("""\r\r\n"""))\n')
  200. out = self.check_script_output(src, br"'\n\n'")
  201. def test_crcrcrlf(self):
  202. src = (b'print(ascii("""\r\r\r\n"""))\n')
  203. out = self.check_script_output(src, br"'\n\n\n'")
  204. def test_crcrcrlf2(self):
  205. src = (b'#coding:iso-8859-1\n'
  206. b'print(ascii("""\r\r\r\n"""))\n')
  207. out = self.check_script_output(src, br"'\n\n\n'")
  208. class UTF8ValidatorTest(unittest.TestCase):
  209. @unittest.skipIf(not sys.platform.startswith("linux"),
  210. "Too slow to run on non-Linux platforms")
  211. def test_invalid_utf8(self):
  212. # This is a port of test_utf8_decode_invalid_sequences in
  213. # test_unicode.py to exercise the separate utf8 validator in
  214. # Parser/tokenizer.c used when reading source files.
  215. # That file is written using low-level C file I/O, so the only way to
  216. # test it is to write actual files to disk.
  217. # Each example is put inside a string at the top of the file so
  218. # it's an otherwise valid Python source file. Put some newlines
  219. # beforehand so we can assert that the error is reported on the
  220. # correct line.
  221. template = b'\n\n\n"%s"\n'
  222. fn = TESTFN
  223. self.addCleanup(unlink, fn)
  224. def check(content):
  225. with open(fn, 'wb') as fp:
  226. fp.write(template % content)
  227. rc, stdout, stderr = script_helper.assert_python_failure(fn)
  228. # We want to assert that the python subprocess failed gracefully,
  229. # not via a signal.
  230. self.assertGreaterEqual(rc, 1)
  231. self.assertIn(b"Non-UTF-8 code starting with", stderr)
  232. self.assertIn(b"on line 4", stderr)
  233. # continuation bytes in a sequence of 2, 3, or 4 bytes
  234. continuation_bytes = [bytes([x]) for x in range(0x80, 0xC0)]
  235. # start bytes of a 2-byte sequence equivalent to code points < 0x7F
  236. invalid_2B_seq_start_bytes = [bytes([x]) for x in range(0xC0, 0xC2)]
  237. # start bytes of a 4-byte sequence equivalent to code points > 0x10FFFF
  238. invalid_4B_seq_start_bytes = [bytes([x]) for x in range(0xF5, 0xF8)]
  239. invalid_start_bytes = (
  240. continuation_bytes + invalid_2B_seq_start_bytes +
  241. invalid_4B_seq_start_bytes + [bytes([x]) for x in range(0xF7, 0x100)]
  242. )
  243. for byte in invalid_start_bytes:
  244. check(byte)
  245. for sb in invalid_2B_seq_start_bytes:
  246. for cb in continuation_bytes:
  247. check(sb + cb)
  248. for sb in invalid_4B_seq_start_bytes:
  249. for cb1 in continuation_bytes[:3]:
  250. for cb3 in continuation_bytes[:3]:
  251. check(sb+cb1+b'\x80'+cb3)
  252. for cb in [bytes([x]) for x in range(0x80, 0xA0)]:
  253. check(b'\xE0'+cb+b'\x80')
  254. check(b'\xE0'+cb+b'\xBF')
  255. # surrogates
  256. for cb in [bytes([x]) for x in range(0xA0, 0xC0)]:
  257. check(b'\xED'+cb+b'\x80')
  258. check(b'\xED'+cb+b'\xBF')
  259. for cb in [bytes([x]) for x in range(0x80, 0x90)]:
  260. check(b'\xF0'+cb+b'\x80\x80')
  261. check(b'\xF0'+cb+b'\xBF\xBF')
  262. for cb in [bytes([x]) for x in range(0x90, 0xC0)]:
  263. check(b'\xF4'+cb+b'\x80\x80')
  264. check(b'\xF4'+cb+b'\xBF\xBF')
  265. class BytesSourceEncodingTest(AbstractSourceEncodingTest, unittest.TestCase):
  266. def check_script_output(self, src, expected):
  267. with captured_stdout() as stdout:
  268. exec(src)
  269. out = stdout.getvalue().encode('latin1')
  270. self.assertEqual(out.rstrip(), expected)
  271. class FileSourceEncodingTest(AbstractSourceEncodingTest, unittest.TestCase):
  272. def check_script_output(self, src, expected):
  273. with tempfile.TemporaryDirectory() as tmpd:
  274. fn = os.path.join(tmpd, 'test.py')
  275. with open(fn, 'wb') as fp:
  276. fp.write(src)
  277. res = script_helper.assert_python_ok(fn)
  278. self.assertEqual(res.out.rstrip(), expected)
  279. if __name__ == "__main__":
  280. unittest.main()