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