Debian Codegraph @

test/spec_tests.py

raw
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3
4 import sys
5 from difflib import unified_diff
6 import argparse
7 import re
8 import json
9 from cmark import CMark
10 from normalize import normalize_html
11
12 parser = argparse.ArgumentParser(description='Run cmark tests.')
13 parser.add_argument('-p', '--program', dest='program', nargs='?', default=None,
14 help='program to test')
15 parser.add_argument('-s', '--spec', dest='spec', nargs='?', default='spec.txt',
16 help='path to spec')
17 parser.add_argument('-P', '--pattern', dest='pattern', nargs='?',
18 default=None, help='limit to sections matching regex pattern')
19 parser.add_argument('--library-dir', dest='library_dir', nargs='?',
20 default=None, help='directory containing dynamic library')
21 parser.add_argument('--no-normalize', dest='normalize',
22 action='store_const', const=False, default=True,
23 help='do not normalize HTML')
24 parser.add_argument('-d', '--dump-tests', dest='dump_tests',
25 action='store_const', const=True, default=False,
26 help='dump tests in JSON format')
27 parser.add_argument('--debug-normalization', dest='debug_normalization',
28 action='store_const', const=True,
29 default=False, help='filter stdin through normalizer for testing')
30 parser.add_argument('-n', '--number', type=int, default=None,
31 help='only consider the test with the given number')
32 args = parser.parse_args(sys.argv[1:])
33
34 def out(str):
35 sys.stdout.buffer.write(str.encode('utf-8'))
36
37 def print_test_header(headertext, example_number, start_line, end_line):
38 out("Example %d (lines %d-%d) %s\n" % (example_number,start_line,end_line,headertext))
39
40 def do_test(converter, test, normalize, result_counts):
41 [retcode, actual_html, err] = converter(test['markdown'])
42 if retcode == 0:
43 expected_html = test['html']
44 unicode_error = None
45 if normalize:
46 try:
47 passed = normalize_html(actual_html) == normalize_html(expected_html)
48 except UnicodeDecodeError as e:
49 unicode_error = e
50 passed = False
51 else:
52 passed = actual_html == expected_html
53 if passed:
54 result_counts['pass'] += 1
55 else:
56 print_test_header(test['section'], test['example'], test['start_line'], test['end_line'])
57 out(test['markdown'] + '\n')
58 if unicode_error:
59 out("Unicode error: " + str(unicode_error) + '\n')
60 out("Expected: " + repr(expected_html) + '\n')
61 out("Got: " + repr(actual_html) + '\n')
62 else:
63 expected_html_lines = expected_html.splitlines(True)
64 actual_html_lines = actual_html.splitlines(True)
65 for diffline in unified_diff(expected_html_lines, actual_html_lines,
66 "expected HTML", "actual HTML"):
67 out(diffline)
68 out('\n')
69 result_counts['fail'] += 1
70 else:
71 print_test_header(test['section'], test['example'], test['start_line'], test['end_line'])
72 out("program returned error code %d\n" % retcode)
73 sys.stdout.buffer.write(err)
74 result_counts['error'] += 1
75
76 def get_tests(specfile):
77 line_number = 0
78 start_line = 0
79 end_line = 0
80 example_number = 0
81 markdown_lines = []
82 html_lines = []
83 state = 0 # 0 regular text, 1 markdown example, 2 html output
84 headertext = ''
85 tests = []
86
87 header_re = re.compile('#+ ')
88
89 with open(specfile, 'r', encoding='utf-8', newline='\n') as specf:
90 for line in specf:
91 line_number = line_number + 1
92 l = line.strip()
93 if l == "`" * 32 + " example":
94 state = 1
95 elif l == "`" * 32:
96 state = 0
97 example_number = example_number + 1
98 end_line = line_number
99 tests.append({
100 "markdown":''.join(markdown_lines).replace('→',"\t"),
101 "html":''.join(html_lines).replace('→',"\t"),
102 "example": example_number,
103 "start_line": start_line,
104 "end_line": end_line,
105 "section": headertext})
106 start_line = 0
107 markdown_lines = []
108 html_lines = []
109 elif l == ".":
110 state = 2
111 elif state == 1:
112 if start_line == 0:
113 start_line = line_number - 1
114 markdown_lines.append(line)
115 elif state == 2:
116 html_lines.append(line)
117 elif state == 0 and re.match(header_re, line):
118 headertext = header_re.sub('', line).strip()
119 return tests
120
121 if __name__ == "__main__":
122 if args.debug_normalization:
123 out(normalize_html(sys.stdin.read()))
124 exit(0)
125
126 all_tests = get_tests(args.spec)
127 if args.pattern:
128 pattern_re = re.compile(args.pattern, re.IGNORECASE)
129 else:
130 pattern_re = re.compile('.')
131 tests = [ test for test in all_tests if re.search(pattern_re, test['section']) and (not args.number or test['example'] == args.number) ]
132 if args.dump_tests:
133 out(json.dumps(tests, ensure_ascii=False, indent=2))
134 exit(0)
135 else:
136 skipped = len(all_tests) - len(tests)
137 converter = CMark(prog=args.program, library_dir=args.library_dir).to_html
138 result_counts = {'pass': 0, 'fail': 0, 'error': 0, 'skip': skipped}
139 for test in tests:
140 do_test(converter, test, args.normalize, result_counts)
141 out("{pass} passed, {fail} failed, {error} errored, {skip} skipped\n".format(**result_counts))
142 exit(result_counts['fail'] + result_counts['error'])