Skip to content

Commit 780fec8

Browse files
committed
Added ability to round-trip test cases
- Switched test_designated_initializers to use the new code
1 parent fbc5d8e commit 780fec8

1 file changed

Lines changed: 48 additions & 8 deletions

File tree

test/test_pycparserext.py

Lines changed: 48 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,53 @@
22
import pytest
33

44

5+
# Inspired from pycparser's compare_asts test function
6+
def _compare_asts(first, second):
7+
if type(first) is not type(second):
8+
return False
9+
10+
if isinstance(first, tuple):
11+
if first[0] != second[0]:
12+
return False
13+
14+
return _compare_asts(first[1], second[1])
15+
16+
for attr in first.attr_names:
17+
if getattr(first, attr) != getattr(second, attr):
18+
return False
19+
20+
for i, c1 in enumerate(first.children()):
21+
if not _compare_asts(c1, second.children()[i]):
22+
return False
23+
return True
24+
25+
26+
def _round_trip_matches(src):
27+
from pycparserext.ext_c_parser import GnuCParser
28+
from pycparserext.ext_c_generator import GnuCGenerator
29+
30+
p = GnuCParser()
31+
32+
first_ast = p.parse(src)
33+
34+
gen = GnuCGenerator().visit(first_ast)
35+
36+
second_ast = p.parse(gen)
37+
38+
if not _compare_asts(first_ast, second_ast):
39+
print('First AST:')
40+
first_ast.show()
41+
42+
print('Generated code:')
43+
print(gen)
44+
45+
print('Second AST:')
46+
second_ast.show()
47+
48+
return False
49+
return True
50+
51+
552
def test_asm_volatile_1():
653
src = """
754
void read_tsc(void) {
@@ -388,14 +435,7 @@ def test_designated_initializers():
388435
389436
char char_map[256] = { [0 ... 255] = '?', ['0' ... '9'] = 'X' };
390437
"""
391-
import pycparserext.ext_c_parser as ext_c_parser
392-
import pycparserext.ext_c_generator as ext_c_generator
393-
394-
parser = ext_c_parser.GnuCParser()
395-
ast = parser.parse(src)
396-
ast.show()
397-
gen = ext_c_generator.GnuCGenerator()
398-
print(gen.visit(ast))
438+
assert _round_trip_matches(src)
399439

400440

401441
def test_node_visitor():

0 commit comments

Comments
 (0)