1import unittest
2from test import support
3import os
4import sys
5import subprocess
6
7
8SYMBOL_FILE              = support.findfile('symbol.py')
9GRAMMAR_FILE             = os.path.join(os.path.dirname(__file__),
10                                        '..', '..', 'Include', 'graminit.h')
11TEST_PY_FILE             = 'symbol_test.py'
12
13
14class TestSymbolGeneration(unittest.TestCase):
15
16    def _copy_file_without_generated_symbols(self, source_file, dest_file):
17        with open(source_file) as fp:
18            lines = fp.readlines()
19        with open(dest_file, 'w') as fp:
20            fp.writelines(lines[:lines.index("#--start constants--\n") + 1])
21            fp.writelines(lines[lines.index("#--end constants--\n"):])
22
23    def _generate_symbols(self, grammar_file, target_symbol_py_file):
24        proc = subprocess.Popen([sys.executable,
25                                 SYMBOL_FILE,
26                                 grammar_file,
27                                 target_symbol_py_file], stderr=subprocess.PIPE)
28        stderr = proc.communicate()[1]
29        return proc.returncode, stderr
30
31    def compare_files(self, file1, file2):
32        with open(file1) as fp:
33            lines1 = fp.readlines()
34        with open(file2) as fp:
35            lines2 = fp.readlines()
36        self.assertEqual(lines1, lines2)
37
38    @unittest.skipIf(not os.path.exists(GRAMMAR_FILE),
39                     'test only works from source build directory')
40    def test_real_grammar_and_symbol_file(self):
41        output = support.TESTFN
42        self.addCleanup(support.unlink, output)
43
44        self._copy_file_without_generated_symbols(SYMBOL_FILE, output)
45
46        exitcode, stderr = self._generate_symbols(GRAMMAR_FILE, output)
47        self.assertEqual(b'', stderr)
48        self.assertEqual(0, exitcode)
49
50        self.compare_files(SYMBOL_FILE, output)
51
52
53if __name__ == "__main__":
54    unittest.main()
55