Add MSVS Project file support. (Greg Spencer)
[scons.git] / runtest.py
1 #!/usr/bin/env python
2 #
3 # runtest.py - wrapper script for running SCons tests
4 #
5 # This script mainly exists to set PYTHONPATH to the right list of
6 # directories to test the SCons modules.
7 #
8 # By default, it directly uses the modules in the local tree:
9 # ./src/ (source files we ship) and ./etc/ (other modules we don't).
10 #
11 # HOWEVER, now that SCons has Repository support, we don't have
12 # Aegis copy all of the files into the local tree.  So if you're
13 # using Aegis and want to run tests by hand using this script, you
14 # must "aecp ." the entire source tree into your local directory
15 # structure.  When you're done with your change, you can then
16 # "aecpu -unch ." to un-copy any files that you haven't changed.
17 #
18 # When any -p option is specified, this script assumes it's in a
19 # directory in which a build has been performed, and sets PYTHONPATH
20 # so that it *only* references the modules that have unpacked from
21 # the specified built package, to test whether the packages are good.
22 #
23 # Options:
24 #
25 #       -a              Run all tests; does a virtual 'find' for
26 #                       all SCons tests under the current directory.
27 #
28 #       -d              Debug.  Runs the script under the Python
29 #                       debugger (pdb.py) so you don't have to
30 #                       muck with PYTHONPATH yourself.
31 #
32 #       -h              Print the help and exit.
33 #
34 #       -o file         Print test results to the specified file
35 #                       in the format expected by aetest(5).  This
36 #                       is intended for use in the batch_test_command
37 #                       field in the Aegis project config file.
38 #
39 #       -P Python       Use the specified Python interpreter.
40 #
41 #       -p package      Test against the specified package.
42 #
43 #       -q              Quiet.  By default, runtest.py prints the
44 #                       command line it will execute before
45 #                       executing it.  This suppresses that print.
46 #
47 #       -X              The scons "script" is an executable; don't
48 #                       feed it to Python.
49 #
50 #       -x scons        The scons script to use for tests.
51 #
52 # (Note:  There used to be a -v option that specified the SCons
53 # version to be tested, when we were installing in a version-specific
54 # library directory.  If we ever resurrect that as the default, then
55 # you can find the appropriate code in the 0.04 version of this script,
56 # rather than reinventing that wheel.)
57 #
58
59 import getopt
60 import glob
61 import os
62 import os.path
63 import re
64 import stat
65 import string
66 import sys
67
68 all = 0
69 debug = ''
70 tests = []
71 printcmd = 1
72 package = None
73 scons = None
74 scons_exec = None
75 output = None
76 version = ''
77
78 if os.name == 'java':
79     python = os.path.join(sys.prefix, 'jython')
80 else:
81     python = sys.executable
82
83 cwd = os.getcwd()
84
85 if sys.platform == 'win32' or os.name == 'java':
86     lib_dir = os.path.join(sys.exec_prefix, "Lib")
87 else:
88     # The hard-coded "python" here is the directory name,
89     # not an executable, so it's all right.
90     lib_dir = os.path.join(sys.exec_prefix, "lib", "python" + sys.version[0:3])
91
92 helpstr = """\
93 Usage: runtest.py [OPTIONS] [TEST ...]
94 Options:
95   -a, --all                   Run all tests.
96   -d, --debug                 Run test scripts under the Python debugger.
97   -h, --help                  Print this message and exit.
98   -o FILE, --output FILE      Print test results to FILE (Aegis format).
99   -P Python                   Use the specified Python interpreter.
100   -p PACKAGE, --package PACKAGE
101                               Test against the specified PACKAGE:
102                                 deb           Debian
103                                 local-tar-gz  .tar.gz standalone package
104                                 local-zip     .zip standalone package
105                                 rpm           Red Hat
106                                 src-tar-gz    .tar.gz source package
107                                 src-zip       .zip source package
108                                 tar-gz        .tar.gz distribution
109                                 zip           .zip distribution
110   -q, --quiet                 Don't print the test being executed.
111   -v version                  Specify the SCons version.
112   -X                          Test script is executable, don't feed to Python.
113   -x SCRIPT, --exec SCRIPT    Test SCRIPT.
114 """
115
116 opts, args = getopt.getopt(sys.argv[1:], "adho:P:p:qv:Xx:",
117                             ['all', 'debug', 'help', 'output=',
118                              'package=', 'python=', 'quiet',
119                              'version=', 'exec='])
120
121 for o, a in opts:
122     if o == '-a' or o == '--all':
123         all = 1
124     elif o == '-d' or o == '--debug':
125         debug = os.path.join(lib_dir, "pdb.py")
126     elif o == '-h' or o == '--help':
127         print helpstr
128         sys.exit(0)
129     elif o == '-o' or o == '--output':
130         if not os.path.isabs(a):
131             a = os.path.join(cwd, a)
132         output = a
133     elif o == '-P' or o == '--python':
134         python = a
135     elif o == '-p' or o == '--package':
136         package = a
137     elif o == '-q' or o == '--quiet':
138         printcmd = 0
139     elif o == '-v' or o == '--version':
140         version = a
141     elif o == '-X':
142         scons_exec = 1
143     elif o == '-x' or o == '--exec':
144         scons = a
145
146 def whereis(file):
147     for dir in string.split(os.environ['PATH'], os.pathsep):
148         f = os.path.join(dir, file)
149         if os.path.isfile(f):
150             try:
151                 st = os.stat(f)
152             except OSError:
153                 continue
154             if stat.S_IMODE(st[stat.ST_MODE]) & 0111:
155                 return f
156     return None
157
158 aegis = whereis('aegis')
159
160 spe = None
161 if aegis:
162     spe = os.popen("aesub '$spe' 2>/dev/null", "r").read()[:-1]
163     spe = string.split(spe, os.pathsep)
164
165 class Test:
166     def __init__(self, path, spe=None):
167         self.path = path
168         self.abspath = os.path.abspath(path)
169         if spe:
170             for dir in spe:
171                 f = os.path.join(dir, path)
172                 if os.path.isfile(f):
173                     self.abspath = f
174                     break
175         self.status = None
176
177 if args:
178     if spe:
179         for a in args:
180             if os.path.isabs(a):
181                 for g in glob.glob(a):
182                     tests.append(Test(g))
183             else:
184                 for dir in spe:
185                     x = os.path.join(dir, a)
186                     globs = glob.glob(x)
187                     if globs:
188                         for g in globs:
189                             tests.append(Test(g))
190                         break
191     else:
192         for a in args:
193             for g in glob.glob(a):
194                 tests.append(Test(g))
195 elif all:
196     tdict = {}
197
198     def find_Test_py(arg, dirname, names, tdict=tdict):
199         for n in filter(lambda n: n[-8:] == "Tests.py", names):
200             t = os.path.join(dirname, n)
201             if not tdict.has_key(t):
202                 tdict[t] = Test(t)
203     os.path.walk('src', find_Test_py, 0)
204
205     def find_py(arg, dirname, names, tdict=tdict):
206         for n in filter(lambda n: n[-3:] == ".py", names):
207             t = os.path.join(dirname, n)
208             if not tdict.has_key(t):
209                 tdict[t] = Test(t)
210     os.path.walk('test', find_py, 0)
211
212     if aegis:
213         cmd = "aegis -list -unf pf 2>/dev/null"
214         for line in os.popen(cmd, "r").readlines():
215             a = string.split(line)
216             if a[0] == "test" and not tdict.has_key(a[-1]):
217                 tdict[a[-1]] = Test(a[-1], spe)
218         cmd = "aegis -list -unf cf 2>/dev/null"
219         for line in os.popen(cmd, "r").readlines():
220             a = string.split(line)
221             if a[0] == "test":
222                 if a[1] == "remove":
223                     del tdict[a[-1]]
224                 elif not tdict.has_key(a[-1]):
225                     tdict[a[-1]] = Test(a[-1], spe)
226
227     keys = tdict.keys()
228     keys.sort()
229     tests = map(tdict.get, keys)
230
231 if package:
232
233     dir = {
234         'deb'          : 'usr',
235         'local-tar-gz' : None,
236         'local-zip'    : None,
237         'rpm'          : 'usr',
238         'src-tar-gz'   : '',
239         'src-zip'      : '',
240         'tar-gz'       : '',
241         'zip'          : '',
242     }
243
244     # The hard-coded "python2.1" here is the library directory
245     # name on Debian systems, not an executable, so it's all right.
246     lib = {
247         'deb'        : os.path.join('python2.1', 'site-packages')
248     }
249
250     if not dir.has_key(package):
251         sys.stderr.write("Unknown package '%s'\n" % package)
252         sys.exit(2)
253
254     test_dir = os.path.join(cwd, 'build', 'test-%s' % package)
255
256     if dir[package] is None:
257         scons_script_dir = test_dir
258         globs = glob.glob(os.path.join(test_dir, 'scons-local-*'))
259         if not globs:
260             sys.stderr.write("No `scons-local-*' dir in `%s'\n" % test_dir)
261             sys.exit(2)
262         scons_lib_dir = None
263         pythonpath_dir = globs[len(globs)-1]
264     elif sys.platform == 'win32':
265         scons_script_dir = os.path.join(test_dir, dir[package], 'Scripts')
266         scons_lib_dir = os.path.join(test_dir, dir[package])
267         pythonpath_dir = scons_lib_dir
268     else:
269         scons_script_dir = os.path.join(test_dir, dir[package], 'bin')
270         l = lib.get(package, 'scons')
271         scons_lib_dir = os.path.join(test_dir, dir[package], 'lib', l)
272         pythonpath_dir = scons_lib_dir
273
274 else:
275     sd = None
276     ld = None
277
278     # XXX:  Logic like the following will be necessary once
279     # we fix runtest.py to run tests within an Aegis change
280     # without symlinks back to the baseline(s).
281     #
282     #if spe:
283     #    if not scons:
284     #        for dir in spe:
285     #            d = os.path.join(dir, 'src', 'script')
286     #            f = os.path.join(d, 'scons.py')
287     #            if os.path.isfile(f):
288     #                sd = d
289     #                scons = f
290     #    spe = map(lambda x: os.path.join(x, 'src', 'engine'), spe)
291     #    ld = string.join(spe, os.pathsep)
292
293     scons_script_dir = sd or os.path.join(cwd, 'src', 'script')
294
295     scons_lib_dir = ld or os.path.join(cwd, 'src', 'engine')
296
297     pythonpath_dir = scons_lib_dir
298
299 if scons:
300     # Let the version of SCons that the -x option pointed to find
301     # its own modules.
302     os.environ['SCONS'] = scons
303 elif scons_lib_dir:
304     # Because SCons is really aggressive about finding its modules,
305     # it sometimes finds SCons modules elsewhere on the system.
306     # This forces SCons to use the modules that are being tested.
307     os.environ['SCONS_LIB_DIR'] = scons_lib_dir
308
309 if scons_exec:
310     os.environ['SCONS_EXEC'] = '1'
311
312 os.environ['SCONS_SCRIPT_DIR'] = scons_script_dir
313 os.environ['SCONS_CWD'] = cwd
314
315 os.environ['SCONS_VERSION'] = version
316
317 old_pythonpath = os.environ.get('PYTHONPATH')
318 os.environ['PYTHONPATH'] = pythonpath_dir + \
319                            os.pathsep + \
320                            os.path.join(cwd, 'build', 'etc') + \
321                            os.pathsep + \
322                            os.path.join(cwd, 'etc')
323 if old_pythonpath:
324     os.environ['PYTHONPATH'] = os.environ['PYTHONPATH'] + \
325                                os.pathsep + \
326                                old_pythonpath
327
328 os.chdir(scons_script_dir)
329
330 class Unbuffered:
331     def __init__(self, file):
332         self.file = file
333     def write(self, arg):
334         self.file.write(arg)
335         self.file.flush()
336     def __getattr__(self, attr):
337         return getattr(self.file, attr)
338
339 sys.stdout = Unbuffered(sys.stdout)
340
341 for t in tests:
342     cmd = string.join([python, debug, t.abspath], " ")
343     if printcmd:
344         sys.stdout.write(cmd + "\n")
345     s = os.system(cmd)
346     if s >= 256:
347         s = s / 256
348     t.status = s
349     if s < 0 or s > 2:
350         sys.stdout.write("Unexpected exit status %d\n" % s)
351
352 fail = filter(lambda t: t.status == 1, tests)
353 no_result = filter(lambda t: t.status == 2, tests)
354
355 if len(tests) != 1:
356     if fail:
357         if len(fail) == 1:
358             sys.stdout.write("\nFailed the following test:\n")
359         else:
360             sys.stdout.write("\nFailed the following %d tests:\n" % len(fail))
361         paths = map(lambda x: x.path, fail)
362         sys.stdout.write("\t" + string.join(paths, "\n\t") + "\n")
363     if no_result:
364         if len(no_result) == 1:
365             sys.stdout.write("\nNO RESULT from the following test:\n")
366         else:
367             sys.stdout.write("\nNO RESULT from the following %d tests:\n" % len(no_result))
368         paths = map(lambda x: x.path, no_result)
369         sys.stdout.write("\t" + string.join(paths, "\n\t") + "\n")
370
371 if output:
372     f = open(output, 'w')
373     f.write("test_result = [\n")
374     for t in tests:
375         f.write('    { file_name = "%s";\n' % t.path)
376         f.write('      exit_status = %d; },\n' % t.status)
377     f.write("];\n")
378     f.close()
379     sys.exit(0)
380 else:
381     if len(fail):
382         sys.exit(1)
383     elif len(no_result):
384         sys.exit(2)
385     else:
386         sys.exit(0)