blob: 53c1cdbb18c818b5e8e2ab993912e1983127d68b [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--
Daniel Dunbara0e52d62009-07-25 13:19:40 +00008 - Use configuration file for clang specific stuff
9 - Use a timeout / ulimit
10 - Detect signaled failures (abort)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000011 - 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:
Daniel Dunbarfecdd002009-07-25 12:05:55 +000026 # Always use absolte paths.
27 path = os.path.abspath(path)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000028 if not os.path.exists(path):
29 print >>sys.stderr,"WARNING: Invalid test \"%s\""%(path,)
30 continue
31
32 if os.path.isdir(path):
33 for dirpath,dirnames,filenames in os.walk(path):
34 dotTests = os.path.join(dirpath,'.tests')
35 if os.path.exists(dotTests):
36 for ln in open(dotTests):
37 if ln.strip():
38 yield os.path.join(dirpath,ln.strip())
39 else:
40 # FIXME: This doesn't belong here
41 if 'Output' in dirnames:
42 dirnames.remove('Output')
43 for f in filenames:
44 base,ext = os.path.splitext(f)
45 if ext in kTestFileExtensions:
46 yield os.path.join(dirpath,f)
47 else:
48 yield path
49
50class TestingProgressDisplay:
51 def __init__(self, opts, numTests, progressBar=None):
52 self.opts = opts
53 self.numTests = numTests
54 self.digits = len(str(self.numTests))
55 self.current = None
56 self.lock = threading.Lock()
57 self.progressBar = progressBar
58 self.progress = 0.
59
60 def update(self, index, tr):
61 # Avoid locking overhead in quiet mode
62 if self.opts.quiet and not tr.failed():
63 return
64
65 # Output lock
66 self.lock.acquire()
67 try:
68 self.handleUpdate(index, tr)
69 finally:
70 self.lock.release()
71
72 def finish(self):
73 if self.progressBar:
74 self.progressBar.clear()
75 elif self.opts.succinct:
76 sys.stdout.write('\n')
77
78 def handleUpdate(self, index, tr):
79 if self.progressBar:
80 if tr.failed():
81 self.progressBar.clear()
82 else:
83 # Force monotonicity
84 self.progress = max(self.progress, float(index)/self.numTests)
85 self.progressBar.update(self.progress, tr.path)
86 return
87 elif self.opts.succinct:
88 if not tr.failed():
89 sys.stdout.write('.')
90 sys.stdout.flush()
91 return
92 else:
93 sys.stdout.write('\n')
94
95 extra = ''
96 if tr.code==TestStatus.Invalid:
97 extra = ' - (Invalid test)'
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000098 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
Daniel Dunbardf084892009-07-25 09:53:43 +0000158 base = TestRunner.getTestOutputBase('Output', path)
159 output = base + '.out'
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000160 testname = path
Daniel Dunbardf084892009-07-25 09:53:43 +0000161 testresults = base + '.testresults'
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000162 TestRunner.mkdir_p(os.path.dirname(testresults))
163 numTests = len(self.provider.tests)
164 digits = len(str(numTests))
165 code = None
Daniel Dunbar7f106812009-07-11 22:46:27 +0000166 elapsed = None
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000167 try:
168 opts = self.provider.opts
169 if opts.debugDoNotTest:
170 code = None
171 else:
Daniel Dunbar7f106812009-07-11 22:46:27 +0000172 startTime = time.time()
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000173 code = TestRunner.runOneTest(path, command, output, testname,
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000174 opts.clang, opts.clangcc,
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000175 output=open(testresults,'w'))
Daniel Dunbar7f106812009-07-11 22:46:27 +0000176 elapsed = time.time() - startTime
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000177 except KeyboardInterrupt:
178 # This is a sad hack. Unfortunately subprocess goes
179 # bonkers with ctrl-c and we start forking merrily.
180 print 'Ctrl-C detected, goodbye.'
181 os.kill(0,9)
182
Daniel Dunbar7f106812009-07-11 22:46:27 +0000183 self.provider.setResult(index, TestResult(path, code, testresults,
184 elapsed))
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000185
186def detectCPUs():
187 """
188 Detects the number of CPUs on a system. Cribbed from pp.
189 """
190 # Linux, Unix and MacOS:
191 if hasattr(os, "sysconf"):
192 if os.sysconf_names.has_key("SC_NPROCESSORS_ONLN"):
193 # Linux & Unix:
194 ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
195 if isinstance(ncpus, int) and ncpus > 0:
196 return ncpus
197 else: # OSX:
198 return int(os.popen2("sysctl -n hw.ncpu")[1].read())
199 # Windows:
200 if os.environ.has_key("NUMBER_OF_PROCESSORS"):
201 ncpus = int(os.environ["NUMBER_OF_PROCESSORS"]);
202 if ncpus > 0:
203 return ncpus
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000204 return 1 # Default
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000205
206def main():
207 global options
208 from optparse import OptionParser
209 parser = OptionParser("usage: %prog [options] {inputs}")
210 parser.add_option("-j", "--threads", dest="numThreads",
211 help="Number of testing threads",
212 type=int, action="store",
213 default=detectCPUs())
214 parser.add_option("", "--clang", dest="clang",
215 help="Program to use as \"clang\"",
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000216 action="store", default=None)
217 parser.add_option("", "--clang-cc", dest="clangcc",
218 help="Program to use as \"clang-cc\"",
219 action="store", default=None)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000220 parser.add_option("", "--vg", dest="useValgrind",
221 help="Run tests under valgrind",
222 action="store_true", default=False)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000223 parser.add_option("-v", "--verbose", dest="showOutput",
224 help="Show all test output",
225 action="store_true", default=False)
226 parser.add_option("-q", "--quiet", dest="quiet",
227 help="Suppress no error output",
228 action="store_true", default=False)
229 parser.add_option("-s", "--succinct", dest="succinct",
230 help="Reduce amount of output",
231 action="store_true", default=False)
232 parser.add_option("", "--max-tests", dest="maxTests",
233 help="Maximum number of tests to run",
234 action="store", type=int, default=None)
235 parser.add_option("", "--max-time", dest="maxTime",
236 help="Maximum time to spend testing (in seconds)",
237 action="store", type=float, default=None)
238 parser.add_option("", "--shuffle", dest="shuffle",
239 help="Run tests in random order",
240 action="store_true", default=False)
241 parser.add_option("", "--seed", dest="seed",
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000242 help="Seed for random number generator (default: random)",
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000243 action="store", default=None)
244 parser.add_option("", "--no-progress-bar", dest="useProgressBar",
245 help="Do not use curses based progress bar",
246 action="store_false", default=True)
247 parser.add_option("", "--debug-do-not-test", dest="debugDoNotTest",
248 help="DEBUG: Skip running actual test script",
249 action="store_true", default=False)
Daniel Dunbar7f106812009-07-11 22:46:27 +0000250 parser.add_option("", "--time-tests", dest="timeTests",
251 help="Track elapsed wall time for each test",
252 action="store_true", default=False)
Douglas Gregor79865192009-06-05 23:57:17 +0000253 parser.add_option("", "--path", dest="path",
254 help="Additional paths to add to testing environment",
255 action="store", type=str, default=None)
256
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000257 (opts, args) = parser.parse_args()
258
259 if not args:
260 parser.error('No inputs specified')
Daniel Dunbar11980cc2009-07-25 13:13:06 +0000261 if opts.useValgrind:
262 parser.error('Support for running with valgrind is '
263 'temporarily disabled')
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000264
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000265 if opts.clang is None:
266 opts.clang = TestRunner.inferClang()
267 if opts.clangcc is None:
268 opts.clangcc = TestRunner.inferClangCC(opts.clang)
269
Daniel Dunbar259a5652009-04-26 01:28:51 +0000270 # FIXME: It could be worth loading these in parallel with testing.
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000271 allTests = list(getTests(args))
272 allTests.sort()
273
274 tests = allTests
275 if opts.seed is not None:
276 try:
277 seed = int(opts.seed)
278 except:
279 parser.error('--seed argument should be an integer')
280 random.seed(seed)
281 if opts.shuffle:
282 random.shuffle(tests)
283 if opts.maxTests is not None:
284 tests = tests[:opts.maxTests]
Douglas Gregor79865192009-06-05 23:57:17 +0000285 if opts.path is not None:
286 os.environ["PATH"] = opts.path + ":" + os.environ["PATH"];
Douglas Gregor79865192009-06-05 23:57:17 +0000287
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000288 extra = ''
289 if len(tests) != len(allTests):
290 extra = ' of %d'%(len(allTests),)
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000291 header = '-- Testing: %d%s tests, %d threads --'%(len(tests),extra,
292 opts.numThreads)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000293
294 progressBar = None
295 if not opts.quiet:
296 if opts.useProgressBar:
297 try:
298 tc = ProgressBar.TerminalController()
299 progressBar = ProgressBar.ProgressBar(tc, header)
300 except ValueError:
301 pass
302
303 if not progressBar:
304 print header
305
306 display = TestingProgressDisplay(opts, len(tests), progressBar)
307 provider = TestProvider(opts, tests, display)
308
309 testers = [Tester(provider) for i in range(opts.numThreads)]
310 startTime = time.time()
311 for t in testers:
312 t.start()
313 try:
314 for t in testers:
315 t.join()
316 except KeyboardInterrupt:
317 sys.exit(1)
318
319 display.finish()
320
321 if not opts.quiet:
322 print 'Testing Time: %.2fs'%(time.time() - startTime)
323
Daniel Dunbar259a5652009-04-26 01:28:51 +0000324 # List test results organized organized by kind.
325 byCode = {}
326 for t in provider.results:
327 if t:
328 if t.code not in byCode:
329 byCode[t.code] = []
330 byCode[t.code].append(t)
331 for title,code in (('Expected Failures', TestStatus.XFail),
332 ('Unexpected Passing Tests', TestStatus.XPass),
333 ('Failing Tests', TestStatus.Fail)):
334 elts = byCode.get(code)
335 if not elts:
336 continue
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000337 print '*'*20
Daniel Dunbar259a5652009-04-26 01:28:51 +0000338 print '%s (%d):' % (title, len(elts))
339 for tr in elts:
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000340 print '\t%s'%(tr.path,)
341
Daniel Dunbar259a5652009-04-26 01:28:51 +0000342 numFailures = len(byCode.get(TestStatus.Fail,[]))
343 if numFailures:
344 print '\nFailures: %d' % (numFailures,)
Douglas Gregor4d1800d2009-06-16 23:40:23 +0000345 sys.exit(1)
346
Daniel Dunbar7f106812009-07-11 22:46:27 +0000347 if opts.timeTests:
Daniel Dunbar3ed4bd12009-07-16 21:18:21 +0000348 print '\nTest Times:'
Daniel Dunbar7f106812009-07-11 22:46:27 +0000349 provider.results.sort(key=lambda t: t and t.elapsed)
350 for tr in provider.results:
351 if tr:
352 print '%.2fs: %s' % (tr.elapsed, tr.path)
353
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000354if __name__=='__main__':
355 main()