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