Debian Codegraph @

js/src/tests/lib/jittests.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
7 # jit_test.py -- Python harness for JavaScript trace tests.
8
9 import os
10 import re
11 import sys
12 import traceback
13 from collections import namedtuple
14 from enum import Enum
15
16 if sys.platform.startswith("linux") or sys.platform.startswith("darwin"):
17 from .tasks_unix import run_all_tests
18 else:
19 from .tasks_win import run_all_tests
20
21 from .progressbar import NullProgressBar, ProgressBar
22 from .results import escape_cmdline
23 from .structuredlog import TestLogger
24 from .tempfile import TemporaryDirectory
25
26 TESTS_LIB_DIR = os.path.dirname(os.path.abspath(__file__))
27 JS_DIR = os.path.dirname(os.path.dirname(TESTS_LIB_DIR))
28 TOP_SRC_DIR = os.path.dirname(os.path.dirname(JS_DIR))
29 TEST_DIR = os.path.join(JS_DIR, "jit-test", "tests")
30 LIB_DIR = os.path.join(JS_DIR, "jit-test", "lib") + os.path.sep
31 MODULE_DIR = os.path.join(JS_DIR, "jit-test", "modules") + os.path.sep
32 SHELL_XDR = "shell.xdr"
33
34
35 class OutputStatus(Enum):
36 OK = 1
37 SKIPPED = 2
38 FAILED = 3
39
40 def __bool__(self):
41 return self != OutputStatus.FAILED
42
43
44 # Backported from Python 3.1 posixpath.py
45
46
47 def _relpath(path, start=None):
48 """Return a relative version of a path"""
49
50 if not path:
51 raise ValueError("no path specified")
52
53 if start is None:
54 start = os.curdir
55
56 start_list = os.path.abspath(start).split(os.sep)
57 path_list = os.path.abspath(path).split(os.sep)
58
59 # Work out how much of the filepath is shared by start and path.
60 i = len(os.path.commonprefix([start_list, path_list]))
61
62 rel_list = [os.pardir] * (len(start_list) - i) + path_list[i:]
63 if not rel_list:
64 return os.curdir
65 return os.path.join(*rel_list)
66
67
68 # Mapping of Python chars to their javascript string representation.
69 QUOTE_MAP = {
70 "\\": "\\\\",
71 "\b": "\\b",
72 "\f": "\\f",
73 "\n": "\\n",
74 "\r": "\\r",
75 "\t": "\\t",
76 "\v": "\\v",
77 }
78
79 # Quote the string S, javascript style.
80
81
82 def js_quote(quote, s):
83 result = quote
84 for c in s:
85 if c == quote:
86 result += "\\" + quote
87 elif c in QUOTE_MAP:
88 result += QUOTE_MAP[c]
89 else:
90 result += c
91 result += quote
92 return result
93
94
95 os.path.relpath = _relpath
96
97
98 def extend_condition(condition, value):
99 if condition:
100 condition += " || "
101 condition += f"({value})"
102 return condition
103
104
105 class JitTest:
106 VALGRIND_CMD = []
107 paths = (d for d in os.environ["PATH"].split(os.pathsep))
108 valgrinds = (os.path.join(d, "valgrind") for d in paths)
109 if any(os.path.exists(p) for p in valgrinds):
110 VALGRIND_CMD = [
111 "valgrind",
112 "-q",
113 "--smc-check=all-non-file",
114 "--error-exitcode=1",
115 "--gen-suppressions=all",
116 "--show-possibly-lost=no",
117 "--leak-check=full",
118 ]
119 if os.uname()[0] == "Darwin":
120 VALGRIND_CMD.append("--dsymutil=yes")
121
122 del paths
123 del valgrinds
124
125 def __init__(self, path):
126 # Absolute path of the test file.
127 self.path = path
128
129 # Path relative to the top mozilla/ directory.
130 self.relpath_top = os.path.relpath(path, TOP_SRC_DIR)
131
132 # Path relative to mozilla/js/src/jit-test/tests/.
133 self.relpath_tests = os.path.relpath(path, TEST_DIR)
134
135 # jit flags to enable
136 self.jitflags = []
137 # True means the test is slow-running
138 self.slow = False
139 # Heavy tests will never run alongside other heavy tests
140 self.heavy = False
141 # True means that OOM is not considered a failure
142 self.allow_oom = False
143 # True means CrashAtUnhandlableOOM is not considered a failure
144 self.allow_unhandlable_oom = False
145 # True means that hitting recursion the limits is not considered a failure.
146 self.allow_overrecursed = False
147 # True means run under valgrind
148 self.valgrind = False
149 # True means force Pacific time for the test
150 self.tz_pacific = False
151 # Additional files to include, in addition to prologue.js
152 self.other_lib_includes = []
153 self.other_script_includes = []
154 # List of other configurations to test with.
155 self.test_also = []
156 # List of other configurations to test with all existing variants.
157 self.test_join = []
158 # Errors to expect and consider passing
159 self.expect_error = ""
160 # Exit status to expect from shell
161 self.expect_status = 0
162 # Exit status or error output.
163 self.expect_crash = False
164 self.is_module = False
165 # Reflect.stringify implementation to test
166 self.test_reflect_stringify = None
167 # Use self-hosted XDR instead of parsing the source stored in the binary.
168 self.selfhosted_xdr_path = None
169 self.selfhosted_xdr_mode = "off"
170
171 # Skip-if condition. We don't have a xulrunner, but we can ask the shell
172 # directly.
173 self.skip_if_cond = ""
174 self.skip_variant_if_cond = {}
175
176 # Expected by the test runner. Always true for jit-tests.
177 self.enable = True
178
179 def copy(self):
180 t = JitTest(self.path)
181 t.jitflags = self.jitflags[:]
182 t.slow = self.slow
183 t.heavy = self.heavy
184 t.allow_oom = self.allow_oom
185 t.allow_unhandlable_oom = self.allow_unhandlable_oom
186 t.allow_overrecursed = self.allow_overrecursed
187 t.valgrind = self.valgrind
188 t.tz_pacific = self.tz_pacific
189 t.other_lib_includes = self.other_lib_includes[:]
190 t.other_script_includes = self.other_script_includes[:]
191 t.test_also = self.test_also
192 t.test_join = self.test_join
193 t.expect_error = self.expect_error
194 t.expect_status = self.expect_status
195 t.expect_crash = self.expect_crash
196 t.test_reflect_stringify = self.test_reflect_stringify
197 t.selfhosted_xdr_path = self.selfhosted_xdr_path
198 t.selfhosted_xdr_mode = self.selfhosted_xdr_mode
199 t.enable = True
200 t.is_module = self.is_module
201 t.skip_if_cond = self.skip_if_cond
202 t.skip_variant_if_cond = self.skip_variant_if_cond
203 return t
204
205 def copy_and_extend_jitflags(self, variant):
206 t = self.copy()
207 t.jitflags.extend(variant)
208 for flags in variant:
209 if flags in self.skip_variant_if_cond:
210 t.skip_if_cond = extend_condition(
211 t.skip_if_cond, self.skip_variant_if_cond[flags]
212 )
213 return t
214
215 def copy_variants(self, variants):
216 # Append variants to be tested in addition to the current set of tests.
217 variants = variants + self.test_also
218
219 # For each existing variant, duplicates it for each list of options in
220 # test_join. This will multiply the number of variants by 2 for set of
221 # options.
222 for join_opts in self.test_join:
223 variants = variants + [opts + join_opts for opts in variants]
224
225 # For each list of jit flags, make a copy of the test.
226 return [self.copy_and_extend_jitflags(v) for v in variants]
227
228 COOKIE = b"|jit-test|"
229
230 # We would use 500019 (5k19), but quit() only accepts values up to 127, due to fuzzers
231 SKIPPED_EXIT_STATUS = 59
232 Directives = {}
233
234 @classmethod
235 def find_directives(cls, file_name):
236 meta = ""
237 line = open(file_name, "rb").readline()
238 i = line.find(cls.COOKIE)
239 if i != -1:
240 meta = ";" + line[i + len(cls.COOKIE) :].decode(errors="strict").strip("\n")
241 return meta
242
243 @classmethod
244 def from_file(cls, path, options):
245 test = cls(path)
246
247 # If directives.txt exists in the test's directory then it may
248 # contain metainformation that will be catenated with
249 # whatever's in the test file. The form of the directive in
250 # the directive file is the same as in the test file. Only
251 # the first line is considered, just as for the test file.
252
253 dir_meta = ""
254 dir_name = os.path.dirname(path)
255 if dir_name in cls.Directives:
256 dir_meta = cls.Directives[dir_name]
257 else:
258 meta_file_name = os.path.join(dir_name, "directives.txt")
259 if os.path.exists(meta_file_name):
260 dir_meta = cls.find_directives(meta_file_name)
261 cls.Directives[dir_name] = dir_meta
262
263 filename, file_extension = os.path.splitext(path)
264 meta = cls.find_directives(path)
265
266 if meta != "" or dir_meta != "":
267 meta = meta + dir_meta
268 parts = meta.split(";")
269 for part in parts:
270 part = part.strip()
271 if not part:
272 continue
273 name, _, value = part.partition(":")
274 if value:
275 value = value.strip()
276 if name == "error":
277 test.expect_error = value
278 elif name == "exitstatus":
279 try:
280 status = int(value, 0)
281 if status == test.SKIPPED_EXIT_STATUS:
282 print(
283 "warning: jit-tests uses {} as a sentinel"
284 " return value {}",
285 test.SKIPPED_EXIT_STATUS,
286 path,
287 )
288 else:
289 test.expect_status = status
290 except ValueError:
291 print("warning: couldn't parse exit status" f" {value}")
292 elif name == "thread-count":
293 try:
294 test.jitflags.append(f"--thread-count={int(value, 0)}")
295 except ValueError:
296 print("warning: couldn't parse thread-count" f" {value}")
297 elif name == "include":
298 test.other_lib_includes.append(value)
299 elif name == "local-include":
300 test.other_script_includes.append(value)
301 elif name == "skip-if":
302 test.skip_if_cond = extend_condition(test.skip_if_cond, value)
303 elif name == "skip-variant-if":
304 try:
305 [variant, condition] = value.split(",")
306 test.skip_variant_if_cond[variant] = extend_condition(
307 test.skip_if_cond, condition
308 )
309 except ValueError:
310 print("warning: couldn't parse skip-variant-if")
311 else:
312 print(
313 f"{path}: warning: unrecognized |jit-test| attribute"
314 f" {part}"
315 )
316 else:
317 if name == "slow":
318 test.slow = True
319 elif name == "heavy":
320 test.heavy = True
321 elif name == "allow-oom":
322 test.allow_oom = True
323 elif name == "allow-unhandlable-oom":
324 test.allow_unhandlable_oom = True
325 elif name == "allow-overrecursed":
326 test.allow_overrecursed = True
327 elif name == "valgrind":
328 test.valgrind = options.valgrind
329 elif name == "tz-pacific":
330 test.tz_pacific = True
331 elif name.startswith("test-also="):
332 test.test_also.append(
333 re.split(r"\s+", name[len("test-also=") :])
334 )
335 elif name.startswith("test-join="):
336 test.test_join.append(
337 re.split(r"\s+", name[len("test-join=") :])
338 )
339 elif name == "module":
340 test.is_module = True
341 elif name == "crash":
342 # Crashes are only allowed in self-test, as it is
343 # intended to verify that our testing infrastructure
344 # works, and not meant as a way to accept temporary
345 # failing tests. These tests should either be fixed or
346 # skipped.
347 assert (
348 "self-test" in path
349 ), f"{path}: has an unexpected crash annotation."
350 test.expect_crash = True
351 elif name.startswith("--"):
352 # // |jit-test| --ion-gvn=off; --no-sse4
353 test.jitflags.append(name)
354 elif name.startswith("-P"):
355 prefAndValue = name.split()
356 assert (
357 len(prefAndValue) == 2
358 ), f"{name}: failed to parse preference"
359 # // |jit-test| -P pref(=value)?
360 test.jitflags.append("--setpref=" + prefAndValue[1])
361 else:
362 print(
363 f"{path}: warning: unrecognized |jit-test| attribute"
364 f" {part}"
365 )
366
367 if options.valgrind_all:
368 test.valgrind = True
369
370 if options.test_reflect_stringify is not None:
371 test.expect_error = ""
372 test.expect_status = 0
373
374 return test
375
376 def command(self, prefix, libdir, moduledir, tempdir, remote_prefix=None):
377 path = self.path
378 if remote_prefix:
379 path = self.path.replace(TEST_DIR, remote_prefix)
380
381 scriptdir_var = os.path.dirname(path)
382 if not scriptdir_var.endswith("/"):
383 scriptdir_var += "/"
384
385 # Note: The tempdir provided as argument is managed by the caller
386 # should remain alive as long as the test harness. Therefore, the XDR
387 # content of the self-hosted code would be accessible to all JS Shell
388 # instances.
389 self.selfhosted_xdr_path = os.path.join(tempdir, SHELL_XDR)
390
391 # Platforms where subprocess immediately invokes exec do not care
392 # whether we use double or single quotes. On windows and when using
393 # a remote device, however, we have to be careful to use the quote
394 # style that is the opposite of what the exec wrapper uses.
395 if remote_prefix:
396 quotechar = '"'
397 else:
398 quotechar = "'"
399
400 # Don't merge the expressions: We want separate -e arguments to avoid
401 # semicolons in the command line, bug 1351607.
402 exprs = [
403 f"const platform={js_quote(quotechar, sys.platform)}",
404 f"const libdir={js_quote(quotechar, libdir)}",
405 f"const scriptdir={js_quote(quotechar, scriptdir_var)}",
406 ]
407
408 # We may have specified '-a' or '-d' twice: once via --jitflags, once
409 # via the "|jit-test|" line. Remove dups because they are toggles.
410 # Note: |dict.fromkeys(flags)| is similar to |set(flags)| but it
411 # preserves order.
412 cmd = prefix + []
413 cmd += list(dict.fromkeys(self.jitflags))
414 # Handle selfhosted XDR file.
415 if self.selfhosted_xdr_mode != "off":
416 cmd += [
417 "--selfhosted-xdr-path",
418 self.selfhosted_xdr_path,
419 "--selfhosted-xdr-mode",
420 self.selfhosted_xdr_mode,
421 ]
422 for expr in exprs:
423 cmd += ["-e", expr]
424 for inc in self.other_lib_includes:
425 cmd += ["-f", libdir + inc]
426 for inc in self.other_script_includes:
427 cmd += ["-f", scriptdir_var + inc]
428 if self.skip_if_cond:
429 cmd += [
430 "-e",
431 f"if ({self.skip_if_cond}) quit({self.SKIPPED_EXIT_STATUS})",
432 ]
433 cmd += ["--module-load-path", moduledir]
434 if self.is_module:
435 cmd += ["--module", path]
436 elif self.test_reflect_stringify is None:
437 cmd += ["-f", path]
438 else:
439 cmd += ["--", self.test_reflect_stringify, "--check", path]
440
441 if self.valgrind:
442 cmd = self.VALGRIND_CMD + cmd
443
444 if self.allow_unhandlable_oom or self.expect_crash:
445 cmd += ["--suppress-minidump"]
446
447 return cmd
448
449 def get_command(self, prefix, tempdir):
450 """Shim for the test runner."""
451 return self.command(prefix, LIB_DIR, MODULE_DIR, tempdir)
452
453
454 def find_tests(substring=None):
455 ans = []
456 for dirpath, dirnames, filenames in os.walk(TEST_DIR):
457 dirnames.sort()
458 filenames.sort()
459 if dirpath == ".":
460 continue
461
462 for filename in filenames:
463 if not filename.endswith(".js"):
464 continue
465 if filename in ("shell.js", "browser.js"):
466 continue
467 test = os.path.join(dirpath, filename)
468 if substring is None or substring in os.path.relpath(test, TEST_DIR):
469 ans.append(test)
470 return ans
471
472
473 def check_output(out, err, rc, timed_out, test, options):
474 # Allow skipping to compose with other expected results
475 if test.skip_if_cond:
476 if rc == test.SKIPPED_EXIT_STATUS:
477 return OutputStatus.SKIPPED
478
479 if timed_out:
480 relpath = os.path.normpath(test.relpath_tests).replace(os.sep, "/")
481 if relpath in options.ignore_timeouts:
482 return OutputStatus.OK
483 return OutputStatus.FAILED
484
485 if test.expect_error:
486 # The shell exits with code 3 on uncaught exceptions.
487 if rc != 3:
488 return OutputStatus.FAILED
489
490 return test.expect_error in err
491
492 for line in out.split("\n"):
493 if line.startswith("Trace stats check failed"):
494 return OutputStatus.FAILED
495
496 for line in err.split("\n"):
497 if "Assertion failed:" in line:
498 return OutputStatus.FAILED
499
500 if test.expect_crash:
501 # Python 3 on Windows interprets process exit codes as unsigned
502 # integers, where Python 2 used to allow signed integers. Account for
503 # each possibility here.
504 if sys.platform == "win32" and rc in (3 - 2**31, 3 + 2**31):
505 return OutputStatus.OK
506
507 if sys.platform != "win32" and rc == -11:
508 return OutputStatus.OK
509
510 # When building with ASan enabled, ASan will convert the -11 returned
511 # value to 1. As a work-around we look for the error output which
512 # includes the crash reason.
513 if rc == 1 and ("Hit MOZ_CRASH" in err or "Assertion failure:" in err):
514 return OutputStatus.OK
515
516 # When running jittests on Android, SEGV results in a return code of
517 # 128 + 11 = 139. Due to a bug in tinybox, we have to check for 138 as
518 # well.
519 if rc == 139 or rc == 138:
520 return OutputStatus.OK
521
522 # Crashing test should always crash as expected, otherwise this is an
523 # error. The JS shell crash() function can be used to force the test
524 # case to crash in unexpected configurations.
525 return OutputStatus.FAILED
526
527 if rc != test.expect_status:
528 # Allow a non-zero exit code if we want to allow OOM, but only if we
529 # actually got OOM.
530 if (
531 test.allow_oom
532 and "out of memory" in err
533 and "Assertion failure" not in err
534 and "MOZ_CRASH" not in err
535 ):
536 return OutputStatus.OK
537
538 # Allow a non-zero exit code if we want to allow unhandlable OOM, but
539 # only if we actually got unhandlable OOM.
540 if test.allow_unhandlable_oom and "MOZ_CRASH([unhandlable oom]" in err:
541 return OutputStatus.OK
542
543 # Allow a non-zero exit code if we want to all too-much-recursion and
544 # the test actually over-recursed.
545 if (
546 test.allow_overrecursed
547 and "too much recursion" in err
548 and "Assertion failure" not in err
549 ):
550 return OutputStatus.OK
551
552 # Allow a zero exit code if we are running under a sanitizer that
553 # forces the exit status.
554 if test.expect_status != 0 and options.unusable_error_status:
555 return OutputStatus.OK
556
557 return OutputStatus.FAILED
558
559 return OutputStatus.OK
560
561
562 def print_automation_format(ok, res, slog):
563 # Output test failures in a parsable format suitable for automation, eg:
564 # TEST-RESULT | filename.js | Failure description (code N, args "--foobar")
565 #
566 # Example:
567 # TEST-PASS | foo/bar/baz.js | (code 0, args "--ion-eager")
568 # TEST-UNEXPECTED-FAIL | foo/bar/baz.js | TypeError: or something (code -9, args "--no-ion")
569 # INFO exit-status : 3
570 # INFO timed-out : False
571 # INFO stdout > foo
572 # INFO stdout > bar
573 # INFO stdout > baz
574 # INFO stderr 2> TypeError: or something
575 # TEST-UNEXPECTED-FAIL | jit_test.py: Test execution interrupted by user
576 result = "TEST-PASS" if ok else "TEST-UNEXPECTED-FAIL"
577 message = "Success" if ok else res.describe_failure()
578 jitflags = " ".join(res.test.jitflags)
579 print(
580 f'{result} | {res.test.relpath_top} | {message} (code {res.rc}, args "{jitflags}") [{res.dt:.1f} s]'
581 )
582
583 details = {
584 "message": message,
585 "extra": {
586 "jitflags": jitflags,
587 },
588 }
589 if res.extra:
590 details["extra"].update(res.extra)
591 slog.test(res.test.relpath_tests, "PASS" if ok else "FAIL", res.dt, **details)
592
593 # For failed tests, print as much information as we have, to aid debugging.
594 if ok:
595 return
596 print(f"INFO exit-status : {res.rc}")
597 print(f"INFO timed-out : {res.timed_out}")
598 warnings = []
599 for line in res.out.splitlines():
600 # See Bug 1868693
601 if line.startswith("WARNING") and "unused DT entry" in line:
602 warnings.append(line)
603 continue
604 print("INFO stdout > " + line.strip())
605 for line in res.err.splitlines():
606 # See Bug 1868693
607 if line.startswith("WARNING") and "unused DT entry" in line:
608 warnings.append(line)
609 continue
610 print("INFO stderr 2> " + line.strip())
611 for line in warnings:
612 print("INFO (warn-stderr) 2> " + line.strip())
613
614
615 def print_test_summary(num_tests, failures, complete, slow_tests, doing, options):
616 def test_details(res):
617 if options.show_failed:
618 return escape_cmdline(res.cmd)
619 return " ".join(res.test.jitflags + [res.test.relpath_tests])
620
621 if failures:
622 if options.write_failures:
623 try:
624 out = open(options.write_failures, "w")
625 # Don't write duplicate entries when we are doing multiple
626 # failures per job.
627 written = set()
628 for res in failures:
629 if res.test.path not in written:
630 out.write(os.path.relpath(res.test.path, TEST_DIR) + "\n")
631 if options.write_failure_output:
632 out.write(res.out)
633 out.write(res.err)
634 out.write("Exit code: " + str(res.rc) + "\n")
635 written.add(res.test.path)
636 out.close()
637 except OSError:
638 sys.stderr.write(
639 "Exception thrown trying to write failure"
640 f" file '{options.write_failures}'\n"
641 )
642 traceback.print_exc()
643 sys.stderr.write("---\n")
644
645 print("FAILURES:")
646 for res in failures:
647 if not res.timed_out:
648 print(" " + test_details(res))
649
650 print("TIMEOUTS:")
651 for res in failures:
652 if res.timed_out:
653 print(" " + test_details(res))
654 else:
655 print(
656 "PASSED ALL"
657 + ("" if complete else f" (partial run -- interrupted by user {doing})")
658 )
659
660 if options.format == "automation":
661 num_failures = len(failures) if failures else 0
662 print("Result summary:")
663 print(f"Passed: {num_tests - num_failures:d}")
664 print(f"Failed: {num_failures:d}")
665
666 if num_tests != 0 and options.show_slow:
667 threshold = options.slow_test_threshold
668 fraction_fast = 1 - len(slow_tests) / num_tests
669 print(f"{fraction_fast * 100:5.2f}% of tests ran in under {threshold}s")
670
671 print(f"Slowest tests that took longer than {threshold}s:")
672 slow_tests.sort(key=lambda res: res.dt, reverse=True)
673 any = False
674 for i in range(min(len(slow_tests), 20)):
675 res = slow_tests[i]
676 print(f" {res.dt:6.2f} {test_details(res)}")
677 any = True
678 if not any:
679 print("None")
680
681 return not failures
682
683
684 def create_progressbar(num_tests, options):
685 if (
686 not options.hide_progress
687 and not options.show_cmd
688 and ProgressBar.conservative_isatty()
689 ):
690 fmt = [
691 {"value": "PASS", "color": "green"},
692 {"value": "FAIL", "color": "red"},
693 {"value": "TIMEOUT", "color": "blue"},
694 {"value": "SKIP", "color": "brightgray"},
695 ]
696 return ProgressBar(num_tests, fmt)
697 return NullProgressBar()
698
699
700 def process_test_results(results, num_tests, pb, options, slog):
701 failures = []
702 timeouts = 0
703 skipped = 0
704 complete = False
705 output_dict = {}
706 doing = "before starting"
707 slow_tests = []
708
709 if num_tests == 0:
710 pb.finish(True)
711 complete = True
712 return print_test_summary(
713 num_tests, failures, complete, slow_tests, doing, options
714 )
715
716 try:
717 for i, res in enumerate(results):
718 status = check_output(
719 res.out, res.err, res.rc, res.timed_out, res.test, options
720 )
721
722 if status:
723 show_output = options.show_output and not options.failed_only
724 else:
725 show_output = options.show_output or not options.no_show_failed
726
727 if show_output:
728 pb.beginline()
729 sys.stdout.write(res.out)
730 sys.stdout.write(res.err)
731 sys.stdout.write(f"Exit code: {res.rc}\n")
732
733 if res.test.valgrind and not show_output:
734 pb.beginline()
735 sys.stdout.write(res.err)
736
737 if options.check_output:
738 if res.test.path in output_dict.keys():
739 if output_dict[res.test.path] != res.out:
740 pb.message(f"FAIL - OUTPUT DIFFERS {res.test.relpath_tests}")
741 else:
742 output_dict[res.test.path] = res.out
743
744 doing = f"after {res.test.relpath_tests}"
745 if status == OutputStatus.SKIPPED:
746 skipped += 1
747 elif status == OutputStatus.FAILED:
748 failures.append(res)
749 if res.timed_out:
750 pb.message(f"TIMEOUT - {res.test.relpath_tests}")
751 timeouts += 1
752 else:
753 pb.message(f"FAIL - {res.test.relpath_tests}")
754
755 if options.format == "automation":
756 print_automation_format(status, res, slog)
757
758 n = i + 1
759 pb.update(
760 n,
761 {
762 "PASS": n - len(failures),
763 "FAIL": len(failures),
764 "TIMEOUT": timeouts,
765 "SKIP": skipped,
766 },
767 )
768
769 if res.dt > options.slow_test_threshold:
770 slow_tests.append(res)
771 complete = True
772 except KeyboardInterrupt:
773 print(
774 "TEST-UNEXPECTED-FAIL | jit_test.py"
775 + " : Test execution interrupted by user"
776 )
777
778 pb.finish(True)
779 return print_test_summary(num_tests, failures, complete, slow_tests, doing, options)
780
781
782 def run_tests(tests, num_tests, prefix, options, remote=False):
783 slog = None
784 if options.format == "automation":
785 slog = TestLogger("jittests")
786 slog.suite_start()
787
788 if remote:
789 ok = run_tests_remote(tests, num_tests, prefix, options, slog)
790 else:
791 ok = run_tests_local(tests, num_tests, prefix, options, slog)
792
793 if slog:
794 slog.suite_end()
795
796 return ok
797
798
799 def run_tests_local(tests, num_tests, prefix, options, slog):
800 # The jstests tasks runner requires the following options. The names are
801 # taken from the jstests options processing code, which are frequently
802 # subtly different from the options jit-tests expects. As such, we wrap
803 # them here, as needed.
804 AdaptorOptions = namedtuple(
805 "AdaptorOptions",
806 [
807 "worker_count",
808 "passthrough",
809 "timeout",
810 "output_fp",
811 "hide_progress",
812 "run_skipped",
813 "show_cmd",
814 "use_xdr",
815 ],
816 )
817 shim_options = AdaptorOptions(
818 options.max_jobs,
819 False,
820 options.timeout,
821 sys.stdout,
822 False,
823 True,
824 options.show_cmd,
825 options.use_xdr,
826 )
827
828 with TemporaryDirectory() as tempdir:
829 pb = create_progressbar(num_tests, options)
830 gen = run_all_tests(tests, prefix, tempdir, pb, shim_options)
831 ok = process_test_results(gen, num_tests, pb, options, slog)
832 return ok
833
834
835 def run_tests_remote(tests, num_tests, prefix, options, slog):
836 # Setup device with everything needed to run our tests.
837 from mozdevice import ADBError, ADBTimeoutError
838
839 from .tasks_adb_remote import get_remote_results
840
841 # Run all tests.
842 pb = create_progressbar(num_tests, options)
843 try:
844 gen = get_remote_results(tests, prefix, pb, options)
845 ok = process_test_results(gen, num_tests, pb, options, slog)
846 except (ADBError, ADBTimeoutError):
847 print("TEST-UNEXPECTED-FAIL | jit_test.py" + " : Device error during test")
848 raise
849 return ok
850
851
852 if __name__ == "__main__":
853 print("Use ../jit-test/jit_test.py to run these tests.")