Debian Codegraph @

testing/testinfo.py

raw
1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this
3 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5 import datetime
6 import errno
7 import json
8 import os
9 import posixpath
10 import re
11 import subprocess
12 from collections import defaultdict
13 from typing import Dict
14
15 import mozpack.path as mozpath
16 import requests
17 import six.moves.urllib_parse as urlparse
18 from mozbuild.base import MachCommandConditions as conditions
19 from mozbuild.base import MozbuildObject
20 from mozfile import which
21 from mozinfo.platforminfo import PlatformInfo
22 from moztest.resolve import TestManifestLoader, TestResolver
23 from redo import retriable
24
25 REFERER = "https://wiki.developer.mozilla.org/en-US/docs/Mozilla/Test-Info"
26 MAX_DAYS = 30
27
28
29 class SetEncoder(json.JSONEncoder):
30 def default(self, obj):
31 if isinstance(obj, set):
32 return list(obj)
33 return super().default(obj)
34
35
36 class TestInfo:
37 """
38 Support 'mach test-info'.
39 """
40
41 def __init__(self, verbose):
42 self.verbose = verbose
43 here = os.path.abspath(os.path.dirname(__file__))
44 self.build_obj = MozbuildObject.from_environment(cwd=here)
45
46 def log_verbose(self, what):
47 if self.verbose:
48 print(what)
49
50
51 class TestInfoTests(TestInfo):
52 """
53 Support 'mach test-info tests': Detailed report of specified tests.
54 """
55
56 def __init__(self, verbose):
57 TestInfo.__init__(self, verbose)
58
59 self._hg = None
60 if conditions.is_hg(self.build_obj):
61 self._hg = which("hg")
62 if not self._hg:
63 raise OSError(errno.ENOENT, "Could not find 'hg' on PATH.")
64
65 self._git = None
66 if conditions.is_git(self.build_obj):
67 self._git = which("git")
68 if not self._git:
69 raise OSError(errno.ENOENT, "Could not find 'git' on PATH.")
70
71 def find_in_hg_or_git(self, test_name):
72 if self._hg:
73 cmd = [self._hg, "files", "-I", test_name]
74 elif self._git:
75 cmd = [self._git, "ls-files", test_name]
76 else:
77 return None
78 try:
79 out = subprocess.check_output(cmd, universal_newlines=True).splitlines()
80 except subprocess.CalledProcessError:
81 out = None
82 return out
83
84 def set_test_name(self):
85 # Generating a unified report for a specific test is complicated
86 # by differences in the test name used in various data sources.
87 # Consider:
88 # - It is often convenient to request a report based only on
89 # a short file name, rather than the full path;
90 # - Bugs may be filed in bugzilla against a simple, short test
91 # name or the full path to the test;
92 # This function attempts to find appropriate names for different
93 # queries based on the specified test name.
94
95 # full_test_name is full path to file in hg (or git)
96 self.full_test_name = None
97 out = self.find_in_hg_or_git(self.test_name)
98 if out and len(out) == 1:
99 self.full_test_name = out[0]
100 elif out and len(out) > 1:
101 print("Ambiguous test name specified. Found:")
102 for line in out:
103 print(line)
104 else:
105 out = self.find_in_hg_or_git("**/%s*" % self.test_name)
106 if out and len(out) == 1:
107 self.full_test_name = out[0]
108 elif out and len(out) > 1:
109 print("Ambiguous test name. Found:")
110 for line in out:
111 print(line)
112 if self.full_test_name:
113 self.full_test_name.replace(os.sep, posixpath.sep)
114 print("Found %s in source control." % self.full_test_name)
115 else:
116 print("Unable to validate test name '%s'!" % self.test_name)
117 self.full_test_name = self.test_name
118
119 # search for full_test_name in test manifests
120 here = os.path.abspath(os.path.dirname(__file__))
121 resolver = TestResolver.from_environment(
122 cwd=here, loader_cls=TestManifestLoader
123 )
124 relpath = self.build_obj._wrap_path_argument(self.full_test_name).relpath()
125 tests = list(resolver.resolve_tests(paths=[relpath]))
126 if len(tests) == 1:
127 relpath = self.build_obj._wrap_path_argument(tests[0]["manifest"]).relpath()
128 print("%s found in manifest %s" % (self.full_test_name, relpath))
129 if tests[0].get("flavor"):
130 print(" flavor: %s" % tests[0]["flavor"])
131 if tests[0].get("skip-if"):
132 print(" skip-if: %s" % tests[0]["skip-if"])
133 if tests[0].get("fail-if"):
134 print(" fail-if: %s" % tests[0]["fail-if"])
135 elif len(tests) == 0:
136 print("%s not found in any test manifest!" % self.full_test_name)
137 else:
138 print("%s found in more than one manifest!" % self.full_test_name)
139
140 # short_name is full_test_name without path
141 self.short_name = None
142 name_idx = self.full_test_name.rfind("/")
143 if name_idx > 0:
144 self.short_name = self.full_test_name[name_idx + 1 :]
145 if self.short_name and self.short_name == self.test_name:
146 self.short_name = None
147
148 def get_platform(self, record):
149 if "platform" in record["build"]:
150 platform = record["build"]["platform"]
151 else:
152 platform = "-"
153 platform_words = platform.split("-")
154 types_label = ""
155 # combine run and build types and eliminate duplicates
156 run_types = []
157 if "run" in record and "type" in record["run"]:
158 run_types = record["run"]["type"]
159 run_types = run_types if isinstance(run_types, list) else [run_types]
160 build_types = []
161 if "build" in record and "type" in record["build"]:
162 build_types = record["build"]["type"]
163 build_types = (
164 build_types if isinstance(build_types, list) else [build_types]
165 )
166 run_types = list(set(run_types + build_types))
167 # '1proc' is used as a treeherder label but does not appear in run types
168 if "e10s" not in run_types:
169 run_types = run_types + ["1proc"]
170 for run_type in run_types:
171 # chunked is not interesting
172 if run_type == "chunked":
173 continue
174 # e10s is the default: implied
175 if run_type == "e10s":
176 continue
177 # sometimes a build/run type is already present in the build platform
178 if run_type in platform_words:
179 continue
180 if types_label:
181 types_label += "-"
182 types_label += run_type
183 return "%s/%s:" % (platform, types_label)
184
185 def report_bugs(self):
186 # Report open bugs matching test name
187 search = self.full_test_name
188 if self.test_name:
189 search = "%s,%s" % (search, self.test_name)
190 if self.short_name:
191 search = "%s,%s" % (search, self.short_name)
192 payload = {"quicksearch": search, "include_fields": "id,summary"}
193 response = requests.get("https://bugzilla.mozilla.org/rest/bug", payload)
194 response.raise_for_status()
195 json_response = response.json()
196 print("\nBugzilla quick search for '%s':" % search)
197 if "bugs" in json_response:
198 for bug in json_response["bugs"]:
199 print("Bug %s: %s" % (bug["id"], bug["summary"]))
200 else:
201 print("No bugs found.")
202
203 def report(
204 self,
205 test_names,
206 start,
207 end,
208 show_info,
209 show_bugs,
210 ):
211 self.start = start
212 self.end = end
213 self.show_info = show_info
214
215 if not self.show_info and not show_bugs:
216 # by default, show everything
217 self.show_info = True
218 show_bugs = True
219
220 for test_name in test_names:
221 print("===== %s =====" % test_name)
222 self.test_name = test_name
223 if len(self.test_name) < 6:
224 print("'%s' is too short for a test name!" % self.test_name)
225 continue
226 self.set_test_name()
227 if show_bugs:
228 self.report_bugs()
229
230
231 class TestInfoReport(TestInfo):
232 """
233 Support 'mach test-info report': Report of test runs summarized by
234 manifest and component.
235 """
236
237 def __init__(self, verbose):
238 TestInfo.__init__(self, verbose)
239 self.threads = []
240
241 @retriable(attempts=3, sleeptime=5, sleepscale=2)
242 def get_url(self, target_url):
243 # if we fail to get valid json (i.e. end point has malformed data), return {}
244 retVal = {}
245 try:
246 self.log_verbose("getting url: %s" % target_url)
247 r = requests.get(target_url, headers={"User-agent": "mach-test-info/1.0"})
248 self.log_verbose("got status: %s" % r.status_code)
249 r.raise_for_status()
250 retVal = r.json()
251 except json.decoder.JSONDecodeError:
252 self.log_verbose("Error retrieving data from %s" % target_url)
253
254 return retVal
255
256 def update_report(self, by_component, result, path_mod):
257 def update_item(item, label, value):
258 # It is important to include any existing item value in case ActiveData
259 # returns multiple records for the same test; that can happen if the report
260 # sometimes maps more than one ActiveData record to the same path.
261 new_value = item.get(label, 0) + value
262 if type(new_value) is int:
263 item[label] = new_value
264 else:
265 item[label] = float(round(new_value, 2)) # pylint: disable=W1633
266
267 if "test" in result and "tests" in by_component:
268 test = result["test"]
269 if path_mod:
270 test = path_mod(test)
271 for bc in by_component["tests"]:
272 for item in by_component["tests"][bc]:
273 if test == item["test"]:
274 # pylint: disable=W1633
275 seconds = float(round(result.get("duration", 0), 2))
276 update_item(item, "total run time, seconds", seconds)
277 update_item(item, "total runs", result.get("count", 0))
278 update_item(item, "skipped runs", result.get("skips", 0))
279 update_item(item, "failed runs", result.get("failures", 0))
280 return True
281 return False
282
283 def path_mod_reftest(self, path):
284 # "<path1> == <path2>" -> "<path1>"
285 path = path.split(" ")[0]
286 # "<path>?<params>" -> "<path>"
287 path = path.split("?")[0]
288 # "<path>#<fragment>" -> "<path>"
289 path = path.split("#")[0]
290 return path
291
292 def path_mod_jsreftest(self, path):
293 # "<path>;assert" -> "<path>"
294 path = path.split(";")[0]
295 return path
296
297 def path_mod_marionette(self, path):
298 # "<path> <test-name>" -> "<path>"
299 path = path.split(" ")[0]
300 # "part1\part2" -> "part1/part2"
301 path = path.replace("\\", os.path.sep)
302 return path
303
304 def path_mod_wpt(self, path):
305 if path[0] == os.path.sep:
306 # "/<path>" -> "<path>"
307 path = path[1:]
308 # "<path>" -> "testing/web-platform/tests/<path>"
309 path = os.path.join("testing", "web-platform", "tests", path)
310 # "<path>?<params>" -> "<path>"
311 path = path.split("?")[0]
312 return path
313
314 def path_mod_jittest(self, path):
315 # "part1\part2" -> "part1/part2"
316 path = path.replace("\\", os.path.sep)
317 # "<path>" -> "js/src/jit-test/tests/<path>"
318 return os.path.join("js", "src", "jit-test", "tests", path)
319
320 def path_mod_xpcshell(self, path):
321 # <manifest>.{ini|toml}:<path> -> "<path>"
322 path = path.split(":")[-1]
323 return path
324
325 def description(
326 self,
327 components,
328 flavor,
329 subsuite,
330 paths,
331 show_manifests,
332 show_tests,
333 show_summary,
334 show_annotations,
335 filter_values,
336 filter_keys,
337 start_date,
338 end_date,
339 ):
340 # provide a natural language description of the report options
341 what = []
342 if show_manifests:
343 what.append("test manifests")
344 if show_tests:
345 what.append("tests")
346 if show_annotations:
347 what.append("test manifest annotations")
348 if show_summary and len(what) == 0:
349 what.append("summary of tests only")
350 if len(what) > 1:
351 what[-1] = "and " + what[-1]
352 what = ", ".join(what)
353 d = "Test summary report for " + what
354 if components:
355 d += ", in specified components (%s)" % components
356 else:
357 d += ", in all components"
358 if flavor:
359 d += ", in specified flavor (%s)" % flavor
360 if subsuite:
361 d += ", in specified subsuite (%s)" % subsuite
362 if paths:
363 d += ", on specified paths (%s)" % paths
364 if filter_values:
365 d += ", containing '%s'" % filter_values
366 if filter_keys:
367 d += " in manifest keys '%s'" % filter_keys
368 else:
369 d += " in any part of manifest entry"
370 d += ", including historical run-time data for the last "
371
372 start = datetime.datetime.strptime(start_date, "%Y-%m-%d")
373 end = datetime.datetime.strptime(end_date, "%Y-%m-%d")
374 d += "%s days on trunk (autoland/m-c)" % ((end - start).days)
375 d += " as of %s." % end_date
376 return d
377
378 # TODO: this is hacked for now and very limited
379 def parse_test(self, summary):
380 if summary.endswith("single tracking bug"):
381 name_part = summary.split("|")[0] # remove 'single tracking bug'
382 name_part.strip()
383 return name_part.split()[-1] # get just the test name, not extra words
384 return None
385
386 def get_runcount_data(self, runcounts_input_file, start, end):
387 # TODO: use start/end properly
388 if runcounts_input_file:
389 try:
390 with open(runcounts_input_file) as f:
391 runcounts = json.load(f)
392 except:
393 print("Unable to load runcounts from path: %s" % runcounts_input_file)
394 raise
395 else:
396 runcounts = self.get_runcounts(days=MAX_DAYS)
397 runcounts = self.squash_runcounts(runcounts, days=MAX_DAYS)
398 return runcounts
399
400 def get_testinfoall_index_url(self):
401 import taskcluster
402
403 index = taskcluster.Index(
404 {
405 "rootUrl": "https://firefox-ci-tc.services.mozilla.com",
406 }
407 )
408 route = "gecko.v2.mozilla-central.latest.source.test-info-all"
409 queue = taskcluster.Queue(
410 {
411 "rootUrl": "https://firefox-ci-tc.services.mozilla.com",
412 }
413 )
414
415 task_id = index.findTask(route)["taskId"]
416 artifacts = queue.listLatestArtifacts(task_id)["artifacts"]
417
418 url = ""
419 for artifact in artifacts:
420 if artifact["name"].endswith("test-run-info.json"):
421 url = queue.buildUrl("getLatestArtifact", task_id, artifact["name"])
422 break
423 return url
424
425 def get_runcounts(self, days=MAX_DAYS):
426 testrundata = {}
427 # get historical data from test-info job artifact; if missing get fresh
428 url = self.get_testinfoall_index_url()
429 print("INFO: requesting runcounts url: %s" % url)
430 olddata = self.get_url(url)
431
432 # fill in any holes we have
433 endday = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(
434 days=1
435 )
436 startday = endday - datetime.timedelta(days=days)
437 urls_to_fetch = []
438 # build list of dates with missing data
439 while startday < endday:
440 nextday = startday + datetime.timedelta(days=1)
441 if not olddata.get(str(nextday.date()), {}):
442 url = "https://treeherder.mozilla.org/api/groupsummary/"
443 url += "?startdate=%s&enddate=%s" % (
444 startday.date(),
445 nextday.date(),
446 )
447 urls_to_fetch.append([str(nextday.date()), url])
448 testrundata[str(nextday.date())] = olddata.get(str(nextday.date()), {})
449
450 startday = nextday
451
452 # limit missing data collection to 5 most recent days days to reduce overall runtime
453 for date, url in urls_to_fetch[-5:]:
454 try:
455 testrundata[date] = self.get_url(url)
456 except requests.exceptions.HTTPError:
457 # We want to see other errors, but can accept HTTPError failures
458 print(f"Unable to retrieve results for url: {url}")
459 pass
460
461 return testrundata
462
463 def squash_runcounts(self, runcounts, days=MAX_DAYS):
464 # squash all testrundata together into 1 big happy family for the last X days
465 endday = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(
466 days=1
467 )
468 oldest = endday - datetime.timedelta(days=days)
469
470 testgroup_runinfo = defaultdict(lambda: defaultdict(int))
471
472 retVal = {}
473 for datekey in runcounts.keys():
474 # strip out older days
475 if datetime.date.fromisoformat(datekey) < oldest.date():
476 continue
477
478 jtn = runcounts[datekey].get("job_type_names", {})
479 if not jtn:
480 print("Warning: Missing job type names from date: %s" % datekey)
481 continue
482
483 # TODO: changed this to include all manifests, not just first
484 for m in runcounts[datekey]["manifests"]:
485 for man_name in m.keys():
486 for job_type_id, result, classification, count in m[man_name]:
487 # HACK: we treat shippable and opt the same for mozinfo and runcounts
488 job_name = jtn[job_type_id].replace("-shippable", "")
489
490 # format: job_type_name, result, classification, count
491 # find matching jtn, result, classification and increment 'count'
492 key = (job_name, result, classification)
493
494 # only keep the "parent" manifest
495 testgroup_runinfo[man_name.split(":")[0]][key] += count
496
497 for m in testgroup_runinfo:
498 retVal[m] = [
499 list(x) + [testgroup_runinfo[m][x]] for x in testgroup_runinfo[m]
500 ]
501 return retVal
502
503 def get_intermittent_failure_data(self, start, end):
504 retVal = {}
505
506 # get IFV bug list
507 # i.e. https://th.m.o/api/failures/?startday=2022-06-22&endday=2022-06-29&tree=all
508 url = (
509 "https://treeherder.mozilla.org/api/failures/?startday=%s&endday=%s&tree=trunk"
510 % (start, end)
511 )
512 if_data = self.get_url(url)
513 buglist = [x["bug_id"] for x in if_data]
514
515 # get bug data for summary, 800 bugs at a time
516 # i.e. https://b.m.o/rest/bug?include_fields=id,product,component,summary&id=1,2,3...
517 max_bugs = 800
518 bug_data = []
519 fields = ["id", "product", "component", "summary"]
520 for bug_index in range(0, len(buglist), max_bugs):
521 bugs = [str(x) for x in buglist[bug_index : bug_index + max_bugs]]
522 if not bugs:
523 print(f"warning: found no bugs in range {bug_index}, +{max_bugs}")
524 continue
525
526 url = "https://bugzilla.mozilla.org/rest/bug?include_fields=%s&id=%s" % (
527 ",".join(fields),
528 ",".join(bugs),
529 )
530 data = self.get_url(url)
531 if data and "bugs" in data.keys():
532 bug_data.extend(data["bugs"])
533
534 # for each summary, parse filename, store component
535 # IF we find >1 bug with same testname, for now summarize as one
536 for bug in bug_data:
537 test_name = self.parse_test(bug["summary"])
538 if not test_name:
539 continue
540
541 c = int([x["bug_count"] for x in if_data if x["bug_id"] == bug["id"]][0])
542 if test_name not in retVal.keys():
543 retVal[test_name] = {
544 "id": bug["id"],
545 "count": 0,
546 "product": bug["product"],
547 "component": bug["component"],
548 }
549 retVal[test_name]["count"] += c
550
551 if bug["product"] != retVal[test_name]["product"]:
552 print(
553 "ERROR | %s | mismatched bugzilla product, bugzilla (%s) != repo (%s)"
554 % (bug["id"], bug["product"], retVal[test_name]["product"])
555 )
556 if bug["component"] != retVal[test_name]["component"]:
557 print(
558 "ERROR | %s | mismatched bugzilla component, bugzilla (%s) != repo (%s)"
559 % (bug["id"], bug["component"], retVal[test_name]["component"])
560 )
561 return retVal
562
563 def report(
564 self,
565 components,
566 flavor,
567 subsuite,
568 paths,
569 show_manifests,
570 show_tests,
571 show_summary,
572 show_annotations,
573 filter_values,
574 filter_keys,
575 show_components,
576 output_file,
577 start,
578 end,
579 show_testruns,
580 runcounts_input_file,
581 config_matrix_output_file,
582 ):
583 def matches_filters(test):
584 """
585 Return True if all of the requested filter_values are found in this test;
586 if filter_keys are specified, restrict search to those test keys.
587 """
588 for value in filter_values:
589 value_found = False
590 for key in test:
591 if not filter_keys or key in filter_keys:
592 if re.search(value, test[key]):
593 value_found = True
594 break
595 if not value_found:
596 return False
597 return True
598
599 start_time = datetime.datetime.now()
600
601 # Ensure useful report by default
602 if (
603 not show_manifests
604 and not show_tests
605 and not show_summary
606 and not show_annotations
607 ):
608 show_manifests = True
609 show_summary = True
610
611 trunk = False
612 if os.environ.get("GECKO_HEAD_REPOSITORY", "") in [
613 "https://hg.mozilla.org/mozilla-central",
614 "https://hg.mozilla.org/try",
615 ]:
616 trunk = True
617 else:
618 show_testruns = False
619
620 by_component = {}
621 if components:
622 components = components.split(",")
623 if filter_keys:
624 filter_keys = filter_keys.split(",")
625 if filter_values:
626 filter_values = filter_values.split(",")
627 else:
628 filter_values = []
629 display_keys = (filter_keys or []) + ["skip-if", "fail-if", "fails-if"]
630 display_keys = set(display_keys)
631 ifd = self.get_intermittent_failure_data(start, end)
632
633 runcount = {}
634
635 if show_testruns and trunk:
636 runcount = self.get_runcount_data(runcounts_input_file, start, end)
637
638 print("Finding tests...")
639 here = os.path.abspath(os.path.dirname(__file__))
640 resolver = TestResolver.from_environment(
641 cwd=here, loader_cls=TestManifestLoader
642 )
643 tests = list(
644 resolver.resolve_tests(paths=paths, flavor=flavor, subsuite=subsuite)
645 )
646
647 manifest_paths = set()
648 for t in tests:
649 if t.get("manifest", None):
650 manifest_path = t["manifest"]
651 if t.get("ancestor_manifest", None):
652 manifest_path = "%s:%s" % (t["ancestor_manifest"], t["manifest"])
653 manifest_paths.add(manifest_path)
654 manifest_count = len(manifest_paths)
655 print(f"Resolver found {len(tests)} tests, {manifest_count} manifests")
656
657 if config_matrix_output_file and trunk:
658 topsrcdir = self.build_obj.topsrcdir
659 config_matrix = {}
660 for manifest in manifest_paths:
661 # we want the first part of the parent:child, as parent shows up in MHTP
662 # TODO: figure out a better solution for child manifests
663 if ".toml" in manifest:
664 relpath = mozpath.relpath(
665 f"{manifest.split('.toml')[0]}.toml", topsrcdir
666 )
667 else:
668 relpath = mozpath.relpath(manifest, topsrcdir)
669 # hack for wpt manifests
670 if relpath.startswith(".."):
671 relpath = "/" + relpath.replace("../", "")
672 config_matrix[relpath] = self.create_matrix_from_task_graph(
673 relpath, runcount
674 )
675 self.write_report(config_matrix, config_matrix_output_file)
676
677 if show_manifests:
678 topsrcdir = self.build_obj.topsrcdir
679 by_component["manifests"] = {}
680 manifest_paths = list(manifest_paths)
681 manifest_paths.sort()
682 relpaths = []
683 for manifest_path in manifest_paths:
684 relpath = mozpath.relpath(manifest_path, topsrcdir)
685 if mozpath.commonprefix((manifest_path, topsrcdir)) != topsrcdir:
686 continue
687 relpaths.append(relpath)
688 reader = self.build_obj.mozbuild_reader(config_mode="empty")
689 files_info = reader.files_info(relpaths)
690 for manifest_path in manifest_paths:
691 relpath = mozpath.relpath(manifest_path, topsrcdir)
692 if mozpath.commonprefix((manifest_path, topsrcdir)) != topsrcdir:
693 continue
694 manifest_info = None
695 if relpath in files_info:
696 bug_component = files_info[relpath].get("BUG_COMPONENT")
697 if bug_component:
698 key = f"{bug_component.product}::{bug_component.component}"
699 else:
700 key = "<unknown bug component>"
701 if (not components) or (key in components):
702 manifest_info = {"manifest": relpath, "tests": 0, "skipped": 0}
703 rkey = key if show_components else "all"
704 if rkey in by_component["manifests"]:
705 by_component["manifests"][rkey].append(manifest_info)
706 else:
707 by_component["manifests"][rkey] = [manifest_info]
708 if manifest_info:
709 for t in tests:
710 if t["manifest"] == manifest_path:
711 manifest_info["tests"] += 1
712 if t.get("skip-if"):
713 manifest_info["skipped"] += 1
714 for key in by_component["manifests"]:
715 by_component["manifests"][key].sort(key=lambda k: k["manifest"])
716
717 if show_tests:
718 by_component["tests"] = {}
719
720 if show_tests or show_summary or show_annotations:
721 test_count = 0
722 failed_count = 0
723 skipped_count = 0
724 annotation_count = 0
725 condition_count = 0
726 component_set = set()
727 relpaths = []
728 conditions = {}
729 known_unconditional_annotations = ["skip", "fail", "asserts", "random"]
730 known_conditional_annotations = [
731 "skip-if",
732 "fail-if",
733 "run-if",
734 "fails-if",
735 "fuzzy-if",
736 "random-if",
737 "asserts-if",
738 ]
739 for t in tests:
740 relpath = t.get("srcdir_relpath")
741 relpaths.append(relpath)
742 reader = self.build_obj.mozbuild_reader(config_mode="empty")
743 files_info = reader.files_info(relpaths)
744 for t in tests:
745 if not matches_filters(t):
746 continue
747 if "referenced-test" in t:
748 # Avoid double-counting reftests: disregard reference file entries
749 continue
750 if show_annotations:
751 for key in t:
752 if key in known_unconditional_annotations:
753 annotation_count += 1
754 if key in known_conditional_annotations:
755 annotation_count += 1
756 # Here 'key' is a manifest annotation type like 'skip-if' and t[key]
757 # is the associated condition. For example, the manifestparser
758 # manifest annotation, "skip-if = os == 'win'", is expected to be
759 # encoded as t['skip-if'] = "os == 'win'".
760 # To allow for reftest manifests, t[key] may have multiple entries
761 # separated by ';', each corresponding to a condition for that test
762 # and annotation type. For example,
763 # "skip-if(Android&&webrender) skip-if(OSX)", would be
764 # encoded as t['skip-if'] = "Android&&webrender;OSX".
765 annotation_conditions = t[key].split(";")
766
767 # if key has \n in it, we need to strip it. for manifestparser format
768 # 1) from the beginning of the line
769 # 2) different conditions if in the middle of the line
770 annotation_conditions = [
771 x.strip("\n") for x in annotation_conditions
772 ]
773 temp = []
774 for condition in annotation_conditions:
775 temp.extend(condition.split("\n"))
776 annotation_conditions = temp
777
778 for c in annotation_conditions:
779 condition_count += 1
780 # Trim reftest fuzzy-if ranges: everything after the first comma
781 # eg. "Android,0-2,1-3" -> "Android"
782 condition = c.split(",")[0]
783 if condition not in conditions:
784 conditions[condition] = 0
785 conditions[condition] += 1
786 test_count += 1
787 relpath = t.get("srcdir_relpath")
788 if relpath in files_info:
789 bug_component = files_info[relpath].get("BUG_COMPONENT")
790 if bug_component:
791 key = f"{bug_component.product}::{bug_component.component}"
792 else:
793 key = "<unknown bug component>"
794 if (not components) or (key in components):
795 component_set.add(key)
796 test_info = {"test": relpath}
797 for test_key in display_keys:
798 value = t.get(test_key)
799 if value:
800 test_info[test_key] = value
801 if t.get("fail-if"):
802 failed_count += 1
803 if t.get("fails-if"):
804 failed_count += 1
805 if t.get("skip-if"):
806 skipped_count += 1
807
808 if "manifest_relpath" in t and "manifest" in t:
809 if "web-platform" in t["manifest_relpath"]:
810 test_info["manifest"] = [t["manifest"]]
811 else:
812 test_info["manifest"] = [t["manifest_relpath"]]
813
814 # handle included manifests as ancestor:child
815 if t.get("ancestor_manifest", None):
816 test_info["manifest"] = [
817 "%s:%s"
818 % (t["ancestor_manifest"], test_info["manifest"][0])
819 ]
820
821 # add in intermittent failure data
822 if ifd.get(relpath):
823 if_data = ifd.get(relpath)
824 test_info["failure_count"] = if_data["count"]
825 if show_testruns:
826 total_runs = 0
827 for m in test_info["manifest"]:
828 if m in runcount.keys():
829 for x in runcount.get(m, []):
830 if not x:
831 break
832 total_runs += x[3]
833 if total_runs > 0:
834 test_info["total_runs"] = total_runs
835
836 if show_tests:
837 rkey = key if show_components else "all"
838 if rkey in by_component["tests"]:
839 # Avoid duplicates: Some test paths have multiple TestResolver
840 # entries, as when a test is included by multiple manifests.
841 found = False
842 for ctest in by_component["tests"][rkey]:
843 if ctest["test"] == test_info["test"]:
844 found = True
845 break
846 if not found:
847 by_component["tests"][rkey].append(test_info)
848 else:
849 for ti in by_component["tests"][rkey]:
850 if ti["test"] == test_info["test"]:
851 if (
852 test_info["manifest"][0]
853 not in ti["manifest"]
854 ):
855 ti_manifest = test_info["manifest"]
856 if test_info.get(
857 "ancestor_manifest", None
858 ):
859 ti_manifest = "%s:%s" % (
860 test_info["ancestor_manifest"],
861 ti_manifest,
862 )
863 ti["manifest"].extend(ti_manifest)
864 else:
865 by_component["tests"][rkey] = [test_info]
866 if show_tests:
867 for key in by_component["tests"]:
868 by_component["tests"][key].sort(key=lambda k: k["test"])
869
870 by_component["description"] = self.description(
871 components,
872 flavor,
873 subsuite,
874 paths,
875 show_manifests,
876 show_tests,
877 show_summary,
878 show_annotations,
879 filter_values,
880 filter_keys,
881 start,
882 end,
883 )
884
885 if show_summary:
886 by_component["summary"] = {}
887 by_component["summary"]["components"] = len(component_set)
888 by_component["summary"]["manifests"] = manifest_count
889 by_component["summary"]["tests"] = test_count
890 by_component["summary"]["failed tests"] = failed_count
891 by_component["summary"]["skipped tests"] = skipped_count
892
893 if show_annotations:
894 by_component["annotations"] = {}
895 by_component["annotations"]["total annotations"] = annotation_count
896 by_component["annotations"]["total conditions"] = condition_count
897 by_component["annotations"]["unique conditions"] = len(conditions)
898 by_component["annotations"]["conditions"] = conditions
899
900 self.write_report(by_component, output_file)
901
902 end_time = datetime.datetime.now()
903 self.log_verbose(
904 "%d seconds total to generate report"
905 % (end_time - start_time).total_seconds()
906 )
907
908 def write_report(self, by_component, output_file):
909 json_report = json.dumps(by_component, indent=2, sort_keys=True, cls=SetEncoder)
910 if output_file:
911 output_file = os.path.abspath(output_file)
912 output_dir = os.path.dirname(output_file)
913 if not os.path.isdir(output_dir):
914 os.makedirs(output_dir)
915
916 with open(output_file, "w") as f:
917 f.write(json_report)
918 else:
919 print(json_report)
920
921 def report_diff(self, before, after, output_file):
922 """
923 Support for 'mach test-info report-diff'.
924 """
925
926 def get_file(path_or_url):
927 if urlparse.urlparse(path_or_url).scheme:
928 response = requests.get(path_or_url)
929 response.raise_for_status()
930 return json.loads(response.text)
931 with open(path_or_url) as f:
932 return json.load(f)
933
934 report1 = get_file(before)
935 report2 = get_file(after)
936
937 by_component = {"tests": {}, "summary": {}}
938 self.diff_summaries(by_component, report1["summary"], report2["summary"])
939 self.diff_all_components(by_component, report1["tests"], report2["tests"])
940 self.write_report(by_component, output_file)
941
942 def diff_summaries(self, by_component, summary1, summary2):
943 """
944 Update by_component with comparison of summaries.
945 """
946 all_keys = set(summary1.keys()) | set(summary2.keys())
947 for key in all_keys:
948 delta = summary2.get(key, 0) - summary1.get(key, 0)
949 by_component["summary"]["%s delta" % key] = delta
950
951 def diff_all_components(self, by_component, tests1, tests2):
952 """
953 Update by_component with any added/deleted tests, for all components.
954 """
955 self.added_count = 0
956 self.deleted_count = 0
957 for component in tests1:
958 component1 = tests1[component]
959 component2 = [] if component not in tests2 else tests2[component]
960 self.diff_component(by_component, component, component1, component2)
961 for component in tests2:
962 if component not in tests1:
963 component2 = tests2[component]
964 self.diff_component(by_component, component, [], component2)
965 by_component["summary"]["added tests"] = self.added_count
966 by_component["summary"]["deleted tests"] = self.deleted_count
967
968 def diff_component(self, by_component, component, component1, component2):
969 """
970 Update by_component[component] with any added/deleted tests for the
971 named component.
972 "added": tests found in component2 but missing from component1.
973 "deleted": tests found in component1 but missing from component2.
974 """
975 tests1 = set([t["test"] for t in component1])
976 tests2 = set([t["test"] for t in component2])
977 deleted = tests1 - tests2
978 added = tests2 - tests1
979 if deleted or added:
980 by_component["tests"][component] = {}
981 if deleted:
982 by_component["tests"][component]["deleted"] = sorted(list(deleted))
983 if added:
984 by_component["tests"][component]["added"] = sorted(list(added))
985 self.added_count += len(added)
986 self.deleted_count += len(deleted)
987 common = len(tests1.intersection(tests2))
988 self.log_verbose(
989 "%s: %d deleted, %d added, %d common"
990 % (component, len(deleted), len(added), common)
991 )
992
993 ################################################################################
994 ###
995 ### Below is code for creating a os/version/processor/config/variant matrix
996 ###
997
998 def build_matrix_cache(self):
999 # this is an attempt to cache the .json for the duration of the task
1000 filename = "task-graph.json"
1001 if os.path.exists(filename):
1002 with open(filename) as f:
1003 data = json.load(f)
1004 else:
1005 url = (
1006 "https://firefox-ci-tc.services.mozilla.com/api/index/v1/task/gecko.v2.mozilla-central.latest.taskgraph.decision/artifacts/public/"
1007 + filename
1008 )
1009
1010 response = requests.get(url, headers={"User-agent": "mach-test-info/1.0"})
1011 data = response.json()
1012 with open(filename, "w") as f:
1013 json.dump(data, f)
1014
1015 for task in data.values():
1016 task_label: str = task["label"]
1017 # HACK: we treat shippable and opt the same from mozinfo, runtime counts
1018 task_label = task_label.replace("-shippable", "")
1019
1020 # we only want test tasks
1021 if not task_label.startswith("test-"):
1022 continue
1023 if task_label.endswith("-cf"):
1024 continue
1025
1026 try:
1027 parts = task_label.split("-")
1028 if int(parts[-1]):
1029 task_label = "-".join(parts[:-1])
1030 except ValueError:
1031 pass
1032
1033 # TODO: this only works for tasks where we schedule by manifest
1034 env = task.get("task", {}).get("payload", {}).get("env", {})
1035
1036 mhtp = json.loads(env.get("MOZHARNESS_TEST_PATHS", "{}"))
1037 if not mhtp:
1038 # mock up logic here if matching task
1039 suite = self.find_non_test_path_loader(task_label)
1040 if not suite:
1041 continue
1042 mhtp[suite] = [suite]
1043
1044 # TODO: figure out a better method for dealing with TEST_TAG
1045 # when we have a test_tag, all skipped manifests are added to chunk 1.
1046 # we are skipping real manifests, but avoiding many overreported manifests.
1047 #
1048 # NOTE: some variants only have a single chunk, so no numbers
1049 if json.loads(env.get("MOZHARNESS_TEST_TAG", "{}")):
1050 if not json.loads(env.get("MOZHARNESS_TEST_PATHS", "{}")):
1051 # mock up logic here if matching task
1052 suite = self.find_non_test_path_loader(task_label)
1053 if not suite:
1054 continue
1055 mhtp[suite] = [suite]
1056
1057 for suite in mhtp:
1058 for manifest in mhtp[suite]:
1059 self.matrix_map[manifest].append(task_label)
1060
1061 extra = task.get("task", {}).get("extra", {}).get("test-setting", {})
1062 platform_info = PlatformInfo(extra)
1063
1064 self.task_tuples[task_label] = platform_info
1065
1066 matrix_map = defaultdict(list)
1067 task_tuples: Dict[str, PlatformInfo] = {}
1068
1069 def find_non_test_path_loader(self, label):
1070 # TODO: how to keep this list synchronized?
1071 known_suites = [
1072 "mochitest-browser-media",
1073 "telemetry-tests-client",
1074 "mochitest-webgl2-ext",
1075 "mochitest-webgl1-ext",
1076 "jittest-1proc",
1077 "mochitest-browser-translations",
1078 "jsreftest",
1079 "mochitest-browser-screenshots",
1080 "marionette-unittest",
1081 ]
1082 match = [x for x in known_suites if x in label]
1083 if match:
1084 return match[0]
1085 return ""
1086
1087 # find manifest in matrix_map and for all tasks that run this
1088 # pull the tuples out and create a definitive list
1089 def create_matrix_from_task_graph(self, target_manifest, runcount):
1090 results = {}
1091
1092 if not self.matrix_map:
1093 self.build_matrix_cache()
1094
1095 # for tasks with no MOZHARNESS_TEST_PATHS, provide basic data
1096 if target_manifest in runcount and self.find_non_test_path_loader(
1097 runcount[target_manifest][0][0]
1098 ):
1099 suite = self.find_non_test_path_loader(runcount[target_manifest][0][0])
1100 self.matrix_map[target_manifest] = self.matrix_map[suite]
1101
1102 for tl in self.matrix_map.get(target_manifest, []):
1103 task_label = tl.replace("-shippable", "")
1104 platform_info = self.task_tuples[task_label]
1105
1106 # add in runcounts, we can find find the index of the given task_label in 'job_type_names',
1107 # use that to get specific runs
1108 passed = 0
1109 failed = 0
1110 if target_manifest in runcount:
1111 # data = [[job_name, result, classification, count], ...]
1112 for data in [
1113 x for x in runcount[target_manifest] if task_label == x[0]
1114 ]:
1115 if data[1] == "passed":
1116 passed += data[-1]
1117 else:
1118 failed += data[-1]
1119
1120 # this helps avoid 'skipped' manifests
1121 if passed == 0 and failed == 0:
1122 continue
1123
1124 if platform_info.os not in results:
1125 results[platform_info.os] = {}
1126 os = results[platform_info.os]
1127 if platform_info.os_version not in os:
1128 os[platform_info.os_version] = {}
1129 os_version = os[platform_info.os_version]
1130 if platform_info.arch not in os_version:
1131 os_version[platform_info.arch] = {}
1132 arch = os_version[platform_info.arch]
1133 if platform_info.build_type not in arch:
1134 arch[platform_info.build_type] = {}
1135
1136 if platform_info.test_variant not in arch[platform_info.build_type]:
1137 arch[platform_info.build_type][platform_info.test_variant] = {
1138 "pass": 0,
1139 "fail": 0,
1140 }
1141 arch[platform_info.build_type][platform_info.test_variant]["pass"] += passed
1142 arch[platform_info.build_type][platform_info.test_variant]["fail"] += failed
1143
1144 return results