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