Debian Codegraph @

testrunner/runner.py

raw symbols SCIP
1 import sys, os, signal, thread, Queue, time
2 import py
3 import subprocess, optparse
4
5 if sys.platform == 'win32':
6 PROCESS_TERMINATE = 0x1
7 try:
8 import win32api, pywintypes
9 except ImportError:
10 def _kill(pid, sig):
11 import ctypes
12 winapi = ctypes.windll.kernel32
13 proch = winapi.OpenProcess(PROCESS_TERMINATE, 0, pid)
14 winapi.TerminateProcess(proch, 1) == 1
15 winapi.CloseHandle(proch)
16 else:
17 def _kill(pid, sig):
18 try:
19 proch = win32api.OpenProcess(PROCESS_TERMINATE, 0, pid)
20 win32api.TerminateProcess(proch, 1)
21 win32api.CloseHandle(proch)
22 except pywintypes.error, e:
23 pass
24 #Try to avoid opening a dialog box if one of the tests causes a system error
25 import ctypes
26 winapi = ctypes.windll.kernel32
27 SetErrorMode = winapi.SetErrorMode
28 SetErrorMode.argtypes=[ctypes.c_int]
29
30 SEM_FAILCRITICALERRORS = 1
31 SEM_NOGPFAULTERRORBOX = 2
32 SEM_NOOPENFILEERRORBOX = 0x8000
33 flags = SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX
34 #Since there is no GetErrorMode, do a double Set
35 old_mode = SetErrorMode(flags)
36 SetErrorMode(old_mode | flags)
37
38 SIGKILL = SIGTERM = 0
39 READ_MODE = 'rU'
40 WRITE_MODE = 'wb'
41 else:
42 def _kill(pid, sig):
43 try:
44 os.kill(pid, sig)
45 except OSError:
46 pass
47
48 SIGKILL = signal.SIGKILL
49 SIGTERM = signal.SIGTERM
50 READ_MODE = 'r'
51 WRITE_MODE = 'w'
52
53 EXECUTEFAILED = -1001
54 RUNFAILED = -1000
55 TIMEDOUT = -999
56
57 def busywait(p, timeout):
58 t0 = time.time()
59 delay = 0.5
60 while True:
61 time.sleep(delay)
62 returncode = p.poll()
63 if returncode is not None:
64 return returncode
65 tnow = time.time()
66 if (tnow-t0) >= timeout:
67 return None
68 delay = min(delay * 1.15, 7.2)
69
70 def run(args, cwd, out, timeout=None):
71 f = out.open('w')
72 try:
73 try:
74 p = subprocess.Popen(args, cwd=str(cwd), stdout=f, stderr=f)
75 except Exception, e:
76 f.write("Failed to run %s with cwd='%s' timeout=%s:\n"
77 " %s\n"
78 % (args, cwd, timeout, e))
79 return RUNFAILED
80
81 if timeout is None:
82 return p.wait()
83 else:
84 returncode = busywait(p, timeout)
85 if returncode is not None:
86 return returncode
87 # timeout!
88 f.write("Timed out running %s with cwd='%s' timeout=%s:\n"
89 " but no error, killing process\n"
90 % (args, cwd, timeout))
91 _kill(p.pid, SIGTERM)
92 if busywait(p, 10) is None:
93 _kill(p.pid, SIGKILL)
94 return TIMEDOUT
95 finally:
96 f.close()
97
98 def dry_run(args, cwd, out, timeout=None):
99 f = out.open('w')
100 try:
101 f.write("run %s with cwd='%s' timeout=%s\n" % (args, cwd, timeout))
102 finally:
103 f.close()
104 return 0
105
106 def getsignalname(n):
107 # "sorted()" to pick a deterministic answer in case of synonyms.
108 # Also, getting SIGABRT is more understandable than SIGIOT...
109 for name, value in sorted(signal.__dict__.items()):
110 if value == n and name.startswith('SIG'):
111 return name
112 return 'signal %d' % (n,)
113
114 def execute_test(cwd, test, out, logfname, interp, test_driver,
115 do_dry_run=False, timeout=None,
116 _win32=(sys.platform=='win32')):
117 args = interp + test_driver
118 args += ['-p', 'resultlog',
119 '--resultlog=%s' % logfname,
120 #'--junitxml=%s.junit' % logfname,
121 test]
122
123 args = map(str, args)
124 interp0 = args[0]
125 if (_win32 and not os.path.isabs(interp0) and
126 ('\\' in interp0 or '/' in interp0)):
127 args[0] = os.path.join(str(cwd), interp0)
128
129 if do_dry_run:
130 runfunc = dry_run
131 else:
132 runfunc = run
133
134 exitcode = runfunc(args, cwd, out, timeout=timeout)
135
136 return exitcode
137
138 def should_report_failure(logdata):
139 # When we have an exitcode of 1, it might be because of failures
140 # that occurred "regularly", or because of another crash of py.test.
141 # We decide heuristically based on logdata: if it looks like it
142 # contains "F", "E" or "P" then it's a regular failure, otherwise
143 # we have to report it.
144 for line in logdata.splitlines():
145 if (line.startswith('F ') or
146 line.startswith('E ') or
147 line.startswith('P ')):
148 return False
149 return True
150
151 def interpret_exitcode(exitcode, test, logdata=""):
152 extralog = ""
153 if exitcode not in (0, 5):
154 failure = True
155 if exitcode != 1 or should_report_failure(logdata):
156 if exitcode > 0:
157 msg = "Exit code %d." % exitcode
158 elif exitcode == TIMEDOUT:
159 msg = "TIMEOUT"
160 elif exitcode == RUNFAILED:
161 msg = "Failed to run interp"
162 elif exitcode == EXECUTEFAILED:
163 msg = "Failed with exception in execute-test"
164 else:
165 msg = "Killed by %s." % getsignalname(-exitcode)
166 extralog = "! %s\n %s\n" % (test, msg)
167 else:
168 extralog = " (somefailed=True in %s)\n" % (test,)
169 else:
170 failure = False
171 return failure, extralog
172
173 def worker(num, n, run_param, testdirs, result_queue):
174 sessdir = run_param.sessdir
175 root = run_param.root
176 get_test_driver = run_param.get_test_driver
177 interp = run_param.interp
178 dry_run = run_param.dry_run
179 timeout = run_param.timeout
180 cleanup = run_param.cleanup
181 # xxx cfg thread start
182 while 1:
183 try:
184 test = testdirs.pop(0)
185 except IndexError:
186 result_queue.put(None) # done
187 return
188 result_queue.put(('start', test))
189 basename = py.path.local(test).purebasename
190 logfname = sessdir.join("%d-%s-pytest-log" % (num, basename))
191 one_output = sessdir.join("%d-%s-output" % (num, basename))
192 num += n
193
194 try:
195 test_driver = get_test_driver(test)
196 exitcode = execute_test(root, test, one_output, logfname,
197 interp, test_driver, do_dry_run=dry_run,
198 timeout=timeout)
199
200 cleanup(test)
201 except:
202 print "execute-test for %r failed with:" % test
203 import traceback
204 traceback.print_exc()
205 exitcode = EXECUTEFAILED
206
207 if one_output.check(file=1):
208 output = one_output.read(READ_MODE)
209 else:
210 output = ""
211 if logfname.check(file=1):
212 logdata = logfname.read(READ_MODE)
213 else:
214 logdata = ""
215
216 failure, extralog = interpret_exitcode(exitcode, test, logdata)
217
218 if extralog:
219 logdata += extralog
220
221 result_queue.put(('done', test, failure, logdata, output))
222
223 invoke_in_thread = thread.start_new_thread
224
225 def start_workers(n, run_param, testdirs):
226 result_queue = Queue.Queue()
227 for i in range(n):
228 invoke_in_thread(worker, (i, n, run_param, testdirs,
229 result_queue))
230 return result_queue
231
232
233 def execute_tests(run_param, testdirs, logfile, out):
234 sessdir = py.path.local.make_numbered_dir(prefix='usession-testrunner-',
235 keep=4)
236 run_param.sessdir = sessdir
237
238 run_param.startup()
239
240 N = run_param.parallel_runs
241 if N > 1:
242 out.write("running %d parallel test workers\n" % N)
243 s = 'setting'
244 if os.environ.get('MAKEFLAGS'):
245 s = 'overriding'
246 out.write("%s MAKEFLAGS to ' ' (space)\n" % s)
247 os.environ['MAKEFLAGS'] = ' '
248 failure = False
249
250 for testname in testdirs:
251 out.write("-- %s\n" % testname)
252 out.write("-- total: %d to run\n" % len(testdirs))
253
254 result_queue = start_workers(N, run_param, testdirs)
255
256 done = 0
257 started = 0
258
259 worker_done = 0
260 while True:
261 res = result_queue.get()
262 if res is None:
263 worker_done += 1
264 if worker_done == N:
265 break
266 continue
267
268 if res[0] == 'start':
269 started += 1
270 now = time.strftime('%H:%M:%S')
271 out.write("++ %s starting %s [%d started in total]\n" % (now, res[1],
272 started))
273 continue
274
275 testname, somefailed, logdata, output = res[1:]
276 done += 1
277 failure = failure or somefailed
278
279 heading = "__ %s [%d done in total, somefailed=%s] " % (
280 testname, done, somefailed)
281
282 out.write(heading + (79-len(heading))*'_'+'\n')
283
284 out.write(output)
285 if logdata:
286 logfile.write(logdata)
287
288 run_param.shutdown()
289
290 return failure
291
292
293 class RunParam(object):
294 dry_run = False
295 interp = [os.path.abspath(sys.executable)]
296 pytestpath = os.path.abspath(os.path.join('py', 'bin', 'py.test'))
297 if not os.path.exists(pytestpath):
298 pytestpath = os.path.abspath(os.path.join('pytest.py'))
299 assert os.path.exists(pytestpath)
300 test_driver = [pytestpath]
301
302 parallel_runs = 1
303 timeout = None
304 cherrypick = None
305
306 def __init__(self, root):
307 self.root = root
308 self.self = self
309
310 def startup(self):
311 pass
312
313 def shutdown(self):
314 pass
315
316 def get_test_driver(self, testdir):
317 return self.test_driver
318
319 def is_test_py_file(self, p):
320 name = p.basename
321 if name.startswith('test_') and name.endswith('.py'):
322 return True
323 if name.startswith('apptest_') and name.endswith('.py'):
324 return True
325 return False
326
327 def reltoroot(self, p):
328 rel = p.relto(self.root)
329 return rel.replace(os.sep, '/')
330
331 def collect_one_testdir(self, testdirs, reldir, tests):
332 testdirs.append(reldir)
333 return
334
335 def collect_testdirs(self, testdirs, p=None):
336 if p is None:
337 p = self.root
338
339 reldir = self.reltoroot(p)
340 if p.check():
341 entries = [p1 for p1 in p.listdir(fil=lambda x: 'test_pypy_c' not in str(x)) if p1.check(dotfile=0)]
342 else:
343 entries = []
344 entries.sort()
345
346 collected = False
347 if p != self.root:
348 for p1 in entries:
349 if self.is_test_py_file(p1):
350 self.collect_one_testdir(testdirs, reldir,
351 [self.reltoroot(t) for t in entries
352 if self.is_test_py_file(t)])
353 collected = True
354 break
355 if not collected:
356 for p1 in entries:
357 if p1.check(dir=1, link=0):
358 self.collect_testdirs(testdirs, p1)
359
360 def cleanup(self, testdir):
361 pass
362
363
364 def main(args):
365 parser = optparse.OptionParser()
366 parser.add_option("--logfile", dest="logfile", default=None,
367 help="accumulated machine-readable logfile")
368 parser.add_option("--output", dest="output", default='-',
369 help="plain test output (default: stdout)")
370 parser.add_option("--config", dest="config", default=[],
371 action="append",
372 help="configuration python file (optional)")
373 parser.add_option("--root", dest="root", default=".",
374 help="root directory for the run")
375 parser.add_option("--parallel-runs", dest="parallel_runs", default=0,
376 type="int",
377 help="number of parallel test runs")
378 parser.add_option("--dry-run", dest="dry_run", default=False,
379 action="store_true",
380 help="dry run"),
381 parser.add_option("--timeout", dest="timeout", default=None,
382 type="int",
383 help="timeout in secs for test processes")
384 parser.add_option("--cherrypick", dest="cherrypick", default=None,
385 type=str,
386 help="tests to run, starting at ROOT")
387
388 opts, args = parser.parse_args(args)
389
390 if opts.logfile is None:
391 print "no logfile specified"
392 sys.exit(2)
393
394 logfile = open(opts.logfile, WRITE_MODE)
395 if opts.output == '-':
396 out = sys.stdout
397 else:
398 out = open(opts.output, WRITE_MODE)
399
400 root = py.path.local(opts.root)
401
402 testdirs = []
403
404 run_param = RunParam(root)
405 # the config files are python files whose run overrides the content
406 # of the run_param instance namespace
407 # in that code function overriding method should not take self
408 # though a self and self.__class__ are available if needed
409 for config_py_file in opts.config:
410 config_py_file = os.path.expanduser(config_py_file)
411 if py.path.local(config_py_file).check(file=1):
412 print >>out, "using config", config_py_file
413 execfile(config_py_file, run_param.__dict__)
414 else:
415 print >>out, "ignoring non-existant config", config_py_file
416
417 if opts.cherrypick:
418 run_param.cherrypick = opts.cherrypick.split(',')
419 if run_param.cherrypick:
420 for p in run_param.cherrypick:
421 run_param.collect_testdirs(testdirs, root.join(p))
422 else:
423 run_param.collect_testdirs(testdirs)
424
425 if opts.parallel_runs:
426 run_param.parallel_runs = opts.parallel_runs
427 if opts.timeout:
428 run_param.timeout = opts.timeout
429 run_param.dry_run = opts.dry_run
430
431 if run_param.dry_run:
432 print >>out, '\n'.join([str((k, getattr(run_param, k))) \
433 for k in dir(run_param) if k[:2] != '__'])
434
435 res = execute_tests(run_param, testdirs, logfile, out)
436
437 if res:
438 sys.exit(1)
439
440
441 if __name__ == '__main__':
442 main(sys.argv)