Repository navigation
Expand file tree
/
Copy pathclassify_test_outcome.py
More file actions
267 lines (235 loc) · 9.55 KB
/
Copy pathclassify_test_outcome.py
File metadata and controls
267 lines (235 loc) · 9.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
"""Classify a CI test process from its exit state, JUnit reports, and diagnostics."""
import argparse
import glob
import hashlib
import json
import os
import re
import subprocess
from pathlib import Path
from xml.etree import ElementTree
HANG_EXIT_CODES = {124}
DIAGNOSTIC_SCAN_BYTES = 2 * 1024 * 1024
HANG_PATTERN = re.compile(
r"\bTimeout\s+\(>\d+(?:\.\d+)?s\)\s+from\s+pytest-timeout\b|"
r"(?:\bfork(?:ed)?(?:\s+(?:process|vm))?\b|\btest process\b|\bcommand\b|\bprocess\b)"
r".{0,80}\b(?:timed out|timeout)\b|"
r"\b(?:timed out|timeout)\b.{0,80}"
r"(?:\bfork(?:ed)?(?:\s+(?:process|vm))?\b|\btest process\b|\bcommand\b|\bprocess\b)",
re.IGNORECASE | re.DOTALL,
)
def _local_name(tag: str) -> str:
return tag.rsplit("}", 1)[-1]
def _junit_counts(
report_files: list[Path],
) -> tuple[dict[str, int], list[dict[str, str]], list[str]]:
totals = {"tests": 0, "failures": 0, "errors": 0, "skipped": 0}
failed_tests = []
parse_errors = []
for report_file in report_files:
try:
root = ElementTree.parse(report_file).getroot()
except (ElementTree.ParseError, OSError) as error:
parse_errors.append(f"{report_file}: {error}")
continue
test_cases = [
element for element in root.iter() if _local_name(element.tag) == "testcase"
]
if test_cases:
totals["tests"] += len(test_cases)
for test_case in test_cases:
children_by_name = {
_local_name(child.tag): child for child in test_case
}
child_names = set(children_by_name)
totals["failures"] += int("failure" in child_names)
totals["errors"] += int("error" in child_names)
totals["skipped"] += int("skipped" in child_names)
for failure_type in ("failure", "error"):
failure = children_by_name.get(failure_type)
if failure is None:
continue
class_name = test_case.attrib.get("classname", "")
test_name = test_case.attrib.get("name", "")
failed_tests.append(
{
"id": f"{class_name}#{test_name}",
"className": class_name,
"name": test_name,
"type": failure_type,
"message": failure.attrib.get("message", "")[:1000],
"report": str(report_file),
}
)
continue
if _local_name(root.tag) in {"testsuite", "testsuites"}:
for key in totals:
try:
totals[key] += int(root.attrib.get(key, "0"))
except ValueError:
parse_errors.append(
f"{report_file}: invalid {key} count {root.attrib.get(key)!r}"
)
return totals, failed_tests, parse_errors
def _contains_process_timeout(diagnostic_files: list[Path]) -> bool:
for diagnostic_file in diagnostic_files:
try:
with diagnostic_file.open("rb") as file_handle:
file_handle.seek(0, os.SEEK_END)
size = file_handle.tell()
file_handle.seek(0)
if size <= DIAGNOSTIC_SCAN_BYTES:
raw_content = file_handle.read()
else:
segment_size = DIAGNOSTIC_SCAN_BYTES // 2
head = file_handle.read(segment_size)
file_handle.seek(-segment_size, os.SEEK_END)
raw_content = head + file_handle.read(segment_size)
content = raw_content.decode("utf-8", errors="replace")
except OSError:
continue
if HANG_PATTERN.search(content):
return True
return False
def _file_manifest(files: list[Path]) -> list[dict[str, object]]:
manifest = []
for file_path in files:
try:
digest = hashlib.sha256(file_path.read_bytes()).hexdigest()
manifest.append(
{
"path": str(file_path),
"bytes": file_path.stat().st_size,
"sha256": digest,
}
)
except OSError as error:
manifest.append({"path": str(file_path), "error": str(error)})
return manifest
def classify_outcome(
step_outcome: str,
exit_code: int | None,
report_files: list[Path],
diagnostic_files: list[Path],
) -> dict[str, object]:
tests, failed_tests, parse_errors = _junit_counts(report_files)
reasons = []
if step_outcome == "cancelled":
classification = "cancelled"
reasons.append("The test step was cancelled.")
elif exit_code in HANG_EXIT_CODES or (
step_outcome != "success" and _contains_process_timeout(diagnostic_files)
):
classification = "hung_test"
reasons.append("The test process exceeded its bounded execution time.")
elif tests["failures"] + tests["errors"] > 0:
classification = "test_failure"
reasons.append("JUnit reported a test failure or error.")
elif parse_errors:
classification = "infrastructure_failure"
reasons.append("One or more JUnit reports could not be parsed.")
elif step_outcome == "success" and tests["tests"] == 0:
classification = "missing_results"
reasons.append("The test step succeeded without reporting any tests.")
elif step_outcome in {"failure", "skipped", "unknown", ""} and tests["tests"] == 0:
classification = "setup_failure"
reasons.append("The test process did not produce a test result.")
elif step_outcome != "success" or exit_code not in {None, 0}:
classification = "infrastructure_failure"
reasons.append("Tests did not fail, but the surrounding test process failed.")
else:
classification = "passed"
reasons.append("The test process and every reported test passed.")
return {
"schemaVersion": 1,
"classification": classification,
"stepOutcome": step_outcome,
"exitCode": exit_code,
"tests": tests,
"failedTests": failed_tests,
"reportCount": len(report_files),
"reports": _file_manifest(report_files),
"reportParseErrors": parse_errors,
"diagnostics": _file_manifest(diagnostic_files),
"reasons": reasons,
}
def _expand_globs(patterns: list[str]) -> list[Path]:
return sorted(
{
Path(match)
for pattern in patterns
for match in glob.glob(pattern, recursive=True)
if Path(match).is_file()
},
key=str,
)
def _parse_exit_code(value: str) -> int | None:
return int(value) if value.strip() else None
def _source_sha() -> str:
try:
return subprocess.run(
["git", "rev-parse", "HEAD"],
check=True,
capture_output=True,
text=True,
).stdout.strip()
except (OSError, subprocess.CalledProcessError):
return os.environ.get("GITHUB_SHA", "")
def _summary(result: dict[str, object]) -> str:
tests = result["tests"]
context = result.get("context", {})
return "\n".join(
[
"### Test outcome classification",
"",
f"- Classification: `{result['classification']}`",
f"- Source SHA: `{context.get('sourceSha', '')}`",
f"- Profile/lane: `{context.get('profile', '')}` / `{context.get('lane', '')}`",
f"- Step outcome: `{result['stepOutcome']}`",
f"- Exit code: `{result['exitCode']}`",
f"- JUnit: {tests['tests']} tests, {tests['failures']} failures, "
f"{tests['errors']} errors, {tests['skipped']} skipped",
f"- Reports: {result['reportCount']}",
f"- Diagnostics: {len(result['diagnostics'])}",
f"- Reason: {result['reasons'][0]}",
"",
]
)
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--step-outcome", required=True)
parser.add_argument("--exit-code", default="")
parser.add_argument("--report-glob", action="append", default=[])
parser.add_argument("--diagnostic-glob", action="append", default=[])
parser.add_argument("--output", required=True)
parser.add_argument("--summary")
args = parser.parse_args()
report_files = _expand_globs(args.report_glob)
diagnostic_files = _expand_globs(args.diagnostic_glob)
result = classify_outcome(
args.step_outcome,
_parse_exit_code(args.exit_code),
report_files,
diagnostic_files,
)
result["context"] = {
"sourceSha": _source_sha(),
"profile": os.environ.get("TEST_PROFILE", ""),
"lane": os.environ.get("TEST_LANE", ""),
"runId": os.environ.get("GITHUB_RUN_ID", ""),
"runAttempt": os.environ.get("GITHUB_RUN_ATTEMPT", ""),
}
output_path = Path(args.output)
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_text(
json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8"
)
summary = _summary(result)
summary_path = args.summary or os.environ.get("GITHUB_STEP_SUMMARY")
if summary_path:
with Path(summary_path).open("a", encoding="utf-8") as summary_file:
summary_file.write(summary)
print(summary, end="")
return int(args.step_outcome == "success" and result["classification"] != "passed")
if __name__ == "__main__":
raise SystemExit(main())