# ==================================================================================================================== #
# _____ ____ _ _ ___ ______ ____ ____ __ #
# _ __ _ _| ____| _ \ / \ / \ / _ \/ ___\ \ / /\ \ / / \/ | #
# | '_ \| | | | _| | | | |/ _ \ / _ \ | | | \___ \\ \ / / \ \ / /| |\/| | #
# | |_) | |_| | |___| |_| / ___ \ / ___ \ | |_| |___) |\ 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
[docs]
@export
class OsvvmException:
pass
[docs]
@export
@InheritDocString(UnittestException)
class UnittestException(UnittestException, OsvvmException):
"""@InheritDocString(UnittestException)"""
[docs]
@export
@InheritDocString(ut_Testcase)
class Testcase(ut_Testcase):
"""@InheritDocString(ut_Testcase)"""
[docs]
@export
@InheritDocString(ut_Testsuite)
class Testsuite(ut_Testsuite):
"""@InheritDocString(ut_Testsuite)"""
[docs]
@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]
[docs]
def __init__(self) -> None:
pass
[docs]
@export
@InheritDocString(ut_TestsuiteSummary)
class TestsuiteSummary(ut_TestsuiteSummary):
"""@InheritDocString(ut_TestsuiteSummary)"""
_datetime: datetime
[docs]
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
)
[docs]
@export
class BuildSummaryDocument(TestsuiteSummary, Document):
_yamlDocument: Nullable[YAML]
[docs]
def __init__(self, yamlReportFile: Path, analyzeAndConvert: bool = False) -> None:
super().__init__("Unprocessed OSVVM YAML file")
self._yamlDocument = None
Document.__init__(self, yamlReportFile, analyzeAndConvert)
[docs]
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)
[docs]
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
)
[docs]
def __contains__(self, key: str) -> bool:
return key in self._testsuites
[docs]
def __iter__(self) -> Iterator[Testsuite]:
return iter(self._testsuites.values())
[docs]
def __getitem__(self, key: str) -> Testsuite:
return self._testsuites[key]
[docs]
def __len__(self) -> int:
return self._testsuites.__len__()