blob: c43789dad3c5a4cf1074f8dd08d3412a8962d859 [file] [log] [blame]
Eli Friedman77a1fe92009-07-10 20:15:12 +00001#!/usr/bin/env python
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +00002
3"""
4MultiTestRunner - Harness for running multiple tests in the simple clang style.
5
6TODO
7--
8 - Fix Ctrl-c issues
9 - Use a timeout
10 - Detect signalled failures (abort)
11 - Better support for finding tests
12"""
13
14# TOD
15import os, sys, re, random, time
16import threading
17import ProgressBar
18import TestRunner
19from TestRunner import TestStatus
20from Queue import Queue
21
22kTestFileExtensions = set(['.mi','.i','.c','.cpp','.m','.mm','.ll'])
23
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000024def getTests(inputs):
25 for path in inputs:
26 if not os.path.exists(path):
27 print >>sys.stderr,"WARNING: Invalid test \"%s\""%(path,)
28 continue
29
30 if os.path.isdir(path):
31 for dirpath,dirnames,filenames in os.walk(path):
32 dotTests = os.path.join(dirpath,'.tests')
33 if os.path.exists(dotTests):
34 for ln in open(dotTests):
35 if ln.strip():
36 yield os.path.join(dirpath,ln.strip())
37 else:
38 # FIXME: This doesn't belong here
39 if 'Output' in dirnames:
40 dirnames.remove('Output')
41 for f in filenames:
42 base,ext = os.path.splitext(f)
43 if ext in kTestFileExtensions:
44 yield os.path.join(dirpath,f)
45 else:
46 yield path
47
48class TestingProgressDisplay:
49 def __init__(self, opts, numTests, progressBar=None):
50 self.opts = opts
51 self.numTests = numTests
52 self.digits = len(str(self.numTests))
53 self.current = None
54 self.lock = threading.Lock()
55 self.progressBar = progressBar
56 self.progress = 0.
57
58 def update(self, index, tr):
59 # Avoid locking overhead in quiet mode
60 if self.opts.quiet and not tr.failed():
61 return
62
63 # Output lock
64 self.lock.acquire()
65 try:
66 self.handleUpdate(index, tr)
67 finally:
68 self.lock.release()
69
70 def finish(self):
71 if self.progressBar:
72 self.progressBar.clear()
73 elif self.opts.succinct:
74 sys.stdout.write('\n')
75
76 def handleUpdate(self, index, tr):
77 if self.progressBar:
78 if tr.failed():
79 self.progressBar.clear()
80 else:
81 # Force monotonicity
82 self.progress = max(self.progress, float(index)/self.numTests)
83 self.progressBar.update(self.progress, tr.path)
84 return
85 elif self.opts.succinct:
86 if not tr.failed():
87 sys.stdout.write('.')
88 sys.stdout.flush()
89 return
90 else:
91 sys.stdout.write('\n')
92
93 extra = ''
94 if tr.code==TestStatus.Invalid:
95 extra = ' - (Invalid test)'
96 elif tr.code==TestStatus.NoRunLine:
97 extra = ' - (No RUN line)'
98 elif tr.failed():
99 extra = ' - %s'%(TestStatus.getName(tr.code).upper(),)
100 print '%*d/%*d - %s%s'%(self.digits, index+1, self.digits,
101 self.numTests, tr.path, extra)
102
Daniel Dunbar360d16c2009-04-23 05:03:44 +0000103 if tr.failed() and self.opts.showOutput:
104 TestRunner.cat(tr.testResults, sys.stdout)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000105
106class TestResult:
Daniel Dunbar7f106812009-07-11 22:46:27 +0000107 def __init__(self, path, code, testResults, elapsed):
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000108 self.path = path
109 self.code = code
110 self.testResults = testResults
Daniel Dunbar7f106812009-07-11 22:46:27 +0000111 self.elapsed = elapsed
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000112
113 def failed(self):
114 return self.code in (TestStatus.Fail,TestStatus.XPass)
115
116class TestProvider:
117 def __init__(self, opts, tests, display):
118 self.opts = opts
119 self.tests = tests
120 self.index = 0
121 self.lock = threading.Lock()
122 self.results = [None]*len(self.tests)
123 self.startTime = time.time()
124 self.progress = display
125
126 def get(self):
127 self.lock.acquire()
128 try:
129 if self.opts.maxTime is not None:
130 if time.time() - self.startTime > self.opts.maxTime:
131 return None
132 if self.index >= len(self.tests):
133 return None
134 item = self.tests[self.index],self.index
135 self.index += 1
136 return item
137 finally:
138 self.lock.release()
139
140 def setResult(self, index, result):
141 self.results[index] = result
142 self.progress.update(index, result)
143
144class Tester(threading.Thread):
145 def __init__(self, provider):
146 threading.Thread.__init__(self)
147 self.provider = provider
148
149 def run(self):
150 while 1:
151 item = self.provider.get()
152 if item is None:
153 break
154 self.runTest(item)
155
156 def runTest(self, (path,index)):
157 command = path
158 # Use hand concatentation here because we want to override
159 # absolute paths.
160 output = 'Output/' + path + '.out'
161 testname = path
162 testresults = 'Output/' + path + '.testresults'
163 TestRunner.mkdir_p(os.path.dirname(testresults))
164 numTests = len(self.provider.tests)
165 digits = len(str(numTests))
166 code = None
Daniel Dunbar7f106812009-07-11 22:46:27 +0000167 elapsed = None
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000168 try:
169 opts = self.provider.opts
170 if opts.debugDoNotTest:
171 code = None
172 else:
Daniel Dunbar7f106812009-07-11 22:46:27 +0000173 startTime = time.time()
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000174 code = TestRunner.runOneTest(path, command, output, testname,
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000175 opts.clang, opts.clangcc,
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000176 useValgrind=opts.useValgrind,
177 useDGCompat=opts.useDGCompat,
178 useScript=opts.testScript,
179 output=open(testresults,'w'))
Daniel Dunbar7f106812009-07-11 22:46:27 +0000180 elapsed = time.time() - startTime
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000181 except KeyboardInterrupt:
182 # This is a sad hack. Unfortunately subprocess goes
183 # bonkers with ctrl-c and we start forking merrily.
184 print 'Ctrl-C detected, goodbye.'
185 os.kill(0,9)
186
Daniel Dunbar7f106812009-07-11 22:46:27 +0000187 self.provider.setResult(index, TestResult(path, code, testresults,
188 elapsed))
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000189
190def detectCPUs():
191 """
192 Detects the number of CPUs on a system. Cribbed from pp.
193 """
194 # Linux, Unix and MacOS:
195 if hasattr(os, "sysconf"):
196 if os.sysconf_names.has_key("SC_NPROCESSORS_ONLN"):
197 # Linux & Unix:
198 ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
199 if isinstance(ncpus, int) and ncpus > 0:
200 return ncpus
201 else: # OSX:
202 return int(os.popen2("sysctl -n hw.ncpu")[1].read())
203 # Windows:
204 if os.environ.has_key("NUMBER_OF_PROCESSORS"):
205 ncpus = int(os.environ["NUMBER_OF_PROCESSORS"]);
206 if ncpus > 0:
207 return ncpus
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000208 return 1 # Default
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000209
210def main():
211 global options
212 from optparse import OptionParser
213 parser = OptionParser("usage: %prog [options] {inputs}")
214 parser.add_option("-j", "--threads", dest="numThreads",
215 help="Number of testing threads",
216 type=int, action="store",
217 default=detectCPUs())
218 parser.add_option("", "--clang", dest="clang",
219 help="Program to use as \"clang\"",
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000220 action="store", default=None)
221 parser.add_option("", "--clang-cc", dest="clangcc",
222 help="Program to use as \"clang-cc\"",
223 action="store", default=None)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000224 parser.add_option("", "--vg", dest="useValgrind",
225 help="Run tests under valgrind",
226 action="store_true", default=False)
227 parser.add_option("", "--dg", dest="useDGCompat",
228 help="Use llvm dejagnu compatibility mode",
229 action="store_true", default=False)
230 parser.add_option("", "--script", dest="testScript",
231 help="Default script to use",
232 action="store", default=None)
233 parser.add_option("-v", "--verbose", dest="showOutput",
234 help="Show all test output",
235 action="store_true", default=False)
236 parser.add_option("-q", "--quiet", dest="quiet",
237 help="Suppress no error output",
238 action="store_true", default=False)
239 parser.add_option("-s", "--succinct", dest="succinct",
240 help="Reduce amount of output",
241 action="store_true", default=False)
242 parser.add_option("", "--max-tests", dest="maxTests",
243 help="Maximum number of tests to run",
244 action="store", type=int, default=None)
245 parser.add_option("", "--max-time", dest="maxTime",
246 help="Maximum time to spend testing (in seconds)",
247 action="store", type=float, default=None)
248 parser.add_option("", "--shuffle", dest="shuffle",
249 help="Run tests in random order",
250 action="store_true", default=False)
251 parser.add_option("", "--seed", dest="seed",
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000252 help="Seed for random number generator (default: random)",
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000253 action="store", default=None)
254 parser.add_option("", "--no-progress-bar", dest="useProgressBar",
255 help="Do not use curses based progress bar",
256 action="store_false", default=True)
257 parser.add_option("", "--debug-do-not-test", dest="debugDoNotTest",
258 help="DEBUG: Skip running actual test script",
259 action="store_true", default=False)
Daniel Dunbar7f106812009-07-11 22:46:27 +0000260 parser.add_option("", "--time-tests", dest="timeTests",
261 help="Track elapsed wall time for each test",
262 action="store_true", default=False)
Douglas Gregor79865192009-06-05 23:57:17 +0000263 parser.add_option("", "--path", dest="path",
264 help="Additional paths to add to testing environment",
265 action="store", type=str, default=None)
266
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000267 (opts, args) = parser.parse_args()
268
269 if not args:
270 parser.error('No inputs specified')
271
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000272 if opts.clang is None:
273 opts.clang = TestRunner.inferClang()
274 if opts.clangcc is None:
275 opts.clangcc = TestRunner.inferClangCC(opts.clang)
276
Daniel Dunbar259a5652009-04-26 01:28:51 +0000277 # FIXME: It could be worth loading these in parallel with testing.
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000278 allTests = list(getTests(args))
279 allTests.sort()
280
281 tests = allTests
282 if opts.seed is not None:
283 try:
284 seed = int(opts.seed)
285 except:
286 parser.error('--seed argument should be an integer')
287 random.seed(seed)
288 if opts.shuffle:
289 random.shuffle(tests)
290 if opts.maxTests is not None:
291 tests = tests[:opts.maxTests]
Douglas Gregor79865192009-06-05 23:57:17 +0000292 if opts.path is not None:
293 os.environ["PATH"] = opts.path + ":" + os.environ["PATH"];
Douglas Gregor79865192009-06-05 23:57:17 +0000294
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000295 extra = ''
296 if len(tests) != len(allTests):
297 extra = ' of %d'%(len(allTests),)
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000298 header = '-- Testing: %d%s tests, %d threads --'%(len(tests),extra,
299 opts.numThreads)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000300
301 progressBar = None
302 if not opts.quiet:
303 if opts.useProgressBar:
304 try:
305 tc = ProgressBar.TerminalController()
306 progressBar = ProgressBar.ProgressBar(tc, header)
307 except ValueError:
308 pass
309
310 if not progressBar:
311 print header
312
313 display = TestingProgressDisplay(opts, len(tests), progressBar)
314 provider = TestProvider(opts, tests, display)
315
316 testers = [Tester(provider) for i in range(opts.numThreads)]
317 startTime = time.time()
318 for t in testers:
319 t.start()
320 try:
321 for t in testers:
322 t.join()
323 except KeyboardInterrupt:
324 sys.exit(1)
325
326 display.finish()
327
328 if not opts.quiet:
329 print 'Testing Time: %.2fs'%(time.time() - startTime)
330
Daniel Dunbar259a5652009-04-26 01:28:51 +0000331 # List test results organized organized by kind.
332 byCode = {}
333 for t in provider.results:
334 if t:
335 if t.code not in byCode:
336 byCode[t.code] = []
337 byCode[t.code].append(t)
338 for title,code in (('Expected Failures', TestStatus.XFail),
339 ('Unexpected Passing Tests', TestStatus.XPass),
340 ('Failing Tests', TestStatus.Fail)):
341 elts = byCode.get(code)
342 if not elts:
343 continue
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000344 print '*'*20
Daniel Dunbar259a5652009-04-26 01:28:51 +0000345 print '%s (%d):' % (title, len(elts))
346 for tr in elts:
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000347 print '\t%s'%(tr.path,)
348
Daniel Dunbar259a5652009-04-26 01:28:51 +0000349 numFailures = len(byCode.get(TestStatus.Fail,[]))
350 if numFailures:
351 print '\nFailures: %d' % (numFailures,)
Douglas Gregor4d1800d2009-06-16 23:40:23 +0000352 sys.exit(1)
353
Daniel Dunbar7f106812009-07-11 22:46:27 +0000354 if opts.timeTests:
Daniel Dunbar3ed4bd12009-07-16 21:18:21 +0000355 print '\nTest Times:'
Daniel Dunbar7f106812009-07-11 22:46:27 +0000356 provider.results.sort(key=lambda t: t and t.elapsed)
357 for tr in provider.results:
358 if tr:
359 print '%.2fs: %s' % (tr.elapsed, tr.path)
360
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000361if __name__=='__main__':
362 main()