3 from __future__
import print_function
8 from subprocess
import Popen
, STDOUT
, PIPE
9 from select
import select
11 # Pseudo-TTY and terminal manipulation
12 import pty
, array
, fcntl
, termios
14 IS_PY_3
= sys
.version_info
[0] == 3
21 debug_file
.write(data
)
24 def log(data
, end
='\n'):
26 log_file
.write(data
+ end
)
31 # TODO: do we need to support '\n' too
35 parser
= argparse
.ArgumentParser(
36 description
="Run a test file against a Mal implementation")
37 parser
.add_argument('--rundir',
38 help="change to the directory before running tests")
39 parser
.add_argument('--start-timeout', default
=10, type=int,
40 help="default timeout for initial prompt")
41 parser
.add_argument('--test-timeout', default
=20, type=int,
42 help="default timeout for each individual test action")
43 parser
.add_argument('--pre-eval', default
=None, type=str,
44 help="Mal code to evaluate prior to running the test")
45 parser
.add_argument('--no-pty', action
='store_true',
46 help="Use direct pipes instead of pseudo-tty")
47 parser
.add_argument('--log-file', type=str,
48 help="Write messages to the named file in addition the screen")
49 parser
.add_argument('--debug-file', type=str,
50 help="Write all test interaction the named file")
51 parser
.add_argument('--hard', action
='store_true',
52 help="Turn soft tests (soft, deferrable, optional) into hard failures")
54 # Control whether deferrable and optional tests are executed
55 parser
.add_argument('--deferrable', dest
='deferrable', action
='store_true',
56 help="Enable deferrable tests that follow a ';>>> deferrable=True'")
57 parser
.add_argument('--no-deferrable', dest
='deferrable', action
='store_false',
58 help="Disable deferrable tests that follow a ';>>> deferrable=True'")
59 parser
.set_defaults(deferrable
=True)
60 parser
.add_argument('--optional', dest
='optional', action
='store_true',
61 help="Enable optional tests that follow a ';>>> optional=True'")
62 parser
.add_argument('--no-optional', dest
='optional', action
='store_false',
63 help="Disable optional tests that follow a ';>>> optional=True'")
64 parser
.set_defaults(optional
=True)
66 parser
.add_argument('test_file', type=str,
67 help="a test file formatted as with mal test data")
68 parser
.add_argument('mal_cmd', nargs
="*",
69 help="Mal implementation command line. Use '--' to "
70 "specify a Mal command line with dashed options.")
71 parser
.add_argument('--crlf', dest
='crlf', action
='store_true',
72 help="Write \\r\\n instead of \\n to the input")
75 def __init__(self
, args
, no_pty
=False, line_break
="\n"):
76 #print "args: %s" % repr(args)
79 # Cleanup child process on exit
80 atexit
.register(self
.cleanup
)
85 env
['INPUTRC'] = '/dev/null'
86 env
['PERL_RL'] = 'false'
88 self
.p
= Popen(args
, bufsize
=0,
89 stdin
=PIPE
, stdout
=PIPE
, stderr
=STDOUT
,
92 self
.stdin
= self
.p
.stdin
93 self
.stdout
= self
.p
.stdout
95 # provide tty to get 'interactive' readline to work
96 master
, slave
= pty
.openpty()
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)
103 self
.p
= Popen(args
, bufsize
=0,
104 stdin
=slave
, stdout
=slave
, stderr
=STDOUT
,
105 preexec_fn
=os
.setsid
,
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
111 self
.stdin
= os
.fdopen(master
, 'r+b', 0)
112 self
.stdout
= self
.stdin
116 self
.last_prompt
= ""
118 self
.line_break
= line_break
120 def read_to_prompt(self
, prompts
, timeout
):
121 end_time
= time
.time() + timeout
122 while time
.time() < end_time
:
123 [outs
,_
,_
] = select([self
.stdout
], [], [], 1)
124 if self
.stdout
in outs
:
125 new_data
= self
.stdout
.read(1)
126 new_data
= new_data
.decode("utf-8") if IS_PY_3
else new_data
127 #print("new_data: '%s'" % new_data)
129 # Perform newline cleanup
131 self
.buf
+= new_data
.replace("\n", "\r\n")
134 self
.buf
= self
.buf
.replace("\r\r", "\r")
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
)
142 for prompt
in prompts
:
143 regexp
= re
.compile(prompt
)
144 match
= regexp
.search(self
.buf
)
147 buf
= self
.buf
[0:match
.start()]
148 self
.buf
= self
.buf
[end
:]
149 self
.last_prompt
= prompt
150 return buf
.replace("^M", "\r")
153 def writeline(self
, str):
155 return bytes(s
, "utf-8") if IS_PY_3
else s
157 self
.stdin
.write(_to_bytes(str.replace('\r', '\x16\r') + self
.line_break
))
163 os
.killpg(self
.p
.pid
, signal
.SIGTERM
)
169 def __init__(self
, test_file
):
171 f
= open(test_file
, newline
='') if IS_PY_3
else open(test_file
)
172 self
.data
= f
.read().split('\n')
174 self
.deferrable
= False
175 self
.optional
= False
185 line
= self
.data
.pop(0)
186 if re
.match(r
"^\s*$", line
): # blank line
188 elif line
[0:3] == ";;;": # ignore comment
190 elif line
[0:2] == ";;": # output comment
193 elif line
[0:5] == ";>>> ": # settings/commands
195 exec(line
[5:], {}, settings
)
196 if 'soft' in settings
:
197 self
.soft
= settings
['soft']
198 if 'deferrable' in settings
and settings
['deferrable']:
199 self
.deferrable
= "\nSkipping deferrable and optional tests"
201 if 'optional' in settings
and settings
['optional']:
202 self
.optional
= "\nSkipping optional tests"
205 elif line
[0:1] == ";": # unexpected comment
206 raise Exception("Test data error at line %d:\n%s" % (self
.line_num
, line
))
207 self
.form
= line
# the line is a form to send
209 # Now find the output and return value
212 if line
[0:3] == ";=>":
217 elif line
[0:2] == ";/":
218 self
.out
= self
.out
+ line
[2:] + sep
224 if self
.ret
!= None: break
226 if self
.out
[-2:] == sep
and not self
.ret
:
227 # If there is no return value, output should not end in
229 self
.out
= self
.out
[0:-2]
232 args
= parser
.parse_args(sys
.argv
[1:])
233 # Workaround argparse issue with two '--' on command line
234 if sys
.argv
.count('--') > 0:
235 args
.mal_cmd
= sys
.argv
[sys
.argv
.index('--')+1:]
237 if args
.rundir
: os
.chdir(args
.rundir
)
239 if args
.log_file
: log_file
= open(args
.log_file
, "a")
240 if args
.debug_file
: debug_file
= open(args
.debug_file
, "a")
242 r
= Runner(args
.mal_cmd
, no_pty
=args
.no_pty
, line_break
="\r\n" if args
.crlf
else "\n")
243 t
= TestReader(args
.test_file
)
246 def assert_prompt(runner
, prompts
, timeout
):
247 # Wait for the initial prompt
248 header
= runner
.read_to_prompt(prompts
, timeout
=timeout
)
249 if not header
== None:
251 log("Started with:\n%s" % header
)
253 log("Did not receive one of following prompt(s): %s" % repr(prompts
))
254 log(" Got : %s" % repr(r
.buf
))
258 # Wait for the initial prompt
260 assert_prompt(r
, ['[^\s()<>]+> '], args
.start_timeout
)
262 _
, exc
, _
= sys
.exc_info()
263 log("\nException: %s" % repr(exc
))
264 log("Output before exception:\n%s" % r
.buf
)
267 # Send the pre-eval code if any
269 sys
.stdout
.write("RUNNING pre-eval: %s" % args
.pre_eval
)
270 r
.writeline(args
.pre_eval
)
271 assert_prompt(r
, ['[^\s()<>]+> '], args
.test_timeout
)
280 if args
.deferrable
== False and t
.deferrable
:
284 if args
.optional
== False and t
.optional
:
292 if t
.form
== None: continue
294 log("TEST: %s -> [%s,%s]" % (repr(t
.form
), repr(t
.out
), t
.ret
), end
='')
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
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
))]
308 res
= r
.read_to_prompt(['\r\n[^\s()<>]+> ', '\n[^\s()<>]+> '],
309 timeout
=args
.test_timeout
)
310 #print "%s,%s,%s" % (idx, repr(p.before), repr(p.after))
311 if (t
.ret
== "" and t
.out
== ""):
312 log(" -> SUCCESS (result ignored)")
314 elif (re
.search(expects
[0], res
, re
.S
) or
315 re
.search(expects
[1], res
, re
.S
)):
319 if t
.soft
and not args
.hard
:
320 log(" -> SOFT FAIL (line %d):" % t
.line_num
)
324 log(" -> FAIL (line %d):" % t
.line_num
)
327 log(" Expected : %s" % repr(expects
[0]))
328 log(" Got : %s" % repr(res
))
329 failed_test
= """%sFAILED TEST (line %d): %s -> [%s,%s]:
331 Got : %s""" % (fail_type
, t
.line_num
, t
.form
, repr(t
.out
),
332 t
.ret
, repr(expects
[0]), repr(res
))
333 failures
.append(failed_test
)
335 _
, exc
, _
= sys
.exc_info()
336 log("\nException: %s" % repr(exc
))
337 log("Output before exception:\n%s" % r
.buf
)
340 if len(failures
) > 0:
346 TEST RESULTS (for %s):
347 %3d: soft failing tests
351 """ % (args
.test_file
, soft_fail_cnt
, fail_cnt
,
355 debug("\n") # add some separate to debug log