TempestParser 3.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,346 @@
1
+ """Parser for tempest / testr / stestr console logs (`.log` input).
2
+
3
+ The log is read line by line. Two layouts are understood, also mixed in one file.
4
+
5
+ The testr layout, a class line followed by its tests:
6
+
7
+ tempest.api.compute.servers.test_servers.ServersTestJSON <- class line
8
+ test_create_server[id-1111,smoke] OK 1.50 <- test line
9
+ test_ipv6[id-3333](ipv6) FAIL 0.50 <- options in brackets
10
+ setUpClass (tempest.api.network.test_ports <- class setup failed,
11
+ PortsTestJSON) FAIL 0.00 name wrapped or not
12
+
13
+ Slowest 2 tests took 2.00 secs: <- slowest tests,
14
+ tempest.api.compute.servers.test_servers.ServersTestJSON up to a blank line
15
+ test_create_server[id-1111,smoke] 1.50
16
+
17
+ The stestr / subunit-trace layout (`tempest run`), one line per test with its worker:
18
+
19
+ {0} tempest.api.compute.servers.test_servers.ServersTestJSON.test_create [1.500000s] ... ok
20
+ {1} tempest.api.network.test_ports.PortsTestJSON.test_list_ports ... SKIPPED: reason
21
+ {0} tempest.api.compute.servers.test_servers.ServersTestJSON.test_x [0.5s] ... FAILED
22
+
23
+ Captured traceback: <- attachments of the
24
+ ~~~~~~~~~~~~~~~~~~~ test above, indented
25
+ Traceback (most recent call last):
26
+ ...
27
+
28
+ Slowest Tests: <- `stestr --slowest`
29
+ Test id Runtime (s)
30
+ -------------------------------------------- -----------
31
+ tempest.api.compute....test_create_server[id-1111,smoke] 1.500
32
+
33
+ Failure blocks, in both layouts, and the summary:
34
+
35
+ ======================================================================
36
+ FAIL: tempest.api.compute.servers.test_servers.ServersTestJSON.test_x[id-2222]
37
+ ---------------------------------------------------------------------- <- failure head
38
+ Traceback (most recent call last): <- trace (or Captured
39
+ ... attachments) up to the
40
+ Details: 1 != 2 next head or summary;
41
+ Details: lines are
42
+ Ran 3 tests in 2.000s (stestr: "Ran: 3 tests in ...") the message
43
+
44
+ Lines may carry a CI timestamp prefix (`2026-01-01 10:00:00.123456 | `, optionally with a host
45
+ `| controller | `), which is removed. A log can hold several runs; they all import into one run
46
+ named after the file. The log has no date, so the run is dated by the file's modification time.
47
+ """
48
+ import logging
49
+ import re
50
+ from collections.abc import Iterable
51
+ from datetime import datetime
52
+ from typing import IO
53
+
54
+ from tempest_parser.manager.models import file_date, parse_seconds
55
+ from tempest_parser.manager.test_manager import TestsManager
56
+
57
+ # (class, test name, uuid, options)
58
+ TestId = tuple[str, str, str, str]
59
+
60
+ log = logging.getLogger(__name__)
61
+
62
+ # CI job output: "2026-01-01 10:00:00.123456 | " and an optional "host | "
63
+ _PREFIX_RE = re.compile(
64
+ r"^\d{4}-\d\d-\d\d[ T]\d\d:\d\d:\d\d(?:[.,]\d+)?(?:Z|[+-]\d\d:?\d\d)? \|(?: [\w.-]+ \|)? ?")
65
+ # a dotted name on a line of its own: tempest.api.compute.servers.test_servers.ServersTestJSON
66
+ _CLASS_RE = re.compile(r"^[A-Za-z_]\w*(\.\w+)+$")
67
+ # test_name[tags](options) RESULT time; the result and time are optional
68
+ _TEST_RE = re.compile(
69
+ r"^(?P<name>test_[^\s\[(]*)(?P<tags>\[[^\]]*\])?(?P<options>\([^)]*\))?"
70
+ r"\s*(?P<result>[A-Z][A-Z_]*)?\s*(?P<time>\d+(\.\d+)?s?)?\s*$")
71
+ # setUpClass (tempest.api.x.Class) FAIL 0.00, or with the class name wrapped to the next line
72
+ _SETUP_RE = re.compile(r"^(?P<kind>setUpClass|tearDownClass) \((?P<prefix>[^)\s]*)(?P<rest>.*)$")
73
+ # stestr: {0} full.test.id [1.500000s] ... ok / {1} full.test.id ... SKIPPED: reason
74
+ _RESULT_RE = re.compile(
75
+ r"^\{\d+\}\s+(?P<id>(?:setUpClass|tearDownClass) \([^)]*\)|\S+)"
76
+ r"(?:\s+\[(?P<time>\d+(?:\.\d+)?)s[^\]]*\])?\s+\.\.\.\s+(?P<status>[A-Za-z_]+)"
77
+ r"(?::\s*(?P<reason>.*))?$")
78
+ # a full test id: class.test_name[tags](options)
79
+ _ID_RE = re.compile(
80
+ r"^(?P<cls>[A-Za-z_][\w.]*?)\.(?P<name>[^.\[\]()\s]+)(?P<tags>\[[^\]]*\])?(?P<options>\(.*\))?$")
81
+ _SLOWEST_RE = re.compile(r"^Slowest \d+ tests? took")
82
+ _SLOWEST_TABLE_ROW_RE = re.compile(r"^(?P<id>\S+)\s+\d+(?:\.\d+)?$")
83
+ _SUMMARY_RE = re.compile(r"^Ran:? \d+ tests? in ")
84
+ # failure head prefixes written by some runners: "FAIL: tempest...."
85
+ _HEAD_PREFIX_RE = re.compile(r"^(FAIL|ERROR): ")
86
+ _CAPTURED_RE = re.compile(r"^Captured (?P<name>[\w-]+):$")
87
+
88
+ # stestr result words; anything else is upper-cased
89
+ _STATUS = {"ok": "OK", "success": "OK", "failed": "FAIL", "fail": "FAIL", "skipped": "SKIP",
90
+ "skip": "SKIP", "error": "ERROR", "xfail": "X_FAIL", "uxsuccess": "X_OK"}
91
+
92
+ FLOW, SLOWEST, SLOWEST_TABLE, FAIL_HEAD, FAIL_BODY = range(5)
93
+
94
+
95
+ def _is_rule(line: str, char: str, length: int = 20) -> bool:
96
+ return len(line) >= length and line == char * len(line)
97
+
98
+
99
+ def split_test_id(test_id: str) -> TestId | None:
100
+ """(class, test name, uuid, options) of "class.test_name[id-x,tags](options)" or
101
+ "setUpClass (class)"; None when it isn't a test id."""
102
+ setup = _SETUP_RE.match(test_id)
103
+ if setup:
104
+ if setup.group("rest") != ")":
105
+ return None
106
+ return setup.group("kind"), setup.group("prefix"), "", ""
107
+ match = _ID_RE.match(test_id)
108
+ if match is None:
109
+ return None
110
+ uuid = ""
111
+ for tag in (match.group("tags") or "[]")[1:-1].split(","):
112
+ if tag.startswith("id-"):
113
+ uuid = tag
114
+ return match.group("cls"), match.group("name"), uuid, match.group("options") or ""
115
+
116
+
117
+ def _attachment_trace(lines: list[str]) -> list[str]:
118
+ """The trace lines of a failure: the "Captured traceback:" attachment (stestr) without its
119
+ indent when there is one, else the lines as they are."""
120
+ sections: dict[str, list[str]] = {}
121
+ current = None
122
+ skip_rule = False
123
+ for index, line in enumerate(lines):
124
+ if skip_rule:
125
+ skip_rule = False
126
+ continue
127
+ captured = _CAPTURED_RE.match(line)
128
+ if captured and index + 1 < len(lines) and _is_rule(lines[index + 1], "~", 3):
129
+ current = sections.setdefault(captured.group("name"), [])
130
+ skip_rule = True
131
+ elif current is not None:
132
+ current.append(line[4:] if line.startswith(" ") else line)
133
+ # attachments but no traceback: keep them all
134
+ body = list(sections.get("traceback", lines) if sections else lines)
135
+ while body and not body[-1].strip():
136
+ body.pop()
137
+ return body
138
+
139
+
140
+ class TempestLogParser:
141
+ def __init__(self, test_manager: TestsManager, source: IO[str],
142
+ status_filters: Iterable[str] | None = None, run_name: str | None = None,
143
+ run_date: datetime | None = None) -> None:
144
+ self.test_mgr = test_manager
145
+ self.source = source
146
+ self.status_filters = list(status_filters or [])
147
+ self.run_name = run_name or getattr(source, "name", "<stdin>").lower()
148
+ self.run_date = run_date or file_date(source)
149
+
150
+ self._state = FLOW
151
+ self._class_name = ""
152
+ # wrapped "setUpClass (prefix" line waiting for "ClassName) RESULT time"
153
+ self._setup_prefix: tuple[str, str] | None = None
154
+ # tests left out by the status filters: their slowest and failure entries are ignored
155
+ self._filtered: set[tuple[str, str, str]] = set()
156
+ # the failure being collected: its head (test id) and trace lines
157
+ self._head: str | None = None
158
+ self._trace: list[str] = []
159
+ self._slowest_rows = False
160
+
161
+ def parse(self) -> None:
162
+ for line in self.source:
163
+ self._feed(_PREFIX_RE.sub("", line.rstrip("\r\n")))
164
+ self._end_failure()
165
+ self.test_mgr.add_execution(self.run_name, self.run_date)
166
+ self.test_mgr.log_summaries([self.run_name])
167
+
168
+ def _feed(self, line: str) -> None:
169
+ stripped = line.strip()
170
+ if _is_rule(stripped, "=", 6):
171
+ self._end_failure()
172
+ self._state = FAIL_HEAD
173
+ return
174
+ if _SUMMARY_RE.match(stripped):
175
+ self._end_failure()
176
+ self._state = FLOW
177
+ return
178
+ result = _RESULT_RE.match(stripped)
179
+ if result:
180
+ self._end_failure()
181
+ self._result_line(result)
182
+ return
183
+ if self._state == FAIL_HEAD:
184
+ if _is_rule(stripped, "-"):
185
+ self._state = FAIL_BODY
186
+ return
187
+ if not stripped:
188
+ return
189
+ if self._head is None:
190
+ self._head = _HEAD_PREFIX_RE.sub("", stripped)
191
+ return
192
+ # not a failure block ("Worker Balance" lines and the like)
193
+ self._head = None
194
+ self._state = FLOW
195
+ if self._state == FAIL_BODY:
196
+ self._body_line(line, stripped)
197
+ return
198
+ if self._state == SLOWEST:
199
+ if stripped:
200
+ self._slowest_line(re.sub(" +", " ", stripped))
201
+ else:
202
+ self._state = FLOW
203
+ return
204
+ if self._state == SLOWEST_TABLE:
205
+ self._slowest_table_line(stripped)
206
+ return
207
+ if _SLOWEST_RE.match(stripped):
208
+ self._state = SLOWEST
209
+ self._class_name = ""
210
+ return
211
+ if stripped == "Slowest Tests:":
212
+ self._state = SLOWEST_TABLE
213
+ self._slowest_rows = False
214
+ return
215
+ if stripped:
216
+ self._flow_line(re.sub(" +", " ", stripped))
217
+
218
+ # results: testr layout
219
+
220
+ def _flow_line(self, line: str) -> None:
221
+ setup = _SETUP_RE.match(line)
222
+ if setup:
223
+ self._class_name = ""
224
+ rest = setup.group("rest")
225
+ if rest.startswith(")"):
226
+ # the whole class name on one line
227
+ self._setup_result(setup.group("kind"), setup.group("prefix"), rest[1:])
228
+ self._setup_prefix = None
229
+ else:
230
+ self._setup_prefix = (setup.group("kind"), setup.group("prefix"))
231
+ return
232
+ if self._setup_prefix is not None and ")" in line:
233
+ kind, prefix = self._setup_prefix
234
+ self._setup_prefix = None
235
+ name, _, rest = line.partition(")")
236
+ self._setup_result(kind, prefix + "." + name.strip(), rest)
237
+ return
238
+ if _CLASS_RE.match(line):
239
+ self._class_name = line
240
+ self._setup_prefix = None
241
+ return
242
+ test = _TEST_RE.match(line)
243
+ if test and test.group("result") and self._class_name:
244
+ self._add_result(self._class_name, test.group("name"), "", test.group("options") or "",
245
+ test.group("result"), test.group("time"))
246
+ return
247
+ log.debug("Unknown text in line: %s", line)
248
+
249
+ def _setup_result(self, kind: str, class_name: str, rest: str) -> None:
250
+ # "FAIL 0.00": the class setup or teardown failed
251
+ parts = rest.split()
252
+ if parts:
253
+ self._add_result(kind, class_name, "", "", parts[0],
254
+ parts[1] if len(parts) > 1 else None)
255
+
256
+ def _add_result(self, class_name: str, test_name: str, uuid: str, options: str, result: str,
257
+ time: str | None, message: str = "") -> None:
258
+ if result in self.status_filters:
259
+ self._filtered.add((class_name, test_name, options))
260
+ return
261
+ self.test_mgr.add_result_for_test(
262
+ self.run_name, class_name, test_name, uuid, options, result, parse_seconds(time),
263
+ message=message)
264
+
265
+ # results: stestr layout
266
+
267
+ def _result_line(self, match: re.Match[str]) -> None:
268
+ test = split_test_id(match.group("id"))
269
+ self._state = FLOW
270
+ if test is None:
271
+ log.debug("Unknown test id in line: %s", match.group(0))
272
+ return
273
+ status = _STATUS.get(match.group("status").lower(), match.group("status").upper())
274
+ class_name, test_name, uuid, options = test
275
+ reason = match.group("reason") or ""
276
+ self._add_result(class_name, test_name, uuid, options, status, match.group("time"),
277
+ message=reason if status == "SKIP" else "")
278
+ # the attachments printed under the line: kept for failures, dropped otherwise
279
+ self._state = FAIL_BODY
280
+ self._head = match.group("id") if status not in ("OK", "SKIP", "X_FAIL") else None
281
+ self._trace = []
282
+
283
+ # slowest tests
284
+
285
+ def _slowest_line(self, line: str) -> None:
286
+ if _CLASS_RE.match(line):
287
+ self._class_name = line
288
+ return
289
+ if _SETUP_RE.match(line):
290
+ self._class_name = ""
291
+ return
292
+ test = _TEST_RE.match(line)
293
+ if test is None or not self._class_name:
294
+ return
295
+ self._mark_slowest(self._class_name, test.group("name"), "", test.group("options") or "")
296
+
297
+ def _slowest_table_line(self, line: str) -> None:
298
+ row = _SLOWEST_TABLE_ROW_RE.match(line)
299
+ test = split_test_id(row.group("id")) if row else None
300
+ if test is not None:
301
+ self._slowest_rows = True
302
+ self._mark_slowest(*test)
303
+ elif self._slowest_rows and not line:
304
+ self._state = FLOW
305
+
306
+ def _mark_slowest(self, class_name: str, test_name: str, uuid: str, options: str) -> None:
307
+ if (class_name, test_name, options) in self._filtered:
308
+ return
309
+ self.test_mgr.mark_slowest_test_in_execution_by_name(
310
+ self.run_name, class_name, test_name, uuid=uuid, test_options=options)
311
+
312
+ # failures
313
+
314
+ def _body_line(self, line: str, stripped: str) -> None:
315
+ if _is_rule(stripped, "-") and self._trace and not line.startswith(" "):
316
+ # stestr's failure list: a test id over a line of dashes starts the next failure
317
+ previous = self._trace[-1]
318
+ before = self._trace[-2] if len(self._trace) > 1 else ""
319
+ if split_test_id(previous) and not before.strip():
320
+ self._trace.pop()
321
+ self._end_failure()
322
+ self._head = previous
323
+ self._state = FAIL_BODY
324
+ return
325
+ self._trace.append(line)
326
+
327
+ def _end_failure(self) -> None:
328
+ """Store the failure collected so far (head and trace) on its test."""
329
+ head, lines = self._head, self._trace
330
+ self._head, self._trace = None, []
331
+ if head is None:
332
+ return
333
+ test = split_test_id(head if head.startswith(("setUpClass", "tearDownClass"))
334
+ else head.split()[0])
335
+ if test is None:
336
+ # a section title such as "Totals", not a test
337
+ return
338
+ class_name, test_name, uuid, options = test
339
+ if (class_name, test_name, options) in self._filtered:
340
+ return
341
+ lines = _attachment_trace(lines)
342
+ message = "".join(line.lstrip() + "\n" for line in lines
343
+ if line.lstrip().startswith("Details: "))
344
+ trace = "".join(line + "\n" for line in lines)
345
+ self.test_mgr.add_fail_data_for_test(
346
+ self.run_name, class_name, test_name, options, trace, message, uuid=uuid or None)
File without changes
File without changes
@@ -0,0 +1,75 @@
1
+ import csv
2
+
3
+ from tempest_parser.const import REQUIRED_RUN, Status
4
+ from tempest_parser.manager.models import Case, Execution, Result
5
+ from tempest_parser.manager.test_manager import TestsManager
6
+
7
+
8
+ class CSVReporter:
9
+ """Writes every run as columns, tests as rows.
10
+
11
+ Header: "", "class/test name", required/added column, then per run its date
12
+ (and file name with `detailed`).
13
+ Class rows: "Class", <class name>, blanks.
14
+ Test rows: <number>, <test name + options>, R or A, then per run its result
15
+ (and the message, plus the trace for failures, with `detailed`).
16
+ """
17
+
18
+ REQUIRED = REQUIRED_RUN
19
+
20
+ def __init__(self, test_manager: TestsManager) -> None:
21
+ self.test_manager = test_manager
22
+ executions = test_manager.executions
23
+ self._required = executions.get(self.REQUIRED)
24
+ self._runs = sorted(
25
+ (execution for name, execution in executions.items() if name != self.REQUIRED),
26
+ key=lambda execution: execution.name)
27
+
28
+ @staticmethod
29
+ def _date_cell(execution: Execution) -> str:
30
+ # one date part per line keeps the columns narrow
31
+ return execution.date_label.replace('/', '\n').replace(' ', '\n')
32
+
33
+ def _header(self, detailed: bool) -> list[str]:
34
+ if self._required is not None:
35
+ header = ["", "class/test name", self._date_cell(self._required)]
36
+ else:
37
+ header = ["", "class/test name", "Required vs Added"]
38
+ for run in self._runs:
39
+ header.append(self._date_cell(run))
40
+ if detailed:
41
+ header.append(run.filename)
42
+ return header
43
+
44
+ @staticmethod
45
+ def _details(result: Result) -> str:
46
+ if result.result == Status.FAIL:
47
+ return result.message + '\n' + result.trace
48
+ if result.result == Status.SKIP:
49
+ return result.message
50
+ return ''
51
+
52
+ def _test_row(self, number: int, test: Case, detailed: bool) -> list[str | int]:
53
+ results = test.results
54
+ row: list[str | int] = [number, test.test_name + test.test_options,
55
+ results[self.REQUIRED].result if self.REQUIRED in results else Status.ADDED]
56
+ for run in self._runs:
57
+ result = results.get(run.name)
58
+ row.append(result.result if result else '')
59
+ if detailed:
60
+ row.append(self._details(result) if result else '')
61
+ return row
62
+
63
+ def generate_to_file(self, filename: str, detailed: bool = False) -> None:
64
+ header = self._header(detailed)
65
+ tests = self.test_manager.tests
66
+ with open(filename, 'w', newline='', encoding='utf-8') as target:
67
+ writer = csv.writer(target, lineterminator='\n')
68
+ writer.writerow(header)
69
+ number = 0
70
+ for class_name in sorted(tests):
71
+ writer.writerow(
72
+ ["Class", class_name] + [""] * (len(header) - 2))
73
+ for test in tests[class_name]:
74
+ number += 1
75
+ writer.writerow(self._test_row(number, test, detailed))
@@ -0,0 +1,74 @@
1
+ """Machine-readable summary of the runs, for CI pipelines (`--json-file`, `--fail-on`)."""
2
+ import json
3
+ from collections import Counter
4
+ from collections.abc import Iterable
5
+ from typing import Any
6
+
7
+ from tempest_parser.const import REQUIRED_RUN
8
+ from tempest_parser.manager.test_manager import TestsManager
9
+
10
+
11
+ def status_counts(test_manager: TestsManager) -> dict[str, Counter[str]]:
12
+ """{run name: Counter(status: tests)} for every run except the required list."""
13
+ counts: dict[str, Counter[str]] = {
14
+ name: Counter() for name in test_manager.executions if name != REQUIRED_RUN}
15
+ for tests in test_manager.tests.values():
16
+ for test in tests:
17
+ for name, result in test.results.items():
18
+ if name in counts:
19
+ counts[name][result.result] += 1
20
+ return counts
21
+
22
+
23
+ def failing_results(test_manager: TestsManager,
24
+ statuses: Iterable[str]) -> list[tuple[str, str, str, str]]:
25
+ """[(run name, class, test name, status)] of the results whose status is in `statuses`."""
26
+ statuses = set(statuses)
27
+ found = []
28
+ for class_name, tests in sorted(test_manager.tests.items()):
29
+ for test in tests:
30
+ for name, result in test.results.items():
31
+ if name != REQUIRED_RUN and result.result in statuses:
32
+ found.append((name, class_name, test.test_name, result.result))
33
+ return found
34
+
35
+
36
+ class JSONReporter:
37
+ """Per run: name, file name, date (ISO 8601, UTC), test count, counts of the main
38
+ statuses, total time in seconds and the count of every status found.
39
+
40
+ {"runs": [{"name": "run_1.log", "file": "run_1.log", "date": "2026-11-23T22:08:00+00:00",
41
+ "total": 26, "ok": 22, "fail": 2, "error": 0, "skip": 2, "time": 41.5,
42
+ "statuses": {"OK": 22, "FAIL": 2, "SKIP": 2}}]}
43
+ """
44
+
45
+ def __init__(self, test_manager: TestsManager) -> None:
46
+ self.test_manager = test_manager
47
+
48
+ def summary(self) -> dict[str, list[dict[str, Any]]]:
49
+ tm = self.test_manager
50
+ counts = status_counts(tm)
51
+ summaries = tm.summarize(list(counts))
52
+ runs = []
53
+ for execution in tm.get_sorted_executions():
54
+ if execution.name == REQUIRED_RUN:
55
+ continue
56
+ summary = summaries[execution.name]
57
+ runs.append({
58
+ "name": execution.name,
59
+ "file": execution.filename,
60
+ "date": execution.date.isoformat(timespec="seconds"),
61
+ "total": summary.total,
62
+ "ok": summary.ok,
63
+ "fail": summary.fail,
64
+ "error": summary.error,
65
+ "skip": summary.skip,
66
+ "time": round(summary.time, 3),
67
+ "statuses": dict(sorted(counts[execution.name].items())),
68
+ })
69
+ return {"runs": runs}
70
+
71
+ def generate_to_file(self, path: str) -> None:
72
+ with open(path, "w", encoding="utf-8") as target:
73
+ json.dump(self.summary(), target, indent=2, ensure_ascii=False)
74
+ target.write("\n")