blob: 854d60bb408d4773dca3c1fe7caef9f73bc02c8b [file] [log] [blame]
Eli Friedman77a1fe92009-07-10 20:15:12 +00001#!/usr/bin/env python
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +00002#
3# TestRunner.py - This script is used to run arbitrary unit tests. Unit
4# tests must contain the command used to run them in the input file, starting
5# immediately after a "RUN:" string.
6#
7# This runner recognizes and replaces the following strings in the command:
8#
9# %s - Replaced with the input name of the program, or the program to
10# execute, as appropriate.
Daniel Dunbar4d8076a2009-04-10 19:49:21 +000011# %S - Replaced with the directory where the input resides.
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000012# %llvmgcc - llvm-gcc command
13# %llvmgxx - llvm-g++ command
14# %prcontext - prcontext.tcl script
15# %t - temporary file name (derived from testcase name)
16#
17
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000018import errno
Daniel Dunbar69e07a72009-06-17 21:33:37 +000019import os
Daniel Dunbar8fe83f12009-07-25 09:42:24 +000020import platform
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000021import re
Daniel Dunbar69e07a72009-06-17 21:33:37 +000022import signal
23import subprocess
24import sys
25
Daniel Dunbar78a88e72009-07-25 10:14:19 +000026# Increase determinism by explicitly choosing the environment.
Daniel Dunbar3b2505b2009-07-25 12:57:15 +000027kChildEnv = {}
28for var in ('PATH', 'SYSTEMROOT'):
29 kChildEnv[var] = os.environ.get(var, '')
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000030
Daniel Dunbar8fe83f12009-07-25 09:42:24 +000031kSystemName = platform.system()
32
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000033class TestStatus:
34 Pass = 0
35 XFail = 1
36 Fail = 2
37 XPass = 3
Daniel Dunbar8bf0ccd2009-07-25 12:47:38 +000038 Invalid = 4
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000039
Daniel Dunbar8bf0ccd2009-07-25 12:47:38 +000040 kNames = ['Pass','XFail','Fail','XPass','Invalid']
Daniel Dunbarfbbb1e72009-07-02 23:58:07 +000041 @staticmethod
Daniel Dunbar8afede22009-07-02 23:56:37 +000042 def getName(code):
43 return TestStatus.kNames[code]
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000044
45def mkdir_p(path):
46 if not path:
47 pass
48 elif os.path.exists(path):
49 pass
50 else:
51 parent = os.path.dirname(path)
52 if parent != path:
53 mkdir_p(parent)
54 try:
55 os.mkdir(path)
56 except OSError,e:
57 if e.errno != errno.EEXIST:
58 raise
59
Daniel Dunbar9a676b72009-07-29 02:57:25 +000060def executeScript(script, commands, cwd, useValgrind):
Daniel Dunbar10aebbb2009-07-25 15:26:08 +000061 # Write script file
62 f = open(script,'w')
63 if kSystemName == 'Windows':
64 f.write('\nif %ERRORLEVEL% NEQ 0 EXIT\n'.join(commands))
65 else:
66 f.write(' &&\n'.join(commands))
67 f.write('\n')
68 f.close()
69
70 if kSystemName == 'Windows':
71 command = ['cmd','/c', script]
72 else:
73 command = ['/bin/sh', script]
Daniel Dunbar9a676b72009-07-29 02:57:25 +000074 if useValgrind:
75 # FIXME: Running valgrind on sh is overkill. We probably could just
76 # ron on clang with no real loss.
77 command = ['valgrind', '-q',
78 '--tool=memcheck', '--leak-check=no', '--trace-children=yes',
79 '--error-exitcode=123'] + command
Daniel Dunbar10aebbb2009-07-25 15:26:08 +000080
81 p = subprocess.Popen(command, cwd=cwd,
82 stdin=subprocess.PIPE,
83 stdout=subprocess.PIPE,
84 stderr=subprocess.PIPE,
85 env=kChildEnv)
86 out,err = p.communicate()
87 exitCode = p.wait()
88
89 # Detect Ctrl-C in subprocess.
90 if exitCode == -signal.SIGINT:
91 raise KeyboardInterrupt
92
93 return out, err, exitCode
94
Daniel Dunbara957d992009-07-25 14:46:05 +000095import StringIO
Daniel Dunbar9a676b72009-07-29 02:57:25 +000096def runOneTest(testPath, tmpBase, clang, clangcc, useValgrind):
Daniel Dunbara957d992009-07-25 14:46:05 +000097 # Make paths absolute.
98 tmpBase = os.path.abspath(tmpBase)
99 testPath = os.path.abspath(testPath)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000100
101 # Create the output directory if it does not already exist.
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000102
Daniel Dunbara957d992009-07-25 14:46:05 +0000103 mkdir_p(os.path.dirname(tmpBase))
104 script = tmpBase + '.script'
Daniel Dunbar8fe83f12009-07-25 09:42:24 +0000105 if kSystemName == 'Windows':
Daniel Dunbara957d992009-07-25 14:46:05 +0000106 script += '.bat'
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000107
Daniel Dunbara957d992009-07-25 14:46:05 +0000108 substitutions = [('%s', testPath),
109 ('%S', os.path.dirname(testPath)),
110 ('%t', tmpBase + '.tmp'),
111 (' clang ', ' ' + clang + ' '),
112 (' clang-cc ', ' ' + clangcc + ' ')]
Daniel Dunbar025f80d2009-07-25 11:27:37 +0000113
114 # Collect the test lines from the script.
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000115 scriptLines = []
116 xfailLines = []
Daniel Dunbara957d992009-07-25 14:46:05 +0000117 for ln in open(testPath):
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000118 if 'RUN:' in ln:
Daniel Dunbar025f80d2009-07-25 11:27:37 +0000119 # Isolate the command to run.
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000120 index = ln.index('RUN:')
121 ln = ln[index+4:]
Daniel Dunbar025f80d2009-07-25 11:27:37 +0000122
Daniel Dunbar322f7892009-07-25 12:23:35 +0000123 # Strip trailing newline.
124 scriptLines.append(ln)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000125 elif 'XFAIL' in ln:
126 xfailLines.append(ln)
Daniel Dunbar025f80d2009-07-25 11:27:37 +0000127
128 # FIXME: Support something like END, in case we need to process large
129 # files.
Daniel Dunbara957d992009-07-25 14:46:05 +0000130
131 # Verify the script contains a run line.
132 if not scriptLines:
133 return (TestStatus.Fail, "Test has no run line!")
Daniel Dunbar322f7892009-07-25 12:23:35 +0000134
135 # Apply substitutions to the script.
136 def processLine(ln):
137 # Apply substitutions
138 for a,b in substitutions:
139 ln = ln.replace(a,b)
140
Daniel Dunbar322f7892009-07-25 12:23:35 +0000141 # Strip the trailing newline and any extra whitespace.
142 return ln.strip()
143 scriptLines = map(processLine, scriptLines)
Daniel Dunbar025f80d2009-07-25 11:27:37 +0000144
145 # Validate interior lines for '&&', a lovely historical artifact.
146 for i in range(len(scriptLines) - 1):
147 ln = scriptLines[i]
148
149 if not ln.endswith('&&'):
Daniel Dunbara957d992009-07-25 14:46:05 +0000150 return (TestStatus.Fail,
Daniel Dunbar67796472009-07-27 19:01:13 +0000151 ("MISSING \'&&\': %s\n" +
152 "FOLLOWED BY : %s\n") % (ln, scriptLines[i + 1]))
Daniel Dunbar025f80d2009-07-25 11:27:37 +0000153
154 # Strip off '&&'
155 scriptLines[i] = ln[:-2]
Daniel Dunbar025f80d2009-07-25 11:27:37 +0000156
Daniel Dunbar10aebbb2009-07-25 15:26:08 +0000157 out, err, exitCode = executeScript(script, scriptLines,
Daniel Dunbar9a676b72009-07-29 02:57:25 +0000158 os.path.dirname(testPath),
159 useValgrind)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000160 if xfailLines:
Daniel Dunbara957d992009-07-25 14:46:05 +0000161 ok = exitCode != 0
162 status = (TestStatus.XPass, TestStatus.XFail)[ok]
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000163 else:
Daniel Dunbara957d992009-07-25 14:46:05 +0000164 ok = exitCode == 0
165 status = (TestStatus.Fail, TestStatus.Pass)[ok]
166
167 if ok:
168 return (status,'')
169
170 output = StringIO.StringIO()
171 print >>output, "Script:"
172 print >>output, "--"
173 print >>output, '\n'.join(scriptLines)
174 print >>output, "--"
175 print >>output, "Exit Code: %r" % exitCode
176 print >>output, "Command Output (stdout):"
177 print >>output, "--"
178 output.write(out)
179 print >>output, "--"
180 print >>output, "Command Output (stderr):"
181 print >>output, "--"
182 output.write(err)
183 print >>output, "--"
184 return (status, output.getvalue())
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000185
186def capture(args):
Daniel Dunbar8fe83f12009-07-25 09:42:24 +0000187 p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000188 out,_ = p.communicate()
189 return out
190
191def which(command):
Daniel Dunbar67796472009-07-27 19:01:13 +0000192 # FIXME: Take configuration object.
193
Daniel Dunbar8fe83f12009-07-25 09:42:24 +0000194 # Check for absolute match first.
195 if os.path.exists(command):
196 return command
197
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000198 # Would be nice if Python had a lib function for this.
Daniel Dunbar67796472009-07-27 19:01:13 +0000199 paths = kChildEnv['PATH']
Daniel Dunbar8fe83f12009-07-25 09:42:24 +0000200 if not paths:
201 paths = os.defpath
202
203 # Get suffixes to search.
204 pathext = os.environ.get('PATHEXT', '').split(os.pathsep)
205
206 # Search the paths...
207 for path in paths.split(os.pathsep):
208 for ext in pathext:
209 p = os.path.join(path, command + ext)
210 if os.path.exists(p):
211 return p
212
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000213 return None
214
215def inferClang():
216 # Determine which clang to use.
217 clang = os.getenv('CLANG')
218
219 # If the user set clang in the environment, definitely use that and don't
220 # try to validate.
221 if clang:
222 return clang
223
224 # Otherwise look in the path.
225 clang = which('clang')
226
227 if not clang:
228 print >>sys.stderr, "error: couldn't find 'clang' program, try setting CLANG in your environment"
229 sys.exit(1)
230
231 return clang
232
233def inferClangCC(clang):
234 clangcc = os.getenv('CLANGCC')
235
236 # If the user set clang in the environment, definitely use that and don't
237 # try to validate.
238 if clangcc:
239 return clangcc
240
241 # Otherwise try adding -cc since we expect to be looking in a build
242 # directory.
Daniel Dunbar8fe83f12009-07-25 09:42:24 +0000243 if clang.endswith('.exe'):
244 clangccName = clang[:-4] + '-cc.exe'
245 else:
246 clangccName = clang + '-cc'
247 clangcc = which(clangccName)
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000248 if not clangcc:
249 # Otherwise ask clang.
250 res = capture([clang, '-print-prog-name=clang-cc'])
251 res = res.strip()
252 if res and os.path.exists(res):
253 clangcc = res
254
255 if not clangcc:
256 print >>sys.stderr, "error: couldn't find 'clang-cc' program, try setting CLANGCC in your environment"
257 sys.exit(1)
258
259 return clangcc
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000260
Daniel Dunbardf084892009-07-25 09:53:43 +0000261def getTestOutputBase(dir, testpath):
Daniel Dunbarfecdd002009-07-25 12:05:55 +0000262 """getTestOutputBase(dir, testpath) - Get the full path for temporary files
Daniel Dunbardf084892009-07-25 09:53:43 +0000263 corresponding to the given test path."""
264
265 # Form the output base out of the test parent directory name and the test
266 # name. FIXME: Find a better way to organize test results.
267 return os.path.join(dir,
268 os.path.basename(os.path.dirname(testpath)),
269 os.path.basename(testpath))
270
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000271def main():
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000272 global options
273 from optparse import OptionParser
274 parser = OptionParser("usage: %prog [options] {tests}")
275 parser.add_option("", "--clang", dest="clang",
276 help="Program to use as \"clang\"",
277 action="store", default=None)
278 parser.add_option("", "--clang-cc", dest="clangcc",
279 help="Program to use as \"clang-cc\"",
280 action="store", default=None)
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000281 (opts, args) = parser.parse_args()
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000282
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000283 if not args:
284 parser.error('No tests specified')
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000285
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000286 if opts.clang is None:
287 opts.clang = inferClang()
288 if opts.clangcc is None:
289 opts.clangcc = inferClangCC(opts.clang)
290
291 for path in args:
Daniel Dunbara957d992009-07-25 14:46:05 +0000292 base = getTestOutputBase('Output', path) + '.out'
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000293
Daniel Dunbara957d992009-07-25 14:46:05 +0000294 status,output = runOneTest(path, base, opts.clang, opts.clangcc)
295 print '%s: %s' % (TestStatus.getName(status).upper(), path)
296 if status == TestStatus.Fail or status == TestStatus.XPass:
297 print "%s TEST '%s' FAILED %s" % ('*'*20, path, '*'*20)
298 sys.stdout.write(output)
299 print "*" * 20
300 sys.exit(1)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000301
Daniel Dunbara957d992009-07-25 14:46:05 +0000302 sys.exit(0)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000303
304if __name__=='__main__':
305 main()