Debian Codegraph @

js/src/tests/lib/tests.py

raw
1 # Library for JSTest tests.
2 #
3 # This contains classes that represent an individual test, including
4 # metadata, and know how to run the tests and determine failures.
5
6 import os
7 import sys
8 from contextlib import contextmanager
9
10 # When run on tbpl, we run each test multiple times with the following
11 # arguments.
12 JITFLAGS = {
13 "all": [
14 [], # no flags, normal baseline and ion
15 [
16 "--ion-eager",
17 "--ion-offthread-compile=off", # implies --baseline-eager
18 "--more-compartments",
19 ],
20 [
21 "--ion-eager",
22 "--ion-offthread-compile=off",
23 "--ion-check-range-analysis",
24 "--ion-extra-checks",
25 "--no-sse3",
26 "--no-threads",
27 ],
28 ["--baseline-eager", "--write-protect-code=off"],
29 ["--no-blinterp", "--no-baseline", "--no-ion", "--more-compartments"],
30 ["--blinterp-eager"],
31 ],
32 # Like 'all' above but for jstests. This has fewer jit-specific
33 # configurations.
34 "jstests": [
35 [], # no flags, normal baseline and ion
36 [
37 "--ion-eager",
38 "--ion-offthread-compile=off", # implies --baseline-eager
39 "--more-compartments",
40 ],
41 ["--baseline-eager", "--write-protect-code=off"],
42 ["--no-blinterp", "--no-baseline", "--no-ion", "--more-compartments"],
43 ],
44 # used by jit_test.py
45 "ion": [
46 ["--baseline-eager", "--write-protect-code=off"],
47 ["--ion-eager", "--ion-offthread-compile=off", "--more-compartments"],
48 ],
49 # Run reduced variants on debug builds, since they take longer time.
50 "debug": [
51 [], # no flags, normal baseline and ion
52 [
53 "--ion-eager",
54 "--ion-offthread-compile=off", # implies --baseline-eager
55 "--more-compartments",
56 ],
57 ["--baseline-eager", "--write-protect-code=off"],
58 ],
59 # Cover cases useful for tsan. Note that we test --ion-eager without
60 # --ion-offthread-compile=off here, because it helps catch races.
61 "tsan": [
62 [],
63 [
64 "--ion-eager",
65 "--ion-check-range-analysis",
66 "--ion-extra-checks",
67 "--no-sse3",
68 ],
69 ["--no-blinterp", "--no-baseline", "--no-ion"],
70 ],
71 "baseline": [
72 ["--no-ion"],
73 ],
74 # Interpreter-only, for tools that cannot handle binary code generation.
75 "interp": [
76 [
77 "--no-blinterp",
78 "--no-baseline",
79 "--no-asmjs",
80 "--wasm-compiler=none",
81 "--no-native-regexp",
82 ]
83 ],
84 "none": [[]], # no flags, normal baseline and ion
85 }
86
87
88 def get_jitflags(variant, **kwargs):
89 if variant not in JITFLAGS:
90 print(f'Invalid jitflag: "{variant}"')
91 sys.exit(1)
92 if variant == "none" and "none" in kwargs:
93 return kwargs["none"]
94 return JITFLAGS[variant]
95
96
97 def valid_jitflags():
98 return JITFLAGS.keys()
99
100
101 def get_environment_overlay(js_shell, gc_zeal):
102 """
103 Build a dict of additional environment variables that must be set to run
104 tests successfully.
105 """
106
107 # When updating this also update |buildBrowserEnv| in layout/tools/reftest/runreftest.py.
108 env = {
109 # Force Pacific time zone to avoid failures in Date tests.
110 "TZ": "PST8PDT",
111 # Force date strings to English.
112 "LC_ALL": "en_US.UTF-8",
113 # Tell the shell to disable crash dialogs on windows.
114 "XRE_NO_WINDOWS_CRASH_DIALOG": "1",
115 }
116
117 # Add the binary's directory to the library search path so that we find the
118 # nspr and icu we built, instead of the platform supplied ones (or none at
119 # all on windows).
120 if sys.platform.startswith("linux"):
121 env["LD_LIBRARY_PATH"] = os.path.dirname(js_shell)
122 elif sys.platform.startswith("darwin"):
123 env["DYLD_LIBRARY_PATH"] = os.path.dirname(js_shell)
124 elif sys.platform.startswith("win"):
125 env["PATH"] = os.path.dirname(js_shell)
126
127 if gc_zeal:
128 env["JS_GC_ZEAL"] = gc_zeal
129
130 return env
131
132
133 @contextmanager
134 def change_env(env_overlay):
135 # Apply the overlaid environment and record the current state.
136 prior_env = {}
137 for key, val in env_overlay.items():
138 prior_env[key] = os.environ.get(key, None)
139 if "PATH" in key and key in os.environ:
140 os.environ[key] = f"{val}{os.pathsep}{os.environ[key]}"
141 else:
142 os.environ[key] = val
143
144 try:
145 # Execute with the new environment.
146 yield
147
148 finally:
149 # Restore the prior environment.
150 for key, val in prior_env.items():
151 if val is not None:
152 os.environ[key] = val
153 else:
154 del os.environ[key]
155
156
157 def get_cpu_count():
158 """
159 Guess at a reasonable parallelism count to set as the default for the
160 current machine and run.
161 """
162 # Python 2.6+
163 try:
164 import multiprocessing
165
166 return multiprocessing.cpu_count()
167 except (ImportError, NotImplementedError):
168 pass
169
170 # POSIX
171 try:
172 res = int(os.sysconf("SC_NPROCESSORS_ONLN"))
173 if res > 0:
174 return res
175 except (AttributeError, ValueError):
176 pass
177
178 # Windows
179 try:
180 res = int(os.environ["NUMBER_OF_PROCESSORS"])
181 if res > 0:
182 return res
183 except (KeyError, ValueError):
184 pass
185
186 return 1
187
188
189 class RefTestCase:
190 """A test case consisting of a test and an expected result."""
191
192 def __init__(self, root, path, extra_helper_paths=None, wpt=None):
193 # str: path of the tests root dir
194 self.root = root
195 # str: path of JS file relative to tests root dir
196 self.path = path
197 # [str]: Extra options to pass to the shell
198 self.options = []
199 # [str]: JIT flags to pass to the shell
200 self.jitflags = []
201 # [str]: flags to never pass to the shell for this test
202 self.ignoredflags = []
203 # str or None: path to reflect-stringify.js file to test
204 # instead of actually running tests
205 self.test_reflect_stringify = None
206 # bool: True => test is module code
207 self.is_module = False
208 # bool: True => test is asynchronous and runs additional code after completing the first
209 # turn of the event loop.
210 self.is_async = False
211 # bool: True => run test, False => don't run
212 self.enable = True
213 # str?: Optional error type
214 self.error = None
215 # bool: expected result, True => pass
216 self.expect = True
217 # bool: True => ignore output as 'random'
218 self.random = False
219 # bool: True => test may run slowly
220 self.slow = False
221 # bool: True => test will not run alongside any other heavy tests
222 self.heavy = False
223 # bool: True => test is test262 testcase with raw flag, that turns off
224 # running shell.js files inside test262
225 self.is_test262_raw = False
226
227 # Use self-hosted XDR instead of parsing the source stored in the binary.
228 # str?: Path computed when generating the command
229 self.selfhosted_xdr_path = None
230 # str: XDR mode (= "off", "encode", "decode") to use with the
231 # self-hosted code.
232 self.selfhosted_xdr_mode = "off"
233
234 # The terms parsed to produce the above properties.
235 self.terms = None
236
237 # The tag between |...| in the test header.
238 self.tag = None
239
240 # Anything occuring after -- in the test header.
241 self.comment = None
242
243 self.extra_helper_paths = extra_helper_paths or []
244 self.wpt = wpt
245
246 def prefix_command(self):
247 """Return the '-f' options needed to run a test with the given path."""
248 path = self.path
249 prefix = []
250 while path != "":
251 assert path != "/"
252 path = os.path.dirname(path)
253
254 if self.is_test262_raw and path != "":
255 # Skip running shell.js under test262 if the test has raw flag.
256 # Top-level shell.js is still necessary to define reportCompare.
257 continue
258
259 shell_path = os.path.join(self.root, path, "shell.js")
260 if os.path.exists(shell_path):
261 prefix.append(shell_path)
262 prefix.append("-f")
263 prefix.reverse()
264
265 for extra_path in self.extra_helper_paths:
266 prefix.append("-f")
267 prefix.append(extra_path)
268
269 return prefix
270
271 def abs_path(self):
272 return os.path.join(self.root, self.path)
273
274 def get_command(self, prefix, tempdir):
275 cmd = prefix + self.jitflags + self.options + self.prefix_command()
276 # Note: The tempdir provided as argument is managed by the caller
277 # should remain alive as long as the test harness. Therefore, the XDR
278 # content of the self-hosted code would be accessible to all JS Shell
279 # instances.
280 if self.selfhosted_xdr_mode != "off":
281 self.selfhosted_xdr_path = os.path.join(tempdir, "shell.xdr")
282 cmd += [
283 "--selfhosted-xdr-path",
284 self.selfhosted_xdr_path,
285 "--selfhosted-xdr-mode",
286 self.selfhosted_xdr_mode,
287 ]
288 if self.test_reflect_stringify is not None:
289 cmd += [self.test_reflect_stringify, "--check", self.abs_path()]
290 elif self.is_module:
291 cmd += ["--module", self.abs_path()]
292 else:
293 cmd += ["-f", self.abs_path()]
294 for flag in self.ignoredflags:
295 if flag in cmd:
296 cmd.remove(flag)
297 return cmd
298
299 def __str__(self):
300 ans = self.path
301 if not self.enable:
302 ans += ", skip"
303 if self.error is not None:
304 ans += ", error=" + self.error
305 if not self.expect:
306 ans += ", fails"
307 if self.random:
308 ans += ", random"
309 if self.slow:
310 ans += ", slow"
311 if self.heavy:
312 ans += ", heavy"
313 if "-d" in self.options:
314 ans += ", debugMode"
315 return ans
316
317 @staticmethod
318 def build_js_cmd_prefix(js_path, js_args, debugger_prefix):
319 parts = []
320 if debugger_prefix:
321 parts += debugger_prefix
322 parts.append(js_path)
323 if js_args:
324 parts += js_args
325 return parts
326
327 def __cmp__(self, other):
328 if self.path == other.path:
329 return 0
330 elif self.path < other.path:
331 return -1
332 return 1
333
334 def __hash__(self):
335 return self.path.__hash__()
336
337 def __repr__(self):
338 return "<lib.tests.RefTestCase %s>" % (self.path,)