Debian Codegraph @

js/src/tests/lib/manifest.py

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