Debian Codegraph @

js/src/jit-test/jit_test.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 import math
7 import os
8 import platform
9 import posixpath
10 import shlex
11 import subprocess
12 import sys
13 import traceback
14
15 read_input = input
16 if sys.version_info.major == 2:
17 read_input = raw_input
18
19
20 def add_tests_dir_to_path():
21 from os.path import dirname, exists, join, realpath
22
23 js_src_dir = dirname(dirname(realpath(sys.argv[0])))
24 assert exists(join(js_src_dir, "jsapi.h"))
25 sys.path.insert(0, join(js_src_dir, "tests"))
26
27
28 add_tests_dir_to_path()
29
30 from lib import jittests
31 from lib.tempfile import TemporaryDirectory
32 from lib.tests import (
33 change_env,
34 get_cpu_count,
35 get_environment_overlay,
36 get_jitflags,
37 valid_jitflags,
38 )
39
40
41 def which(name):
42 if name.find(os.path.sep) != -1:
43 return os.path.abspath(name)
44
45 for path in os.environ["PATH"].split(os.pathsep):
46 full = os.path.join(path, name)
47 if os.path.exists(full):
48 return os.path.abspath(full)
49
50 return name
51
52
53 def choose_item(jobs, max_items):
54 job_count = len(jobs)
55
56 # Don't present a choice if there are too many tests
57 if job_count > max_items:
58 raise Exception("Too many jobs.")
59
60 def display_job(job):
61 flags = ""
62 if len(job.jitflags) != 0:
63 flags = "({})".format(" ".join(job.jitflags))
64 return f"{job.path} {flags}"
65
66 for i, job in enumerate(jobs, 1):
67 print(f"{i}) {display_job(job)}")
68
69 item = read_input("Which one:\n")
70 try:
71 item = int(item)
72 if item > job_count or item < 1:
73 raise Exception(f"Input isn't between 1 and {job_count}")
74 except ValueError:
75 raise Exception("Unrecognized input")
76
77 return jobs[item - 1]
78
79
80 def main(argv):
81 # The [TESTS] optional arguments are paths of test files relative
82 # to the jit-test/tests directory.
83 import argparse
84
85 op = argparse.ArgumentParser(description="Run jit-test JS shell tests")
86 op.add_argument(
87 "-s",
88 "--show-cmd",
89 dest="show_cmd",
90 action="store_true",
91 help="show js shell command run",
92 )
93 op.add_argument(
94 "-f",
95 "--show-failed-cmd",
96 dest="show_failed",
97 action="store_true",
98 help="show command lines of failed tests",
99 )
100 op.add_argument(
101 "-o",
102 "--show-output",
103 dest="show_output",
104 action="store_true",
105 help="show output from js shell",
106 )
107 op.add_argument(
108 "-F",
109 "--failed-only",
110 dest="failed_only",
111 action="store_true",
112 help="if --show-output is given, only print output for" " failed tests",
113 )
114 op.add_argument(
115 "--no-show-failed",
116 dest="no_show_failed",
117 action="store_true",
118 help="don't print output for failed tests" " (no-op with --show-output)",
119 )
120 op.add_argument(
121 "-x",
122 "--exclude",
123 dest="exclude",
124 default=[],
125 action="append",
126 help="exclude given test dir or path",
127 )
128 op.add_argument(
129 "--exclude-from",
130 dest="exclude_from",
131 type=str,
132 help="exclude each test dir or path in FILE",
133 )
134 op.add_argument(
135 "--slow",
136 dest="run_slow",
137 action="store_true",
138 help="also run tests marked as slow",
139 )
140 op.add_argument(
141 "--no-slow",
142 dest="run_slow",
143 action="store_false",
144 help="do not run tests marked as slow (the default)",
145 )
146 op.add_argument(
147 "-t",
148 "--timeout",
149 dest="timeout",
150 type=float,
151 default=150.0,
152 help="set test timeout in seconds",
153 )
154 op.add_argument(
155 "--no-progress",
156 dest="hide_progress",
157 action="store_true",
158 help="hide progress bar",
159 )
160 op.add_argument(
161 "--tinderbox",
162 dest="format",
163 action="store_const",
164 const="automation",
165 help="Use automation-parseable output format",
166 )
167 op.add_argument(
168 "--format",
169 dest="format",
170 default="none",
171 choices=("automation", "none"),
172 help="Output format (default %(default)s).",
173 )
174 op.add_argument(
175 "--args",
176 dest="shell_args",
177 metavar="ARGS",
178 default="",
179 help="extra args to pass to the JS shell",
180 )
181 op.add_argument(
182 "--feature-args",
183 dest="feature_args",
184 metavar="ARGS",
185 default="",
186 help="even more args to pass to the JS shell "
187 "(for compatibility with jstests.py)",
188 )
189 op.add_argument(
190 "-w",
191 "--write-failures",
192 dest="write_failures",
193 metavar="FILE",
194 help="Write a list of failed tests to [FILE]",
195 )
196 op.add_argument(
197 "-C",
198 "--check-output",
199 action="store_true",
200 dest="check_output",
201 help="Run tests to check output for different jit-flags",
202 )
203 op.add_argument(
204 "-r",
205 "--read-tests",
206 dest="read_tests",
207 metavar="FILE",
208 help="Run test files listed in [FILE]",
209 )
210 op.add_argument(
211 "-R",
212 "--retest",
213 dest="retest",
214 metavar="FILE",
215 help="Retest using test list file [FILE]",
216 )
217 op.add_argument(
218 "-g",
219 "--debug",
220 action="store_const",
221 const="gdb",
222 dest="debugger",
223 help="Run a single test under the gdb debugger",
224 )
225 op.add_argument(
226 "-G",
227 "--debug-rr",
228 action="store_const",
229 const="rr",
230 dest="debugger",
231 help="Run a single test under the rr debugger",
232 )
233 op.add_argument(
234 "--debugger", type=str, help="Run a single test under the specified debugger"
235 )
236 op.add_argument("--one", action="store_true", help="Run a single test only.")
237 op.add_argument(
238 "--valgrind",
239 dest="valgrind",
240 action="store_true",
241 help="Enable the |valgrind| flag, if valgrind is in $PATH.",
242 )
243 op.add_argument(
244 "--unusable-error-status",
245 action="store_true",
246 help="Ignore incorrect exit status on tests that should return nonzero.",
247 )
248 op.add_argument(
249 "--valgrind-all",
250 dest="valgrind_all",
251 action="store_true",
252 help="Run all tests with valgrind, if valgrind is in $PATH.",
253 )
254 op.add_argument(
255 "--write-failure-output",
256 dest="write_failure_output",
257 action="store_true",
258 help="With --write-failures=FILE, additionally write the"
259 " output of failed tests to [FILE]",
260 )
261 op.add_argument(
262 "--jitflags",
263 dest="jitflags",
264 default="none",
265 choices=valid_jitflags(),
266 help="IonMonkey option combinations (default %(default)s).",
267 )
268 op.add_argument(
269 "--ion",
270 dest="jitflags",
271 action="store_const",
272 const="ion",
273 help="Run tests once with --ion-eager and once with"
274 " --baseline-eager (equivalent to --jitflags=ion)",
275 )
276 op.add_argument(
277 "--no-xdr",
278 dest="use_xdr",
279 action="store_false",
280 help="Whether to disable caching of self-hosted parsed content in XDR format.",
281 )
282 op.add_argument(
283 "--tbpl",
284 dest="jitflags",
285 action="store_const",
286 const="all",
287 help="Run tests with all IonMonkey option combinations"
288 " (equivalent to --jitflags=all)",
289 )
290 op.add_argument(
291 "-j",
292 "--worker-count",
293 dest="max_jobs",
294 type=int,
295 default=max(1, get_cpu_count()),
296 help="Number of tests to run in parallel (default %(default)s).",
297 )
298 op.add_argument(
299 "--remote", action="store_true", help="Run tests on a remote device"
300 )
301 op.add_argument(
302 "--deviceIP",
303 action="store",
304 type=str,
305 dest="device_ip",
306 help="IP address of remote device to test",
307 )
308 op.add_argument(
309 "--devicePort",
310 action="store",
311 type=int,
312 dest="device_port",
313 default=20701,
314 help="port of remote device to test",
315 )
316 op.add_argument(
317 "--deviceSerial",
318 action="store",
319 type=str,
320 dest="device_serial",
321 default=None,
322 help="ADB device serial number of remote device to test",
323 )
324 op.add_argument(
325 "--remoteTestRoot",
326 dest="remote_test_root",
327 action="store",
328 type=str,
329 default="/data/local/tmp/test_root",
330 help="The remote directory to use as test root" " (e.g. %(default)s)",
331 )
332 op.add_argument(
333 "--localLib",
334 dest="local_lib",
335 action="store",
336 type=str,
337 help="The location of libraries to push -- preferably" " stripped",
338 )
339 op.add_argument(
340 "--repeat", type=int, default=1, help="Repeat tests the given number of times."
341 )
342 op.add_argument("--this-chunk", type=int, default=1, help="The test chunk to run.")
343 op.add_argument(
344 "--total-chunks", type=int, default=1, help="The total number of test chunks."
345 )
346 op.add_argument(
347 "--ignore-timeouts",
348 dest="ignore_timeouts",
349 metavar="FILE",
350 help="Ignore timeouts of tests listed in [FILE]",
351 )
352 op.add_argument(
353 "--retry-remote-timeouts",
354 dest="timeout_retry",
355 type=int,
356 default=1,
357 help="Number of time to retry timeout on remote devices",
358 )
359 op.add_argument(
360 "--test-reflect-stringify",
361 dest="test_reflect_stringify",
362 help="instead of running tests, use them to test the "
363 "Reflect.stringify code in specified file",
364 )
365 # --enable-webrender is ignored as it is not relevant for JIT
366 # tests, but is required for harness compatibility.
367 op.add_argument(
368 "--enable-webrender",
369 action="store_true",
370 dest="enable_webrender",
371 default=False,
372 help=argparse.SUPPRESS,
373 )
374 op.add_argument("js_shell", metavar="JS_SHELL", help="JS shell to run tests with")
375 op.add_argument(
376 "-z", "--gc-zeal", help="GC zeal mode to use when running the shell"
377 )
378 op.add_argument(
379 "--show-slow",
380 action="store_true",
381 help="Show tests taking longer than a minimum time (in seconds).",
382 )
383 op.add_argument(
384 "--slow-test-threshold",
385 type=float,
386 default=5.0,
387 help="Time in seconds a test can take until it is considered slow "
388 "(default %(default)s).",
389 )
390
391 options, test_args = op.parse_known_args(argv)
392 js_shell = which(options.js_shell)
393 test_environment = get_environment_overlay(js_shell, options.gc_zeal)
394
395 if not (os.path.isfile(js_shell) and os.access(js_shell, os.X_OK)):
396 if (
397 platform.system() != "Windows"
398 or os.path.isfile(js_shell)
399 or not os.path.isfile(js_shell + ".exe")
400 or not os.access(js_shell + ".exe", os.X_OK)
401 ):
402 op.error("shell is not executable: " + js_shell)
403
404 if options.retest:
405 options.read_tests = options.retest
406 options.write_failures = options.retest
407
408 test_list = []
409 read_all = True
410
411 if test_args:
412 read_all = False
413 for arg in test_args:
414 test_list += jittests.find_tests(arg)
415
416 if options.read_tests:
417 read_all = False
418 try:
419 f = open(options.read_tests)
420 for line in f:
421 test_list.append(os.path.join(jittests.TEST_DIR, line.strip("\n")))
422 f.close()
423 except OSError:
424 if options.retest:
425 read_all = True
426 else:
427 sys.stderr.write(
428 "Exception thrown trying to read test file"
429 f" '{options.read_tests}'\n"
430 )
431 traceback.print_exc()
432 sys.stderr.write("---\n")
433
434 if read_all:
435 test_list = jittests.find_tests()
436
437 if options.exclude_from:
438 with open(options.exclude_from) as fh:
439 for line in fh:
440 line_exclude = line.strip()
441 if not line_exclude.startswith("#") and len(line_exclude):
442 options.exclude.append(line_exclude)
443
444 if options.exclude:
445 exclude_list = []
446 for exclude in options.exclude:
447 exclude_list += jittests.find_tests(exclude)
448 test_list = [test for test in test_list if test not in set(exclude_list)]
449
450 if not test_list:
451 print("No tests found matching command line arguments.", file=sys.stderr)
452 sys.exit(0)
453
454 test_list = [jittests.JitTest.from_file(_, options) for _ in test_list]
455
456 if not options.run_slow:
457 test_list = [_ for _ in test_list if not _.slow]
458
459 if options.test_reflect_stringify is not None:
460 for test in test_list:
461 test.test_reflect_stringify = options.test_reflect_stringify
462
463 # If chunking is enabled, determine which tests are part of this chunk.
464 # This code was adapted from testing/mochitest/runtestsremote.py.
465 if options.total_chunks > 1:
466 total_tests = len(test_list)
467 tests_per_chunk = math.ceil(total_tests / float(options.total_chunks))
468 start = int(round((options.this_chunk - 1) * tests_per_chunk))
469 end = int(round(options.this_chunk * tests_per_chunk))
470 test_list = test_list[start:end]
471
472 if not test_list:
473 print(
474 "No tests found matching command line arguments after filtering.",
475 file=sys.stderr,
476 )
477 sys.exit(0)
478
479 # The full test list is ready. Now create copies for each JIT configuration.
480 test_flags = get_jitflags(options.jitflags)
481
482 test_list = [_ for test in test_list for _ in test.copy_variants(test_flags)]
483
484 job_list = (test for test in test_list)
485 job_count = len(test_list)
486
487 if options.repeat:
488
489 def repeat_copy(job_list_generator, repeat):
490 job_list = list(job_list_generator)
491 for i in range(repeat):
492 for test in job_list:
493 if i == 0:
494 yield test
495 else:
496 yield test.copy()
497
498 job_list = repeat_copy(job_list, options.repeat)
499 job_count *= options.repeat
500
501 if options.ignore_timeouts:
502 read_all = False
503 try:
504 with open(options.ignore_timeouts) as f:
505 ignore = set()
506 for line in f.readlines():
507 path = line.strip("\n")
508 ignore.add(path)
509 options.ignore_timeouts = ignore
510 except OSError:
511 sys.exit("Error reading file: " + options.ignore_timeouts)
512 else:
513 options.ignore_timeouts = set()
514
515 prefix = (
516 [js_shell] + shlex.split(options.shell_args) + shlex.split(options.feature_args)
517 )
518 prologue = os.path.join(jittests.LIB_DIR, "prologue.js")
519 if options.remote:
520 prologue = posixpath.join(options.remote_test_root, "lib", "prologue.js")
521
522 prefix += ["-p", prologue]
523
524 if options.one:
525 try:
526 jobs = list(job_list)
527 tc = choose_item(jobs, max_items=50)
528 except Exception as e:
529 sys.exit(str(e))
530
531 with change_env(test_environment):
532 with TemporaryDirectory() as tempdir:
533 cmd = tc.command(prefix, jittests.LIB_DIR, jittests.MODULE_DIR, tempdir)
534 os.execvp(cmd[0], cmd)
535 sys.exit()
536 elif options.debugger:
537 if job_count > 1:
538 print(
539 "Multiple tests match command line"
540 " arguments, debugger can only run one"
541 )
542 jobs = list(job_list)
543
544 try:
545 tc = choose_item(jobs, max_items=50)
546 except Exception as e:
547 sys.exit(str(e))
548 else:
549 tc = next(job_list)
550
551 if options.debugger == "gdb":
552 debug_cmd = ["gdb", "--args"]
553 elif options.debugger == "lldb":
554 debug_cmd = ["lldb", "--"]
555 elif options.debugger == "rr":
556 debug_cmd = ["rr", "record"]
557 else:
558 debug_cmd = options.debugger.split()
559
560 with change_env(test_environment):
561 with TemporaryDirectory() as tempdir:
562 if options.debugger == "rr":
563 subprocess.call(
564 debug_cmd
565 + tc.command(
566 prefix, jittests.LIB_DIR, jittests.MODULE_DIR, tempdir
567 )
568 )
569 os.execvp("rr", ["rr", "replay"])
570 else:
571 os.execvp(
572 debug_cmd[0],
573 debug_cmd
574 + tc.command(
575 prefix, jittests.LIB_DIR, jittests.MODULE_DIR, tempdir
576 ),
577 )
578 sys.exit()
579
580 try:
581 ok = None
582 if options.remote:
583 ok = jittests.run_tests(job_list, job_count, prefix, options, remote=True)
584 else:
585 with change_env(test_environment):
586 ok = jittests.run_tests(job_list, job_count, prefix, options)
587 if not ok:
588 sys.exit(2)
589 except OSError:
590 if not os.path.exists(prefix[0]):
591 print(
592 "JS shell argument: file does not exist:" f" '{prefix[0]}'",
593 file=sys.stderr,
594 )
595 sys.exit(1)
596 else:
597 raise
598
599
600 if __name__ == "__main__":
601 main(sys.argv[1:])