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.
File without changes
@@ -0,0 +1,65 @@
1
+ """Statuses, report columns and input formats, each defined once."""
2
+ import os
3
+ from enum import Enum, StrEnum
4
+
5
+
6
+ class Status(StrEnum):
7
+ """Result of one test in one run, as stored and shown in the reports.
8
+
9
+ Results are kept as plain strings, so values read from files that aren't listed here
10
+ still work; these are the ones the importers produce and the reports look for.
11
+ """
12
+ OK = "OK"
13
+ FAIL = "FAIL"
14
+ ERROR = "ERROR"
15
+ SKIP = "SKIP"
16
+ X_FAIL = "X_FAIL" # expected failure
17
+ X_OK = "X_OK" # unexpected success
18
+ REQUIRED = "R" # listed in the baseline test list (the "required" run)
19
+ ADDED = "A" # not in the baseline test list (CSV reports)
20
+
21
+
22
+ class Column(Enum):
23
+ """Summary columns of the HTML reports; the value is the label."""
24
+ PASS = "Pass"
25
+ FAIL = "Fail"
26
+ ERROR = "Error"
27
+ NA = "NA"
28
+ SKIP = "Skip"
29
+ ADDED = "Added"
30
+
31
+ @property
32
+ def css(self) -> str:
33
+ return self.value.lower()
34
+
35
+
36
+ class InputFormat(StrEnum):
37
+ """Input formats; the value is the `-f` option value."""
38
+ SUBUNIT = "subunit"
39
+ CSV = "csv"
40
+ RALLY_JSON = "json"
41
+ XML_TEMPEST = "t_xml"
42
+ XML_RAW = "r_xml"
43
+ LOG = "log"
44
+
45
+ @property
46
+ def label(self) -> str:
47
+ """File extension without the dot, as shown in messages."""
48
+ return "xml" if self in (InputFormat.XML_TEMPEST, InputFormat.XML_RAW) else self.value
49
+
50
+ @property
51
+ def extension(self) -> str:
52
+ return "." + self.label
53
+
54
+ @classmethod
55
+ def from_filename(cls, filename: str) -> "InputFormat | None":
56
+ """Format for a file name by its extension (`.xml` is tempest XML), or None."""
57
+ extension = os.path.splitext(filename)[1]
58
+ for fmt in (cls.SUBUNIT, cls.CSV, cls.RALLY_JSON, cls.XML_TEMPEST, cls.LOG):
59
+ if fmt.extension == extension:
60
+ return fmt
61
+ return None
62
+
63
+
64
+ # name of the run that holds the baseline test list (-i)
65
+ REQUIRED_RUN = "required"
@@ -0,0 +1,6 @@
1
+ [ParserConfig]
2
+ # link where all tests listed to compare trend to
3
+ # should be standard tempest output
4
+ default_test_list=res/all_tests_tag_18.list
5
+ # Add details column by default to trending report
6
+ default_detailed=false
File without changes
@@ -0,0 +1,600 @@
1
+ import csv
2
+ import json
3
+ import logging
4
+ import re
5
+ from collections.abc import Iterable
6
+ from datetime import UTC, datetime
7
+ from typing import IO, Any
8
+ from xml.etree.ElementTree import Element, parse
9
+
10
+ from subunit import make_stream_binary
11
+ from subunit.filters import run_tests_from_stream
12
+ from subunit.test_results import TestByTestResult
13
+ from testtools import StreamToExtendedDecorator
14
+
15
+ from tempest_parser.const import REQUIRED_RUN, Status
16
+ from tempest_parser.manager.models import file_date, parse_seconds
17
+ from tempest_parser.manager.test_manager import TestsManager
18
+
19
+ log = logging.getLogger(__name__)
20
+
21
+ CSV_OWN = 1
22
+ CSV_XUNIT = 2
23
+
24
+
25
+ # C0 and C1 control characters, DEL included
26
+ _CONTROL_CHARS = ''.join(map(chr, [*range(0, 32), *range(127, 160)]))
27
+ _CONTROL_CHARS_RE = re.compile(f'[{re.escape(_CONTROL_CHARS)}]')
28
+
29
+
30
+ def remove_control_chars(s: str) -> str:
31
+ return _CONTROL_CHARS_RE.sub('', s)
32
+
33
+
34
+ def k8s_slow_extract(_reason: str) -> tuple[str, str]:
35
+ """(message, trace) of a k8s failure: the Go error strings and "not to have occurred"
36
+ lines as the message, or the whole text as the trace when there are none."""
37
+ _tmp: list[str] = []
38
+ _m = ""
39
+ _t = ""
40
+ _lines = _reason.splitlines()
41
+ for idx in range(len(_lines)-1):
42
+ _line = _lines[idx].strip()
43
+ _next_line = _lines[idx+1].strip()
44
+ if _line.startswith("<*errors.errorString") and \
45
+ _next_line.startswith("s: \""):
46
+ raw = _next_line.split('"')[1].encode('ascii', 'ignore')
47
+ if raw.count(b"\\x00") > 1:
48
+ raw = raw.replace(b"\\x00", b"")
49
+ _tmp.append(remove_control_chars(raw.decode('utf-8')))
50
+ elif _next_line.startswith("not to have occurred"):
51
+ _tmp.append(_line.encode('ascii', 'ignore').decode('ascii'))
52
+ if len(_tmp) > 0:
53
+ _m = "\n".join(_tmp)
54
+ else:
55
+ _t = _reason
56
+ return _m, _t
57
+
58
+
59
+ class ImporterBase:
60
+ def __init__(
61
+ self,
62
+ test_manager: TestsManager,
63
+ source: IO[Any],
64
+ use_raw_names: bool = False,
65
+ status_filters: Iterable[str] | None = None,
66
+ force_single_execution: str | None = None,
67
+ run_name: str | None = None,
68
+ run_date: datetime | None = None,
69
+ ) -> None:
70
+ self.source = source
71
+ self.tm = test_manager
72
+ self.use_raw_names = use_raw_names
73
+ self.forced_execution_name = force_single_execution
74
+ self.status_filters = list(status_filters or [])
75
+ # --run-name / --run-date: replace the name and date taken from the file
76
+ self.run_name = run_name
77
+ self.run_date = run_date
78
+
79
+ def execution_name(self, default: str) -> str:
80
+ return self.run_name or default
81
+
82
+ def execution_date(self) -> datetime:
83
+ return self.run_date or file_date(self.source)
84
+
85
+ def add_execution(self, name: str, date: datetime) -> None:
86
+ self.tm.add_execution(name, date)
87
+
88
+
89
+ # Example of pytest4 xml structure
90
+ """<?xml version="1.0" encoding="UTF-8"?>
91
+ <testsuites disabled="" errors="" failures="" name="" tests="" time="">
92
+ <testsuite disabled="" errors="" failures="" hostname="" id=""
93
+ name="" package="" skipped="" tests="" time="" timestamp="">
94
+ <properties>
95
+ <property name="" value=""/>
96
+ </properties>
97
+ <testcase assertions="" classname="" name="" status="" time="">
98
+ <skipped/>
99
+ <error message="" type=""/>
100
+ <failure message="" type=""/>
101
+ <system-out/>
102
+ <system-err/>
103
+ </testcase>
104
+ <system-out/>
105
+ <system-err/>
106
+ </testsuite>
107
+ </testsuites>
108
+ """
109
+
110
+
111
+ _error_status_map = {
112
+ 'skipped': Status.SKIP,
113
+ 'failure': Status.FAIL,
114
+ 'error': Status.ERROR,
115
+ 'system-err': Status.ERROR
116
+ }
117
+
118
+
119
+ # --xml-time-unit: divisor from the file's time attributes to seconds
120
+ XML_TIME_UNITS = {"s": 1.0, "ms": 1000.0}
121
+
122
+
123
+ class XMLImporter(ImporterBase):
124
+ # time attributes are seconds in jUnit XML, but some tools write whole milliseconds
125
+ time_scale = 1.0
126
+
127
+ def __init__(self, test_manager: TestsManager, source: IO[Any],
128
+ time_unit: str | None = None, **kwargs: Any) -> None:
129
+ """`time_unit` "s" or "ms" sets the unit of the time attributes; None guesses it
130
+ from the file (see _detect_time_scale)."""
131
+ super().__init__(test_manager, source, **kwargs)
132
+ if time_unit is not None and time_unit not in XML_TIME_UNITS:
133
+ raise ValueError(f"Unknown XML time unit: {time_unit!r}")
134
+ self.time_unit = time_unit
135
+
136
+ @staticmethod
137
+ def _detect_time_scale(root: Element) -> float:
138
+ """1.0 (seconds) when any testcase time has a decimal point, else 1000.0: a file
139
+ of whole numbers only is read as milliseconds."""
140
+ times = [tc.get('time', '') for tc in root.iter('testcase')]
141
+ if any('.' in t for t in times) or not any(t.strip() for t in times):
142
+ return 1.0
143
+ return 1000.0
144
+
145
+ def _parse_duration(self, duration: str) -> float | None:
146
+ seconds = parse_seconds(duration)
147
+ return None if seconds is None else seconds / self.time_scale
148
+
149
+ @staticmethod
150
+ def _parse_status(status: list[Element]) -> tuple[str, str, str]:
151
+ # XML has one child node for status and text as a reason
152
+ if not len(status):
153
+ return Status.OK, "Test passed", ""
154
+ else:
155
+ _status = ""
156
+ _reason = ""
157
+ _sysout = ""
158
+ _idx = 0
159
+ # cut system-out
160
+ while len(status) > 0 and _idx < len(status):
161
+ if status[_idx].tag == 'system-out':
162
+ _status = Status.OK
163
+ _sysout = f"{status[_idx].tag}:\n{status[_idx].text}"
164
+ _ = status.pop(_idx)
165
+ else:
166
+ _idx += 1
167
+
168
+ # iterate others
169
+ while len(status) > 0:
170
+ # last encountered node will be the status
171
+ _s = status.pop()
172
+ _status = _error_status_map[_s.tag]
173
+ _reason = f"{_s.tag}:\n{_s.text}\n{_reason}"
174
+ return _status, _reason, _sysout
175
+
176
+ def _is_k8s_error(self, reason: str) -> bool:
177
+ _e1 = reason.count('errors.errorString')
178
+ _e2 = reason.count('errors.StatusError')
179
+ _k8s = reason.count('k8s.io')
180
+ _m = re.findall(
181
+ r"^.{0,3}\s+\d{1,2}\s\d{1,2}:\d{1,2}:\d{1,2}\.\d{0,3}:.*$",
182
+ reason,
183
+ re.MULTILINE
184
+ )
185
+ return bool(_e1 or _e2 or _k8s or _m)
186
+
187
+ def _detect_pytest_errors(self, reason: str) -> list[str]:
188
+ _lines = re.findall(r"^[E]\s+.*$", reason, re.MULTILINE)
189
+ return _lines if len(_lines) > 0 else []
190
+
191
+ def _parse_pytest_error(self, lines: list[str]) -> tuple[str, str]:
192
+ # Extract message
193
+ _msg = ""
194
+ _trace = ""
195
+ for line in lines:
196
+ line = line[1:].strip()
197
+ # Save all message in the traceback
198
+ # detect message
199
+ m = re.search(r"^[a-z,A-Z]+\:\s.*$", line, re.MULTILINE)
200
+ if m:
201
+ _msg = m.group(0)
202
+ else:
203
+ _trace += line + '\n'
204
+ return _msg, _trace
205
+
206
+ def parse(self) -> None:
207
+ tree = parse(self.source)
208
+ root = tree.getroot()
209
+
210
+ _execution_date = self.execution_date()
211
+ self.time_scale = (self._detect_time_scale(root) if self.time_unit is None
212
+ else XML_TIME_UNITS[self.time_unit])
213
+ _all_testsuites = []
214
+ # We should be ready for multiple test suites in one xml
215
+ if root.tag == 'testsuite':
216
+ _all_testsuites.append(root)
217
+ else:
218
+ _all_testsuites += root.findall('testsuite')
219
+
220
+ for _testsuite in _all_testsuites:
221
+
222
+ # _execution_name = _testsuite.attrib['id']
223
+ _execution_name = self.execution_name(
224
+ self.forced_execution_name or self.source.name)
225
+
226
+ # iterate through tests
227
+ for _test_node in _testsuite.findall('testcase'):
228
+ _class_name = _test_node.attrib['classname']
229
+ # remove any '%' symbols and following number
230
+ _symbol_index = _class_name.find('%')
231
+ if _symbol_index > 0:
232
+ _class_name = _class_name[:_symbol_index] + \
233
+ _class_name[_symbol_index + 2:]
234
+
235
+ # get all attributes from xml
236
+ # _uuid = _test_node.attrib['id']
237
+ _test_name = _test_node.attrib['name']
238
+ if self.use_raw_names:
239
+ _options = ''
240
+ _uuid = ''
241
+ _tags: list[str] = []
242
+ else:
243
+ _, _test_name, _uuid, _options, _tags = \
244
+ self.tm.split_test_name(
245
+ _class_name + "." + _test_name
246
+ )
247
+ _duration = self._parse_duration(_test_node.attrib.get('time', '0'))
248
+
249
+ _status, _reason, _sysout = self._parse_status(
250
+ list(_test_node)
251
+ )
252
+ # _options = ''
253
+ _message = ""
254
+ _trace = ""
255
+ if _status == Status.SKIP:
256
+ # no trace present
257
+ _message = _reason if _reason else ""
258
+ elif _status == Status.FAIL:
259
+ # Check if there is a inner Traceback present
260
+ # and prior to save the message, try to detect error type
261
+ _pytest_lines = self._detect_pytest_errors(_reason)
262
+ if _reason.count('Traceback') > 1:
263
+ # There is multiple tracebacks present
264
+ # correct one has line after Trace as 'File'
265
+ _tmp = ""
266
+ _lines = _reason.splitlines()
267
+ for idx in range(len(_lines)-1):
268
+ _line = _lines[idx].strip()
269
+ _next_line = _lines[idx+1].strip()
270
+ if _line.startswith("Traceback") and \
271
+ (_next_line.startswith('File') or \
272
+ _next_line.find('Traceback (') >= 0):
273
+ _tmp = "\n".join(_lines[idx:])
274
+ break
275
+ _trace = _tmp
276
+ elif self._is_k8s_error(_reason):
277
+ # This is a k8s-conformance error
278
+ # Try to extract with regex
279
+
280
+ # This is not good, error messages can be multilined
281
+ # _errs = re.findall(
282
+ # r"^.{0,3}\s+\d{1,2}\s\d{1,2}:\d{1,2}:\d{1,2}\.\d{0,3}:.*$",
283
+ # _reason,
284
+ # re.MULTILINE
285
+ # )
286
+
287
+ # All between "<digit>\n" and "\n/go"
288
+ _errs = re.findall(
289
+ r"(?s)(?<=\d\n)(.*?)(?=\n\/go)",
290
+ _reason,
291
+ re.MULTILINE
292
+ )
293
+ if not _errs:
294
+ # Parse the error message line by line
295
+ _message, _trace = k8s_slow_extract(_reason)
296
+ else:
297
+ _message = "\n".join(_errs)
298
+ elif _pytest_lines:
299
+ # This is a pytest error
300
+ _message, _trace = self._parse_pytest_error(
301
+ _pytest_lines
302
+ )
303
+ else:
304
+ _trace = _reason
305
+
306
+ if _status in self.status_filters:
307
+ continue
308
+
309
+ # add this result to list
310
+ self.tm.add_result_for_test(
311
+ _execution_name,
312
+ _class_name,
313
+ _test_name,
314
+ _uuid,
315
+ _options,
316
+ _status,
317
+ _duration,
318
+ message=_message,
319
+ trace=_trace,
320
+ tags=_tags
321
+ )
322
+
323
+ self.add_execution(_execution_name, _execution_date)
324
+
325
+
326
+ # Rally and xunit CSV statuses
327
+ _rally_status_map = {
328
+ 'success': Status.OK,
329
+ 'fail': Status.FAIL,
330
+ 'skip': Status.SKIP,
331
+ 'xfail': Status.X_FAIL,
332
+ 'usuccess': Status.X_OK
333
+ }
334
+
335
+
336
+ class JSONImporter(ImporterBase):
337
+ @staticmethod
338
+ def _parse_status(status: str) -> str:
339
+ return _rally_status_map[status]
340
+
341
+ def parse(self) -> None:
342
+ data = json.load(self.source)
343
+
344
+ # Use filename as name for the execution
345
+ _execution_name = self.execution_name(self.source.name)
346
+ _execution_date = self.execution_date()
347
+
348
+ verification = next(iter(data['verifications']))
349
+
350
+ # iterate through test cases and add up results
351
+ for _test_name, _test_value in data['tests'].items():
352
+ _class_name, _test_name, _uuid, _options, _tags = \
353
+ self.tm.split_test_name(_test_name)
354
+ _test_value_results = _test_value['by_verification'][verification]
355
+ _status = self._parse_status(_test_value_results['status'])
356
+ _duration = parse_seconds(_test_value_results['duration'])
357
+ _message = _test_value_results.get('details', '')
358
+ _trace = _test_value_results.get('traceback', '')
359
+ if _status in self.status_filters:
360
+ continue
361
+
362
+ self.tm.add_result_for_test(
363
+ _execution_name,
364
+ _class_name,
365
+ _test_name,
366
+ _uuid,
367
+ _options,
368
+ _status,
369
+ _duration,
370
+ message=_message,
371
+ trace=_trace,
372
+ tags=_tags
373
+ )
374
+
375
+ self.add_execution(_execution_name, _execution_date)
376
+
377
+
378
+ class CSVImporter(ImporterBase):
379
+ subtype: int | None = None
380
+
381
+ def __init__(self, test_manager: TestsManager, source: IO[Any], **kwargs: Any) -> None:
382
+ super().__init__(test_manager, source, **kwargs)
383
+
384
+ # read all rows, then detect file sub-type
385
+ # by the first row that starts with 'Class' or a tempest test name
386
+ self.rows = [row for row in csv.reader(self.source, delimiter=',')
387
+ if row]
388
+
389
+ for row in self.rows:
390
+ if row[0] == 'Class':
391
+ self.subtype = CSV_OWN
392
+ break
393
+ if row[0].startswith("tempest."):
394
+ self.subtype = CSV_XUNIT
395
+ break
396
+
397
+ @staticmethod
398
+ def _parse_status(status: str) -> str:
399
+ return _rally_status_map[status]
400
+
401
+ def parse(self) -> None:
402
+ if self.subtype == CSV_OWN:
403
+ self.parse_own_csv()
404
+ elif self.subtype == CSV_XUNIT:
405
+ self.parse_xunit_csv()
406
+
407
+ @staticmethod
408
+ def _header_date(cell: str) -> datetime | None:
409
+ """The run date of a CSV header cell ("dd\\nmm\\nYYYY\\nHH:MM\\nGMT"), or None."""
410
+ try:
411
+ date = datetime.strptime(" ".join(cell.split()), "%d %m %Y %H:%M GMT")
412
+ except ValueError:
413
+ return None
414
+ return date.replace(tzinfo=UTC)
415
+
416
+ def _own_csv_runs(self, header: list[str],
417
+ row: list[str]) -> list[tuple[str, datetime, int, int | None]]:
418
+ """[(name, date, column, details column or None)] for the run columns of an own CSV
419
+ export, worked out from the header and the first test row."""
420
+ # old exports without the required/added column: <number>,<test>,<status>,<message>
421
+ first = 3 if row[2] in (Status.REQUIRED, Status.ADDED, "") else 2
422
+ count = len(row) - first
423
+ cells = header[len(header) - count:] if count else []
424
+ # -d adds a file name column after each run's date column
425
+ detailed = count >= 2 and count % 2 == 0 and self._header_date(cells[1]) is None
426
+ step = 2 if detailed else 1
427
+ base = self.execution_name(self.source.name)
428
+ names: dict[str, int] = {}
429
+ runs = []
430
+ for number, index in enumerate(range(0, count, step), start=1):
431
+ date = self.run_date or self._header_date(cells[index]) or self.execution_date()
432
+ if count // step == 1:
433
+ name = base
434
+ elif detailed and cells[index + 1]:
435
+ name = cells[index + 1]
436
+ else:
437
+ name = f"{base} #{number}"
438
+ # two runs from files with the same name stay apart
439
+ names[name] = names.get(name, 0) + 1
440
+ if names[name] > 1:
441
+ name = f"{name} #{names[name]}"
442
+ runs.append((name, date, first + index, first + index + 1 if detailed else None))
443
+ return runs
444
+
445
+ def parse_own_csv(self) -> None:
446
+ """Every run of a CSV written by the CSV report, with the required list when the
447
+ export had one (its date is in the header's third cell)."""
448
+ header = self.rows[0]
449
+ runs = None
450
+ required_date = self._header_date(header[2]) if len(header) > 2 else None
451
+ _class_name = ''
452
+ for row in self.rows[1:]:
453
+ if row[0].lower() == 'class':
454
+ _class_name = row[1]
455
+ continue
456
+ if not row[0].isdigit():
457
+ raise ValueError(
458
+ "Invalid CSV structure. Please, follow format:\n"
459
+ "\tClass,<class name>,,\n"
460
+ "\t<number>,<test_name>,<R or A>,<status>,<message>")
461
+ if runs is None:
462
+ runs = self._own_csv_runs(header, row)
463
+ # options were written after the name: test_name(options)
464
+ options_match = re.fullmatch(r"(test_\w*)(\(.*\))", row[1])
465
+ _test_name, _options = options_match.groups() if options_match else (row[1], '')
466
+ if required_date is not None and row[2] == Status.REQUIRED:
467
+ self.tm.add_result_for_test(
468
+ REQUIRED_RUN, _class_name, _test_name, '', _options, Status.REQUIRED, 0.0)
469
+ for name, _date, column, details in runs:
470
+ _status = row[column] if column < len(row) else ''
471
+ if not _status or _status in self.status_filters:
472
+ continue
473
+ _message = row[details] if details is not None and details < len(row) else ''
474
+ self.tm.add_result_for_test(
475
+ name, _class_name, _test_name, '', _options, _status, None, message=_message)
476
+
477
+ if required_date is not None:
478
+ self.add_execution(REQUIRED_RUN, required_date)
479
+ for name, date, _column, _details in runs or []:
480
+ self.add_execution(name, date)
481
+
482
+ def parse_xunit_csv(self) -> None:
483
+ _execution_name = self.execution_name(self.source.name)
484
+ _execution_date = self.execution_date()
485
+
486
+ for row in self.rows:
487
+ # parse the data, skip the header and other non-test rows
488
+ if not row[0].startswith("tempest."):
489
+ continue
490
+ _splitted_test_name = row[0].rsplit('.', 1)
491
+ _class_name = _splitted_test_name[0]
492
+ _test_name = _splitted_test_name[1]
493
+ _status = self._parse_status(row[1])
494
+ _message = row[2]
495
+ if _status in self.status_filters:
496
+ continue
497
+
498
+ self.tm.add_result_for_test(
499
+ _execution_name,
500
+ _class_name,
501
+ _test_name,
502
+ '',
503
+ '',
504
+ _status,
505
+ None,
506
+ message=_message,
507
+ test_name_bare=True
508
+ )
509
+
510
+ self.add_execution(_execution_name, _execution_date)
511
+
512
+
513
+ # subunit has no type information, so its result class is Any to mypy
514
+ class TParserResult(TestByTestResult): # type: ignore[misc]
515
+ @staticmethod
516
+ def _parse_status(status: str) -> str:
517
+ return {
518
+ 'success': Status.OK,
519
+ 'failure': Status.FAIL,
520
+ 'error': Status.ERROR,
521
+ 'skip': Status.SKIP,
522
+ 'xfail': Status.X_FAIL,
523
+ 'uxsuccess': Status.X_OK
524
+ }[status]
525
+
526
+ def __init__(self, name: str, tm: TestsManager,
527
+ status_filters: Iterable[str] | None = None) -> None:
528
+ super().__init__(self._on_test)
529
+ self._execution_name = name
530
+ self.tm = tm
531
+ self.status_filters = list(status_filters or [])
532
+ self.counter = 0
533
+
534
+ def _on_test(self, test: Any, status: str, start_time: datetime | None,
535
+ stop_time: datetime | None, tags: Iterable[str] | None,
536
+ details: dict[str, Any]) -> None:
537
+ _test_name = "none"
538
+ _uuid = ""
539
+ _test_options = ""
540
+ _id = test.id()
541
+ if _id.startswith("setUpClass"):
542
+ _class_name, _, _, _, _ = self.tm.split_test_name(_id)
543
+ else:
544
+ _class_name, _test_name, _uuid, _test_options, _tags = \
545
+ self.tm.split_test_name(_id)
546
+
547
+ _status = self._parse_status(status)
548
+
549
+ _message = ''
550
+ _tb = ''
551
+
552
+ if _status in self.status_filters:
553
+ return
554
+
555
+ if _status in (Status.FAIL, Status.ERROR) and 'traceback' in details:
556
+ _tb = details['traceback'].as_text()
557
+ elif _status == Status.SKIP and 'reason' in details:
558
+ _message = details['reason'].as_text()
559
+
560
+ _time = None
561
+ if start_time is not None and stop_time is not None:
562
+ _time = (stop_time - start_time).total_seconds()
563
+
564
+ self.tm.add_result_for_test(
565
+ self._execution_name,
566
+ _class_name,
567
+ _test_name,
568
+ _uuid,
569
+ _test_options,
570
+ _status,
571
+ _time,
572
+ tags=tags,
573
+ message=_message,
574
+ trace=_tb
575
+ )
576
+
577
+ self.counter += 1
578
+
579
+
580
+ class SubunitImporter(ImporterBase):
581
+
582
+ def __init__(self, test_manager: TestsManager, source: IO[Any], **kwargs: Any) -> None:
583
+ super().__init__(test_manager, source, **kwargs)
584
+ self.source = make_stream_binary(source)
585
+
586
+ def parse(self) -> None:
587
+ _execution_date = self.execution_date()
588
+ _execution_name = self.execution_name(getattr(self.source, "name", "<stdin>"))
589
+
590
+ _result = TParserResult(
591
+ _execution_name, self.tm, status_filters=self.status_filters)
592
+ run_tests_from_stream(
593
+ self.source,
594
+ StreamToExtendedDecorator(_result),
595
+ protocol_version=2,
596
+ passthrough_subunit=False
597
+ )
598
+ log.debug("%s: %d tests", _execution_name, _result.counter)
599
+
600
+ self.add_execution(_execution_name, _execution_date)