Debian Codegraph @

js/src/tests/lib/results.py

raw
1 import json
2 import re
3 import shlex
4
5 from .progressbar import NullProgressBar, ProgressBar
6 from .structuredlog import TestLogger
7
8 # subprocess.list2cmdline does not properly escape for sh-like shells
9
10
11 def escape_cmdline(args):
12 return " ".join([shlex.quote(a) for a in args])
13
14
15 class TestOutput:
16 """Output from a test run."""
17
18 def __init__(self, test, cmd, out, err, rc, dt, timed_out, extra=None):
19 self.test = test # Test
20 self.cmd = cmd # str: command line of test
21 self.out = out # str: stdout
22 self.err = err # str: stderr
23 self.rc = rc # int: return code
24 self.dt = dt # float: run time
25 self.timed_out = timed_out # bool: did the test time out
26 self.extra = extra # includes the pid on some platforms
27
28 def describe_failure(self):
29 if self.timed_out:
30 return "Timeout"
31 lines = self.err.splitlines()
32 for line in lines:
33 # Skip the asm.js compilation success message.
34 if "Successfully compiled asm.js code" not in line:
35 return line
36 return "Unknown"
37
38
39 class NullTestOutput:
40 """Variant of TestOutput that indicates a test was not run."""
41
42 def __init__(self, test):
43 self.test = test
44 self.cmd = ""
45 self.out = ""
46 self.err = ""
47 self.rc = 0
48 self.dt = 0.0
49 self.timed_out = False
50
51
52 class TestResult:
53 PASS = "PASS"
54 FAIL = "FAIL"
55 CRASH = "CRASH"
56
57 """Classified result from a test run."""
58
59 def __init__(self, test, result, results, wpt_results=None):
60 self.test = test
61 self.result = result
62 self.results = results
63 self.wpt_results = wpt_results # Only used for wpt tests.
64
65 @classmethod
66 def from_wpt_output(cls, output):
67 """Parse the output from a web-platform test that uses testharness.js.
68 (The output is written to stdout in js/src/tests/testharnessreport.js.)
69 """
70 from wptrunner.executors.base import testharness_result_converter
71
72 rc = output.rc
73 stdout = output.out.split("\n")
74 if rc != 0:
75 if rc == 3:
76 harness_status = "ERROR"
77 harness_message = "Exit code reported exception"
78 else:
79 harness_status = "CRASH"
80 harness_message = "Exit code reported crash"
81 tests = []
82 else:
83 for idx, line in enumerate(stdout):
84 if line.startswith("WPT OUTPUT: "):
85 msg = line[len("WPT OUTPUT: ") :]
86 data = [output.test.wpt.url] + json.loads(msg)
87 harness_status_obj, tests = testharness_result_converter(
88 output.test.wpt, data
89 )
90 harness_status = harness_status_obj.status
91 harness_message = "Reported by harness: %s" % (
92 harness_status_obj.message,
93 )
94 del stdout[idx]
95 break
96 else:
97 harness_status = "ERROR"
98 harness_message = "No harness output found"
99 tests = []
100 stdout.append("Harness status: %s (%s)" % (harness_status, harness_message))
101
102 result = cls.PASS
103 results = []
104 subtests = []
105 expected_harness_status = output.test.wpt.expected()
106 if harness_status != expected_harness_status:
107 if harness_status == "CRASH":
108 result = cls.CRASH
109 else:
110 result = cls.FAIL
111 else:
112 for test in tests:
113 test_output = 'Subtest "%s": ' % (test.name,)
114 expected = output.test.wpt.expected(test.name)
115 if test.status == expected:
116 test_result = (cls.PASS, "")
117 test_output += "as expected: %s" % (test.status,)
118 else:
119 test_result = (cls.FAIL, test.message)
120 result = cls.FAIL
121 test_output += "expected %s, found %s" % (expected, test.status)
122 if test.message:
123 test_output += ' (with message: "%s")' % (test.message,)
124 subtests.append(
125 {
126 "test": output.test.wpt.id,
127 "subtest": test.name,
128 "status": test.status,
129 "expected": expected,
130 }
131 )
132 results.append(test_result)
133 stdout.append(test_output)
134
135 output.out = "\n".join(stdout) + "\n"
136
137 wpt_results = {
138 "name": output.test.wpt.id,
139 "status": harness_status,
140 "expected": expected_harness_status,
141 "subtests": subtests,
142 }
143
144 return cls(output.test, result, results, wpt_results)
145
146 @classmethod
147 def from_output(cls, output):
148 test = output.test
149 result = None # str: overall result, see class-level variables
150 results = [] # (str,str) list: subtest results (pass/fail, message)
151
152 if test.wpt:
153 return cls.from_wpt_output(output)
154
155 out, err, rc = output.out, output.err, output.rc
156
157 failures = 0
158 passes = 0
159
160 expected_rcs = []
161 if test.path.endswith("-n.js"):
162 expected_rcs.append(3)
163
164 for line in out.split("\n"):
165 if line.startswith(" FAILED!"):
166 failures += 1
167 msg = line[len(" FAILED! ") :]
168 results.append((cls.FAIL, msg))
169 elif line.startswith(" PASSED!"):
170 passes += 1
171 msg = line[len(" PASSED! ") :]
172 results.append((cls.PASS, msg))
173 else:
174 m = re.match(
175 "--- NOTE: IN THIS TESTCASE, WE EXPECT EXIT CODE"
176 " ((?:-|\\d)+) ---",
177 line,
178 )
179 if m:
180 expected_rcs.append(int(m.group(1)))
181
182 if test.error is not None:
183 expected_rcs.append(3)
184 if test.error not in err:
185 failures += 1
186 results.append((cls.FAIL, f"Expected uncaught error: {test.error}"))
187
188 if rc and rc not in expected_rcs:
189 if rc == 3:
190 result = cls.FAIL
191 else:
192 result = cls.CRASH
193 else:
194 if (rc or passes > 0) and failures == 0:
195 result = cls.PASS
196 else:
197 result = cls.FAIL
198
199 return cls(test, result, results)
200
201
202 class TestDuration:
203 def __init__(self, test, duration):
204 self.test = test
205 self.duration = duration
206
207
208 class ResultsSink:
209 def __init__(self, testsuite, options, testcount):
210 self.options = options
211 self.fp = options.output_fp
212 if self.options.format == "automation":
213 self.slog = TestLogger(testsuite)
214 self.slog.suite_start()
215
216 self.wptreport = None
217 if self.options.wptreport:
218 try:
219 from .wptreport import WptreportHandler
220
221 self.wptreport = WptreportHandler(self.options.wptreport)
222 self.wptreport.suite_start()
223 except ImportError:
224 pass
225
226 self.groups = {}
227 self.output_dict = {}
228 self.counts = {"PASS": 0, "FAIL": 0, "TIMEOUT": 0, "SKIP": 0}
229 self.slow_tests = []
230 self.n = 0
231
232 if options.hide_progress:
233 self.pb = NullProgressBar()
234 else:
235 fmt = [
236 {"value": "PASS", "color": "green"},
237 {"value": "FAIL", "color": "red"},
238 {"value": "TIMEOUT", "color": "blue"},
239 {"value": "SKIP", "color": "brightgray"},
240 ]
241 self.pb = ProgressBar(testcount, fmt)
242
243 def push(self, output):
244 if self.options.show_slow and output.dt >= self.options.slow_test_threshold:
245 self.slow_tests.append(TestDuration(output.test, output.dt))
246 if output.timed_out:
247 self.counts["TIMEOUT"] += 1
248 if isinstance(output, NullTestOutput):
249 if self.options.format == "automation":
250 self.print_automation_result(
251 "TEST-KNOWN-FAIL", output.test, time=output.dt, skip=True
252 )
253 self.counts["SKIP"] += 1
254 self.n += 1
255 else:
256 result = TestResult.from_output(output)
257
258 if self.wptreport is not None and result.wpt_results:
259 self.wptreport.test(result.wpt_results, output.dt)
260
261 tup = (result.result, result.test.expect, result.test.random)
262 dev_label = self.LABELS[tup][1]
263
264 if self.options.check_output:
265 if output.test.path in self.output_dict.keys():
266 if self.output_dict[output.test.path] != output:
267 self.counts["FAIL"] += 1
268 self.print_automation_result(
269 "TEST-UNEXPECTED-FAIL",
270 result.test,
271 time=output.dt,
272 message="Same test with different flag producing different output",
273 )
274 else:
275 self.output_dict[output.test.path] = output
276
277 if output.timed_out:
278 dev_label = "TIMEOUTS"
279 self.groups.setdefault(dev_label, []).append(result)
280
281 if dev_label == "REGRESSIONS":
282 show_output = (
283 self.options.show_output or not self.options.no_show_failed
284 )
285 elif dev_label == "TIMEOUTS":
286 show_output = self.options.show_output
287 else:
288 show_output = self.options.show_output and not self.options.failed_only
289
290 if dev_label in ("REGRESSIONS", "TIMEOUTS"):
291 show_cmd = self.options.show_cmd
292 else:
293 show_cmd = self.options.show_cmd and not self.options.failed_only
294
295 if show_output or show_cmd:
296 self.pb.beginline()
297
298 if show_output:
299 print(
300 f"## {output.test.path}: rc = {output.rc:d}, run time = {output.dt}",
301 file=self.fp,
302 )
303
304 if show_cmd:
305 print(escape_cmdline(output.cmd), file=self.fp)
306
307 if show_output:
308
309 def write_with_fallback(fp, data):
310 try:
311 fp.write(data)
312 except UnicodeEncodeError as e:
313 # In case the data contains something not directly
314 # encodable, use \uXXXX.
315 fp.write(f"WARNING: Falling back from exception: {e}\n")
316 fp.write("WARNING: The following output is escaped, ")
317 fp.write("and may be different than original one.\n")
318 fp.write(
319 data.encode("ascii", "namereplace").decode("ascii")
320 )
321
322 write_with_fallback(self.fp, output.out)
323 write_with_fallback(self.fp, output.err)
324
325 self.n += 1
326
327 if result.result == TestResult.PASS and not result.test.random:
328 self.counts["PASS"] += 1
329 elif result.test.expect and not result.test.random:
330 self.counts["FAIL"] += 1
331 else:
332 self.counts["SKIP"] += 1
333
334 if self.options.format == "automation":
335 if result.result != TestResult.PASS and len(result.results) > 1:
336 for sub_ok, msg in result.results:
337 tup = (sub_ok, result.test.expect, result.test.random)
338 label = self.LABELS[tup][0]
339 if label == "TEST-UNEXPECTED-PASS":
340 label = "TEST-PASS (EXPECTED RANDOM)"
341 self.print_automation_result(
342 label, result.test, time=output.dt, message=msg
343 )
344 tup = (result.result, result.test.expect, result.test.random)
345 self.print_automation_result(
346 self.LABELS[tup][0],
347 result.test,
348 time=output.dt,
349 extra=getattr(output, "extra", None),
350 )
351 return
352
353 if dev_label:
354
355 def singular(label):
356 return "FIXED" if label == "FIXES" else label[:-1]
357
358 self.pb.message(f"{singular(dev_label)} - {output.test.path}")
359
360 self.pb.update(self.n, self.counts)
361
362 def finish(self, completed):
363 self.pb.finish(completed)
364 if self.options.format == "automation":
365 self.slog.suite_end()
366 else:
367 self.list(completed)
368
369 if self.n != 0 and self.options.show_slow:
370 self.show_slow_tests()
371
372 if self.wptreport is not None:
373 self.wptreport.suite_end()
374
375 # Conceptually, this maps (test result x test expectation) to text labels.
376 # key is (result, expect, random)
377 # value is (automation label, dev test category)
378 LABELS = {
379 (TestResult.CRASH, False, False): ("TEST-UNEXPECTED-FAIL", "REGRESSIONS"),
380 (TestResult.CRASH, False, True): ("TEST-UNEXPECTED-FAIL", "REGRESSIONS"),
381 (TestResult.CRASH, True, False): ("TEST-UNEXPECTED-FAIL", "REGRESSIONS"),
382 (TestResult.CRASH, True, True): ("TEST-UNEXPECTED-FAIL", "REGRESSIONS"),
383 (TestResult.FAIL, False, False): ("TEST-KNOWN-FAIL", ""),
384 (TestResult.FAIL, False, True): ("TEST-KNOWN-FAIL (EXPECTED RANDOM)", ""),
385 (TestResult.FAIL, True, False): ("TEST-UNEXPECTED-FAIL", "REGRESSIONS"),
386 (TestResult.FAIL, True, True): ("TEST-KNOWN-FAIL (EXPECTED RANDOM)", ""),
387 (TestResult.PASS, False, False): ("TEST-UNEXPECTED-PASS", "FIXES"),
388 (TestResult.PASS, False, True): ("TEST-PASS (EXPECTED RANDOM)", ""),
389 (TestResult.PASS, True, False): ("TEST-PASS", ""),
390 (TestResult.PASS, True, True): ("TEST-PASS (EXPECTED RANDOM)", ""),
391 }
392
393 def list(self, completed):
394 for label, results in sorted(self.groups.items()):
395 if label == "":
396 continue
397
398 print(label)
399 for result in results:
400 print(
401 " {}".format(
402 " ".join(
403 result.test.jitflags
404 + result.test.options
405 + [result.test.path]
406 )
407 )
408 )
409
410 if self.options.failure_file:
411 failure_file = open(self.options.failure_file, "w")
412 if not self.all_passed():
413 if "REGRESSIONS" in self.groups:
414 for result in self.groups["REGRESSIONS"]:
415 print(result.test.path, file=failure_file)
416 if "TIMEOUTS" in self.groups:
417 for result in self.groups["TIMEOUTS"]:
418 print(result.test.path, file=failure_file)
419 failure_file.close()
420
421 suffix = "" if completed else " (partial run -- interrupted by user)"
422 if self.all_passed():
423 print("PASS" + suffix)
424 else:
425 print("FAIL" + suffix)
426
427 def show_slow_tests(self):
428 threshold = self.options.slow_test_threshold
429 fraction_fast = 1 - len(self.slow_tests) / self.n
430 self.log_info(f"{fraction_fast * 100:5.2f}% of tests ran in under {threshold}s")
431
432 self.log_info(f"Slowest tests that took longer than {threshold}s:")
433 slow_tests = sorted(self.slow_tests, key=lambda x: x.duration, reverse=True)
434 any = False
435 for i in range(min(len(slow_tests), 20)):
436 test = slow_tests[i]
437 self.log_info(f" {test.duration:6.2f} {test.test}")
438 any = True
439 if not any:
440 self.log_info("None")
441
442 def log_info(self, message):
443 if self.options.format == "automation":
444 self.slog.log_info(message)
445 else:
446 print(message)
447
448 def all_passed(self):
449 return "REGRESSIONS" not in self.groups and "TIMEOUTS" not in self.groups
450
451 def print_automation_result(
452 self, label, test, message=None, skip=False, time=None, extra=None
453 ):
454 result = label
455 result += " | " + test.path
456 args = []
457 if self.options.shell_args:
458 args.append(self.options.shell_args)
459 args += test.jitflags
460 result += ' | (args: "{}")'.format(" ".join(args))
461 if message:
462 result += " | " + message
463 if skip:
464 result += " | (SKIP)"
465 if time > self.options.timeout:
466 result += " | (TIMEOUT)"
467 result += f" [{time:.1f} s]"
468 print(result)
469
470 details = {"extra": extra.copy() if extra else {}}
471 if self.options.shell_args:
472 details["extra"]["shell_args"] = self.options.shell_args
473 details["extra"]["jitflags"] = test.jitflags
474 if message:
475 details["message"] = message
476 status = "FAIL" if "TEST-UNEXPECTED" in label else "PASS"
477
478 self.slog.test(test.path, status, time or 0, **details)