Debian Codegraph @

js/src/gdb/run-tests.py

raw
1 #!/usr/bin/env python
2 # This Source Code Form is subject to the terms of the Mozilla Public
3 # License, v. 2.0. If a copy of the MPL was not distributed with this
4 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
6 # run-tests.py -- Python harness for GDB SpiderMonkey support
7
8 import os
9 import re
10 import subprocess
11 import sys
12
13 # From this directory:
14 import progressbar
15 from taskpool import TaskPool, get_cpu_count
16
17
18 def _relpath(path, start=None):
19 # Backported from Python 3.1 posixpath.py
20 """Return a relative version of a path"""
21
22 if not path:
23 raise ValueError("no path specified")
24
25 if start is None:
26 start = os.curdir
27
28 start_list = os.path.abspath(start).split(os.sep)
29 path_list = os.path.abspath(path).split(os.sep)
30
31 # Work out how much of the filepath is shared by start and path.
32 i = len(os.path.commonprefix([start_list, path_list]))
33
34 rel_list = [os.pardir] * (len(start_list) - i) + path_list[i:]
35 if not rel_list:
36 return os.curdir
37 return os.path.join(*rel_list)
38
39
40 os.path.relpath = _relpath
41
42 # Characters that need to be escaped when used in shell words.
43 shell_need_escapes = re.compile("[^\\w\\d%+,-./:=@'\"]", re.DOTALL)
44 # Characters that need to be escaped within double-quoted strings.
45 shell_dquote_escapes = re.compile('[^\\w\\d%+,-./:=@"]', re.DOTALL)
46
47
48 def make_shell_cmd(l):
49 def quote(s):
50 if shell_need_escapes.search(s):
51 if s.find("'") < 0:
52 return "'" + s + "'"
53 return '"' + shell_dquote_escapes.sub("\\g<0>", s) + '"'
54 return s
55
56 return " ".join([quote(_) for _ in l])
57
58
59 # An instance of this class collects the lists of passing, failing, and
60 # timing-out tests, runs the progress bar, and prints a summary at the end.
61 class Summary:
62 class SummaryBar(progressbar.ProgressBar):
63 def __init__(self, limit):
64 super(Summary.SummaryBar, self).__init__("", limit, 24)
65
66 def start(self):
67 self.label = "[starting ]"
68 self.update(0)
69
70 def counts(self, run, failures, timeouts):
71 self.label = "[%4d|%4d|%4d|%4d]" % (run - failures, failures, timeouts, run)
72 self.update(run)
73
74 def __init__(self, num_tests):
75 self.run = 0
76 self.failures = [] # kind of judgemental; "unexpecteds"?
77 self.timeouts = []
78 if not OPTIONS.hide_progress:
79 self.bar = Summary.SummaryBar(num_tests)
80
81 # Progress bar control.
82 def start(self):
83 if not OPTIONS.hide_progress:
84 self.bar.start()
85
86 def update(self):
87 if not OPTIONS.hide_progress:
88 self.bar.counts(self.run, len(self.failures), len(self.timeouts))
89
90 # Call 'thunk' to show some output, while getting the progress bar out of the way.
91
92 def interleave_output(self, thunk):
93 if not OPTIONS.hide_progress:
94 self.bar.clear()
95 thunk()
96 self.update()
97
98 def passed(self, test):
99 self.run += 1
100 self.update()
101
102 def failed(self, test):
103 self.run += 1
104 self.failures.append(test)
105 self.update()
106
107 def timeout(self, test):
108 self.run += 1
109 self.timeouts.append(test)
110 self.update()
111
112 def finish(self):
113 if not OPTIONS.hide_progress:
114 self.bar.finish()
115
116 if self.failures:
117 print("tests failed:")
118 for test in self.failures:
119 test.show(sys.stdout)
120
121 if OPTIONS.worklist:
122 try:
123 with open(OPTIONS.worklist) as out:
124 for test in self.failures:
125 out.write(test.name + "\n")
126 except OSError as err:
127 sys.stderr.write(
128 "Error writing worklist file '%s': %s" % (OPTIONS.worklist, err)
129 )
130 sys.exit(1)
131
132 if OPTIONS.write_failures:
133 try:
134 with open(OPTIONS.write_failures, "w") as out:
135 for test in self.failures:
136 test.show(out)
137 except OSError as err:
138 sys.stderr.write(
139 "Error writing worklist file '%s': %s"
140 % (OPTIONS.write_failures, err)
141 )
142 sys.exit(1)
143
144 if self.timeouts:
145 print("tests timed out:")
146 for test in self.timeouts:
147 test.show(sys.stdout)
148
149 if self.failures or self.timeouts:
150 sys.exit(2)
151
152
153 class Test(TaskPool.Task):
154 def __init__(self, path, summary):
155 super(Test, self).__init__()
156 self.test_path = path # path to .py test file
157 self.summary = summary
158
159 # test.name is the name of the test relative to the top of the test
160 # directory. This is what we use to report failures and timeouts,
161 # and when writing test lists.
162 self.name = os.path.relpath(self.test_path, OPTIONS.testdir)
163
164 self.stdout = ""
165 self.stderr = ""
166 self.returncode = None
167
168 def cmd(self):
169 testlibdir = os.path.normpath(
170 os.path.join(OPTIONS.testdir, "..", "lib-for-tests")
171 )
172 return [
173 OPTIONS.gdb_executable,
174 "-nw", # Don't create a window (unnecessary?)
175 "-nx", # Don't read .gdbinit.
176 "--ex",
177 "add-auto-load-safe-path %s" % (OPTIONS.bindir,),
178 "--ex",
179 "set env LD_LIBRARY_PATH %s" % (OPTIONS.bindir,),
180 "--ex",
181 "file %s" % (os.path.join(OPTIONS.bindir, "gdb-tests"),),
182 "--eval-command",
183 "python testlibdir=%r" % (testlibdir,),
184 "--eval-command",
185 "python testscript=%r" % (self.test_path,),
186 "--eval-command",
187 "python exec(open(%r).read())" % os.path.join(testlibdir, "catcher.py"),
188 ]
189
190 def start(self, pipe, deadline):
191 super(Test, self).start(pipe, deadline)
192 if OPTIONS.show_cmd:
193 self.summary.interleave_output(lambda: self.show_cmd(sys.stdout))
194
195 def onStdout(self, text):
196 self.stdout += text
197
198 def onStderr(self, text):
199 self.stderr += text
200
201 def onFinished(self, returncode):
202 self.returncode = returncode
203 if OPTIONS.show_output:
204 self.summary.interleave_output(lambda: self.show_output(sys.stdout))
205 if returncode != 0:
206 self.summary.failed(self)
207 else:
208 self.summary.passed(self)
209
210 def onTimeout(self):
211 self.summary.timeout(self)
212
213 def show_cmd(self, out):
214 out.write("Command: %s\n" % (make_shell_cmd(self.cmd()),))
215
216 def show_output(self, out):
217 if self.stdout:
218 out.write("Standard output:")
219 out.write("\n" + self.stdout + "\n")
220 if self.stderr:
221 out.write("Standard error:")
222 out.write("\n" + self.stderr + "\n")
223
224 def show(self, out):
225 out.write(self.name + "\n")
226 if OPTIONS.write_failure_output:
227 self.show_cmd(out)
228 self.show_output(out)
229 out.write("GDB exit code: %r\n" % (self.returncode,))
230
231
232 def find_tests(dir, substring=None):
233 ans = []
234 for dirpath, _, filenames in os.walk(dir):
235 if dirpath == ".":
236 continue
237 for filename in filenames:
238 if not filename.endswith(".py"):
239 continue
240 test = os.path.join(dirpath, filename)
241 if substring is None or substring in os.path.relpath(test, dir):
242 ans.append(test)
243 return ans
244
245
246 def build_test_exec(builddir):
247 subprocess.check_call(["make"], cwd=builddir)
248
249
250 def run_tests(tests, summary):
251 jobs = OPTIONS.workercount
252 # python 3.3 fixed a bug with concurrently writing .pyc files.
253 # https://bugs.python.org/issue13146
254 embedded_version = (
255 subprocess.check_output(
256 [
257 OPTIONS.gdb_executable,
258 "--batch",
259 "--ex",
260 "python import sys; print(sys.hexversion)",
261 ]
262 )
263 .decode("ascii")
264 .strip()
265 )
266 if hex(int(embedded_version)) < "0x3030000":
267 jobs = 1
268
269 pool = TaskPool(tests, job_limit=jobs, timeout=OPTIONS.timeout)
270 pool.run_all()
271
272
273 OPTIONS = None
274
275
276 def main(argv):
277 global OPTIONS
278 script_path = os.path.abspath(__file__)
279 script_dir = os.path.dirname(script_path)
280
281 # OBJDIR is a standalone SpiderMonkey build directory. This is where we
282 # find the SpiderMonkey shared library to link against.
283 #
284 # The [TESTS] optional arguments are paths of test files relative
285 # to the jit-test/tests directory.
286 from optparse import OptionParser
287
288 op = OptionParser(usage="%prog [options] OBJDIR [TESTS...]")
289 op.add_option(
290 "-s",
291 "--show-cmd",
292 dest="show_cmd",
293 action="store_true",
294 help="show GDB shell command run",
295 )
296 op.add_option(
297 "-o",
298 "--show-output",
299 dest="show_output",
300 action="store_true",
301 help="show output from GDB",
302 )
303 op.add_option(
304 "-x",
305 "--exclude",
306 dest="exclude",
307 action="append",
308 help="exclude given test dir or path",
309 )
310 op.add_option(
311 "-t",
312 "--timeout",
313 dest="timeout",
314 type=float,
315 default=150.0,
316 help="set test timeout in seconds",
317 )
318 op.add_option(
319 "-j",
320 "--worker-count",
321 dest="workercount",
322 type=int,
323 help="Run [WORKERCOUNT] tests at a time",
324 )
325 op.add_option(
326 "--no-progress",
327 dest="hide_progress",
328 action="store_true",
329 help="hide progress bar",
330 )
331 op.add_option(
332 "--worklist",
333 dest="worklist",
334 metavar="FILE",
335 help="Read tests to run from [FILE] (or run all if [FILE] not found);\n"
336 "write failures back to [FILE]",
337 )
338 op.add_option(
339 "-r",
340 "--read-tests",
341 dest="read_tests",
342 metavar="FILE",
343 help="Run test files listed in [FILE]",
344 )
345 op.add_option(
346 "-w",
347 "--write-failures",
348 dest="write_failures",
349 metavar="FILE",
350 help="Write failing tests to [FILE]",
351 )
352 op.add_option(
353 "--write-failure-output",
354 dest="write_failure_output",
355 action="store_true",
356 help="With --write-failures=FILE, additionally write the output of failed "
357 "tests to [FILE]",
358 )
359 op.add_option(
360 "--gdb",
361 dest="gdb_executable",
362 metavar="EXECUTABLE",
363 default="gdb",
364 help="Run tests with [EXECUTABLE], rather than plain 'gdb'.",
365 )
366 op.add_option(
367 "--srcdir",
368 dest="srcdir",
369 default=os.path.abspath(os.path.join(script_dir, "..")),
370 help="Use SpiderMonkey sources in [SRCDIR].",
371 )
372 op.add_option(
373 "--testdir",
374 dest="testdir",
375 default=os.path.join(script_dir, "tests"),
376 help="Find tests in [TESTDIR].",
377 )
378 op.add_option(
379 "--builddir", dest="builddir", help="Build test executable from [BUILDDIR]."
380 )
381 op.add_option("--bindir", dest="bindir", help="Run test executable from [BINDIR].")
382 (OPTIONS, args) = op.parse_args(argv)
383 if len(args) < 1:
384 op.error("missing OBJDIR argument")
385 OPTIONS.objdir = os.path.abspath(args[0])
386
387 test_args = args[1:]
388
389 if not OPTIONS.workercount:
390 OPTIONS.workercount = get_cpu_count()
391
392 # Compute defaults for OPTIONS.builddir and OPTIONS.bindir now, since we've
393 # computed OPTIONS.objdir.
394 if not OPTIONS.builddir:
395 OPTIONS.builddir = os.path.join(OPTIONS.objdir, "js", "src", "gdb")
396 if not OPTIONS.bindir:
397 OPTIONS.bindir = os.path.join(OPTIONS.objdir, "dist", "bin")
398
399 test_set = set()
400
401 # All the various sources of test names accumulate.
402 if test_args:
403 for arg in test_args:
404 test_set.update(find_tests(OPTIONS.testdir, arg))
405 if OPTIONS.worklist:
406 try:
407 with open(OPTIONS.worklist) as f:
408 for line in f:
409 test_set.update(os.path.join(OPTIONS.testdir, line.strip("\n")))
410 except OSError:
411 # With worklist, a missing file means to start the process with
412 # the complete list of tests.
413 sys.stderr.write(
414 "Couldn't read worklist file '%s'; running all tests\n"
415 % (OPTIONS.worklist,)
416 )
417 test_set = set(find_tests(OPTIONS.testdir))
418 if OPTIONS.read_tests:
419 try:
420 with open(OPTIONS.read_tests) as f:
421 for line in f:
422 test_set.update(os.path.join(OPTIONS.testdir, line.strip("\n")))
423 except OSError as err:
424 sys.stderr.write(
425 "Error trying to read test file '%s': %s\n" % (OPTIONS.read_tests, err)
426 )
427 sys.exit(1)
428
429 # If none of the above options were passed, and no tests were listed
430 # explicitly, use the complete set.
431 if not test_args and not OPTIONS.worklist and not OPTIONS.read_tests:
432 test_set = set(find_tests(OPTIONS.testdir))
433
434 if OPTIONS.exclude:
435 exclude_set = set()
436 for exclude in OPTIONS.exclude:
437 exclude_set.update(find_tests(OPTIONS.testdir, exclude))
438 test_set -= exclude_set
439
440 if not test_set:
441 sys.stderr.write("No tests found matching command line arguments.\n")
442 sys.exit(1)
443
444 summary = Summary(len(test_set))
445 test_list = [Test(_, summary) for _ in sorted(test_set)]
446
447 # Build the test executable from all the .cpp files found in the test
448 # directory tree.
449 try:
450 build_test_exec(OPTIONS.builddir)
451 except subprocess.CalledProcessError as err:
452 sys.stderr.write("Error building test executable: %s\n" % (err,))
453 sys.exit(1)
454
455 # Run the tests.
456 try:
457 summary.start()
458 run_tests(test_list, summary)
459 summary.finish()
460 except OSError as err:
461 sys.stderr.write("Error running tests: %s\n" % (err,))
462 sys.exit(1)
463
464 sys.exit(0)
465
466
467 if __name__ == "__main__":
468 main(sys.argv[1:])