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
33 if platform
.system().find("CYGWIN_NT") >= 0:
34 # TODO: this is weird, is this really right on Cygwin?
40 parser
= argparse
.ArgumentParser(
41 description
="Run a test file against a Mal implementation")
42 parser
.add_argument('--rundir',
43 help="change to the directory before running tests")
44 parser
.add_argument('--start-timeout', default
=10, type=int,
45 help="default timeout for initial prompt")
46 parser
.add_argument('--test-timeout', default
=20, type=int,
47 help="default timeout for each individual test action")
48 parser
.add_argument('--pre-eval', default
=None, type=str,
49 help="Mal code to evaluate prior to running the test")
50 parser
.add_argument('--no-pty', action
='store_true',
51 help="Use direct pipes instead of pseudo-tty")
52 parser
.add_argument('--log-file', type=str,
53 help="Write messages to the named file in addition the screen")
54 parser
.add_argument('--debug-file', type=str,
55 help="Write all test interaction the named file")
56 parser
.add_argument('--hard', action
='store_true',
57 help="Turn soft tests following a ';>>> soft=True' into hard failures")
59 # Control whether deferrable and optional tests are executed
60 parser
.add_argument('--deferrable', dest
='deferrable', action
='store_true',
61 help="Enable deferrable tests that follow a ';>>> deferrable=True'")
62 parser
.add_argument('--no-deferrable', dest
='deferrable', action
='store_false',
63 help="Disable deferrable tests that follow a ';>>> deferrable=True'")
64 parser
.set_defaults(deferrable
=True)
65 parser
.add_argument('--optional', dest
='optional', action
='store_true',
66 help="Enable optional tests that follow a ';>>> optional=True'")
67 parser
.add_argument('--no-optional', dest
='optional', action
='store_false',
68 help="Disable optional tests that follow a ';>>> optional=True'")
69 parser
.set_defaults(optional
=True)
71 parser
.add_argument('test_file', type=argparse
.FileType('r'),
72 help="a test file formatted as with mal test data")
73 parser
.add_argument('mal_cmd', nargs
="*",
74 help="Mal implementation command line. Use '--' to "
75 "specify a Mal command line with dashed options.")
78 def __init__(self
, args
, no_pty
=False):
79 #print "args: %s" % repr(args)
82 # Cleanup child process on exit
83 atexit
.register(self
.cleanup
)
88 env
['INPUTRC'] = '/dev/null'
89 env
['PERL_RL'] = 'false'
91 self
.p
= Popen(args
, bufsize
=0,
92 stdin
=PIPE
, stdout
=PIPE
, stderr
=STDOUT
,
95 self
.stdin
= self
.p
.stdin
96 self
.stdout
= self
.p
.stdout
98 # provide tty to get 'interactive' readline to work
99 master
, slave
= pty
.openpty()
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)
106 self
.p
= Popen(args
, bufsize
=0,
107 stdin
=slave
, stdout
=slave
, stderr
=STDOUT
,
108 preexec_fn
=os
.setsid
,
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
114 self
.stdin
= os
.fdopen(master
, 'r+b', 0)
115 self
.stdout
= self
.stdin
119 self
.last_prompt
= ""
121 def read_to_prompt(self
, prompts
, timeout
):
122 end_time
= time
.time() + timeout
123 while time
.time() < end_time
:
124 [outs
,_
,_
] = select([self
.stdout
], [], [], 1)
125 if self
.stdout
in outs
:
126 new_data
= self
.stdout
.read(1)
127 new_data
= new_data
.decode("utf-8") if IS_PY_3
else new_data
128 #print("new_data: '%s'" % new_data)
130 # Perform newline cleanup
132 self
.buf
+= new_data
.replace("\n", "\r\n")
135 self
.buf
= self
.buf
.replace("\r\r", "\r")
136 for prompt
in prompts
:
137 regexp
= re
.compile(prompt
)
138 match
= regexp
.search(self
.buf
)
141 buf
= self
.buf
[0:end
-len(prompt
)]
142 self
.buf
= self
.buf
[end
:]
143 self
.last_prompt
= prompt
147 def writeline(self
, str):
149 return bytes(s
, "utf-8") if IS_PY_3
else s
151 self
.stdin
.write(_to_bytes(str + "\n"))
157 os
.killpg(self
.p
.pid
, signal
.SIGTERM
)
163 def __init__(self
, test_file
):
165 self
.data
= test_file
.read().split('\n')
167 self
.deferrable
= False
168 self
.optional
= False
178 line
= self
.data
.pop(0)
179 if re
.match(r
"^\s*$", line
): # blank line
181 elif line
[0:3] == ";;;": # ignore comment
183 elif line
[0:2] == ";;": # output comment
186 elif line
[0:5] == ";>>> ": # settings/commands
188 exec(line
[5:], {}, settings
)
189 if 'soft' in settings
:
190 self
.soft
= settings
['soft']
191 if 'deferrable' in settings
and settings
['deferrable']:
192 self
.deferrable
= "\nSkipping deferrable and optional tests"
194 if 'optional' in settings
and settings
['optional']:
195 self
.optional
= "\nSkipping optional tests"
198 elif line
[0:1] == ";": # unexpected comment
199 log("Test data error at line %d:\n%s" % (self
.line_num
, line
))
201 self
.form
= line
# the line is a form to send
203 # Now find the output and return value
206 if line
[0:3] == ";=>":
211 elif line
[0:2] == "; ":
212 self
.out
= self
.out
+ line
[2:] + sep
222 args
= parser
.parse_args(sys
.argv
[1:])
223 # Workaround argparse issue with two '--' on command line
224 if sys
.argv
.count('--') > 0:
225 args
.mal_cmd
= sys
.argv
[sys
.argv
.index('--')+1:]
227 if args
.rundir
: os
.chdir(args
.rundir
)
229 if args
.log_file
: log_file
= open(args
.log_file
, "a")
230 if args
.debug_file
: debug_file
= open(args
.debug_file
, "a")
232 r
= Runner(args
.mal_cmd
, no_pty
=args
.no_pty
)
233 t
= TestReader(args
.test_file
)
236 def assert_prompt(runner
, prompts
, timeout
):
237 # Wait for the initial prompt
238 header
= runner
.read_to_prompt(prompts
, timeout
=timeout
)
239 if not header
== None:
241 log("Started with:\n%s" % header
)
243 log("Did not one of following prompt(s): %s" % repr(prompts
))
244 log(" Got : %s" % repr(r
.buf
))
248 # Wait for the initial prompt
250 assert_prompt(r
, ['user> ', 'mal-user> '], args
.start_timeout
)
252 _
, exc
, _
= sys
.exc_info()
253 log("\nException: %s" % repr(exc
))
254 log("Output before exception:\n%s" % r
.buf
)
257 # Send the pre-eval code if any
259 sys
.stdout
.write("RUNNING pre-eval: %s" % args
.pre_eval
)
260 p
.write(args
.pre_eval
)
261 assert_prompt(args
.test_timeout
)
270 if args
.deferrable
== False and t
.deferrable
:
274 if args
.optional
== False and t
.optional
:
282 if t
.form
== None: continue
284 log("TEST: %s -> [%s,%s]" % (t
.form
, repr(t
.out
), t
.ret
), end
='')
286 # The repeated form is to get around an occasional OS X issue
287 # where the form is repeated.
288 # https://github.com/kanaka/mal/issues/30
289 expected
= ["%s%s%s%s" % (t
.form
, sep
, t
.out
, t
.ret
),
290 "%s%s%s%s%s%s" % (t
.form
, sep
, t
.form
, sep
, t
.out
, t
.ret
)]
295 res
= r
.read_to_prompt(['\r\nuser> ', '\nuser> ',
296 '\r\nmal-user> ', '\nmal-user> '],
297 timeout
=args
.test_timeout
)
298 #print "%s,%s,%s" % (idx, repr(p.before), repr(p.after))
299 if t
.ret
== "*" or res
in expected
:
303 if t
.soft
and not args
.hard
:
304 log(" -> SOFT FAIL (line %d):" % t
.line_num
)
308 log(" -> FAIL (line %d):" % t
.line_num
)
311 log(" Expected : %s" % repr(expected
[0]))
312 log(" Got : %s" % repr(res
))
313 failed_test
= """%sFAILED TEST (line %d): %s -> [%s,%s]:
315 Got : %s""" % (fail_type
, t
.line_num
, t
.form
, repr(t
.out
), t
.ret
, repr(expected
[0]), repr(res
))
316 failures
.append(failed_test
)
318 _
, exc
, _
= sys
.exc_info()
319 log("\nException: %s" % repr(exc
))
320 log("Output before exception:\n%s" % r
.buf
)
323 if len(failures
) > 0:
329 TEST RESULTS (for %s):
330 %3d: soft failing tests
334 """ % (args
.test_file
.name
, soft_fail_cnt
, fail_cnt
,
338 debug("\n") # add some separate to debug log