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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
|
# ==================================================================================================================== #
# _____ ____ _ _ ___ ______ ____ ____ __ #
# _ __ _ _| ____| _ \ / \ / \ / _ \/ ___\ \ / /\ \ / / \/ | #
# | '_ \| | | | _| | | | |/ _ \ / _ \ | | | \___ \\ \ / / \ \ / /| |\/| | #
# | |_) | |_| | |___| |_| / ___ \ / ___ \ | |_| |___) |\ V / \ V / | | | | #
# | .__/ \__, |_____|____/_/ \_\/_/ \_(_)___/|____/ \_/ \_/ |_| |_| #
# |_| |___/ #
# ==================================================================================================================== #
# Authors: #
# Patrick Lehmann #
# #
# License: #
# ==================================================================================================================== #
# Copyright 2021-2025 Electronic Design Automation Abstraction (EDA²) #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# You may obtain a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
# #
# SPDX-License-Identifier: Apache-2.0 #
# ==================================================================================================================== #
#
"""Reader for OSVVM test report summary files in YAML format."""
from datetime import timedelta, datetime
from pathlib import Path
from typing import Optional as Nullable, Iterator, Iterable, Mapping, Any, List
from ruamel.yaml import YAML, CommentedMap, CommentedSeq
from pyTooling.Decorators import export, InheritDocString, notimplemented
from pyTooling.MetaClasses import ExtendedType
from pyTooling.Stopwatch import Stopwatch
from pyTooling.Versioning import CalendarVersion, SemanticVersion
from pyEDAA.Reports.Unittesting import UnittestException, Document, TestcaseStatus, TestsuiteStatus, TestsuiteType, TestsuiteKind
from pyEDAA.Reports.Unittesting import TestsuiteSummary as ut_TestsuiteSummary, Testsuite as ut_Testsuite
from pyEDAA.Reports.Unittesting import Testcase as ut_Testcase
@export
class OsvvmException:
pass
@export
@InheritDocString(UnittestException)
class UnittestException(UnittestException, OsvvmException):
"""@InheritDocString(UnittestException)"""
@export
@InheritDocString(ut_Testcase)
class Testcase(ut_Testcase):
"""@InheritDocString(ut_Testcase)"""
@export
@InheritDocString(ut_Testsuite)
class Testsuite(ut_Testsuite):
"""@InheritDocString(ut_Testsuite)"""
@export
class BuildInformation(metaclass=ExtendedType, slots=True):
_startTime: datetime
_finishTime: datetime
_elapsed: timedelta
_simulator: str
_simulatorVersion: SemanticVersion
_osvvmVersion: CalendarVersion
_buildErrorCode: int
_analyzeErrorCount: int
_simulateErrorCount: int
def __init__(self) -> None:
pass
@export
class Settings(metaclass=ExtendedType, slots=True):
_baseDirectory: Path
_reportsSubdirectory: Path
_simulationLogFile: Path
_simulationHtmlLogFile: Path
_requirementsSubdirectory: Path
_coverageSubdirectory: Path
_report2CssFiles: List[Path]
_report2PngFile: List[Path]
def __init__(self) -> None:
pass
@export
@InheritDocString(ut_TestsuiteSummary)
class TestsuiteSummary(ut_TestsuiteSummary):
"""@InheritDocString(ut_TestsuiteSummary)"""
_datetime: datetime
def __init__(
self,
name: str,
startTime: Nullable[datetime] = None,
setupDuration: Nullable[timedelta] = None,
testDuration: Nullable[timedelta] = None,
teardownDuration: Nullable[timedelta] = None,
totalDuration: Nullable[timedelta] = None,
status: TestsuiteStatus = TestsuiteStatus.Unknown,
warningCount: int = 0,
errorCount: int = 0,
fatalCount: int = 0,
testsuites: Nullable[Iterable[TestsuiteType]] = None,
keyValuePairs: Nullable[Mapping[str, Any]] = None,
parent: Nullable[TestsuiteType] = None
) -> None:
"""
Initializes the fields of a test summary.
:param name: Name of the test summary.
:param startTime: Time when the test summary was started.
:param setupDuration: Duration it took to set up the test summary.
:param testDuration: Duration of all tests listed in the test summary.
:param teardownDuration: Duration it took to tear down the test summary.
:param totalDuration: Total duration of the entity's execution (setup + test + teardown)
:param status: Overall status of the test summary.
:param warningCount: Count of encountered warnings incl. warnings from sub-elements.
:param errorCount: Count of encountered errors incl. errors from sub-elements.
:param fatalCount: Count of encountered fatal errors incl. fatal errors from sub-elements.
:param testsuites: List of test suites to initialize the test summary with.
:param keyValuePairs: Mapping of key-value pairs to initialize the test summary with.
:param parent: Reference to the parent test summary.
"""
super().__init__(
name,
startTime,
setupDuration,
testDuration,
teardownDuration,
totalDuration,
status,
warningCount,
errorCount,
fatalCount,
testsuites,
keyValuePairs,
parent
)
@export
class BuildSummaryDocument(TestsuiteSummary, Document):
_yamlDocument: Nullable[YAML]
def __init__(self, yamlReportFile: Path, analyzeAndConvert: bool = False) -> None:
super().__init__("Unprocessed OSVVM YAML file")
self._yamlDocument = None
Document.__init__(self, yamlReportFile, analyzeAndConvert)
def Analyze(self) -> None:
"""
Analyze the YAML file, parse the content into an YAML data structure.
.. hint::
The time spend for analysis will be made available via property :data:`AnalysisDuration`..
"""
if not self._path.exists():
raise UnittestException(f"OSVVM YAML file '{self._path}' does not exist.") \
from FileNotFoundError(f"File '{self._path}' not found.")
with Stopwatch() as sw:
try:
yamlReader = YAML()
self._yamlDocument = yamlReader.load(self._path)
except Exception as ex:
raise UnittestException(f"Couldn't open '{self._path}'.") from ex
self._analysisDuration = sw.Duration
@notimplemented
def Write(self, path: Nullable[Path] = None, overwrite: bool = False) -> None:
"""
Write the data model as XML into a file adhering to the Any JUnit dialect.
:param path: Optional path to the YAML file, if internal path shouldn't be used.
:param overwrite: If true, overwrite an existing file.
:raises UnittestException: If the file cannot be overwritten.
:raises UnittestException: If the internal YAML data structure wasn't generated.
:raises UnittestException: If the file cannot be opened or written.
"""
if path is None:
path = self._path
if not overwrite and path.exists():
raise UnittestException(f"OSVVM YAML file '{path}' can not be overwritten.") \
from FileExistsError(f"File '{path}' already exists.")
# if regenerate:
# self.Generate(overwrite=True)
if self._yamlDocument is None:
ex = UnittestException(f"Internal YAML document tree is empty and needs to be generated before write is possible.")
# ex.add_note(f"Call 'BuildSummaryDocument.Generate()' or 'BuildSummaryDocument.Write(..., regenerate=True)'.")
raise ex
# with path.open("w", encoding="utf-8") as file:
# self._yamlDocument.writexml(file, addindent="\t", encoding="utf-8", newl="\n")
@staticmethod
def _ParseSequenceFromYAML(node: CommentedMap, fieldName: str) -> Nullable[CommentedSeq]:
try:
value = node[fieldName]
except KeyError as ex:
newEx = UnittestException(f"Sequence field '{fieldName}' not found in node starting at line {node.lc.line + 1}.")
newEx.add_note(f"Available fields: {', '.join(key for key in node)}")
raise newEx from ex
if value is None:
return ()
elif not isinstance(value, CommentedSeq):
line = node._yaml_line_col.data[fieldName][0] + 1
ex = UnittestException(f"Field '{fieldName}' is not a sequence.") # TODO: from TypeError??
ex.add_note(f"Found type {value.__class__.__name__} at line {line}.")
raise ex
return value
@staticmethod
def _ParseMapFromYAML(node: CommentedMap, fieldName: str) -> Nullable[CommentedMap]:
try:
value = node[fieldName]
except KeyError as ex:
newEx = UnittestException(f"Dictionary field '{fieldName}' not found in node starting at line {node.lc.line + 1}.")
newEx.add_note(f"Available fields: {', '.join(key for key in node)}")
raise newEx from ex
if value is None:
return {}
elif not isinstance(value, CommentedMap):
line = node._yaml_line_col.data[fieldName][0] + 1
ex = UnittestException(f"Field '{fieldName}' is not a list.") # TODO: from TypeError??
ex.add_note(f"Type mismatch found for line {line}.")
raise ex
return value
@staticmethod
def _ParseStrFieldFromYAML(node: CommentedMap, fieldName: str) -> Nullable[str]:
try:
value = node[fieldName]
except KeyError as ex:
newEx = UnittestException(f"String field '{fieldName}' not found in node starting at line {node.lc.line + 1}.")
newEx.add_note(f"Available fields: {', '.join(key for key in node)}")
raise newEx from ex
if not isinstance(value, str):
raise UnittestException(f"Field '{fieldName}' is not of type str.") # TODO: from TypeError??
return value
@staticmethod
def _ParseIntFieldFromYAML(node: CommentedMap, fieldName: str) -> Nullable[int]:
try:
value = node[fieldName]
except KeyError as ex:
newEx = UnittestException(f"Integer field '{fieldName}' not found in node starting at line {node.lc.line + 1}.")
newEx.add_note(f"Available fields: {', '.join(key for key in node)}")
raise newEx from ex
if not isinstance(value, int):
raise UnittestException(f"Field '{fieldName}' is not of type int.") # TODO: from TypeError??
return value
@staticmethod
def _ParseDateFieldFromYAML(node: CommentedMap, fieldName: str) -> Nullable[datetime]:
try:
value = node[fieldName]
except KeyError as ex:
newEx = UnittestException(f"Date field '{fieldName}' not found in node starting at line {node.lc.line + 1}.")
newEx.add_note(f"Available fields: {', '.join(key for key in node)}")
raise newEx from ex
if not isinstance(value, datetime):
raise UnittestException(f"Field '{fieldName}' is not of type datetime.") # TODO: from TypeError??
return value
@staticmethod
def _ParseDurationFieldFromYAML(node: CommentedMap, fieldName: str) -> Nullable[timedelta]:
try:
value = node[fieldName]
except KeyError as ex:
newEx = UnittestException(f"Duration field '{fieldName}' not found in node starting at line {node.lc.line + 1}.")
newEx.add_note(f"Available fields: {', '.join(key for key in node)}")
raise newEx from ex
if not isinstance(value, float):
raise UnittestException(f"Field '{fieldName}' is not of type float.") # TODO: from TypeError??
return timedelta(seconds=value)
def Convert(self) -> None:
"""
Convert the parsed YAML data structure into a test entity hierarchy.
This method converts the root element.
.. hint::
The time spend for model conversion will be made available via property :data:`ModelConversionDuration`.
:raises UnittestException: If XML was not read and parsed before.
"""
if self._yamlDocument is None:
ex = UnittestException(f"OSVVM YAML file '{self._path}' needs to be read and analyzed by a YAML parser.")
ex.add_note(f"Call 'Document.Analyze()' or create document using 'Document(path, parse=True)'.")
raise ex
with Stopwatch() as sw:
self._name = self._yamlDocument["Name"]
buildInfo = self._ParseMapFromYAML(self._yamlDocument, "BuildInfo")
self._startTime = self._ParseDateFieldFromYAML(buildInfo, "StartTime")
self._totalDuration = self._ParseDurationFieldFromYAML(buildInfo, "Elapsed")
if "TestSuites" in self._yamlDocument:
for yamlTestsuite in self._ParseSequenceFromYAML(self._yamlDocument, "TestSuites"):
self._ConvertTestsuite(self, yamlTestsuite)
self.Aggregate()
self._modelConversion = sw.Duration
def _ConvertTestsuite(self, parentTestsuite: Testsuite, yamlTestsuite: CommentedMap) -> None:
testsuiteName = self._ParseStrFieldFromYAML(yamlTestsuite, "Name")
totalDuration = self._ParseDurationFieldFromYAML(yamlTestsuite, "ElapsedTime")
testsuite = Testsuite(
testsuiteName,
totalDuration=totalDuration,
parent=parentTestsuite
)
# if yamlTestsuite['TestCases'] is not None:
for yamlTestcase in self._ParseSequenceFromYAML(yamlTestsuite, 'TestCases'):
self._ConvertTestcase(testsuite, yamlTestcase)
def _ConvertTestcase(self, parentTestsuite: Testsuite, yamlTestcase: CommentedMap) -> None:
testcaseName = self._ParseStrFieldFromYAML(yamlTestcase, "TestCaseName")
totalDuration = self._ParseDurationFieldFromYAML(yamlTestcase, "ElapsedTime")
yamlStatus = self._ParseStrFieldFromYAML(yamlTestcase, "Status").lower()
yamlResults = self._ParseMapFromYAML(yamlTestcase, "Results")
assertionCount = self._ParseIntFieldFromYAML(yamlResults, "AffirmCount")
passedAssertionCount = self._ParseIntFieldFromYAML(yamlResults, "PassedCount")
totalErrors = self._ParseIntFieldFromYAML(yamlResults, "TotalErrors")
yamlAlertCount = self._ParseMapFromYAML(yamlResults, "AlertCount")
warningCount = self._ParseIntFieldFromYAML(yamlAlertCount, "Warning")
errorCount = self._ParseIntFieldFromYAML(yamlAlertCount, "Error")
fatalCount = self._ParseIntFieldFromYAML(yamlAlertCount, "Failure")
# FIXME: write a Parse classmethod in enum
if yamlStatus == "passed":
status = TestcaseStatus.Passed
elif yamlStatus == "skipped":
status = TestcaseStatus.Skipped
elif yamlStatus == "failed":
status = TestcaseStatus.Failed
else:
status = TestcaseStatus.Unknown
if totalErrors == warningCount + errorCount + fatalCount:
if warningCount > 0:
status |= TestcaseStatus.Warned
if errorCount > 0:
status |= TestcaseStatus.Errored
if fatalCount > 0:
status |= TestcaseStatus.Aborted
# else:
# status |= TestcaseStatus.Inconsistent
_ = Testcase(
testcaseName,
totalDuration=totalDuration,
assertionCount=assertionCount,
passedAssertionCount=passedAssertionCount,
warningCount=warningCount,
status=status,
errorCount=errorCount,
fatalCount=fatalCount,
parent=parentTestsuite
)
def __contains__(self, key: str) -> bool:
return key in self._testsuites
def __iter__(self) -> Iterator[Testsuite]:
return iter(self._testsuites.values())
def __getitem__(self, key: str) -> Testsuite:
return self._testsuites[key]
def __len__(self) -> int:
return self._testsuites.__len__()
|