Debian Codegraph @

js/src/tests/lib/manifest.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 # Library for JSTest manifests.
2 #
3 # This includes classes for representing and parsing JS manifests.
4
5 import os
6 import posixpath
7 import re
8 import sys
9 from subprocess import PIPE, Popen
10
11 from .remote import init_device
12 from .tests import RefTestCase
13
14
15 def split_path_into_dirs(path):
16 dirs = [path]
17
18 while True:
19 path, tail = os.path.split(path)
20 if not tail:
21 break
22 dirs.append(path)
23 return dirs
24
25
26 class XULInfo:
27 def __init__(self, abi, os, isdebug):
28 self.abi = abi
29 self.os = os
30 self.isdebug = isdebug
31
32 def as_js(self):
33 """Return JS that when executed sets up variables so that JS expression
34 predicates on XUL build info evaluate properly."""
35
36 return (
37 "var winWidget = {};"
38 "var gtkWidget = {};"
39 "var cocoaWidget = {};"
40 "var is64Bit = {};"
41 "var xulRuntime = {{ shell: true }};"
42 "var release_or_beta = getBuildConfiguration('release_or_beta');"
43 "var isDebugBuild={}; var Android={}; ".format(
44 str(self.os == "WINNT").lower(),
45 str(self.os == "Darwin").lower(),
46 str(self.os == "Linux").lower(),
47 str("x86-" not in self.abi).lower(),
48 str(self.isdebug).lower(),
49 str(self.os == "Android").lower(),
50 )
51 )
52
53 @classmethod
54 def create(cls, jsdir):
55 """Create a XULInfo based on the current platform's characteristics."""
56
57 # Our strategy is to find the autoconf.mk generated for the build and
58 # read the values from there.
59
60 # Find config/autoconf.mk.
61 dirs = split_path_into_dirs(os.getcwd()) + split_path_into_dirs(jsdir)
62
63 path = None
64 for dir in dirs:
65 _path = posixpath.join(dir, "config", "autoconf.mk")
66 if os.path.isfile(_path):
67 path = _path
68 break
69
70 if path is None:
71 print(
72 "Can't find config/autoconf.mk on a directory containing"
73 f" the JS shell (searched from {jsdir})"
74 )
75 sys.exit(1)
76
77 # Read the values.
78 val_re = re.compile(r"(TARGET_XPCOM_ABI|OS_TARGET|MOZ_DEBUG)\s*=\s*(.*)")
79 kw = {"isdebug": False}
80 for line in open(path, encoding="utf-8"):
81 m = val_re.match(line)
82 if m:
83 key, val = m.groups()
84 val = val.rstrip()
85 if key == "TARGET_XPCOM_ABI":
86 kw["abi"] = val
87 if key == "OS_TARGET":
88 kw["os"] = val
89 if key == "MOZ_DEBUG":
90 kw["isdebug"] = val == "1"
91 return cls(**kw)
92
93
94 class XULInfoTester:
95 def __init__(self, xulinfo, options, js_args):
96 self.js_prologue = xulinfo.as_js()
97 self.js_bin = options.js_shell
98 self.js_args = js_args
99 # options here are the command line options
100 self.options = options
101 # Maps JS expr to evaluation result.
102 self.cache = {}
103
104 if not self.options.remote:
105 return
106 self.device = init_device(options)
107 self.js_bin = posixpath.join(options.remote_test_root, "bin", "js")
108
109 def test(self, cond, options=[]):
110 if self.options.remote:
111 return self._test_remote(cond, options=options)
112 return self._test_local(cond, options=options)
113
114 def _test_remote(self, cond, options=[]):
115 from mozdevice import ADBDevice, ADBProcessError
116
117 ans = self.cache.get(cond, None)
118 if ans is not None:
119 return ans
120
121 env = {
122 "LD_LIBRARY_PATH": posixpath.join(self.options.remote_test_root, "bin"),
123 }
124
125 cmd = (
126 [self.js_bin]
127 + self.js_args
128 + options
129 + [
130 # run in safe configuration, since it is hard to debug
131 # crashes when running code here. In particular, msan will
132 # error out if the jit is active.
133 "--no-baseline",
134 "--no-blinterp",
135 "-e",
136 self.js_prologue,
137 "-e",
138 f"print(!!({cond}))",
139 ]
140 )
141 cmd = ADBDevice._escape_command_line(cmd)
142 try:
143 # Allow ADBError or ADBTimeoutError to terminate the test run,
144 # but handle ADBProcessError in order to support the use of
145 # non-zero exit codes in the JavaScript shell tests.
146 out = self.device.shell_output(
147 cmd, env=env, cwd=self.options.remote_test_root, timeout=None
148 )
149 err = ""
150 except ADBProcessError as e:
151 out = ""
152 err = str(e.adb_process.stdout)
153
154 if out == "true":
155 ans = True
156 elif out == "false":
157 ans = False
158 else:
159 raise Exception(
160 f"Failed to test XUL condition {cond!r};"
161 f" output was {out!r}, stderr was {err!r}"
162 )
163 self.cache[cond] = ans
164 return ans
165
166 def _test_local(self, cond, options=[]):
167 """Test a XUL predicate condition against this local info."""
168 ans = self.cache.get(cond, None)
169 if ans is None:
170 cmd = (
171 [self.js_bin]
172 + self.js_args
173 + options
174 + [
175 # run in safe configuration, since it is hard to debug
176 # crashes when running code here. In particular, msan will
177 # error out if the jit is active.
178 "--no-baseline",
179 "--no-blinterp",
180 "-e",
181 self.js_prologue,
182 "-e",
183 f"print(!!({cond}))",
184 ]
185 )
186 p = Popen(
187 cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True
188 )
189 out, err = p.communicate()
190 if out in ("true\n", "true\r\n"):
191 ans = True
192 elif out in ("false\n", "false\r\n"):
193 ans = False
194 else:
195 raise Exception(
196 f"Failed to test XUL condition {cond!r};"
197 f" output was {out!r}, stderr was {err!r}"
198 )
199 self.cache[cond] = ans
200 return ans
201
202
203 class NullXULInfoTester:
204 """Can be used to parse manifests without a JS shell."""
205
206 def test(self, cond, options=[]):
207 return False
208
209
210 def _parse_one(testcase, terms, xul_tester):
211 pos = 0
212 parts = terms.split()
213 while pos < len(parts):
214 if parts[pos] == "fails":
215 testcase.expect = False
216 pos += 1
217 elif parts[pos] == "skip":
218 testcase.expect = testcase.enable = False
219 pos += 1
220 elif parts[pos] == "random":
221 testcase.random = True
222 pos += 1
223 elif parts[pos].startswith("shell-option("):
224 # This directive adds an extra option to pass to the shell.
225 option = parts[pos][len("shell-option(") : -1]
226 testcase.options.append(option)
227 pos += 1
228 elif parts[pos].startswith("fails-if"):
229 cond = parts[pos][len("fails-if(") : -1]
230 if xul_tester.test(cond, testcase.options):
231 testcase.expect = False
232 pos += 1
233 elif parts[pos].startswith("asserts-if"):
234 # This directive means we may flunk some number of
235 # NS_ASSERTIONs in the browser. For the shell, ignore it.
236 pos += 1
237 elif parts[pos].startswith("skip-if"):
238 cond = parts[pos][len("skip-if(") : -1]
239 if xul_tester.test(cond, testcase.options):
240 testcase.expect = testcase.enable = False
241 pos += 1
242 elif parts[pos].startswith("ignore-flag"):
243 flag = parts[pos][len("ignore-flag(") : -1]
244 testcase.ignoredflags.append(flag)
245 pos += 1
246 elif parts[pos].startswith("random-if"):
247 cond = parts[pos][len("random-if(") : -1]
248 if xul_tester.test(cond, testcase.options):
249 testcase.random = True
250 pos += 1
251 elif parts[pos] == "slow":
252 testcase.slow = True
253 pos += 1
254 elif parts[pos].startswith("slow-if"):
255 cond = parts[pos][len("slow-if(") : -1]
256 if xul_tester.test(cond, testcase.options):
257 testcase.slow = True
258 pos += 1
259 elif parts[pos] == "silentfail":
260 # silentfails use tons of memory, and Darwin doesn't support ulimit.
261 if xul_tester.test("cocoaWidget", testcase.options):
262 testcase.expect = testcase.enable = False
263 pos += 1
264 elif parts[pos].startswith("error:"):
265 # This directive allows to specify an error type.
266 (_, _, errortype) = parts[pos].partition(":")
267 testcase.error = errortype
268 pos += 1
269 elif parts[pos] == "module":
270 # This directive marks the test as module code.
271 testcase.is_module = True
272 pos += 1
273 elif parts[pos] == "test262-raw":
274 testcase.is_test262_raw = True
275 pos += 1
276 elif parts[pos] == "async":
277 # This directive marks the test as async.
278 testcase.is_async = True
279 pos += 1
280 else:
281 print(f'warning: invalid manifest line element "{parts[pos]}"')
282 pos += 1
283
284
285 def _build_manifest_script_entry(script_name, test):
286 line = []
287 properties = []
288 if test.terms:
289 # Remove jsreftest internal terms.
290 terms = " ".join(
291 [
292 term
293 for term in test.terms.split()
294 if not (
295 term == "module"
296 or term == "async"
297 or term.startswith("error:")
298 or term.startswith("ignore-flag(")
299 or term.startswith("shell-option(")
300 or term == "test262-raw"
301 )
302 ]
303 )
304 if terms:
305 line.append(terms)
306 if test.error:
307 properties.append("error=" + test.error)
308 if test.is_module:
309 properties.append("module")
310 if test.is_async:
311 properties.append("async")
312 if test.is_test262_raw:
313 properties.append("test262_raw")
314 line.append("script")
315 script = script_name
316 if properties:
317 script = ";".join([script] + properties)
318 line.append(script)
319 if test.comment:
320 line.append("#")
321 line.append(test.comment)
322 return " ".join(line)
323
324
325 def _map_prefixes_left(test_gen):
326 """
327 Splits tests into a dictionary keyed on the first component of the test
328 path, aggregating tests with a common base path into a list.
329 """
330 byprefix = {}
331 for t in test_gen:
332 left, sep, remainder = t.path.partition(os.sep)
333 if left not in byprefix:
334 byprefix[left] = []
335 if remainder:
336 t.path = remainder
337 byprefix[left].append(t)
338 return byprefix
339
340
341 def _emit_manifest_at(location, relative, test_gen, depth):
342 """
343 location - str: absolute path where we want to write the manifest
344 relative - str: relative path from topmost manifest directory to current
345 test_gen - (str): generator of all test paths and directorys
346 depth - int: number of dirs we are below the topmost manifest dir
347 """
348 manifests = _map_prefixes_left(test_gen)
349
350 filename = os.path.join(location, "jstests.list")
351 manifest = []
352 numTestFiles = 0
353 for k, test_list in manifests.items():
354 fullpath = os.path.join(location, k)
355 if os.path.isdir(fullpath):
356 manifest.append("include " + k + "/jstests.list")
357 relpath = os.path.join(relative, k)
358 _emit_manifest_at(fullpath, relpath, test_list, depth + 1)
359 else:
360 numTestFiles += 1
361 assert len(test_list) == 1, test_list
362 line = _build_manifest_script_entry(k, test_list[0])
363 manifest.append(line)
364
365 # Always present our manifest in sorted order.
366 manifest.sort()
367
368 # If we have tests, we have to set the url-prefix so reftest can find them.
369 if numTestFiles > 0:
370 manifest = [
371 "url-prefix {}jsreftest.html?test={}/".format("../" * depth, relative)
372 ] + manifest
373
374 fp = open(filename, "w", encoding="utf-8", newline="\n")
375 try:
376 fp.write("\n".join(manifest) + "\n")
377 finally:
378 fp.close()
379
380
381 def make_manifests(location, test_gen):
382 _emit_manifest_at(location, "", test_gen, 0)
383
384
385 def _find_all_js_files(location):
386 for root, dirs, files in os.walk(location):
387 root = root[len(location) + 1 :]
388 for fn in files:
389 if fn.endswith(".js"):
390 yield root, fn
391
392
393 # The pattern for test header lines.
394 TEST_HEADER_PATTERN = r"""
395 # Ignore any space before the tag.
396 \s*
397
398 # The reftest tag is enclosed in pipes.
399 \|(?P<tag>.*?)\|
400
401 # Ignore any space before the options.
402 \s*
403
404 # Accept some options.
405 (?P<options>.*?)
406
407 # Ignore space before the comments.
408 \s*
409
410 # Accept an optional comment starting with "--".
411 (?:
412 # Unless "--" is directly preceded by "(".
413 (?<!\()
414 --
415
416 # Ignore more space.
417 \s*
418
419 # The actual comment.
420 (?P<comment>.*)
421 )?
422 """
423
424
425 TEST_HEADER_PATTERN_INLINE = re.compile(
426 r"""
427 # Start a single line comment
428 //
429 """
430 + TEST_HEADER_PATTERN
431 + r"""
432 # Match the end of line.
433 $
434 """,
435 re.VERBOSE,
436 )
437 TEST_HEADER_PATTERN_MULTI = re.compile(
438 r"""
439 # Start a multi line comment
440 /\*
441 """
442 + TEST_HEADER_PATTERN
443 + r"""
444 # Match the end of comment.
445 \*/
446 """,
447 re.VERBOSE,
448 )
449
450
451 def _append_terms_and_comment(testcase, terms, comment):
452 if testcase.terms is None:
453 testcase.terms = terms
454 else:
455 testcase.terms += " " + terms
456
457 if testcase.comment is None:
458 testcase.comment = comment
459 elif comment:
460 testcase.comment += "; " + comment
461
462
463 def _parse_test_header(fullpath, testcase, xul_tester):
464 """
465 This looks a bit weird. The reason is that it needs to be efficient, since
466 it has to be done on every test
467 """
468 fp = open(fullpath, encoding="utf-8")
469 try:
470 buf = fp.read(512)
471 finally:
472 fp.close()
473
474 # Bail early if we do not start with a single comment.
475 if not buf.startswith("//"):
476 return
477
478 # Extract the token.
479 buf, _, _ = buf.partition("\n")
480 matches = TEST_HEADER_PATTERN_INLINE.match(buf)
481
482 if not matches:
483 matches = TEST_HEADER_PATTERN_MULTI.match(buf)
484 if not matches:
485 return
486
487 testcase.tag = matches.group("tag")
488 _append_terms_and_comment(
489 testcase, matches.group("options"), matches.group("comment")
490 )
491 _parse_one(testcase, matches.group("options"), xul_tester)
492
493
494 def _parse_external_manifest(filename, relpath):
495 """
496 Reads an external manifest file for test suites whose individual test cases
497 can't be decorated with reftest comments.
498 filename - str: name of the manifest file
499 relpath - str: relative path of the directory containing the manifest
500 within the test suite
501 """
502 if not os.path.exists(filename):
503 return []
504
505 entries = []
506
507 with open(filename, encoding="utf-8") as fp:
508 manifest_re = re.compile(
509 r"^\s*(?P<terms>.*)\s+(?P<type>include|script)\s+(?P<path>\S+)$"
510 )
511 include_re = re.compile(r"^\s*include\s+(?P<path>\S+)$")
512 for line in fp:
513 line, _, comment = line.partition("#")
514 line = line.strip()
515 if not line:
516 continue
517 matches = manifest_re.match(line)
518 if not matches:
519 matches = include_re.match(line)
520 if not matches:
521 print("warning: unrecognized line in jstests.list:" f" {line}")
522 continue
523
524 include_file = matches.group("path")
525 include_filename = os.path.join(os.path.dirname(filename), include_file)
526 include_relpath = os.path.join(relpath, os.path.dirname(include_file))
527 include_entries = _parse_external_manifest(
528 include_filename, include_relpath
529 )
530 entries.extend(include_entries)
531 continue
532
533 path = os.path.normpath(os.path.join(relpath, matches.group("path")))
534 if matches.group("type") == "include":
535 # The manifest spec wants a reference to another manifest here,
536 # but we need just the directory. We do need the trailing
537 # separator so we don't accidentally match other paths of which
538 # this one is a prefix.
539 assert path.endswith("jstests.list")
540 path = path[: -len("jstests.list")]
541
542 entries.append(
543 {
544 "path": path,
545 "terms": matches.group("terms"),
546 "comment": comment.strip(),
547 }
548 )
549
550 # if one directory name is a prefix of another, we want the shorter one
551 # first
552 entries.sort(key=lambda x: x["path"])
553 return entries
554
555
556 def _apply_external_manifests(filename, testcase, entries, xul_tester):
557 for entry in entries:
558 if filename.startswith(entry["path"]):
559 # The reftest spec would require combining the terms (failure types)
560 # that may already be defined in the test case with the terms
561 # specified in entry; for example, a skip overrides a random, which
562 # overrides a fails. Since we don't necessarily know yet in which
563 # environment the test cases will be run, we'd also have to
564 # consider skip-if, random-if, and fails-if with as-yet unresolved
565 # conditions.
566 # At this point, we use external manifests only for test cases
567 # that can't have their own failure type comments, so we simply
568 # use the terms for the most specific path.
569 _append_terms_and_comment(testcase, entry["terms"], entry["comment"])
570 _parse_one(testcase, entry["terms"], xul_tester)
571
572
573 def _is_test_file(path_from_root, basename, filename, path_options):
574 # Any file whose basename matches something in this set is ignored.
575 EXCLUDED = set(
576 (
577 "browser.js",
578 "shell.js",
579 "template.js",
580 "user.js",
581 "js-test-driver-begin.js",
582 "js-test-driver-end.js",
583 )
584 )
585
586 # Skip js files in the root test directory.
587 if not path_from_root:
588 return False
589
590 # Skip files that we know are not tests.
591 if basename in EXCLUDED:
592 return False
593
594 if not path_options.should_run(filename):
595 return False
596
597 return True
598
599
600 def count_tests(location, path_options):
601 count = 0
602 for root, basename in _find_all_js_files(location):
603 filename = os.path.join(root, basename)
604 if _is_test_file(root, basename, filename, path_options):
605 count += 1
606 return count
607
608
609 def load_reftests(location, path_options, xul_tester):
610 """
611 Locates all tests by walking the filesystem starting at |location|.
612 Uses xul_tester to evaluate any test conditions in the test header.
613 Failure type and comment for a test case can come from
614 - an external manifest entry for the test case,
615 - an external manifest entry for a containing directory,
616 - most commonly: the header of the test case itself.
617 """
618 manifestFile = os.path.join(location, "jstests.list")
619 externalManifestEntries = _parse_external_manifest(manifestFile, "")
620
621 for root, basename in _find_all_js_files(location):
622 # Get the full path and relative location of the file.
623 filename = os.path.join(root, basename)
624 if not _is_test_file(root, basename, filename, path_options):
625 continue
626
627 # Skip empty files.
628 fullpath = os.path.join(location, filename)
629
630 testcase = RefTestCase(location, filename)
631 _apply_external_manifests(
632 filename, testcase, externalManifestEntries, xul_tester
633 )
634 _parse_test_header(fullpath, testcase, xul_tester)
635 yield testcase