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/.
12 from collections
import defaultdict
14 import mozpack
.path
as mozpath
16 import six
.moves
.urllib_parse
as urlparse
17 from mozbuild
.base
import MachCommandConditions
as conditions
18 from mozbuild
.base
import MozbuildObject
19 from mozfile
import which
20 from moztest
.resolve
import TestManifestLoader
, TestResolver
22 REFERER
= "https://wiki.developer.mozilla.org/en-US/docs/Mozilla/Test-Info"
26 class TestInfo(object):
28 Support 'mach test-info'.
31 def __init__(self
, verbose
):
32 self
.verbose
= verbose
33 here
= os
.path
.abspath(os
.path
.dirname(__file__
))
34 self
.build_obj
= MozbuildObject
.from_environment(cwd
=here
)
36 def log_verbose(self
, what
):
41 class TestInfoTests(TestInfo
):
43 Support 'mach test-info tests': Detailed report of specified tests.
46 def __init__(self
, verbose
):
47 TestInfo
.__init
__(self
, verbose
)
50 if conditions
.is_hg(self
.build_obj
):
51 self
._hg
= which("hg")
53 raise OSError(errno
.ENOENT
, "Could not find 'hg' on PATH.")
56 if conditions
.is_git(self
.build_obj
):
57 self
._git
= which("git")
59 raise OSError(errno
.ENOENT
, "Could not find 'git' on PATH.")
61 def find_in_hg_or_git(self
, test_name
):
63 cmd
= [self
._hg
, "files", "-I", test_name
]
65 cmd
= [self
._git
, "ls-files", test_name
]
69 out
= subprocess
.check_output(cmd
, universal_newlines
=True).splitlines()
70 except subprocess
.CalledProcessError
:
74 def set_test_name(self
):
75 # Generating a unified report for a specific test is complicated
76 # by differences in the test name used in various data sources.
78 # - It is often convenient to request a report based only on
79 # a short file name, rather than the full path;
80 # - Bugs may be filed in bugzilla against a simple, short test
81 # name or the full path to the test;
82 # This function attempts to find appropriate names for different
83 # queries based on the specified test name.
85 # full_test_name is full path to file in hg (or git)
86 self
.full_test_name
= None
87 out
= self
.find_in_hg_or_git(self
.test_name
)
88 if out
and len(out
) == 1:
89 self
.full_test_name
= out
[0]
90 elif out
and len(out
) > 1:
91 print("Ambiguous test name specified. Found:")
95 out
= self
.find_in_hg_or_git("**/%s*" % self
.test_name
)
96 if out
and len(out
) == 1:
97 self
.full_test_name
= out
[0]
98 elif out
and len(out
) > 1:
99 print("Ambiguous test name. Found:")
102 if self
.full_test_name
:
103 self
.full_test_name
.replace(os
.sep
, posixpath
.sep
)
104 print("Found %s in source control." % self
.full_test_name
)
106 print("Unable to validate test name '%s'!" % self
.test_name
)
107 self
.full_test_name
= self
.test_name
109 # search for full_test_name in test manifests
110 here
= os
.path
.abspath(os
.path
.dirname(__file__
))
111 resolver
= TestResolver
.from_environment(
112 cwd
=here
, loader_cls
=TestManifestLoader
114 relpath
= self
.build_obj
._wrap
_path
_argument
(self
.full_test_name
).relpath()
115 tests
= list(resolver
.resolve_tests(paths
=[relpath
]))
117 relpath
= self
.build_obj
._wrap
_path
_argument
(tests
[0]["manifest"]).relpath()
118 print("%s found in manifest %s" % (self
.full_test_name
, relpath
))
119 if tests
[0].get("flavor"):
120 print(" flavor: %s" % tests
[0]["flavor"])
121 if tests
[0].get("skip-if"):
122 print(" skip-if: %s" % tests
[0]["skip-if"])
123 if tests
[0].get("fail-if"):
124 print(" fail-if: %s" % tests
[0]["fail-if"])
125 elif len(tests
) == 0:
126 print("%s not found in any test manifest!" % self
.full_test_name
)
128 print("%s found in more than one manifest!" % self
.full_test_name
)
130 # short_name is full_test_name without path
131 self
.short_name
= None
132 name_idx
= self
.full_test_name
.rfind("/")
134 self
.short_name
= self
.full_test_name
[name_idx
+ 1 :]
135 if self
.short_name
and self
.short_name
== self
.test_name
:
136 self
.short_name
= None
138 def get_platform(self
, record
):
139 if "platform" in record
["build"]:
140 platform
= record
["build"]["platform"]
143 platform_words
= platform
.split("-")
145 # combine run and build types and eliminate duplicates
147 if "run" in record
and "type" in record
["run"]:
148 run_types
= record
["run"]["type"]
149 run_types
= run_types
if isinstance(run_types
, list) else [run_types
]
151 if "build" in record
and "type" in record
["build"]:
152 build_types
= record
["build"]["type"]
154 build_types
if isinstance(build_types
, list) else [build_types
]
156 run_types
= list(set(run_types
+ build_types
))
157 # '1proc' is used as a treeherder label but does not appear in run types
158 if "e10s" not in run_types
:
159 run_types
= run_types
+ ["1proc"]
160 for run_type
in run_types
:
161 # chunked is not interesting
162 if run_type
== "chunked":
164 # e10s is the default: implied
165 if run_type
== "e10s":
167 # sometimes a build/run type is already present in the build platform
168 if run_type
in platform_words
:
172 types_label
+= run_type
173 return "%s/%s:" % (platform
, types_label
)
175 def report_bugs(self
):
176 # Report open bugs matching test name
177 search
= self
.full_test_name
179 search
= "%s,%s" % (search
, self
.test_name
)
181 search
= "%s,%s" % (search
, self
.short_name
)
182 payload
= {"quicksearch": search
, "include_fields": "id,summary"}
183 response
= requests
.get("https://bugzilla.mozilla.org/rest/bug", payload
)
184 response
.raise_for_status()
185 json_response
= response
.json()
186 print("\nBugzilla quick search for '%s':" % search
)
187 if "bugs" in json_response
:
188 for bug
in json_response
["bugs"]:
189 print("Bug %s: %s" % (bug
["id"], bug
["summary"]))
191 print("No bugs found.")
203 self
.show_info
= show_info
205 if not self
.show_info
and not show_bugs
:
206 # by default, show everything
207 self
.show_info
= True
210 for test_name
in test_names
:
211 print("===== %s =====" % test_name
)
212 self
.test_name
= test_name
213 if len(self
.test_name
) < 6:
214 print("'%s' is too short for a test name!" % self
.test_name
)
221 class TestInfoReport(TestInfo
):
223 Support 'mach test-info report': Report of test runs summarized by
224 manifest and component.
227 def __init__(self
, verbose
):
228 TestInfo
.__init
__(self
, verbose
)
231 def update_report(self
, by_component
, result
, path_mod
):
232 def update_item(item
, label
, value
):
233 # It is important to include any existing item value in case ActiveData
234 # returns multiple records for the same test; that can happen if the report
235 # sometimes maps more than one ActiveData record to the same path.
236 new_value
= item
.get(label
, 0) + value
237 if type(new_value
) == int:
238 item
[label
] = new_value
240 item
[label
] = float(round(new_value
, 2)) # pylint: disable=W1633
242 if "test" in result
and "tests" in by_component
:
243 test
= result
["test"]
245 test
= path_mod(test
)
246 for bc
in by_component
["tests"]:
247 for item
in by_component
["tests"][bc
]:
248 if test
== item
["test"]:
249 # pylint: disable=W1633
250 seconds
= float(round(result
.get("duration", 0), 2))
251 update_item(item
, "total run time, seconds", seconds
)
252 update_item(item
, "total runs", result
.get("count", 0))
253 update_item(item
, "skipped runs", result
.get("skips", 0))
254 update_item(item
, "failed runs", result
.get("failures", 0))
258 def path_mod_reftest(self
, path
):
259 # "<path1> == <path2>" -> "<path1>"
260 path
= path
.split(" ")[0]
261 # "<path>?<params>" -> "<path>"
262 path
= path
.split("?")[0]
263 # "<path>#<fragment>" -> "<path>"
264 path
= path
.split("#")[0]
267 def path_mod_jsreftest(self
, path
):
268 # "<path>;assert" -> "<path>"
269 path
= path
.split(";")[0]
272 def path_mod_marionette(self
, path
):
273 # "<path> <test-name>" -> "<path>"
274 path
= path
.split(" ")[0]
275 # "part1\part2" -> "part1/part2"
276 path
= path
.replace("\\", os
.path
.sep
)
279 def path_mod_wpt(self
, path
):
280 if path
[0] == os
.path
.sep
:
281 # "/<path>" -> "<path>"
283 # "<path>" -> "testing/web-platform/tests/<path>"
284 path
= os
.path
.join("testing", "web-platform", "tests", path
)
285 # "<path>?<params>" -> "<path>"
286 path
= path
.split("?")[0]
289 def path_mod_jittest(self
, path
):
290 # "part1\part2" -> "part1/part2"
291 path
= path
.replace("\\", os
.path
.sep
)
292 # "<path>" -> "js/src/jit-test/tests/<path>"
293 return os
.path
.join("js", "src", "jit-test", "tests", path
)
295 def path_mod_xpcshell(self
, path
):
296 # <manifest>.{ini|toml}:<path> -> "<path>"
297 path
= path
.split(":")[-1]
315 # provide a natural language description of the report options
318 what
.append("test manifests")
322 what
.append("test manifest annotations")
323 if show_summary
and len(what
) == 0:
324 what
.append("summary of tests only")
326 what
[-1] = "and " + what
[-1]
327 what
= ", ".join(what
)
328 d
= "Test summary report for " + what
330 d
+= ", in specified components (%s)" % components
332 d
+= ", in all components"
334 d
+= ", in specified flavor (%s)" % flavor
336 d
+= ", in specified subsuite (%s)" % subsuite
338 d
+= ", on specified paths (%s)" % paths
340 d
+= ", containing '%s'" % filter_values
342 d
+= " in manifest keys '%s'" % filter_keys
344 d
+= " in any part of manifest entry"
345 d
+= ", including historical run-time data for the last "
347 start
= datetime
.datetime
.strptime(start_date
, "%Y-%m-%d")
348 end
= datetime
.datetime
.strptime(end_date
, "%Y-%m-%d")
349 d
+= "%s days on trunk (autoland/m-c)" % ((end
- start
).days
)
350 d
+= " as of %s." % end_date
353 # TODO: this is hacked for now and very limited
354 def parse_test(self
, summary
):
355 if summary
.endswith("single tracking bug"):
356 name_part
= summary
.split("|")[0] # remove 'single tracking bug'
358 return name_part
.split()[-1] # get just the test name, not extra words
361 def get_runcount_data(self
, start
, end
):
362 # TODO: use start/end properly
363 runcounts
= self
.get_runcounts(days
=MAX_DAYS
)
364 runcounts
= self
.squash_runcounts(runcounts
, days
=MAX_DAYS
)
367 def get_testinfoall_index_url(self
):
370 queue
= taskcluster
.Queue()
371 index
= taskcluster
.Index(
373 "rootUrl": "https://firefox-ci-tc.services.mozilla.com",
376 route
= "gecko.v2.mozilla-central.latest.source.test-info-all"
378 task_id
= index
.findTask(route
)["taskId"]
379 artifacts
= queue
.listLatestArtifacts(task_id
)["artifacts"]
382 for artifact
in artifacts
:
383 if artifact
["name"].endswith("test-run-info.json"):
384 url
= queue
.buildUrl("getLatestArtifact", task_id
, artifact
["name"])
388 def get_runcounts(self
, days
=MAX_DAYS
):
390 # get historical data from test-info job artifact; if missing get fresh
392 url
= self
.get_testinfoall_index_url()
393 print("INFO: requesting runcounts url: %s" % url
)
394 r
= requests
.get(url
, headers
={"User-agent": "mach-test-info/1.0"})
396 testrundata
= r
.json()
400 # fill in any holes we have
401 endday
= datetime
.datetime
.now(datetime
.timezone
.utc
) - datetime
.timedelta(
404 startday
= endday
- datetime
.timedelta(days
=days
)
405 while startday
< endday
:
406 nextday
= startday
+ datetime
.timedelta(days
=1)
410 str(nextday
) not in testrundata
.keys()
411 or testrundata
[str(nextday
)] == {}
414 url
= "https://treeherder.mozilla.org/api/groupsummary/"
415 url
+= "?startdate=%s&enddate=%s" % (
420 print("INFO: requesting groupsummary url: %s" % url
)
422 url
, headers
={"User-agent": "mach-test-info/1.0"}
425 except requests
.exceptions
.HTTPError
:
430 testrundata
[str(nextday
.date())] = r
.json()
431 except json
.decoder
.JSONDecodeError
:
433 "Warning unable to retrieve (from treeherder's groupsummary api) testrun data for date: %s, skipping for now"
436 testrundata
[str(nextday
.date())] = {}
442 def squash_runcounts(self
, runcounts
, days
=MAX_DAYS
):
443 # squash all testrundata together into 1 big happy family for the last X days
444 endday
= datetime
.datetime
.now(datetime
.timezone
.utc
) - datetime
.timedelta(
447 oldest
= endday
- datetime
.timedelta(days
=days
)
449 testgroup_runinfo
= defaultdict(lambda: defaultdict(int))
452 for datekey
in runcounts
.keys():
453 # strip out older days
454 if datetime
.date
.fromisoformat(datekey
) < oldest
.date():
457 jtn
= runcounts
[datekey
].get("job_type_names", {})
459 print("Warning: Missing job type names from date: %s" % datekey
)
462 for m
in runcounts
[datekey
]["manifests"]:
463 man_name
= list(m
.keys())[0]
465 for job_type_id
, result
, classification
, count
in m
[man_name
]:
466 # format: job_type_name, result, classification, count
467 # find matching jtn, result, classification and increment 'count'
468 job_name
= jtn
[job_type_id
]
469 key
= (job_name
, result
, classification
)
470 testgroup_runinfo
[man_name
][key
] += count
472 for m
in testgroup_runinfo
:
474 list(x
) + [testgroup_runinfo
[m
][x
]] for x
in testgroup_runinfo
[m
]
478 def get_intermittent_failure_data(self
, start
, end
):
482 # i.e. https://th.m.o/api/failures/?startday=2022-06-22&endday=2022-06-29&tree=all
484 "https://treeherder.mozilla.org/api/failures/?startday=%s&endday=%s&tree=trunk"
487 r
= requests
.get(url
, headers
={"User-agent": "mach-test-info/1.0"})
489 buglist
= [x
["bug_id"] for x
in if_data
]
491 # get bug data for summary, 800 bugs at a time
492 # i.e. https://b.m.o/rest/bug?include_fields=id,product,component,summary&id=1,2,3...
495 fields
= ["id", "product", "component", "summary"]
496 for bug_index
in range(0, len(buglist
), max_bugs
):
497 bugs
= [str(x
) for x
in buglist
[bug_index
: bug_index
+ max_bugs
]]
499 print(f
"warning: found no bugs in range {bug_index}, +{max_bugs}")
502 url
= "https://bugzilla.mozilla.org/rest/bug?include_fields=%s&id=%s" % (
506 r
= requests
.get(url
, headers
={"User-agent": "mach-test-info/1.0"})
508 if data
and "bugs" in data
.keys():
509 bug_data
.extend(data
["bugs"])
511 # for each summary, parse filename, store component
512 # IF we find >1 bug with same testname, for now summarize as one
514 test_name
= self
.parse_test(bug
["summary"])
518 c
= int([x
["bug_count"] for x
in if_data
if x
["bug_id"] == bug
["id"]][0])
519 if test_name
not in retVal
.keys():
520 retVal
[test_name
] = {
523 "product": bug
["product"],
524 "component": bug
["component"],
526 retVal
[test_name
]["count"] += c
528 if bug
["product"] != retVal
[test_name
]["product"]:
530 "ERROR | %s | mismatched bugzilla product, bugzilla (%s) != repo (%s)"
531 % (bug
["id"], bug
["product"], retVal
[test_name
]["product"])
533 if bug
["component"] != retVal
[test_name
]["component"]:
535 "ERROR | %s | mismatched bugzilla component, bugzilla (%s) != repo (%s)"
536 % (bug
["id"], bug
["component"], retVal
[test_name
]["component"])
558 def matches_filters(test
):
560 Return True if all of the requested filter_values are found in this test;
561 if filter_keys are specified, restrict search to those test keys.
563 for value
in filter_values
:
566 if not filter_keys
or key
in filter_keys
:
567 if re
.search(value
, test
[key
]):
574 start_time
= datetime
.datetime
.now()
576 # Ensure useful report by default
581 and not show_annotations
583 show_manifests
= True
588 components
= components
.split(",")
590 filter_keys
= filter_keys
.split(",")
592 filter_values
= filter_values
.split(",")
595 display_keys
= (filter_keys
or []) + ["skip-if", "fail-if", "fails-if"]
596 display_keys
= set(display_keys
)
597 ifd
= self
.get_intermittent_failure_data(start
, end
)
600 if show_testruns
and os
.environ
.get("GECKO_HEAD_REPOSITORY", "") in [
601 "https://hg.mozilla.org/mozilla-central",
602 "https://hg.mozilla.org/try",
604 runcount
= self
.get_runcount_data(start
, end
)
606 print("Finding tests...")
607 here
= os
.path
.abspath(os
.path
.dirname(__file__
))
608 resolver
= TestResolver
.from_environment(
609 cwd
=here
, loader_cls
=TestManifestLoader
612 resolver
.resolve_tests(paths
=paths
, flavor
=flavor
, subsuite
=subsuite
)
615 manifest_paths
= set()
617 if t
.get("manifest", None):
618 manifest_path
= t
["manifest"]
619 if t
.get("ancestor_manifest", None):
620 manifest_path
= "%s:%s" % (t
["ancestor_manifest"], t
["manifest"])
621 manifest_paths
.add(manifest_path
)
622 manifest_count
= len(manifest_paths
)
624 "Resolver found {} tests, {} manifests".format(len(tests
), manifest_count
)
628 topsrcdir
= self
.build_obj
.topsrcdir
629 by_component
["manifests"] = {}
630 manifest_paths
= list(manifest_paths
)
631 manifest_paths
.sort()
633 for manifest_path
in manifest_paths
:
634 relpath
= mozpath
.relpath(manifest_path
, topsrcdir
)
635 if mozpath
.commonprefix((manifest_path
, topsrcdir
)) != topsrcdir
:
637 relpaths
.append(relpath
)
638 reader
= self
.build_obj
.mozbuild_reader(config_mode
="empty")
639 files_info
= reader
.files_info(relpaths
)
640 for manifest_path
in manifest_paths
:
641 relpath
= mozpath
.relpath(manifest_path
, topsrcdir
)
642 if mozpath
.commonprefix((manifest_path
, topsrcdir
)) != topsrcdir
:
645 if relpath
in files_info
:
646 bug_component
= files_info
[relpath
].get("BUG_COMPONENT")
648 key
= "{}::{}".format(
649 bug_component
.product
, bug_component
.component
652 key
= "<unknown bug component>"
653 if (not components
) or (key
in components
):
654 manifest_info
= {"manifest": relpath
, "tests": 0, "skipped": 0}
655 rkey
= key
if show_components
else "all"
656 if rkey
in by_component
["manifests"]:
657 by_component
["manifests"][rkey
].append(manifest_info
)
659 by_component
["manifests"][rkey
] = [manifest_info
]
662 if t
["manifest"] == manifest_path
:
663 manifest_info
["tests"] += 1
665 manifest_info
["skipped"] += 1
666 for key
in by_component
["manifests"]:
667 by_component
["manifests"][key
].sort(key
=lambda k
: k
["manifest"])
670 by_component
["tests"] = {}
672 if show_tests
or show_summary
or show_annotations
:
678 component_set
= set()
681 known_unconditional_annotations
= ["skip", "fail", "asserts", "random"]
682 known_conditional_annotations
= [
692 relpath
= t
.get("srcdir_relpath")
693 relpaths
.append(relpath
)
694 reader
= self
.build_obj
.mozbuild_reader(config_mode
="empty")
695 files_info
= reader
.files_info(relpaths
)
697 if not matches_filters(t
):
699 if "referenced-test" in t
:
700 # Avoid double-counting reftests: disregard reference file entries
704 if key
in known_unconditional_annotations
:
705 annotation_count
+= 1
706 if key
in known_conditional_annotations
:
707 annotation_count
+= 1
708 # Here 'key' is a manifest annotation type like 'skip-if' and t[key]
709 # is the associated condition. For example, the manifestparser
710 # manifest annotation, "skip-if = os == 'win'", is expected to be
711 # encoded as t['skip-if'] = "os == 'win'".
712 # To allow for reftest manifests, t[key] may have multiple entries
713 # separated by ';', each corresponding to a condition for that test
714 # and annotation type. For example,
715 # "skip-if(Android&&webrender) skip-if(OSX)", would be
716 # encoded as t['skip-if'] = "Android&&webrender;OSX".
717 annotation_conditions
= t
[key
].split(";")
719 # if key has \n in it, we need to strip it. for manifestparser format
720 # 1) from the beginning of the line
721 # 2) different conditions if in the middle of the line
722 annotation_conditions
= [
723 x
.strip("\n") for x
in annotation_conditions
726 for condition
in annotation_conditions
:
727 temp
.extend(condition
.split("\n"))
728 annotation_conditions
= temp
730 for condition
in annotation_conditions
:
732 # Trim reftest fuzzy-if ranges: everything after the first comma
733 # eg. "Android,0-2,1-3" -> "Android"
734 condition
= condition
.split(",")[0]
735 if condition
not in conditions
:
736 conditions
[condition
] = 0
737 conditions
[condition
] += 1
739 relpath
= t
.get("srcdir_relpath")
740 if relpath
in files_info
:
741 bug_component
= files_info
[relpath
].get("BUG_COMPONENT")
743 key
= "{}::{}".format(
744 bug_component
.product
, bug_component
.component
747 key
= "<unknown bug component>"
748 if (not components
) or (key
in components
):
749 component_set
.add(key
)
750 test_info
= {"test": relpath
}
751 for test_key
in display_keys
:
752 value
= t
.get(test_key
)
754 test_info
[test_key
] = value
757 if t
.get("fails-if"):
762 if "manifest_relpath" in t
and "manifest" in t
:
763 if "web-platform" in t
["manifest_relpath"]:
764 test_info
["manifest"] = [t
["manifest"]]
766 test_info
["manifest"] = [t
["manifest_relpath"]]
768 # handle included manifests as ancestor:child
769 if t
.get("ancestor_manifest", None):
770 test_info
["manifest"] = [
772 % (t
["ancestor_manifest"], test_info
["manifest"][0])
775 # add in intermittent failure data
777 if_data
= ifd
.get(relpath
)
778 test_info
["failure_count"] = if_data
["count"]
781 for m
in test_info
["manifest"]:
783 total_runs
+= sum([x
[3] for x
in runcount
[m
]])
785 test_info
["total_runs"] = total_runs
788 rkey
= key
if show_components
else "all"
789 if rkey
in by_component
["tests"]:
790 # Avoid duplicates: Some test paths have multiple TestResolver
791 # entries, as when a test is included by multiple manifests.
793 for ctest
in by_component
["tests"][rkey
]:
794 if ctest
["test"] == test_info
["test"]:
798 by_component
["tests"][rkey
].append(test_info
)
800 for ti
in by_component
["tests"][rkey
]:
801 if ti
["test"] == test_info
["test"]:
803 test_info
["manifest"][0]
804 not in ti
["manifest"]
806 ti_manifest
= test_info
["manifest"]
808 "ancestor_manifest", None
810 ti_manifest
= "%s:%s" % (
811 test_info
["ancestor_manifest"],
814 ti
["manifest"].extend(ti_manifest
)
816 by_component
["tests"][rkey
] = [test_info
]
818 for key
in by_component
["tests"]:
819 by_component
["tests"][key
].sort(key
=lambda k
: k
["test"])
821 by_component
["description"] = self
.description(
837 by_component
["summary"] = {}
838 by_component
["summary"]["components"] = len(component_set
)
839 by_component
["summary"]["manifests"] = manifest_count
840 by_component
["summary"]["tests"] = test_count
841 by_component
["summary"]["failed tests"] = failed_count
842 by_component
["summary"]["skipped tests"] = skipped_count
845 by_component
["annotations"] = {}
846 by_component
["annotations"]["total annotations"] = annotation_count
847 by_component
["annotations"]["total conditions"] = condition_count
848 by_component
["annotations"]["unique conditions"] = len(conditions
)
849 by_component
["annotations"]["conditions"] = conditions
851 self
.write_report(by_component
, output_file
)
853 end_time
= datetime
.datetime
.now()
855 "%d seconds total to generate report"
856 % (end_time
- start_time
).total_seconds()
859 def write_report(self
, by_component
, output_file
):
860 json_report
= json
.dumps(by_component
, indent
=2, sort_keys
=True)
862 output_file
= os
.path
.abspath(output_file
)
863 output_dir
= os
.path
.dirname(output_file
)
864 if not os
.path
.isdir(output_dir
):
865 os
.makedirs(output_dir
)
867 with
open(output_file
, "w") as f
:
872 def report_diff(self
, before
, after
, output_file
):
874 Support for 'mach test-info report-diff'.
877 def get_file(path_or_url
):
878 if urlparse
.urlparse(path_or_url
).scheme
:
879 response
= requests
.get(path_or_url
)
880 response
.raise_for_status()
881 return json
.loads(response
.text
)
882 with
open(path_or_url
) as f
:
885 report1
= get_file(before
)
886 report2
= get_file(after
)
888 by_component
= {"tests": {}, "summary": {}}
889 self
.diff_summaries(by_component
, report1
["summary"], report2
["summary"])
890 self
.diff_all_components(by_component
, report1
["tests"], report2
["tests"])
891 self
.write_report(by_component
, output_file
)
893 def diff_summaries(self
, by_component
, summary1
, summary2
):
895 Update by_component with comparison of summaries.
897 all_keys
= set(summary1
.keys()) |
set(summary2
.keys())
899 delta
= summary2
.get(key
, 0) - summary1
.get(key
, 0)
900 by_component
["summary"]["%s delta" % key
] = delta
902 def diff_all_components(self
, by_component
, tests1
, tests2
):
904 Update by_component with any added/deleted tests, for all components.
907 self
.deleted_count
= 0
908 for component
in tests1
:
909 component1
= tests1
[component
]
910 component2
= [] if component
not in tests2
else tests2
[component
]
911 self
.diff_component(by_component
, component
, component1
, component2
)
912 for component
in tests2
:
913 if component
not in tests1
:
914 component2
= tests2
[component
]
915 self
.diff_component(by_component
, component
, [], component2
)
916 by_component
["summary"]["added tests"] = self
.added_count
917 by_component
["summary"]["deleted tests"] = self
.deleted_count
919 def diff_component(self
, by_component
, component
, component1
, component2
):
921 Update by_component[component] with any added/deleted tests for the
923 "added": tests found in component2 but missing from component1.
924 "deleted": tests found in component1 but missing from component2.
926 tests1
= set([t
["test"] for t
in component1
])
927 tests2
= set([t
["test"] for t
in component2
])
928 deleted
= tests1
- tests2
929 added
= tests2
- tests1
931 by_component
["tests"][component
] = {}
933 by_component
["tests"][component
]["deleted"] = sorted(list(deleted
))
935 by_component
["tests"][component
]["added"] = sorted(list(added
))
936 self
.added_count
+= len(added
)
937 self
.deleted_count
+= len(deleted
)
938 common
= len(tests1
.intersection(tests2
))
940 "%s: %d deleted, %d added, %d common"
941 % (component
, len(deleted
), len(added
), common
)