blob: dbcb2a74314ede73f502fc63495d713d51e26498 [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
60def remove(path):
61 try:
62 os.remove(path)
63 except OSError:
64 pass
65
66def cat(path, output):
67 f = open(path)
68 output.writelines(f)
69 f.close()
70
Daniel Dunbar69e07a72009-06-17 21:33:37 +000071def runOneTest(FILENAME, SUBST, OUTPUT, TESTNAME, CLANG, CLANGCC,
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000072 useDGCompat=False,
73 useScript=None,
74 output=sys.stdout):
Nuno Lopesa7afc452009-07-11 18:34:43 +000075 OUTPUT = os.path.abspath(OUTPUT)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000076
77 # Create the output directory if it does not already exist.
78 mkdir_p(os.path.dirname(OUTPUT))
79
80 # FIXME
81 #ulimit -t 40
82
83 # FIXME: Load script once
84 # FIXME: Support "short" script syntax
85
86 if useScript:
87 scriptFile = useScript
88 else:
89 # See if we have a per-dir test script.
90 dirScriptFile = os.path.join(os.path.dirname(FILENAME), 'test.script')
91 if os.path.exists(dirScriptFile):
92 scriptFile = dirScriptFile
93 else:
94 scriptFile = FILENAME
95
96 # Verify the script contains a run line.
97 for ln in open(scriptFile):
98 if 'RUN:' in ln:
99 break
100 else:
101 print >>output, "******************** TEST '%s' HAS NO RUN LINE! ********************"%(TESTNAME,)
102 output.flush()
Daniel Dunbar8bf0ccd2009-07-25 12:47:38 +0000103 return TestStatus.Fail
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000104
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000105 FILENAME = os.path.abspath(FILENAME)
106 SCRIPT = OUTPUT + '.script'
Daniel Dunbar8fe83f12009-07-25 09:42:24 +0000107 if kSystemName == 'Windows':
108 SCRIPT += '.bat'
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000109 TEMPOUTPUT = OUTPUT + '.tmp'
110
111 substitutions = [('%s',SUBST),
Daniel Dunbar4d8076a2009-04-10 19:49:21 +0000112 ('%S',os.path.dirname(SUBST)),
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000113 ('%llvmgcc','llvm-gcc -emit-llvm -w'),
114 ('%llvmgxx','llvm-g++ -emit-llvm -w'),
115 ('%prcontext','prcontext.tcl'),
116 ('%t',TEMPOUTPUT),
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000117 (' clang ', ' ' + CLANG + ' '),
118 (' clang-cc ', ' ' + CLANGCC + ' ')]
Daniel Dunbar025f80d2009-07-25 11:27:37 +0000119
120 # Collect the test lines from the script.
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000121 scriptLines = []
122 xfailLines = []
123 for ln in open(scriptFile):
124 if 'RUN:' in ln:
Daniel Dunbar025f80d2009-07-25 11:27:37 +0000125 # Isolate the command to run.
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000126 index = ln.index('RUN:')
127 ln = ln[index+4:]
Daniel Dunbar025f80d2009-07-25 11:27:37 +0000128
Daniel Dunbar322f7892009-07-25 12:23:35 +0000129 # Strip trailing newline.
130 scriptLines.append(ln)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000131 elif 'XFAIL' in ln:
132 xfailLines.append(ln)
Daniel Dunbar025f80d2009-07-25 11:27:37 +0000133
134 # FIXME: Support something like END, in case we need to process large
135 # files.
Daniel Dunbar322f7892009-07-25 12:23:35 +0000136
137 # Apply substitutions to the script.
138 def processLine(ln):
139 # Apply substitutions
140 for a,b in substitutions:
141 ln = ln.replace(a,b)
142
143 if useDGCompat:
144 ln = re.sub(r'\{(.*)\}', r'"\1"', ln)
145
146 # Strip the trailing newline and any extra whitespace.
147 return ln.strip()
148 scriptLines = map(processLine, scriptLines)
Daniel Dunbar025f80d2009-07-25 11:27:37 +0000149
150 # Validate interior lines for '&&', a lovely historical artifact.
151 for i in range(len(scriptLines) - 1):
152 ln = scriptLines[i]
153
154 if not ln.endswith('&&'):
155 print >>output, "MISSING \'&&\': %s" % ln
156 print >>output, "FOLLOWED BY : %s" % scriptLines[i + 1]
157 return TestStatus.Fail
158
159 # Strip off '&&'
160 scriptLines[i] = ln[:-2]
Daniel Dunbar025f80d2009-07-25 11:27:37 +0000161
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000162 if xfailLines:
163 print >>output, "XFAILED '%s':"%(TESTNAME,)
164 output.writelines(xfailLines)
165
166 # Write script file
167 f = open(SCRIPT,'w')
Daniel Dunbar3b2505b2009-07-25 12:57:15 +0000168 if kSystemName == 'Windows':
169 f.write('\nif %ERRORLEVEL% NEQ 0 EXIT\n'.join(scriptLines))
Daniel Dunbar3b2505b2009-07-25 12:57:15 +0000170 else:
171 f.write(' &&\n'.join(scriptLines))
Daniel Dunbar11980cc2009-07-25 13:13:06 +0000172 f.write('\n')
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000173 f.close()
174
175 outputFile = open(OUTPUT,'w')
176 p = None
177 try:
Daniel Dunbar8fe83f12009-07-25 09:42:24 +0000178 if kSystemName == 'Windows':
179 command = ['cmd','/c', SCRIPT]
180 else:
181 command = ['/bin/sh', SCRIPT]
182
183 p = subprocess.Popen(command,
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000184 cwd=os.path.dirname(FILENAME),
Daniel Dunbar02cee152009-07-13 21:24:28 +0000185 stdin=subprocess.PIPE,
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000186 stdout=subprocess.PIPE,
Daniel Dunbar78a88e72009-07-25 10:14:19 +0000187 stderr=subprocess.PIPE,
188 env=kChildEnv)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000189 out,err = p.communicate()
190 outputFile.write(out)
191 outputFile.write(err)
192 SCRIPT_STATUS = p.wait()
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000193
194 # Detect Ctrl-C in subprocess.
195 if SCRIPT_STATUS == -signal.SIGINT:
196 raise KeyboardInterrupt
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000197 except KeyboardInterrupt:
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000198 raise
199 outputFile.close()
200
201 if xfailLines:
202 SCRIPT_STATUS = not SCRIPT_STATUS
203
Daniel Dunbar11980cc2009-07-25 13:13:06 +0000204 if SCRIPT_STATUS:
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000205 print >>output, "******************** TEST '%s' FAILED! ********************"%(TESTNAME,)
206 print >>output, "Command: "
207 output.writelines(scriptLines)
208 if not SCRIPT_STATUS:
209 print >>output, "Output:"
210 else:
211 print >>output, "Incorrect Output:"
212 cat(OUTPUT, output)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000213 print >>output, "******************** TEST '%s' FAILED! ********************"%(TESTNAME,)
214 output.flush()
215 if xfailLines:
216 return TestStatus.XPass
217 else:
218 return TestStatus.Fail
219
220 if xfailLines:
221 return TestStatus.XFail
222 else:
223 return TestStatus.Pass
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000224
225def capture(args):
Daniel Dunbar8fe83f12009-07-25 09:42:24 +0000226 p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000227 out,_ = p.communicate()
228 return out
229
230def which(command):
Daniel Dunbar8fe83f12009-07-25 09:42:24 +0000231 # Check for absolute match first.
232 if os.path.exists(command):
233 return command
234
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000235 # Would be nice if Python had a lib function for this.
Daniel Dunbar8fe83f12009-07-25 09:42:24 +0000236 paths = os.environ.get('PATH')
237 if not paths:
238 paths = os.defpath
239
240 # Get suffixes to search.
241 pathext = os.environ.get('PATHEXT', '').split(os.pathsep)
242
243 # Search the paths...
244 for path in paths.split(os.pathsep):
245 for ext in pathext:
246 p = os.path.join(path, command + ext)
247 if os.path.exists(p):
248 return p
249
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000250 return None
251
252def inferClang():
253 # Determine which clang to use.
254 clang = os.getenv('CLANG')
255
256 # If the user set clang in the environment, definitely use that and don't
257 # try to validate.
258 if clang:
259 return clang
260
261 # Otherwise look in the path.
262 clang = which('clang')
263
264 if not clang:
265 print >>sys.stderr, "error: couldn't find 'clang' program, try setting CLANG in your environment"
266 sys.exit(1)
267
268 return clang
269
270def inferClangCC(clang):
271 clangcc = os.getenv('CLANGCC')
272
273 # If the user set clang in the environment, definitely use that and don't
274 # try to validate.
275 if clangcc:
276 return clangcc
277
278 # Otherwise try adding -cc since we expect to be looking in a build
279 # directory.
Daniel Dunbar8fe83f12009-07-25 09:42:24 +0000280 if clang.endswith('.exe'):
281 clangccName = clang[:-4] + '-cc.exe'
282 else:
283 clangccName = clang + '-cc'
284 clangcc = which(clangccName)
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000285 if not clangcc:
286 # Otherwise ask clang.
287 res = capture([clang, '-print-prog-name=clang-cc'])
288 res = res.strip()
289 if res and os.path.exists(res):
290 clangcc = res
291
292 if not clangcc:
293 print >>sys.stderr, "error: couldn't find 'clang-cc' program, try setting CLANGCC in your environment"
294 sys.exit(1)
295
296 return clangcc
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000297
Daniel Dunbardf084892009-07-25 09:53:43 +0000298def getTestOutputBase(dir, testpath):
Daniel Dunbarfecdd002009-07-25 12:05:55 +0000299 """getTestOutputBase(dir, testpath) - Get the full path for temporary files
Daniel Dunbardf084892009-07-25 09:53:43 +0000300 corresponding to the given test path."""
301
302 # Form the output base out of the test parent directory name and the test
303 # name. FIXME: Find a better way to organize test results.
304 return os.path.join(dir,
305 os.path.basename(os.path.dirname(testpath)),
306 os.path.basename(testpath))
307
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000308def main():
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000309 global options
310 from optparse import OptionParser
311 parser = OptionParser("usage: %prog [options] {tests}")
312 parser.add_option("", "--clang", dest="clang",
313 help="Program to use as \"clang\"",
314 action="store", default=None)
315 parser.add_option("", "--clang-cc", dest="clangcc",
316 help="Program to use as \"clang-cc\"",
317 action="store", default=None)
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000318 parser.add_option("", "--dg", dest="useDGCompat",
319 help="Use llvm dejagnu compatibility mode",
320 action="store_true", default=False)
321 (opts, args) = parser.parse_args()
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000322
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000323 if not args:
324 parser.error('No tests specified')
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000325
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000326 if opts.clang is None:
327 opts.clang = inferClang()
328 if opts.clangcc is None:
329 opts.clangcc = inferClangCC(opts.clang)
330
331 for path in args:
332 command = path
Daniel Dunbarfecdd002009-07-25 12:05:55 +0000333 output = getTestOutputBase('Output', path) + '.out'
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000334 testname = path
335
336 res = runOneTest(path, command, output, testname,
337 opts.clang, opts.clangcc,
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000338 useDGCompat=opts.useDGCompat,
339 useScript=os.getenv("TEST_SCRIPT"))
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000340
341 sys.exit(res == TestStatus.Fail or res == TestStatus.XPass)
342
343if __name__=='__main__':
344 main()