blob: ddd543c30ff9a5023434aa90259aafc967ed8dae [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 output=sys.stdout):
Nuno Lopesa7afc452009-07-11 18:34:43 +000073 OUTPUT = os.path.abspath(OUTPUT)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000074
75 # Create the output directory if it does not already exist.
76 mkdir_p(os.path.dirname(OUTPUT))
77
Daniel Dunbara0e52d62009-07-25 13:19:40 +000078 scriptFile = FILENAME
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000079
80 # Verify the script contains a run line.
81 for ln in open(scriptFile):
82 if 'RUN:' in ln:
83 break
84 else:
85 print >>output, "******************** TEST '%s' HAS NO RUN LINE! ********************"%(TESTNAME,)
86 output.flush()
Daniel Dunbar8bf0ccd2009-07-25 12:47:38 +000087 return TestStatus.Fail
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000088
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000089 FILENAME = os.path.abspath(FILENAME)
90 SCRIPT = OUTPUT + '.script'
Daniel Dunbar8fe83f12009-07-25 09:42:24 +000091 if kSystemName == 'Windows':
92 SCRIPT += '.bat'
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000093 TEMPOUTPUT = OUTPUT + '.tmp'
94
95 substitutions = [('%s',SUBST),
Daniel Dunbar4d8076a2009-04-10 19:49:21 +000096 ('%S',os.path.dirname(SUBST)),
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +000097 ('%llvmgcc','llvm-gcc -emit-llvm -w'),
98 ('%llvmgxx','llvm-g++ -emit-llvm -w'),
99 ('%prcontext','prcontext.tcl'),
100 ('%t',TEMPOUTPUT),
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000101 (' clang ', ' ' + CLANG + ' '),
102 (' clang-cc ', ' ' + CLANGCC + ' ')]
Daniel Dunbar025f80d2009-07-25 11:27:37 +0000103
104 # Collect the test lines from the script.
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000105 scriptLines = []
106 xfailLines = []
107 for ln in open(scriptFile):
108 if 'RUN:' in ln:
Daniel Dunbar025f80d2009-07-25 11:27:37 +0000109 # Isolate the command to run.
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000110 index = ln.index('RUN:')
111 ln = ln[index+4:]
Daniel Dunbar025f80d2009-07-25 11:27:37 +0000112
Daniel Dunbar322f7892009-07-25 12:23:35 +0000113 # Strip trailing newline.
114 scriptLines.append(ln)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000115 elif 'XFAIL' in ln:
116 xfailLines.append(ln)
Daniel Dunbar025f80d2009-07-25 11:27:37 +0000117
118 # FIXME: Support something like END, in case we need to process large
119 # files.
Daniel Dunbar322f7892009-07-25 12:23:35 +0000120
121 # Apply substitutions to the script.
122 def processLine(ln):
123 # Apply substitutions
124 for a,b in substitutions:
125 ln = ln.replace(a,b)
126
Daniel Dunbar322f7892009-07-25 12:23:35 +0000127 # Strip the trailing newline and any extra whitespace.
128 return ln.strip()
129 scriptLines = map(processLine, scriptLines)
Daniel Dunbar025f80d2009-07-25 11:27:37 +0000130
131 # Validate interior lines for '&&', a lovely historical artifact.
132 for i in range(len(scriptLines) - 1):
133 ln = scriptLines[i]
134
135 if not ln.endswith('&&'):
136 print >>output, "MISSING \'&&\': %s" % ln
137 print >>output, "FOLLOWED BY : %s" % scriptLines[i + 1]
138 return TestStatus.Fail
139
140 # Strip off '&&'
141 scriptLines[i] = ln[:-2]
Daniel Dunbar025f80d2009-07-25 11:27:37 +0000142
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000143 if xfailLines:
144 print >>output, "XFAILED '%s':"%(TESTNAME,)
145 output.writelines(xfailLines)
146
147 # Write script file
148 f = open(SCRIPT,'w')
Daniel Dunbar3b2505b2009-07-25 12:57:15 +0000149 if kSystemName == 'Windows':
150 f.write('\nif %ERRORLEVEL% NEQ 0 EXIT\n'.join(scriptLines))
Daniel Dunbar3b2505b2009-07-25 12:57:15 +0000151 else:
152 f.write(' &&\n'.join(scriptLines))
Daniel Dunbar11980cc2009-07-25 13:13:06 +0000153 f.write('\n')
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000154 f.close()
155
156 outputFile = open(OUTPUT,'w')
157 p = None
158 try:
Daniel Dunbar8fe83f12009-07-25 09:42:24 +0000159 if kSystemName == 'Windows':
160 command = ['cmd','/c', SCRIPT]
161 else:
162 command = ['/bin/sh', SCRIPT]
163
164 p = subprocess.Popen(command,
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000165 cwd=os.path.dirname(FILENAME),
Daniel Dunbar02cee152009-07-13 21:24:28 +0000166 stdin=subprocess.PIPE,
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000167 stdout=subprocess.PIPE,
Daniel Dunbar78a88e72009-07-25 10:14:19 +0000168 stderr=subprocess.PIPE,
169 env=kChildEnv)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000170 out,err = p.communicate()
171 outputFile.write(out)
172 outputFile.write(err)
173 SCRIPT_STATUS = p.wait()
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000174
175 # Detect Ctrl-C in subprocess.
176 if SCRIPT_STATUS == -signal.SIGINT:
177 raise KeyboardInterrupt
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000178 except KeyboardInterrupt:
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000179 raise
180 outputFile.close()
181
182 if xfailLines:
183 SCRIPT_STATUS = not SCRIPT_STATUS
184
Daniel Dunbar11980cc2009-07-25 13:13:06 +0000185 if SCRIPT_STATUS:
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000186 print >>output, "******************** TEST '%s' FAILED! ********************"%(TESTNAME,)
187 print >>output, "Command: "
188 output.writelines(scriptLines)
Daniel Dunbara0e52d62009-07-25 13:19:40 +0000189 print >>output, "Incorrect Output:"
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000190 cat(OUTPUT, output)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000191 print >>output, "******************** TEST '%s' FAILED! ********************"%(TESTNAME,)
192 output.flush()
193 if xfailLines:
194 return TestStatus.XPass
195 else:
196 return TestStatus.Fail
197
198 if xfailLines:
199 return TestStatus.XFail
200 else:
201 return TestStatus.Pass
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000202
203def capture(args):
Daniel Dunbar8fe83f12009-07-25 09:42:24 +0000204 p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000205 out,_ = p.communicate()
206 return out
207
208def which(command):
Daniel Dunbar8fe83f12009-07-25 09:42:24 +0000209 # Check for absolute match first.
210 if os.path.exists(command):
211 return command
212
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000213 # Would be nice if Python had a lib function for this.
Daniel Dunbar8fe83f12009-07-25 09:42:24 +0000214 paths = os.environ.get('PATH')
215 if not paths:
216 paths = os.defpath
217
218 # Get suffixes to search.
219 pathext = os.environ.get('PATHEXT', '').split(os.pathsep)
220
221 # Search the paths...
222 for path in paths.split(os.pathsep):
223 for ext in pathext:
224 p = os.path.join(path, command + ext)
225 if os.path.exists(p):
226 return p
227
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000228 return None
229
230def inferClang():
231 # Determine which clang to use.
232 clang = os.getenv('CLANG')
233
234 # If the user set clang in the environment, definitely use that and don't
235 # try to validate.
236 if clang:
237 return clang
238
239 # Otherwise look in the path.
240 clang = which('clang')
241
242 if not clang:
243 print >>sys.stderr, "error: couldn't find 'clang' program, try setting CLANG in your environment"
244 sys.exit(1)
245
246 return clang
247
248def inferClangCC(clang):
249 clangcc = os.getenv('CLANGCC')
250
251 # If the user set clang in the environment, definitely use that and don't
252 # try to validate.
253 if clangcc:
254 return clangcc
255
256 # Otherwise try adding -cc since we expect to be looking in a build
257 # directory.
Daniel Dunbar8fe83f12009-07-25 09:42:24 +0000258 if clang.endswith('.exe'):
259 clangccName = clang[:-4] + '-cc.exe'
260 else:
261 clangccName = clang + '-cc'
262 clangcc = which(clangccName)
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000263 if not clangcc:
264 # Otherwise ask clang.
265 res = capture([clang, '-print-prog-name=clang-cc'])
266 res = res.strip()
267 if res and os.path.exists(res):
268 clangcc = res
269
270 if not clangcc:
271 print >>sys.stderr, "error: couldn't find 'clang-cc' program, try setting CLANGCC in your environment"
272 sys.exit(1)
273
274 return clangcc
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000275
Daniel Dunbardf084892009-07-25 09:53:43 +0000276def getTestOutputBase(dir, testpath):
Daniel Dunbarfecdd002009-07-25 12:05:55 +0000277 """getTestOutputBase(dir, testpath) - Get the full path for temporary files
Daniel Dunbardf084892009-07-25 09:53:43 +0000278 corresponding to the given test path."""
279
280 # Form the output base out of the test parent directory name and the test
281 # name. FIXME: Find a better way to organize test results.
282 return os.path.join(dir,
283 os.path.basename(os.path.dirname(testpath)),
284 os.path.basename(testpath))
285
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000286def main():
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000287 global options
288 from optparse import OptionParser
289 parser = OptionParser("usage: %prog [options] {tests}")
290 parser.add_option("", "--clang", dest="clang",
291 help="Program to use as \"clang\"",
292 action="store", default=None)
293 parser.add_option("", "--clang-cc", dest="clangcc",
294 help="Program to use as \"clang-cc\"",
295 action="store", default=None)
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000296 (opts, args) = parser.parse_args()
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000297
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000298 if not args:
299 parser.error('No tests specified')
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000300
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000301 if opts.clang is None:
302 opts.clang = inferClang()
303 if opts.clangcc is None:
304 opts.clangcc = inferClangCC(opts.clang)
305
306 for path in args:
307 command = path
Daniel Dunbarfecdd002009-07-25 12:05:55 +0000308 output = getTestOutputBase('Output', path) + '.out'
Daniel Dunbar69e07a72009-06-17 21:33:37 +0000309 testname = path
310
311 res = runOneTest(path, command, output, testname,
Daniel Dunbara0e52d62009-07-25 13:19:40 +0000312 opts.clang, opts.clangcc)
Daniel Dunbar6fc0bdf2009-03-06 22:20:40 +0000313
314 sys.exit(res == TestStatus.Fail or res == TestStatus.XPass)
315
316if __name__=='__main__':
317 main()