blob: 1da78dd793cd575167bd50ada9feca2f7843f5d4 [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
Daniel Dunbar9a676b72009-07-29 02:57:25 +000012
13 - Support "disabling" tests? The advantage of making this distinct from XFAIL
14 is it makes it more obvious that it is a temporary measure (and MTR can put
15 in a separate category).
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000016"""
17
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000018import os, sys, re, random, time
19import threading
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000020from Queue import Queue
21
Daniel Dunbar1db467f2009-07-31 05:54:17 +000022import ProgressBar
23import TestRunner
24import Util
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000025
Daniel Dunbar1db467f2009-07-31 05:54:17 +000026from TestingConfig import TestingConfig
27from TestRunner import TestStatus
28
29kConfigName = 'lit.cfg'
30
31def getTests(cfg, inputs):
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000032 for path in inputs:
33 if not os.path.exists(path):
Daniel Dunbar1db467f2009-07-31 05:54:17 +000034 Util.warning('Invalid test %r' % path)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000035 continue
36
Daniel Dunbara957d992009-07-25 14:46:05 +000037 if not os.path.isdir(path):
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000038 yield path
Daniel Dunbared92df02009-07-31 18:12:18 +000039 continue
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000040
Daniel Dunbar1db467f2009-07-31 05:54:17 +000041 foundOne = False
Daniel Dunbara957d992009-07-25 14:46:05 +000042 for dirpath,dirnames,filenames in os.walk(path):
43 # FIXME: This doesn't belong here
44 if 'Output' in dirnames:
45 dirnames.remove('Output')
46 for f in filenames:
47 base,ext = os.path.splitext(f)
Daniel Dunbar1db467f2009-07-31 05:54:17 +000048 if ext in cfg.suffixes:
Daniel Dunbara957d992009-07-25 14:46:05 +000049 yield os.path.join(dirpath,f)
Daniel Dunbar1db467f2009-07-31 05:54:17 +000050 foundOne = True
51 if not foundOne:
52 Util.warning('No tests in input directory %r' % path)
Daniel Dunbara957d992009-07-25 14:46:05 +000053
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000054class TestingProgressDisplay:
55 def __init__(self, opts, numTests, progressBar=None):
56 self.opts = opts
57 self.numTests = numTests
58 self.digits = len(str(self.numTests))
59 self.current = None
60 self.lock = threading.Lock()
61 self.progressBar = progressBar
62 self.progress = 0.
63
64 def update(self, index, tr):
65 # Avoid locking overhead in quiet mode
66 if self.opts.quiet and not tr.failed():
67 return
68
69 # Output lock
70 self.lock.acquire()
71 try:
72 self.handleUpdate(index, tr)
73 finally:
74 self.lock.release()
75
76 def finish(self):
77 if self.progressBar:
78 self.progressBar.clear()
79 elif self.opts.succinct:
80 sys.stdout.write('\n')
81
82 def handleUpdate(self, index, tr):
83 if self.progressBar:
84 if tr.failed():
85 self.progressBar.clear()
86 else:
87 # Force monotonicity
88 self.progress = max(self.progress, float(index)/self.numTests)
89 self.progressBar.update(self.progress, tr.path)
90 return
91 elif self.opts.succinct:
92 if not tr.failed():
93 sys.stdout.write('.')
94 sys.stdout.flush()
95 return
96 else:
97 sys.stdout.write('\n')
98
Daniel Dunbara957d992009-07-25 14:46:05 +000099 status = TestStatus.getName(tr.code).upper()
100 print '%s: %s (%*d of %*d)' % (status, tr.path,
101 self.digits, index+1,
102 self.digits, self.numTests)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000103
Daniel Dunbar360d16c2009-04-23 05:03:44 +0000104 if tr.failed() and self.opts.showOutput:
Daniel Dunbara957d992009-07-25 14:46:05 +0000105 print "%s TEST '%s' FAILED %s" % ('*'*20, tr.path, '*'*20)
106 print tr.output
107 print "*" * 20
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000108
109class TestResult:
Daniel Dunbara957d992009-07-25 14:46:05 +0000110 def __init__(self, path, code, output, elapsed):
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000111 self.path = path
112 self.code = code
Daniel Dunbara957d992009-07-25 14:46:05 +0000113 self.output = output
Daniel Dunbar7f106812009-07-11 22:46:27 +0000114 self.elapsed = elapsed
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000115
116 def failed(self):
117 return self.code in (TestStatus.Fail,TestStatus.XPass)
118
119class TestProvider:
Daniel Dunbar1db467f2009-07-31 05:54:17 +0000120 def __init__(self, config, opts, tests, display):
121 self.config = config
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000122 self.opts = opts
123 self.tests = tests
124 self.index = 0
125 self.lock = threading.Lock()
126 self.results = [None]*len(self.tests)
127 self.startTime = time.time()
128 self.progress = display
129
130 def get(self):
131 self.lock.acquire()
132 try:
133 if self.opts.maxTime is not None:
134 if time.time() - self.startTime > self.opts.maxTime:
135 return None
136 if self.index >= len(self.tests):
137 return None
138 item = self.tests[self.index],self.index
139 self.index += 1
140 return item
141 finally:
142 self.lock.release()
143
144 def setResult(self, index, result):
145 self.results[index] = result
146 self.progress.update(index, result)
147
148class Tester(threading.Thread):
149 def __init__(self, provider):
150 threading.Thread.__init__(self)
151 self.provider = provider
152
153 def run(self):
154 while 1:
155 item = self.provider.get()
156 if item is None:
157 break
158 self.runTest(item)
159
Daniel Dunbara957d992009-07-25 14:46:05 +0000160 def runTest(self, (path, index)):
Daniel Dunbardf084892009-07-25 09:53:43 +0000161 base = TestRunner.getTestOutputBase('Output', path)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000162 numTests = len(self.provider.tests)
163 digits = len(str(numTests))
164 code = None
Daniel Dunbar7f106812009-07-11 22:46:27 +0000165 elapsed = None
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000166 try:
167 opts = self.provider.opts
Daniel Dunbar1db467f2009-07-31 05:54:17 +0000168 startTime = time.time()
169 code, output = TestRunner.runOneTest(self.provider.config,
Daniel Dunbar5928ccd2009-08-01 04:06:02 +0000170 path, base)
Daniel Dunbar1db467f2009-07-31 05:54:17 +0000171 elapsed = time.time() - startTime
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000172 except KeyboardInterrupt:
173 # This is a sad hack. Unfortunately subprocess goes
174 # bonkers with ctrl-c and we start forking merrily.
Daniel Dunbar5928ccd2009-08-01 04:06:02 +0000175 print '\nCtrl-C detected, goodbye.'
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000176 os.kill(0,9)
177
Daniel Dunbara957d992009-07-25 14:46:05 +0000178 self.provider.setResult(index, TestResult(path, code, output, elapsed))
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000179
Daniel Dunbar1db467f2009-07-31 05:54:17 +0000180def findConfigPath(root):
181 prev = None
182 while root != prev:
183 cfg = os.path.join(root, kConfigName)
184 if os.path.exists(cfg):
185 return cfg
186
187 prev,root = root,os.path.dirname(root)
188
189 raise ValueError,"Unable to find config file %r" % kConfigName
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000190
Daniel Dunbar2bdccea2009-08-01 03:35:40 +0000191def runTests(opts, provider):
192 # If only using one testing thread, don't use threads at all; this lets us
193 # profile, among other things.
194 if opts.numThreads == 1:
195 t = Tester(provider)
196 t.run()
197 return
198
199 # Otherwise spin up the testing threads and wait for them to finish.
200 testers = [Tester(provider) for i in range(opts.numThreads)]
201 for t in testers:
202 t.start()
203 try:
204 for t in testers:
205 t.join()
206 except KeyboardInterrupt:
207 sys.exit(1)
208
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000209def main():
210 global options
Daniel Dunbar1db467f2009-07-31 05:54:17 +0000211 from optparse import OptionParser, OptionGroup
212 parser = OptionParser("usage: %prog [options] {file-or-path}")
213
214 parser.add_option("", "--root", dest="root",
215 help="Path to root test directory",
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000216 action="store", default=None)
Daniel Dunbar1db467f2009-07-31 05:54:17 +0000217 parser.add_option("", "--config", dest="config",
Daniel Dunbar414be142009-08-01 23:09:12 +0000218 help="Testing configuration file [default='%s']" % kConfigName,
219 action="store", default=None)
Daniel Dunbar1db467f2009-07-31 05:54:17 +0000220
221 group = OptionGroup(parser, "Output Format")
222 # FIXME: I find these names very confusing, although I like the
223 # functionality.
224 group.add_option("-q", "--quiet", dest="quiet",
225 help="Suppress no error output",
226 action="store_true", default=False)
227 group.add_option("-s", "--succinct", dest="succinct",
228 help="Reduce amount of output",
229 action="store_true", default=False)
230 group.add_option("-v", "--verbose", dest="showOutput",
231 help="Show all test output",
232 action="store_true", default=False)
233 group.add_option("", "--no-progress-bar", dest="useProgressBar",
234 help="Do not use curses based progress bar",
235 action="store_false", default=True)
236 parser.add_option_group(group)
237
238 group = OptionGroup(parser, "Test Execution")
239 group.add_option("-j", "--threads", dest="numThreads",
240 help="Number of testing threads",
241 type=int, action="store",
242 default=None)
243 group.add_option("", "--clang", dest="clang",
244 help="Program to use as \"clang\"",
245 action="store", default=None)
246 group.add_option("", "--clang-cc", dest="clangcc",
247 help="Program to use as \"clang-cc\"",
248 action="store", default=None)
249 group.add_option("", "--path", dest="path",
250 help="Additional paths to add to testing environment",
251 action="append", type=str, default=[])
Daniel Dunbar0dec8382009-08-01 10:18:01 +0000252 group.add_option("", "--no-sh", dest="useExternalShell",
253 help="Run tests using an external shell",
254 action="store_false", default=True)
Daniel Dunbar1db467f2009-07-31 05:54:17 +0000255 group.add_option("", "--vg", dest="useValgrind",
256 help="Run tests under valgrind",
257 action="store_true", default=False)
258 group.add_option("", "--time-tests", dest="timeTests",
259 help="Track elapsed wall time for each test",
260 action="store_true", default=False)
261 parser.add_option_group(group)
262
263 group = OptionGroup(parser, "Test Selection")
264 group.add_option("", "--max-tests", dest="maxTests",
265 help="Maximum number of tests to run",
266 action="store", type=int, default=None)
267 group.add_option("", "--max-time", dest="maxTime",
268 help="Maximum time to spend testing (in seconds)",
269 action="store", type=float, default=None)
270 group.add_option("", "--shuffle", dest="shuffle",
271 help="Run tests in random order",
272 action="store_true", default=False)
273 parser.add_option_group(group)
Douglas Gregor79865192009-06-05 23:57:17 +0000274
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000275 (opts, args) = parser.parse_args()
Daniel Dunbar1db467f2009-07-31 05:54:17 +0000276
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000277 if not args:
278 parser.error('No inputs specified')
279
Daniel Dunbar1db467f2009-07-31 05:54:17 +0000280 if opts.numThreads is None:
281 opts.numThreads = Util.detectCPUs()
282
283 inputs = args
284
285 # Resolve root if not given, either infer it from the config file if given,
286 # otherwise from the inputs.
287 if not opts.root:
288 if opts.config:
289 opts.root = os.path.dirname(opts.config)
290 else:
291 opts.root = os.path.commonprefix(inputs)
292
293 # Find the config file, if not specified.
294 if not opts.config:
295 try:
296 opts.config = findConfigPath(opts.root)
297 except ValueError,e:
298 parser.error(e.args[0])
299
300 cfg = TestingConfig.frompath(opts.config)
301
302 # Update the configuration based on the command line arguments.
303 for name in ('PATH','SYSTEMROOT'):
304 if name in cfg.environment:
305 parser.error("'%s' should not be set in configuration!" % name)
306
307 cfg.root = opts.root
308 cfg.environment['PATH'] = os.pathsep.join(opts.path +
309 [os.environ.get('PATH','')])
310 cfg.environment['SYSTEMROOT'] = os.environ.get('SYSTEMROOT','')
Daniel Dunbar67796472009-07-27 19:01:13 +0000311
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000312 if opts.clang is None:
Daniel Dunbar1db467f2009-07-31 05:54:17 +0000313 opts.clang = TestRunner.inferClang(cfg)
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000314 if opts.clangcc is None:
Daniel Dunbar1db467f2009-07-31 05:54:17 +0000315 opts.clangcc = TestRunner.inferClangCC(cfg, opts.clang)
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000316
Daniel Dunbar5928ccd2009-08-01 04:06:02 +0000317 cfg.clang = opts.clang
318 cfg.clangcc = opts.clangcc
319 cfg.useValgrind = opts.useValgrind
Daniel Dunbar0dec8382009-08-01 10:18:01 +0000320 cfg.useExternalShell = opts.useExternalShell
Daniel Dunbar5928ccd2009-08-01 04:06:02 +0000321
Daniel Dunbar259a5652009-04-26 01:28:51 +0000322 # FIXME: It could be worth loading these in parallel with testing.
Daniel Dunbar1db467f2009-07-31 05:54:17 +0000323 allTests = list(getTests(cfg, args))
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000324 allTests.sort()
325
326 tests = allTests
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000327 if opts.shuffle:
328 random.shuffle(tests)
329 if opts.maxTests is not None:
330 tests = tests[:opts.maxTests]
Daniel Dunbar67796472009-07-27 19:01:13 +0000331
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000332 extra = ''
333 if len(tests) != len(allTests):
334 extra = ' of %d'%(len(allTests),)
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000335 header = '-- Testing: %d%s tests, %d threads --'%(len(tests),extra,
336 opts.numThreads)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000337
338 progressBar = None
339 if not opts.quiet:
340 if opts.useProgressBar:
341 try:
342 tc = ProgressBar.TerminalController()
343 progressBar = ProgressBar.ProgressBar(tc, header)
344 except ValueError:
345 pass
346
347 if not progressBar:
348 print header
349
Daniel Dunbar2bdccea2009-08-01 03:35:40 +0000350 # Don't create more threads than tests.
351 opts.numThreads = min(len(tests), opts.numThreads)
352
353 startTime = time.time()
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000354 display = TestingProgressDisplay(opts, len(tests), progressBar)
Daniel Dunbar1db467f2009-07-31 05:54:17 +0000355 provider = TestProvider(cfg, opts, tests, display)
Daniel Dunbar2bdccea2009-08-01 03:35:40 +0000356 runTests(opts, provider)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000357 display.finish()
358
359 if not opts.quiet:
360 print 'Testing Time: %.2fs'%(time.time() - startTime)
361
Daniel Dunbar1db467f2009-07-31 05:54:17 +0000362 # List test results organized by kind.
Daniel Dunbar259a5652009-04-26 01:28:51 +0000363 byCode = {}
364 for t in provider.results:
365 if t:
366 if t.code not in byCode:
367 byCode[t.code] = []
368 byCode[t.code].append(t)
Daniel Dunbarcddab4a2009-07-30 01:57:45 +0000369 for title,code in (('Unexpected Passing Tests', TestStatus.XPass),
Daniel Dunbar259a5652009-04-26 01:28:51 +0000370 ('Failing Tests', TestStatus.Fail)):
371 elts = byCode.get(code)
372 if not elts:
373 continue
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000374 print '*'*20
Daniel Dunbar259a5652009-04-26 01:28:51 +0000375 print '%s (%d):' % (title, len(elts))
376 for tr in elts:
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000377 print '\t%s'%(tr.path,)
378
Daniel Dunbar259a5652009-04-26 01:28:51 +0000379 numFailures = len(byCode.get(TestStatus.Fail,[]))
380 if numFailures:
381 print '\nFailures: %d' % (numFailures,)
Douglas Gregor4d1800d2009-06-16 23:40:23 +0000382 sys.exit(1)
383
Daniel Dunbar7f106812009-07-11 22:46:27 +0000384 if opts.timeTests:
Daniel Dunbar3ed4bd12009-07-16 21:18:21 +0000385 print '\nTest Times:'
Daniel Dunbar7f106812009-07-11 22:46:27 +0000386 provider.results.sort(key=lambda t: t and t.elapsed)
387 for tr in provider.results:
388 if tr:
389 print '%.2fs: %s' % (tr.elapsed, tr.path)
390
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000391if __name__=='__main__':
392 main()