Coverage for pyEDAA/Reports/Unittesting/JUnit/CTestJUnit.py: 89%
133 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-14 02:26 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-14 02:26 +0000
1# ==================================================================================================================== #
2# _____ ____ _ _ ____ _ #
3# _ __ _ _| ____| _ \ / \ / \ | _ \ ___ _ __ ___ _ __| |_ ___ #
4# | '_ \| | | | _| | | | |/ _ \ / _ \ | |_) / _ \ '_ \ / _ \| '__| __/ __| #
5# | |_) | |_| | |___| |_| / ___ \ / ___ \ _| _ < __/ |_) | (_) | | | |_\__ \ #
6# | .__/ \__, |_____|____/_/ \_\/_/ \_(_)_| \_\___| .__/ \___/|_| \__|___/ #
7# |_| |___/ |_| #
8# ==================================================================================================================== #
9# Authors: #
10# Patrick Lehmann #
11# #
12# License: #
13# ==================================================================================================================== #
14# Copyright 2024-2026 Electronic Design Automation Abstraction (EDA²) #
15# Copyright 2023-2023 Patrick Lehmann - Bötzingen, Germany #
16# #
17# Licensed under the Apache License, Version 2.0 (the "License"); #
18# you may not use this file except in compliance with the License. #
19# You may obtain a copy of the License at #
20# #
21# http://www.apache.org/licenses/LICENSE-2.0 #
22# #
23# Unless required by applicable law or agreed to in writing, software #
24# distributed under the License is distributed on an "AS IS" BASIS, #
25# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
26# See the License for the specific language governing permissions and #
27# limitations under the License. #
28# #
29# SPDX-License-Identifier: Apache-2.0 #
30# ==================================================================================================================== #
31#
32"""
33Reader for JUnit unit testing summary files in XML format.
34"""
35from __future__ import annotations
37from pathlib import Path
38from typing import Optional as Nullable, Tuple, TypeVar, Type, ClassVar
40from lxml.etree import ElementTree, Element, SubElement, tostring, _Element
41from pyTooling.Common import firstValue
42from pyTooling.Decorators import export, InheritDocString, DocStringMergeStrategy
43from pyTooling.Stopwatch import Stopwatch
45from pyEDAA.Reports.Unittesting import UnittestError, TestsuiteKind, TestsuiteSummary as ut_TestsuiteSummary, \
46 Testsuite as ut_Testsuite
47from pyEDAA.Reports.Unittesting.JUnit import Testcase as ju_Testcase, Testclass as ju_Testclass, \
48 Testsuite as ju_Testsuite, TestsuiteSummary as ju_TestsuiteSummary, \
49 Document as ju_Document
52TestsuiteType = TypeVar("TestsuiteType", bound="Testsuite")
53TestcaseAggregateReturnType = Tuple[int, int, int]
54TestsuiteAggregateReturnType = Tuple[int, int, int, int, int]
57@export
58@InheritDocString(ju_Testcase, DocStringMergeStrategy.BaseLast)
59class Testcase(ju_Testcase):
60 """
61 This is a derived implementation for the CTest JUnit dialect.
62 """
65@export
66@InheritDocString(ju_Testclass, DocStringMergeStrategy.BaseLast)
67class Testclass(ju_Testclass):
68 """
69 This is a derived implementation for the CTest JUnit dialect.
70 """
73@export
74@InheritDocString(ju_Testsuite, DocStringMergeStrategy.BaseLast)
75class Testsuite(ju_Testsuite):
76 """
77 This is a derived implementation for the CTest JUnit dialect.
78 """
80 @classmethod
81 def FromTestsuite(cls, testsuite: ut_Testsuite) -> Testsuite:
82 """
83 Convert a test suite of the unified test entity data model to the JUnit specific data model's test suite object
84 adhering to the CTest JUnit dialect.
86 :param testsuite: Test suite from unified data model.
87 :returns: Test suite from JUnit specific data model (CTest JUnit dialect).
88 """
89 juTestsuite = cls(
90 testsuite._name,
91 hostname=testsuite._hostname,
92 startTime=testsuite._startTime,
93 duration=testsuite._totalDuration,
94 status= testsuite._status,
95 )
97 juTestsuite._tests = testsuite._tests
98 juTestsuite._skipped = testsuite._skipped
99 juTestsuite._errored = testsuite._errored
100 juTestsuite._failed = testsuite._failed
101 juTestsuite._passed = testsuite._passed
103 for tc in testsuite.IterateTestcases():
104 ts = tc._parent
105 if ts is None: 105 ↛ 106line 105 didn't jump to line 106 because the condition on line 105 was never true
106 raise UnittestError(f"Testcase '{tc._name}' is not part of a hierarchy.")
107 elif ts is testsuite:
108 juTestsuite.AddTestcase(Testcase.FromTestcase(tc))
109 continue
111 classname = ts._name
112 ts = ts._parent
113 while ts is not None and ts._kind > TestsuiteKind.Logical:
114 classname = f"{ts._name}.{classname}"
115 ts = ts._parent
117 if classname in juTestsuite._testclasses:
118 juClass = juTestsuite._testclasses[classname]
119 else:
120 juClass = Testclass(classname, parent=juTestsuite)
122 juClass.AddTestcase(Testcase.FromTestcase(tc))
124 return juTestsuite
127@export
128@InheritDocString(ju_TestsuiteSummary, DocStringMergeStrategy.BaseLast)
129class TestsuiteSummary(ju_TestsuiteSummary):
130 """
131 This is a derived implementation for the CTest JUnit dialect.
132 """
134 @classmethod
135 def FromTestsuiteSummary(cls, testsuiteSummary: ut_TestsuiteSummary) -> TestsuiteSummary:
136 """
137 Convert a test suite summary of the unified test entity data model to the JUnit specific data model's test suite
138 summary object adhering to the CTest JUnit dialect.
140 :param testsuiteSummary: Test suite summary from unified data model.
141 :returns: Test suite summary from JUnit specific data model (CTest JUnit dialect).
142 """
143 return cls(
144 testsuiteSummary._name,
145 startTime=testsuiteSummary._startTime,
146 duration=testsuiteSummary._totalDuration,
147 status=testsuiteSummary._status,
148 testsuites=(Testsuite.FromTestsuite(testsuite) for testsuite in testsuiteSummary._testsuites.values())
149 )
152@export
153class Document(ju_Document):
154 """
155 A document reader and writer for the CTest JUnit XML file format.
157 This class reads, validates and transforms an XML file in the CTest JUnit format into a JUnit data model. It can then
158 be converted into a unified test entity data model.
160 In reverse, a JUnit data model instance with the specific CTest JUnit file format can be created from a unified test
161 entity data model. This data model can be written as XML into a file.
162 """
164 _DIALECT: ClassVar[str] = "CTest + JUnit"
165 _TESTCASE: ClassVar[Type[Testcase]] = Testcase
166 _TESTCLASS: ClassVar[Type[Testclass]] = Testclass
167 _TESTSUITE: ClassVar[Type[Testsuite]] = Testsuite
169 def Analyze(self) -> None:
170 """
171 Analyze the XML file, parse the content into an XML data structure and validate the data structure using an XML
172 schema.
174 .. hint::
176 The time spend for analysis will be made available via property :data:`AnalysisDuration`.
178 The used XML schema definition is specific to the CTest JUnit dialect.
179 """
180 xmlSchemaFile = "CTest-JUnit.xsd"
181 self._Analyze(xmlSchemaFile)
183 def Write(self, path: Nullable[Path] = None, overwrite: bool = False, regenerate: bool = False) -> None:
184 """
185 Write the data model as XML into a file adhering to the CTest dialect.
187 :param path: Optional, path to the XML file, if internal path shouldn't be used.
188 :param overwrite: Optional, if true, overwrite an existing file.
189 :param regenerate: Optional, if true, regenerate the XML structure from data model.
190 :raises UnittestError: If the file cannot be overwritten.
191 :raises UnittestError: If the internal XML data structure wasn't generated.
192 :raises UnittestError: If the file cannot be opened or written.
193 """
194 if path is None:
195 path = self._path
197 if not overwrite and path.exists():
198 raise UnittestError(f"JUnit XML file '{path}' can not be overwritten.") \
199 from FileExistsError(f"File '{path}' already exists.")
201 if regenerate: 201 ↛ 204line 201 didn't jump to line 204 because the condition on line 201 was always true
202 self.Generate(overwrite=True)
204 if self._xmlDocument is None: 204 ↛ 205line 204 didn't jump to line 205 because the condition on line 204 was never true
205 ex = UnittestError("Internal XML document tree is empty and needs to be generated before write is possible.")
206 ex.add_note("Call 'JUnitDocument.Generate()' or 'JUnitDocument.Write(..., regenerate=True)'.")
207 raise ex
209 content = tostring(self._xmlDocument, encoding="utf-8", xml_declaration=True, pretty_print=True)
210 try:
211 with path.open("wb") as file:
212 file.write(content)
213 except OSError as ex:
214 raise UnittestError(f"JUnit XML file '{path}' can not be written.") from ex
216 def Convert(self) -> None:
217 """
218 Convert the parsed and validated XML data structure into a JUnit test entity hierarchy.
220 This method converts the root element.
222 .. hint::
224 The time spend for model conversion will be made available via property :data:`ModelConversionDuration`.
226 :raises UnittestError: If XML was not read and parsed before.
227 """
228 if self._xmlDocument is None: 228 ↛ 229line 228 didn't jump to line 229 because the condition on line 228 was never true
229 ex = UnittestError(f"JUnit XML file '{self._path}' needs to be read and analyzed by an XML parser.")
230 ex.add_note("Call 'JUnitDocument.Analyze()' or create the document using 'JUnitDocument(path, parse=True)'.")
231 raise ex
233 with Stopwatch() as sw:
234 rootElement: _Element = self._xmlDocument.getroot()
236 self._name = self._ConvertName(rootElement, optional=True)
237 self._startTime =self._ConvertTimestamp(rootElement, optional=True)
238 self._duration = self._ConvertTime(rootElement, optional=True)
240 # tests = rootElement.getAttribute("tests")
241 # skipped = rootElement.getAttribute("skipped")
242 # errors = rootElement.getAttribute("errors")
243 # failures = rootElement.getAttribute("failures")
244 # assertions = rootElement.getAttribute("assertions")
246 hostname = self._ConvertHostname(rootElement, optional=True, default=None)
247 ts = Testsuite(self._name, hostname, startTime=self._startTime, duration=self._duration, parent=self)
248 self._ConvertTestsuiteChildren(rootElement, ts)
250 self.Aggregate()
252 self._modelConversion = sw.Duration
254 def _ConvertTestsuite(self, parent: TestsuiteSummary, testsuitesNode: _Element) -> None:
255 """
256 Convert the XML data structure of a ``<testsuite>`` to a test suite.
258 This method uses private helper methods provided by the base-class.
260 :param parent: The test suite summary as a parent element in the test entity hierarchy.
261 :param testsuitesNode: The current XML element node representing a test suite.
262 """
263 newTestsuite = Testsuite(
264 self._ConvertName(testsuitesNode, optional=False),
265 self._ConvertHostname(testsuitesNode, optional=False),
266 self._ConvertTimestamp(testsuitesNode, optional=False),
267 self._ConvertTime(testsuitesNode, optional=False),
268 parent=parent
269 )
271 self._ConvertTestsuiteChildren(testsuitesNode, newTestsuite)
273 def Generate(self, overwrite: bool = False) -> None:
274 """
275 Generate the internal XML data structure from test suites and test cases.
277 This method generates the XML root element (``<testsuite>``) and recursively calls other generated methods.
279 :param overwrite: Optional, overwrite the internal XML data structure.
280 :raises UnittestError: If overwrite is false and the internal XML data structure is not empty.
281 """
282 if not overwrite and self._xmlDocument is not None: 282 ↛ 283line 282 didn't jump to line 283 because the condition on line 282 was never true
283 raise UnittestError("Internal XML document is populated with data.")
285 if self.TestsuiteCount != 1:
286 ex = UnittestError("The CTest JUnit format requires exactly one test suite.")
287 ex.add_note(f"Found {self.TestsuiteCount} test suites.")
288 raise ex
290 testsuite = firstValue(self._testsuites)
292 rootElement = Element("testsuite")
293 rootElement.attrib["name"] = self._name
294 if self._startTime is None:
295 raise UnittestError(
296 f"The {self._DIALECT} format requires a timestamp on <testsuite>, but the report has none."
297 )
298 rootElement.attrib["timestamp"] = f"{self._startTime.isoformat()}"
299 if self._duration is not None:
300 rootElement.attrib["time"] = f"{self._duration.total_seconds():.6f}"
301 rootElement.attrib["tests"] = str(self._tests)
302 rootElement.attrib["failures"] = str(self._failed)
303 # rootElement.attrib["errors"] = str(self._errored)
304 rootElement.attrib["skipped"] = str(self._skipped)
305 rootElement.attrib["disabled"] = "0" # TODO: find a value
306 # if self._assertionCount is not None:
307 # rootElement.attrib["assertions"] = f"{self._assertionCount}"
308 # CTest-JUnit.xsd requires 'hostname', so an unrecorded host is named as unknown.
309 rootElement.attrib["hostname"] = testsuite._hostname if testsuite._hostname is not None else "unknownhost"
311 self._xmlDocument = ElementTree(rootElement)
313 for tc in testsuite._testcases.values():
314 self._GenerateTestcase(tc, rootElement)
316 for testclass in testsuite._testclasses.values():
317 for tc in testclass._testcases.values():
318 self._GenerateTestcase(tc, rootElement)
320 def _GenerateTestcase(self, testcase: Testcase, parentElement: _Element) -> None:
321 """
322 Generate the internal XML data structure for a test case.
324 This method generates the XML element (``<testcase>``) and recursively calls other generated methods.
326 :param testcase: The test case to convert to an XML data structures.
327 :param parentElement: The parent XML data structure element, this data structure part will be added to.
328 """
329 testcaseElement = SubElement(parentElement, "testcase")
330 if testcase.Classname is not None: 330 ↛ 332line 330 didn't jump to line 332 because the condition on line 330 was always true
331 testcaseElement.attrib["classname"] = testcase.Classname
332 testcaseElement.attrib["name"] = testcase._name
333 if testcase._duration is not None: 333 ↛ 335line 333 didn't jump to line 335 because the condition on line 333 was always true
334 testcaseElement.attrib["time"] = f"{testcase._duration.total_seconds():.6f}"
335 if testcase._assertionCount is not None: 335 ↛ 336line 335 didn't jump to line 336 because the condition on line 335 was never true
336 testcaseElement.attrib["assertions"] = f"{testcase._assertionCount}"
338 testcaseElement.attrib["status"] = "run" # TODO: find a value
340 self._GenerateTestcaseChildren(testcase, testcaseElement)