Debian Codegraph @

.ci/generate_test_report_lib.py

raw
1 # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
2 # See https://llvm.org/LICENSE.txt for license information.
3 # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
4 """Library to parse JUnit XML files and return a markdown report."""
5
6 from typing import TypedDict
7 import platform
8
9 from junitparser import JUnitXml, Failure
10
11
12 # This data structure should match the definition in llvm-zorg in
13 # premerge/advisor/advisor_lib.py
14 class FailureExplanation(TypedDict):
15 name: str
16 explained: bool
17 reason: str | None
18
19
20 SEE_BUILD_FILE_STR = "Download the build's log file to see the details."
21 UNRELATED_FAILURES_STR = (
22 "If these failures are unrelated to your changes (for example "
23 "tests are broken or flaky at HEAD), please open an issue at "
24 "https://github.com/llvm/llvm-project/issues and add the "
25 "`infrastructure` label."
26 )
27 # The maximum number of lines to pull from a ninja failure.
28 NINJA_LOG_SIZE_THRESHOLD = 500
29
30
31 def _parse_ninja_log(ninja_log: list[str]) -> list[tuple[str, str]]:
32 """Parses an individual ninja log."""
33 failures = []
34 index = 0
35 while index < len(ninja_log):
36 while index < len(ninja_log) and not ninja_log[index].startswith("FAILED:"):
37 index += 1
38 if index == len(ninja_log):
39 # We hit the end of the log without finding a build failure, go to
40 # the next log.
41 return failures
42 # If we are doing a build with LLVM_ENABLE_RUNTIMES, we can have nested
43 # ninja invocations. The sub-ninja will print that a subcommand failed,
44 # and then the outer ninja will list the command that failed. We should
45 # ignore the outer failure.
46 if ninja_log[index - 1].startswith("ninja: build stopped:"):
47 index += 1
48 continue
49 # We are trying to parse cases like the following:
50 #
51 # [4/5] test/4.stamp
52 # FAILED: touch test/4.stamp
53 # touch test/4.stamp
54 #
55 # index will point to the line that starts with Failed:. The progress
56 # indicator is sometimes the line before this ([4/5] test/4.stamp) and
57 # will contain a pretty printed version of the target being built
58 # (test/4.stamp) when accurate. We instead parse the failed line rather
59 # than the progress indicator as the progress indicator may not be
60 # aligned with the failure.
61 failing_action = ninja_log[index].split("FAILED: ")[1]
62 failure_log = []
63
64 # Parse the lines above the FAILED: string if the line does not come
65 # immediately after a progress indicator to ensure that we capture the
66 # entire failure message.
67 if not ninja_log[index - 1].startswith("["):
68 before_index = index - 1
69 while before_index > 0 and not ninja_log[before_index].startswith("["):
70 failure_log.append(ninja_log[before_index])
71 before_index = before_index - 1
72 failure_log.reverse()
73
74 # Parse the failure information, which comes after the FAILED: tag.
75 while (
76 index < len(ninja_log)
77 and not ninja_log[index].startswith("[")
78 and not ninja_log[index].startswith("ninja: build stopped:")
79 and len(failure_log) < NINJA_LOG_SIZE_THRESHOLD
80 ):
81 failure_log.append(ninja_log[index])
82 index += 1
83 failures.append((failing_action, "\n".join(failure_log)))
84 return failures
85
86
87 def find_failure_in_ninja_logs(ninja_logs: list[list[str]]) -> list[tuple[str, str]]:
88 """Extracts failure messages from ninja output.
89
90 This function takes stdout/stderr from ninja in the form of a list of files
91 represented as a list of lines. This function then returns tuples containing
92 the name of the target and the error message.
93
94 Args:
95 ninja_logs: A list of files in the form of a list of lines representing the log
96 files captured from ninja.
97
98 Returns:
99 A list of tuples. The first string is the name of the target that failed. The
100 second string is the error message.
101 """
102 failures = []
103 for ninja_log in ninja_logs:
104 log_failures = _parse_ninja_log(ninja_log)
105 failures.extend(log_failures)
106 return failures
107
108
109 def _format_failures(
110 failures: list[tuple[str, str]], failure_explanations: dict[str, FailureExplanation]
111 ) -> list[str]:
112 """Formats failures into summary views for the report."""
113 output = []
114 for build_failure in failures:
115 failed_action, failure_message = build_failure
116 failure_explanation = None
117 if failed_action in failure_explanations:
118 failure_explanation = failure_explanations[failed_action]
119 output.append("<details>")
120 if failure_explanation:
121 output.extend(
122 [
123 f"<summary>{failed_action} (Likely Already Failing)</summary>" "",
124 failure_explanation["reason"],
125 "",
126 ]
127 )
128 else:
129 output.extend([f"<summary>{failed_action}</summary>", ""])
130 output.extend(
131 [
132 "```",
133 failure_message,
134 "```",
135 "</details>",
136 ]
137 )
138 return output
139
140
141 def get_failures(junit_objects) -> dict[str, list[tuple[str, str]]]:
142 failures = {}
143 for results in junit_objects:
144 for testsuite in results:
145 for test in testsuite:
146 if (
147 not test.is_passed
148 and test.result
149 and isinstance(test.result[0], Failure)
150 ):
151 if failures.get(testsuite.name) is None:
152 failures[testsuite.name] = []
153 failures[testsuite.name].append(
154 (test.classname + "/" + test.name, test.result[0].text)
155 )
156 return failures
157
158
159 def are_all_failures_explained(
160 failures: list[tuple[str, str]], failure_explanations: dict[str, FailureExplanation]
161 ) -> bool:
162 for failed_action, _ in failures:
163 if failed_action not in failure_explanations:
164 return False
165 else:
166 assert failure_explanations[failed_action]["explained"]
167 return True
168
169
170 # Set size_limit to limit the byte size of the report. The default is 1MB as this
171 # is the most that can be put into an annotation. If the generated report exceeds
172 # this limit and failures are listed, it will be generated again without failures
173 # listed. This minimal report will always fit into an annotation.
174 # If include failures is False, total number of test will be reported but their names
175 # and output will not be.
176 def generate_report(
177 title,
178 return_code,
179 junit_objects,
180 ninja_logs: list[list[str]],
181 size_limit=1024 * 1024,
182 list_failures=True,
183 failure_explanations_list: list[FailureExplanation] = [],
184 ) -> tuple[str, bool]:
185 failures = get_failures(junit_objects)
186 tests_run = 0
187 tests_skipped = 0
188 tests_failed = 0
189
190 failure_explanations: dict[str, FailureExplanation] = {}
191 for failure_explanation in failure_explanations_list:
192 if not failure_explanation["explained"]:
193 continue
194 failure_explanations[failure_explanation["name"]] = failure_explanation
195 all_failures_explained = True
196 if failures:
197 for _, failures_list in failures.items():
198 all_failures_explained &= are_all_failures_explained(
199 failures_list, failure_explanations
200 )
201
202 for results in junit_objects:
203 for testsuite in results:
204 tests_run += testsuite.tests
205 tests_skipped += testsuite.skipped
206 tests_failed += testsuite.failures
207
208 report = [f"# {title}", ""]
209
210 if tests_run == 0:
211 if return_code == 0:
212 report.extend(
213 [
214 ":white_check_mark: The build succeeded and no tests ran. "
215 "This is expected in some build configurations."
216 ]
217 )
218 else:
219 ninja_failures = find_failure_in_ninja_logs(ninja_logs)
220 all_failures_explained &= are_all_failures_explained(
221 ninja_failures, failure_explanations
222 )
223 if not ninja_failures:
224 all_failures_explained = False
225 report.extend(
226 [
227 "The build failed before running any tests. Detailed "
228 "information about the build failure could not be "
229 "automatically obtained.",
230 "",
231 SEE_BUILD_FILE_STR,
232 "",
233 UNRELATED_FAILURES_STR,
234 ]
235 )
236 else:
237 report.extend(
238 [
239 "The build failed before running any tests. Click on a "
240 "failure below to see the details.",
241 "",
242 ]
243 )
244 report.extend(_format_failures(ninja_failures, failure_explanations))
245 report.extend(
246 [
247 "",
248 UNRELATED_FAILURES_STR,
249 ]
250 )
251 return ("\n".join(report), all_failures_explained)
252
253 tests_passed = tests_run - tests_skipped - tests_failed
254
255 def plural(num_tests):
256 return "test" if num_tests == 1 else "tests"
257
258 if tests_passed:
259 report.append(f"* {tests_passed} {plural(tests_passed)} passed")
260 if tests_skipped:
261 report.append(f"* {tests_skipped} {plural(tests_skipped)} skipped")
262 if tests_failed:
263 report.append(f"* {tests_failed} {plural(tests_failed)} failed")
264
265 if not list_failures:
266 report.extend(
267 [
268 "",
269 "Failed tests and their output was too large to report. "
270 + SEE_BUILD_FILE_STR,
271 ]
272 )
273 elif failures:
274 report.extend(
275 ["", "## Failed Tests", "(click on a test name to see its output)"]
276 )
277
278 for testsuite_name, failures in failures.items():
279 report.extend(["", f"### {testsuite_name}"])
280 report.extend(_format_failures(failures, failure_explanations))
281 elif return_code != 0:
282 # No tests failed but the build was in a failed state. Bring this to the user's
283 # attention.
284 ninja_failures = find_failure_in_ninja_logs(ninja_logs)
285 if not ninja_failures:
286 all_failures_explained = False
287 report.extend(
288 [
289 "",
290 "All executed tests passed, but another part of the build **failed**. "
291 "Information about the build failure could not be automatically "
292 "obtained.",
293 "",
294 SEE_BUILD_FILE_STR,
295 ]
296 )
297 else:
298 all_failures_explained &= are_all_failures_explained(
299 ninja_failures, failure_explanations
300 )
301 report.extend(
302 [
303 "",
304 "All executed tests passed, but another part of the build **failed**. Click on "
305 "a failure below to see the details.",
306 "",
307 ]
308 )
309 report.extend(_format_failures(ninja_failures, failure_explanations))
310 else:
311 report.extend(
312 ["", ":white_check_mark: The build succeeded and all tests passed."]
313 )
314
315 if failures or return_code != 0:
316 report.extend(["", UNRELATED_FAILURES_STR])
317
318 report = "\n".join(report)
319 if len(report.encode("utf-8")) > size_limit:
320 return generate_report(
321 title,
322 return_code,
323 junit_objects,
324 ninja_logs,
325 size_limit,
326 list_failures=False,
327 )
328
329 return (report, all_failures_explained)
330
331
332 def load_info_from_files(build_log_files):
333 junit_files = [
334 junit_file for junit_file in build_log_files if junit_file.endswith(".xml")
335 ]
336 ninja_log_files = [
337 ninja_log for ninja_log in build_log_files if ninja_log.endswith(".log")
338 ]
339 ninja_logs = []
340 for ninja_log_file in ninja_log_files:
341 with open(ninja_log_file, "r") as ninja_log_file_handle:
342 ninja_logs.append(
343 [log_line.strip() for log_line in ninja_log_file_handle.readlines()]
344 )
345 return [JUnitXml.fromfile(p) for p in junit_files], ninja_logs
346
347
348 def generate_report_from_files(title, return_code, build_log_files):
349 junit_objects, ninja_logs = load_info_from_files(build_log_files)
350 return generate_report(title, return_code, junit_objects, ninja_logs)
351
352
353 def compute_platform_title() -> str:
354 logo = ":window:" if platform.system() == "Windows" else ":penguin:"
355 # On Linux the machine value is x86_64 on Windows it is AMD64.
356 if platform.machine() == "x86_64" or platform.machine() == "AMD64":
357 arch = "x64"
358 else:
359 arch = platform.machine()
360 return f"{logo} {platform.system()} {arch} Test Results"