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