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