2fbc9f49d0bf5dac4ccadd45eb24677c74027f19
[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 if aegis:
161     sp = os.popen("aesub '$sp' 2>/dev/null", "r").read()[:-1]
162     sp = string.split(sp, os.pathsep)
163     spe = os.popen("aesub '$spe' 2>/dev/null", "r").read()[:-1]
164     spe = string.split(spe, os.pathsep)
165 else:
166     sp = [cwd]
167     spe = []
168
169 class Test:
170     def __init__(self, path, spe=None):
171         self.path = path
172         self.abspath = os.path.abspath(path)
173         if spe:
174             for dir in spe:
175                 f = os.path.join(dir, path)
176                 if os.path.isfile(f):
177                     self.abspath = f
178                     break
179         self.status = None
180
181 if args:
182     if spe:
183         for a in args:
184             if os.path.isabs(a):
185                 for g in glob.glob(a):
186                     tests.append(Test(g))
187             else:
188                 for dir in spe:
189                     x = os.path.join(dir, a)
190                     globs = glob.glob(x)
191                     if globs:
192                         for g in globs:
193                             tests.append(Test(g))
194                         break
195     else:
196         for a in args:
197             for g in glob.glob(a):
198                 tests.append(Test(g))
199 elif all:
200     tdict = {}
201
202     def find_Test_py(arg, dirname, names, tdict=tdict):
203         for n in filter(lambda n: n[-8:] == "Tests.py", names):
204             t = os.path.join(dirname, n)
205             if not tdict.has_key(t):
206                 tdict[t] = Test(t)
207     os.path.walk('src', find_Test_py, 0)
208
209     def find_py(arg, dirname, names, tdict=tdict):
210         for n in filter(lambda n: n[-3:] == ".py", names):
211             t = os.path.join(dirname, n)
212             if not tdict.has_key(t):
213                 tdict[t] = Test(t)
214     os.path.walk('test', find_py, 0)
215
216     if aegis:
217         cmd = "aegis -list -unf pf 2>/dev/null"
218         for line in os.popen(cmd, "r").readlines():
219             a = string.split(line)
220             if a[0] == "test" and not tdict.has_key(a[-1]):
221                 tdict[a[-1]] = Test(a[-1], spe)
222         cmd = "aegis -list -unf cf 2>/dev/null"
223         for line in os.popen(cmd, "r").readlines():
224             a = string.split(line)
225             if a[0] == "test":
226                 if a[1] == "remove":
227                     del tdict[a[-1]]
228                 elif not tdict.has_key(a[-1]):
229                     tdict[a[-1]] = Test(a[-1], spe)
230
231     keys = tdict.keys()
232     keys.sort()
233     tests = map(tdict.get, keys)
234
235 if package:
236
237     dir = {
238         'deb'          : 'usr',
239         'local-tar-gz' : None,
240         'local-zip'    : None,
241         'rpm'          : 'usr',
242         'src-tar-gz'   : '',
243         'src-zip'      : '',
244         'tar-gz'       : '',
245         'zip'          : '',
246     }
247
248     # The hard-coded "python2.1" here is the library directory
249     # name on Debian systems, not an executable, so it's all right.
250     lib = {
251         'deb'        : os.path.join('python2.1', 'site-packages')
252     }
253
254     if not dir.has_key(package):
255         sys.stderr.write("Unknown package '%s'\n" % package)
256         sys.exit(2)
257
258     test_dir = os.path.join(cwd, 'build', 'test-%s' % package)
259
260     if dir[package] is None:
261         scons_script_dir = test_dir
262         globs = glob.glob(os.path.join(test_dir, 'scons-local-*'))
263         if not globs:
264             sys.stderr.write("No `scons-local-*' dir in `%s'\n" % test_dir)
265             sys.exit(2)
266         scons_lib_dir = None
267         pythonpath_dir = globs[len(globs)-1]
268     elif sys.platform == 'win32':
269         scons_script_dir = os.path.join(test_dir, dir[package], 'Scripts')
270         scons_lib_dir = os.path.join(test_dir, dir[package])
271         pythonpath_dir = scons_lib_dir
272     else:
273         scons_script_dir = os.path.join(test_dir, dir[package], 'bin')
274         l = lib.get(package, 'scons')
275         scons_lib_dir = os.path.join(test_dir, dir[package], 'lib', l)
276         pythonpath_dir = scons_lib_dir
277
278 else:
279     sd = None
280     ld = None
281
282     # XXX:  Logic like the following will be necessary once
283     # we fix runtest.py to run tests within an Aegis change
284     # without symlinks back to the baseline(s).
285     #
286     #if spe:
287     #    if not scons:
288     #        for dir in spe:
289     #            d = os.path.join(dir, 'src', 'script')
290     #            f = os.path.join(d, 'scons.py')
291     #            if os.path.isfile(f):
292     #                sd = d
293     #                scons = f
294     #    spe = map(lambda x: os.path.join(x, 'src', 'engine'), spe)
295     #    ld = string.join(spe, os.pathsep)
296
297     scons_script_dir = sd or os.path.join(cwd, 'src', 'script')
298
299     scons_lib_dir = ld or os.path.join(cwd, 'src', 'engine')
300
301     pythonpath_dir = scons_lib_dir
302
303 if scons:
304     # Let the version of SCons that the -x option pointed to find
305     # its own modules.
306     os.environ['SCONS'] = scons
307 elif scons_lib_dir:
308     # Because SCons is really aggressive about finding its modules,
309     # it sometimes finds SCons modules elsewhere on the system.
310     # This forces SCons to use the modules that are being tested.
311     os.environ['SCONS_LIB_DIR'] = scons_lib_dir
312
313 if scons_exec:
314     os.environ['SCONS_EXEC'] = '1'
315
316 os.environ['SCONS_SCRIPT_DIR'] = scons_script_dir
317 os.environ['SCONS_CWD'] = cwd
318
319 os.environ['SCONS_VERSION'] = version
320
321 old_pythonpath = os.environ.get('PYTHONPATH')
322
323 pythonpaths = [ pythonpath_dir ]
324 for p in sp:
325     pythonpaths.append(os.path.join(p, 'build', 'etc'))
326     pythonpaths.append(os.path.join(p, 'etc'))
327 os.environ['PYTHONPATH'] = string.join(pythonpaths, os.pathsep)
328
329 if old_pythonpath:
330     os.environ['PYTHONPATH'] = os.environ['PYTHONPATH'] + \
331                                os.pathsep + \
332                                old_pythonpath
333
334 os.chdir(scons_script_dir)
335
336 class Unbuffered:
337     def __init__(self, file):
338         self.file = file
339     def write(self, arg):
340         self.file.write(arg)
341         self.file.flush()
342     def __getattr__(self, attr):
343         return getattr(self.file, attr)
344
345 sys.stdout = Unbuffered(sys.stdout)
346
347 for t in tests:
348     cmd = string.join([python, debug, t.abspath], " ")
349     if printcmd:
350         sys.stdout.write(cmd + "\n")
351     s = os.system(cmd)
352     if s >= 256:
353         s = s / 256
354     t.status = s
355     if s < 0 or s > 2:
356         sys.stdout.write("Unexpected exit status %d\n" % s)
357
358 fail = filter(lambda t: t.status == 1, tests)
359 no_result = filter(lambda t: t.status == 2, tests)
360
361 if len(tests) != 1:
362     if fail:
363         if len(fail) == 1:
364             sys.stdout.write("\nFailed the following test:\n")
365         else:
366             sys.stdout.write("\nFailed the following %d tests:\n" % len(fail))
367         paths = map(lambda x: x.path, fail)
368         sys.stdout.write("\t" + string.join(paths, "\n\t") + "\n")
369     if no_result:
370         if len(no_result) == 1:
371             sys.stdout.write("\nNO RESULT from the following test:\n")
372         else:
373             sys.stdout.write("\nNO RESULT from the following %d tests:\n" % len(no_result))
374         paths = map(lambda x: x.path, no_result)
375         sys.stdout.write("\t" + string.join(paths, "\n\t") + "\n")
376
377 if output:
378     f = open(output, 'w')
379     f.write("test_result = [\n")
380     for t in tests:
381         f.write('    { file_name = "%s";\n' % t.path)
382         f.write('      exit_status = %d; },\n' % t.status)
383     f.write("];\n")
384     f.close()
385     sys.exit(0)
386 else:
387     if len(fail):
388         sys.exit(1)
389     elif len(no_result):
390         sys.exit(2)
391     else:
392         sys.exit(0)