Debian Codegraph @

codegen/genHtml5LibTests.py

raw
1 #!/usr/bin/env python3
2
3 import glob
4 import json
5 import re
6
7 state_map = {
8 'Data state': 0,
9 'RCDATA state': 1,
10 'RAWTEXT state': 2,
11 'PLAINTEXT state': 3,
12 'Script data state': 4,
13 'CDATA section state': 5,
14 }
15
16 for filename in sorted(glob.glob('../html5lib-tests/tokenizer/*.test')):
17 match = re.search('/([^/]*).test$', filename)
18 if match is None:
19 continue
20 testname = match[1]
21 if testname == 'xmlViolation':
22 continue
23
24 with open(filename) as json_data:
25 root = json.load(json_data)
26
27 test_out = open(f'test/html-tokenizer/{testname}.test', 'w')
28 result_out = open(f'result/html-tokenizer/{testname}.test', 'w')
29
30 counter = 0
31
32 for tests in root.values():
33 for test in tests:
34 input = test['input']
35
36 # Skip surrogate tests
37 if re.search(r'\\uD[89A-F]', input, re.I):
38 continue
39
40 input = re.sub(r'\\u([A-Fa-f0-9]{4})',
41 lambda m: chr(int(m[1], 16)),
42 input)
43
44 output = ''
45 for token in test['output']:
46 if token[1] == '\0':
47 continue
48
49 output += token[0] + '\n'
50
51 if token[0] == 'DOCTYPE':
52 for i in range(1, 4):
53 if token[i] is None:
54 output += '<none>\n'
55 else:
56 output += token[i] + '\n'
57 else:
58 output += token[1]
59 if token[0] == 'StartTag':
60 for name, value in token[2].items():
61 output += f' {name}={value}'
62 output += '\n'
63
64 output = re.sub(r'\\u([A-Fa-f0-9]{4})',
65 lambda m: chr(int(m[1], 16)),
66 output)
67
68 # The HTML5 spec splits handling of U+0000 across
69 # tokenizer and tree builder. We already ignore
70 # U+0000 in body text when tokenizing.
71 output = re.sub(r'\x00', '', output)
72
73 for state in test.get('initialStates', ['Data state']):
74 state_no = state_map.get(state)
75 if state_no is None:
76 raise Exception(f'{filename}: unknown state: {state}')
77 if state_no == 5:
78 continue
79
80 start_tag = test.get('lastStartTag', '-')
81
82 test_out.write(f'{counter} {start_tag} {state_no} '
83 f'{len(input.encode())}\n')
84 test_out.write(input)
85 test_out.write('\n')
86
87 result_out.write(f'{counter}\n')
88 result_out.write(output)
89
90 counter += 1
91
92 test_out.close()
93 result_out.close()