Merge pull request #396 from inkydragon/fix-test-on-windows
[jackhill/mal.git] / runtest.py
1 #!/usr/bin/env python
2
3 from __future__ import print_function
4 import os, sys, re
5 import argparse, time
6 import signal, atexit
7
8 from subprocess import Popen, STDOUT, PIPE
9 from select import select
10
11 # Pseudo-TTY and terminal manipulation
12 import pty, array, fcntl, termios
13
14 IS_PY_3 = sys.version_info[0] == 3
15
16 debug_file = None
17 log_file = None
18
19 def debug(data):
20 if debug_file:
21 debug_file.write(data)
22 debug_file.flush()
23
24 def log(data, end='\n'):
25 if log_file:
26 log_file.write(data + end)
27 log_file.flush()
28 print(data, end=end)
29 sys.stdout.flush()
30
31 # TODO: do we need to support '\n' too
32 sep = "\r\n"
33 rundir = None
34
35 parser = argparse.ArgumentParser(
36 description="Run a test file against a Mal implementation")
37 parser.add_argument('--rundir',
38 help="change to the directory before running tests")
39 parser.add_argument('--start-timeout', default=10, type=int,
40 help="default timeout for initial prompt")
41 parser.add_argument('--test-timeout', default=20, type=int,
42 help="default timeout for each individual test action")
43 parser.add_argument('--pre-eval', default=None, type=str,
44 help="Mal code to evaluate prior to running the test")
45 parser.add_argument('--no-pty', action='store_true',
46 help="Use direct pipes instead of pseudo-tty")
47 parser.add_argument('--log-file', type=str,
48 help="Write messages to the named file in addition the screen")
49 parser.add_argument('--debug-file', type=str,
50 help="Write all test interaction the named file")
51 parser.add_argument('--hard', action='store_true',
52 help="Turn soft tests (soft, deferrable, optional) into hard failures")
53
54 # Control whether deferrable and optional tests are executed
55 parser.add_argument('--deferrable', dest='deferrable', action='store_true',
56 help="Enable deferrable tests that follow a ';>>> deferrable=True'")
57 parser.add_argument('--no-deferrable', dest='deferrable', action='store_false',
58 help="Disable deferrable tests that follow a ';>>> deferrable=True'")
59 parser.set_defaults(deferrable=True)
60 parser.add_argument('--optional', dest='optional', action='store_true',
61 help="Enable optional tests that follow a ';>>> optional=True'")
62 parser.add_argument('--no-optional', dest='optional', action='store_false',
63 help="Disable optional tests that follow a ';>>> optional=True'")
64 parser.set_defaults(optional=True)
65
66 parser.add_argument('test_file', type=str,
67 help="a test file formatted as with mal test data")
68 parser.add_argument('mal_cmd', nargs="*",
69 help="Mal implementation command line. Use '--' to "
70 "specify a Mal command line with dashed options.")
71
72 class Runner():
73 def __init__(self, args, no_pty=False):
74 #print "args: %s" % repr(args)
75 self.no_pty = no_pty
76
77 # Cleanup child process on exit
78 atexit.register(self.cleanup)
79
80 self.p = None
81 env = os.environ
82 env['TERM'] = 'dumb'
83 env['INPUTRC'] = '/dev/null'
84 env['PERL_RL'] = 'false'
85 if no_pty:
86 self.p = Popen(args, bufsize=0,
87 stdin=PIPE, stdout=PIPE, stderr=STDOUT,
88 preexec_fn=os.setsid,
89 env=env)
90 self.stdin = self.p.stdin
91 self.stdout = self.p.stdout
92 else:
93 # provide tty to get 'interactive' readline to work
94 master, slave = pty.openpty()
95
96 # Set terminal size large so that readline will not send
97 # ANSI/VT escape codes when the lines are long.
98 buf = array.array('h', [100, 200, 0, 0])
99 fcntl.ioctl(master, termios.TIOCSWINSZ, buf, True)
100
101 self.p = Popen(args, bufsize=0,
102 stdin=slave, stdout=slave, stderr=STDOUT,
103 preexec_fn=os.setsid,
104 env=env)
105 # Now close slave so that we will get an exception from
106 # read when the child exits early
107 # http://stackoverflow.com/questions/11165521
108 os.close(slave)
109 self.stdin = os.fdopen(master, 'r+b', 0)
110 self.stdout = self.stdin
111
112 #print "started"
113 self.buf = ""
114 self.last_prompt = ""
115
116 def read_to_prompt(self, prompts, timeout):
117 end_time = time.time() + timeout
118 while time.time() < end_time:
119 [outs,_,_] = select([self.stdout], [], [], 1)
120 if self.stdout in outs:
121 new_data = self.stdout.read(1)
122 new_data = new_data.decode("utf-8") if IS_PY_3 else new_data
123 #print("new_data: '%s'" % new_data)
124 debug(new_data)
125 # Perform newline cleanup
126 if self.no_pty:
127 self.buf += new_data.replace("\n", "\r\n")
128 else:
129 self.buf += new_data
130 self.buf = self.buf.replace("\r\r", "\r")
131 # Remove ANSI codes generally
132 #ansi_escape = re.compile(r'\x1B\[[0-?]*[ -/]*[@-~]')
133 # Remove rustyline ANSI CSI codes:
134 # - [6C - CR + cursor forward
135 # - [6K - CR + erase in line
136 ansi_escape = re.compile(r'\r\x1B\[[0-9]*[CK]')
137 self.buf = ansi_escape.sub('', self.buf)
138 for prompt in prompts:
139 regexp = re.compile(prompt)
140 match = regexp.search(self.buf)
141 if match:
142 end = match.end()
143 buf = self.buf[0:match.start()]
144 self.buf = self.buf[end:]
145 self.last_prompt = prompt
146 return buf.replace("^M", "\r")
147 return None
148
149 def writeline(self, str):
150 def _to_bytes(s):
151 return bytes(s, "utf-8") if IS_PY_3 else s
152
153 self.stdin.write(_to_bytes(str.replace('\r', '\x16\r') + "\n"))
154
155 def cleanup(self):
156 #print "cleaning up"
157 if self.p:
158 try:
159 os.killpg(self.p.pid, signal.SIGTERM)
160 except OSError:
161 pass
162 self.p = None
163
164 class TestReader:
165 def __init__(self, test_file):
166 self.line_num = 0
167 f = open(test_file, newline='') if IS_PY_3 else open(test_file)
168 self.data = f.read().split('\n')
169 self.soft = False
170 self.deferrable = False
171 self.optional = False
172
173 def next(self):
174 self.msg = None
175 self.form = None
176 self.out = ""
177 self.ret = None
178
179 while self.data:
180 self.line_num += 1
181 line = self.data.pop(0)
182 if re.match(r"^\s*$", line): # blank line
183 continue
184 elif line[0:3] == ";;;": # ignore comment
185 continue
186 elif line[0:2] == ";;": # output comment
187 self.msg = line[3:]
188 return True
189 elif line[0:5] == ";>>> ": # settings/commands
190 settings = {}
191 exec(line[5:], {}, settings)
192 if 'soft' in settings:
193 self.soft = settings['soft']
194 if 'deferrable' in settings and settings['deferrable']:
195 self.deferrable = "\nSkipping deferrable and optional tests"
196 return True
197 if 'optional' in settings and settings['optional']:
198 self.optional = "\nSkipping optional tests"
199 return True
200 continue
201 elif line[0:1] == ";": # unexpected comment
202 raise Exception("Test data error at line %d:\n%s" % (self.line_num, line))
203 self.form = line # the line is a form to send
204
205 # Now find the output and return value
206 while self.data:
207 line = self.data[0]
208 if line[0:3] == ";=>":
209 self.ret = line[3:]
210 self.line_num += 1
211 self.data.pop(0)
212 break
213 elif line[0:2] == ";/":
214 self.out = self.out + line[2:] + sep
215 self.line_num += 1
216 self.data.pop(0)
217 else:
218 self.ret = ""
219 break
220 if self.ret != None: break
221
222 if self.out[-2:] == sep and not self.ret:
223 # If there is no return value, output should not end in
224 # separator
225 self.out = self.out[0:-2]
226 return self.form
227
228 args = parser.parse_args(sys.argv[1:])
229 # Workaround argparse issue with two '--' on command line
230 if sys.argv.count('--') > 0:
231 args.mal_cmd = sys.argv[sys.argv.index('--')+1:]
232
233 if args.rundir: os.chdir(args.rundir)
234
235 if args.log_file: log_file = open(args.log_file, "a")
236 if args.debug_file: debug_file = open(args.debug_file, "a")
237
238 r = Runner(args.mal_cmd, no_pty=args.no_pty)
239 t = TestReader(args.test_file)
240
241
242 def assert_prompt(runner, prompts, timeout):
243 # Wait for the initial prompt
244 header = runner.read_to_prompt(prompts, timeout=timeout)
245 if not header == None:
246 if header:
247 log("Started with:\n%s" % header)
248 else:
249 log("Did not one of following prompt(s): %s" % repr(prompts))
250 log(" Got : %s" % repr(r.buf))
251 sys.exit(1)
252
253
254 # Wait for the initial prompt
255 try:
256 assert_prompt(r, ['[^\s()<>]+> '], args.start_timeout)
257 except:
258 _, exc, _ = sys.exc_info()
259 log("\nException: %s" % repr(exc))
260 log("Output before exception:\n%s" % r.buf)
261 sys.exit(1)
262
263 # Send the pre-eval code if any
264 if args.pre_eval:
265 sys.stdout.write("RUNNING pre-eval: %s" % args.pre_eval)
266 r.writeline(args.pre_eval)
267 assert_prompt(r, ['[^\s()<>]+> '], args.test_timeout)
268
269 test_cnt = 0
270 pass_cnt = 0
271 fail_cnt = 0
272 soft_fail_cnt = 0
273 failures = []
274
275 while t.next():
276 if args.deferrable == False and t.deferrable:
277 log(t.deferrable)
278 break
279
280 if args.optional == False and t.optional:
281 log(t.optional)
282 break
283
284 if t.msg != None:
285 log(t.msg)
286 continue
287
288 if t.form == None: continue
289
290 log("TEST: %s -> [%s,%s]" % (repr(t.form), repr(t.out), t.ret), end='')
291
292 # The repeated form is to get around an occasional OS X issue
293 # where the form is repeated.
294 # https://github.com/kanaka/mal/issues/30
295 expects = ["%s%s%s%s" % (re.escape(t.form), sep,
296 t.out, re.escape(t.ret)),
297 "%s%s%s%s%s%s" % (re.escape(t.form), sep,
298 re.escape(t.form), sep,
299 t.out, re.escape(t.ret))]
300
301 r.writeline(t.form)
302 try:
303 test_cnt += 1
304 res = r.read_to_prompt(['\r\n[^\s()<>]+> ', '\n[^\s()<>]+> '],
305 timeout=args.test_timeout)
306 #print "%s,%s,%s" % (idx, repr(p.before), repr(p.after))
307 if (t.ret == "" and t.out == ""):
308 log(" -> SUCCESS (result ignored)")
309 pass_cnt += 1
310 elif (re.search(expects[0], res, re.S) or
311 re.search(expects[1], res, re.S)):
312 log(" -> SUCCESS")
313 pass_cnt += 1
314 else:
315 if t.soft and not args.hard:
316 log(" -> SOFT FAIL (line %d):" % t.line_num)
317 soft_fail_cnt += 1
318 fail_type = "SOFT "
319 else:
320 log(" -> FAIL (line %d):" % t.line_num)
321 fail_cnt += 1
322 fail_type = ""
323 log(" Expected : %s" % repr(expects[0]))
324 log(" Got : %s" % repr(res))
325 failed_test = """%sFAILED TEST (line %d): %s -> [%s,%s]:
326 Expected : %s
327 Got : %s""" % (fail_type, t.line_num, t.form, repr(t.out),
328 t.ret, repr(expects[0]), repr(res))
329 failures.append(failed_test)
330 except:
331 _, exc, _ = sys.exc_info()
332 log("\nException: %s" % repr(exc))
333 log("Output before exception:\n%s" % r.buf)
334 sys.exit(1)
335
336 if len(failures) > 0:
337 log("\nFAILURES:")
338 for f in failures:
339 log(f)
340
341 results = """
342 TEST RESULTS (for %s):
343 %3d: soft failing tests
344 %3d: failing tests
345 %3d: passing tests
346 %3d: total tests
347 """ % (args.test_file, soft_fail_cnt, fail_cnt,
348 pass_cnt, test_cnt)
349 log(results)
350
351 debug("\n") # add some separate to debug log
352
353 if fail_cnt > 0:
354 sys.exit(1)
355 sys.exit(0)