Perl: still seems to need --raw in some situations.
[jackhill/mal.git] / runtest.py
CommitLineData
31690700
JM
1#!/usr/bin/env python
2
3import os, sys, re
7907cd90 4import argparse, time
b3c30da9 5import signal, atexit
31690700 6
7907cd90
JM
7from subprocess import Popen, STDOUT, PIPE
8from select import select
31690700 9
b3c30da9
JM
10# Pseudo-TTY and terminal manipulation
11import pty, array, fcntl, termios
12
8e4628da 13IS_PY_3 = sys.version_info[0] == 3
14
31690700
JM
15# TODO: do we need to support '\n' too
16sep = "\r\n"
7907cd90 17#sep = "\n"
31690700
JM
18rundir = None
19
20parser = argparse.ArgumentParser(
21 description="Run a test file against a Mal implementation")
22parser.add_argument('--rundir',
23 help="change to the directory before running tests")
24parser.add_argument('--start-timeout', default=10, type=int,
25 help="default timeout for initial prompt")
26parser.add_argument('--test-timeout', default=20, type=int,
27 help="default timeout for each individual test action")
cc021efe
JM
28parser.add_argument('--pre-eval', default=None, type=str,
29 help="Mal code to evaluate prior to running the test")
ab01be18
JM
30parser.add_argument('--no-pty', action='store_true',
31 help="Use direct pipes instead of pseudo-tty")
31690700
JM
32
33parser.add_argument('test_file', type=argparse.FileType('r'),
34 help="a test file formatted as with mal test data")
35parser.add_argument('mal_cmd', nargs="*",
36 help="Mal implementation command line. Use '--' to "
37 "specify a Mal command line with dashed options.")
38
7907cd90 39class Runner():
8caf6211 40 def __init__(self, args, no_pty=False):
612bfe4a 41 #print "args: %s" % repr(args)
ab01be18 42 self.no_pty = no_pty
612bfe4a
JM
43
44 # Cleanup child process on exit
45 atexit.register(self.cleanup)
46
8caf6211
JM
47 self.p = None
48 env = os.environ
49 env['TERM'] = 'dumb'
92dcc815 50 env['INPUTRC'] = '/dev/null'
ab01be18 51 if no_pty:
612bfe4a
JM
52 self.p = Popen(args, bufsize=0,
53 stdin=PIPE, stdout=PIPE, stderr=STDOUT,
8caf6211
JM
54 preexec_fn=os.setsid,
55 env=env)
7907cd90
JM
56 self.stdin = self.p.stdin
57 self.stdout = self.p.stdout
58 else:
59 # provide tty to get 'interactive' readline to work
60 master, slave = pty.openpty()
b3c30da9
JM
61
62 # Set terminal size large so that readline will not send
63 # ANSI/VT escape codes when the lines are long.
64 buf = array.array('h', [100, 200, 0, 0])
65 fcntl.ioctl(master, termios.TIOCSWINSZ, buf, True)
66
612bfe4a
JM
67 self.p = Popen(args, bufsize=0,
68 stdin=slave, stdout=slave, stderr=STDOUT,
8caf6211
JM
69 preexec_fn=os.setsid,
70 env=env)
7907cd90
JM
71 self.stdin = os.fdopen(master, 'r+b', 0)
72 self.stdout = self.stdin
73
74 #print "started"
75 self.buf = ""
76 self.last_prompt = ""
77
78 def read_to_prompt(self, prompts, timeout):
79 end_time = time.time() + timeout
80 while time.time() < end_time:
96deb6a9
JM
81 [outs,_,_] = select([self.stdout], [], [], 1)
82 if self.stdout in outs:
83 new_data = self.stdout.read(1)
7907cd90 84 #print "new_data: '%s'" % new_data
8e4628da 85 new_data = new_data.decode("utf-8") if IS_PY_3 else new_data
ab01be18 86 if self.no_pty:
9a383535
JM
87 self.buf += new_data.replace("\n", "\r\n")
88 else:
89 self.buf += new_data
7907cd90
JM
90 for prompt in prompts:
91 regexp = re.compile(prompt)
92 match = regexp.search(self.buf)
93 if match:
94 end = match.end()
95 buf = self.buf[0:end-len(prompt)]
96 self.buf = self.buf[end:]
97 self.last_prompt = prompt
98 return buf
99 return None
100
96deb6a9 101 def writeline(self, str):
8e4628da 102 def _to_bytes(s):
103 return bytes(s, "utf-8") if IS_PY_3 else s
104
105 self.stdin.write(_to_bytes(str + "\n"))
7907cd90 106
f6c83b2b 107 def cleanup(self):
612bfe4a 108 #print "cleaning up"
f6c83b2b 109 if self.p:
10034e82
JM
110 try:
111 os.killpg(self.p.pid, signal.SIGTERM)
112 except OSError:
113 pass
f6c83b2b
JM
114 self.p = None
115
116
31690700
JM
117args = parser.parse_args(sys.argv[1:])
118test_data = args.test_file.read().split('\n')
119
120if args.rundir: os.chdir(args.rundir)
121
8caf6211 122r = Runner(args.mal_cmd, no_pty=args.no_pty)
53beaa0a 123
31690700
JM
124
125test_idx = 0
126def read_test(data):
127 global test_idx
128 form, output, ret = None, "", None
129 while data:
130 test_idx += 1
131 line = data.pop(0)
132 if re.match(r"^\s*$", line): # blank line
133 continue
134 elif line[0:3] == ";;;": # ignore comment
135 continue
136 elif line[0:2] == ";;": # output comment
8e4628da 137 print(line[3:])
31690700
JM
138 continue
139 elif line[0:2] == ";": # unexpected comment
8e4628da 140 print("Test data error at line %d:\n%s" % (test_idx, line))
31690700
JM
141 return None, None, None, test_idx
142 form = line # the line is a form to send
143
144 # Now find the output and return value
145 while data:
146 line = data[0]
147 if line[0:3] == ";=>":
148 ret = line[3:].replace('\\r', '\r').replace('\\n', '\n')
149 test_idx += 1
150 data.pop(0)
151 break
152 elif line[0:2] == "; ":
153 output = output + line[2:] + sep
154 test_idx += 1
155 data.pop(0)
156 else:
157 ret = "*"
158 break
159 if ret: break
160
161 return form, output, ret, test_idx
162
cc021efe
JM
163def assert_prompt(timeout):
164 # Wait for the initial prompt
7907cd90
JM
165 header = r.read_to_prompt(['user> ', 'mal-user> '], timeout=timeout)
166 if not header == None:
167 if header:
8e4628da 168 print("Started with:\n%s" % header)
7907cd90 169 else:
8e4628da 170 print("Did not get 'user> ' or 'mal-user> ' prompt")
171 print(" Got : %s" % repr(r.buf))
cc021efe
JM
172 sys.exit(1)
173
31690700
JM
174
175# Wait for the initial prompt
cc021efe
JM
176assert_prompt(args.start_timeout)
177
178# Send the pre-eval code if any
179if args.pre_eval:
180 sys.stdout.write("RUNNING pre-eval: %s" % args.pre_eval)
7907cd90 181 p.write(args.pre_eval)
cc021efe 182 assert_prompt(args.test_timeout)
31690700
JM
183
184fail_cnt = 0
185
186while test_data:
187 form, out, ret, line_num = read_test(test_data)
188 if form == None:
189 break
190 sys.stdout.write("TEST: %s -> [%s,%s]" % (form, repr(out), repr(ret)))
191 sys.stdout.flush()
192 expected = "%s%s%s%s" % (form, sep, out, ret)
193
96deb6a9 194 r.writeline(form)
31690700 195 try:
7907cd90
JM
196 res = r.read_to_prompt(['\r\nuser> ', '\nuser> ',
197 '\r\nmal-user> ', '\nmal-user> '],
198 timeout=args.test_timeout)
31690700 199 #print "%s,%s,%s" % (idx, repr(p.before), repr(p.after))
7907cd90 200 if ret == "*" or res == expected:
8e4628da 201 print(" -> SUCCESS")
31690700 202 else:
8e4628da 203 print(" -> FAIL (line %d):" % line_num)
204 print(" Expected : %s" % repr(expected))
205 print(" Got : %s" % repr(res))
31690700 206 fail_cnt += 1
10034e82
JM
207 except KeyboardInterrupt:
208 print("\nKeyboard interrupt.")
209 print("Output so far:\n%s" % r.buf)
210 sys.exit(1)
7907cd90 211 except:
10034e82
JM
212 _, exc, _ = sys.exc_info()
213 print("\nException: %s" % repr(exc.message))
31690700
JM
214 sys.exit(1)
215
216if fail_cnt > 0:
8e4628da 217 print("FAILURES: %d" % fail_cnt)
31690700
JM
218 sys.exit(2)
219sys.exit(0)