Coverage for pyEDAA/Reports/Unittesting/JUnit/GoogleTestJUnit.py: 85%
163 statements
« prev ^ index » next coverage.py v7.16.0, created at 2026-08-29 03:43 +0000
« prev ^ index » next coverage.py v7.16.0, created at 2026-08-29 03:43 +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 pathlib import Path
36from time import perf_counter_ns
37from typing import Optional as Nullable, Generator, Tuple, Union, TypeVar, Type, ClassVar
39from lxml.etree import ElementTree, Element, SubElement, tostring, _Element
40from pyTooling.Decorators import export, InheritDocString
42from pyEDAA.Reports.Unittesting import UnittestException, TestsuiteKind
43from pyEDAA.Reports.Unittesting import TestcaseStatus, TestsuiteStatus, IterationScheme
44from pyEDAA.Reports.Unittesting import TestsuiteSummary as ut_TestsuiteSummary, Testsuite as ut_Testsuite
45from pyEDAA.Reports.Unittesting.JUnit import Testcase as ju_Testcase, Testclass as ju_Testclass, Testsuite as ju_Testsuite
46from pyEDAA.Reports.Unittesting.JUnit import TestsuiteSummary as ju_TestsuiteSummary, Document as ju_Document
49TestsuiteType = TypeVar("TestsuiteType", bound="Testsuite")
50TestcaseAggregateReturnType = Tuple[int, int, int]
51TestsuiteAggregateReturnType = Tuple[int, int, int, int, int]
54@export
55@InheritDocString(ju_Testcase, merge=True)
56class Testcase(ju_Testcase):
57 """
58 This is a derived implementation for the GoogleTest JUnit dialect.
59 """
62@export
63@InheritDocString(ju_Testclass, merge=True)
64class Testclass(ju_Testclass):
65 """
66 This is a derived implementation for the GoogleTest JUnit dialect.
67 """
70@export
71@InheritDocString(ju_Testsuite, merge=True)
72class Testsuite(ju_Testsuite):
73 """
74 This is a derived implementation for the GoogleTest JUnit dialect.
75 """
77 @classmethod
78 def FromTestsuite(cls, testsuite: ut_Testsuite) -> "Testsuite":
79 """
80 Convert a test suite of the unified test entity data model to the JUnit specific data model's test suite object
81 adhering to the GoogleTest JUnit dialect.
83 :param testsuite: Test suite from unified data model.
84 :returns: Test suite from JUnit specific data model (GoogleTest JUnit dialect).
85 """
86 juTestsuite = cls(
87 testsuite._name,
88 hostname=testsuite._hostname,
89 startTime=testsuite._startTime,
90 duration=testsuite._totalDuration,
91 status= testsuite._status,
92 )
94 juTestsuite._tests = testsuite._tests
95 juTestsuite._skipped = testsuite._skipped
96 juTestsuite._errored = testsuite._errored
97 juTestsuite._failed = testsuite._failed
98 juTestsuite._passed = testsuite._passed
100 for tc in testsuite.IterateTestcases():
101 ts = tc._parent
102 if ts is None: 102 ↛ 103line 102 didn't jump to line 103 because the condition on line 102 was never true
103 raise UnittestException(f"Testcase '{tc._name}' is not part of a hierarchy.")
105 classname = ts._name
106 ts = ts._parent
107 while ts is not None and ts._kind > TestsuiteKind.Logical:
108 classname = f"{ts._name}.{classname}"
109 ts = ts._parent
111 if classname in juTestsuite._testclasses:
112 juClass = juTestsuite._testclasses[classname]
113 else:
114 juClass = Testclass(classname, parent=juTestsuite)
116 juClass.AddTestcase(Testcase.FromTestcase(tc))
118 return juTestsuite
121@export
122@InheritDocString(ju_TestsuiteSummary, merge=True)
123class TestsuiteSummary(ju_TestsuiteSummary):
124 """
125 This is a derived implementation for the GoogleTest JUnit dialect.
126 """
128 @classmethod
129 def FromTestsuiteSummary(cls, testsuiteSummary: ut_TestsuiteSummary) -> "TestsuiteSummary":
130 """
131 Convert a test suite summary of the unified test entity data model to the JUnit specific data model's test suite
132 summary object adhering to the GoogleTest JUnit dialect.
134 :param testsuiteSummary: Test suite summary from unified data model.
135 :returns: Test suite summary from JUnit specific data model (GoogleTest JUnit dialect).
136 """
137 return cls(
138 testsuiteSummary._name,
139 startTime=testsuiteSummary._startTime,
140 duration=testsuiteSummary._totalDuration,
141 status=testsuiteSummary._status,
142 testsuites=(ut_Testsuite.FromTestsuite(testsuite) for testsuite in testsuiteSummary._testsuites.values())
143 )
146@export
147class Document(ju_Document):
148 """
149 A document reader and writer for the GoogelTest JUnit XML file format.
151 This class reads, validates and transforms an XML file in the GoogelTest JUnit format into a JUnit data model. It can
152 then be converted into a unified test entity data model.
154 In reverse, a JUnit data model instance with the specific GoogelTest JUnit file format can be created from a unified
155 test entity data model. This data model can be written as XML into a file.
156 """
158 _DIALECT: ClassVar[str] = "GoogleTest + JUnit"
159 _TESTCASE: ClassVar[Type[Testcase]] = Testcase
160 _TESTCLASS: ClassVar[Type[Testclass]] = Testclass
161 _TESTSUITE: ClassVar[Type[Testsuite]] = Testsuite
163 @classmethod
164 def FromTestsuiteSummary(cls, xmlReportFile: Path, testsuiteSummary: ut_TestsuiteSummary):
165 doc = cls(xmlReportFile)
166 doc._name = testsuiteSummary._name
167 doc._startTime = testsuiteSummary._startTime
168 doc._duration = testsuiteSummary._totalDuration
169 doc._status = testsuiteSummary._status
170 doc._tests = testsuiteSummary._tests
171 doc._skipped = testsuiteSummary._skipped
172 doc._errored = testsuiteSummary._errored
173 doc._failed = testsuiteSummary._failed
174 doc._passed = testsuiteSummary._passed
176 doc.AddTestsuites(Testsuite.FromTestsuite(testsuite) for testsuite in testsuiteSummary._testsuites.values())
178 return doc
180 def Analyze(self) -> None:
181 """
182 Analyze the XML file, parse the content into an XML data structure and validate the data structure using an XML
183 schema.
185 .. hint::
187 The time spend for analysis will be made available via property :data:`AnalysisDuration`.
189 The used XML schema definition is specific to the GoogleTest JUnit dialect.
190 """
191 xmlSchemaFile = "GoogleTest-JUnit.xsd"
192 self._Analyze(xmlSchemaFile)
194 def Write(self, path: Nullable[Path] = None, overwrite: bool = False, regenerate: bool = False) -> None:
195 """
196 Write the data model as XML into a file adhering to the GoogleTest dialect.
198 :param path: Optional path to the XMl file, if internal path shouldn't be used.
199 :param overwrite: If true, overwrite an existing file.
200 :param regenerate: If true, regenerate the XML structure from data model.
201 :raises UnittestException: If the file cannot be overwritten.
202 :raises UnittestException: If the internal XML data structure wasn't generated.
203 :raises UnittestException: If the file cannot be opened or written.
204 """
205 if path is None:
206 path = self._path
208 if not overwrite and path.exists(): 208 ↛ 209line 208 didn't jump to line 209 because the condition on line 208 was never true
209 raise UnittestException(f"JUnit XML file '{path}' can not be overwritten.") \
210 from FileExistsError(f"File '{path}' already exists.")
212 if regenerate: 212 ↛ 215line 212 didn't jump to line 215 because the condition on line 212 was always true
213 self.Generate(overwrite=True)
215 if self._xmlDocument is None: 215 ↛ 216line 215 didn't jump to line 216 because the condition on line 215 was never true
216 ex = UnittestException(f"Internal XML document tree is empty and needs to be generated before write is possible.")
217 ex.add_note(f"Call 'JUnitDocument.Generate()' or 'JUnitDocument.Write(..., regenerate=True)'.")
218 raise ex
220 try:
221 with path.open("wb") as file:
222 file.write(tostring(self._xmlDocument, encoding="utf-8", xml_declaration=True, pretty_print=True))
223 except Exception as ex:
224 raise UnittestException(f"JUnit XML file '{path}' can not be written.") from ex
226 def Convert(self) -> None:
227 """
228 Convert the parsed and validated XML data structure into a JUnit test entity hierarchy.
230 This method converts the root element.
232 .. hint::
234 The time spend for model conversion will be made available via property :data:`ModelConversionDuration`.
236 :raises UnittestException: If XML was not read and parsed before.
237 """
238 if self._xmlDocument is None: 238 ↛ 239line 238 didn't jump to line 239 because the condition on line 238 was never true
239 ex = UnittestException(f"JUnit XML file '{self._path}' needs to be read and analyzed by an XML parser.")
240 ex.add_note(f"Call 'JUnitDocument.Analyze()' or create the document using 'JUnitDocument(path, parse=True)'.")
241 raise ex
243 startConversion = perf_counter_ns()
244 rootElement: _Element = self._xmlDocument.getroot()
246 self._name = self._ConvertName(rootElement, optional=True)
247 self._startTime =self._ConvertTimestamp(rootElement, optional=True)
248 self._duration = self._ConvertTime(rootElement, optional=True)
250 # tests = rootElement.getAttribute("tests")
251 # skipped = rootElement.getAttribute("skipped")
252 # errors = rootElement.getAttribute("errors")
253 # failures = rootElement.getAttribute("failures")
254 # assertions = rootElement.getAttribute("assertions")
256 for rootNode in rootElement.iterchildren(tag="testsuite"): # type: _Element
257 self._ConvertTestsuite(self, rootNode)
259 self.Aggregate()
260 endConversation = perf_counter_ns()
261 self._modelConversion = (endConversation - startConversion) / 1e9
263 def _ConvertTestsuite(self, parent: TestsuiteSummary, testsuitesNode: _Element) -> None:
264 """
265 Convert the XML data structure of a ``<testsuite>`` to a test suite.
267 This method uses private helper methods provided by the base-class.
269 :param parent: The test suite summary as a parent element in the test entity hierarchy.
270 :param testsuitesNode: The current XML element node representing a test suite.
271 """
272 newTestsuite = Testsuite(
273 self._ConvertName(testsuitesNode, optional=False),
274 self._ConvertHostname(testsuitesNode, optional=True),
275 self._ConvertTimestamp(testsuitesNode, optional=False),
276 self._ConvertTime(testsuitesNode, optional=False),
277 parent=parent
278 )
280 self._ConvertTestsuiteChildren(testsuitesNode, newTestsuite)
282 def Generate(self, overwrite: bool = False) -> None:
283 """
284 Generate the internal XML data structure from test suites and test cases.
286 This method generates the XML root element (``<testsuites>``) and recursively calls other generated methods.
288 :param overwrite: Overwrite the internal XML data structure.
289 :raises UnittestException: If overwrite is false and the internal XML data structure is not empty.
290 """
291 if not overwrite and self._xmlDocument is not None: 291 ↛ 292line 291 didn't jump to line 292 because the condition on line 291 was never true
292 raise UnittestException(f"Internal XML document is populated with data.")
294 rootElement = Element("testsuites")
295 rootElement.attrib["name"] = self._name
296 if self._startTime is None:
297 raise UnittestException(
298 f"The {self._DIALECT} format requires a timestamp on <testsuites>, but the report has none."
299 )
300 rootElement.attrib["timestamp"] = f"{self._startTime.isoformat()}"
301 if self._duration is not None: 301 ↛ 303line 301 didn't jump to line 303 because the condition on line 301 was always true
302 rootElement.attrib["time"] = f"{self._duration.total_seconds():.6f}"
303 rootElement.attrib["tests"] = str(self._tests)
304 rootElement.attrib["failures"] = str(self._failed)
305 rootElement.attrib["errors"] = str(self._errored)
306 # rootElement.attrib["skipped"] = str(self._skipped)
307 rootElement.attrib["disabled"] = "0" # TODO: find a value
308 # if self._assertionCount is not None:
309 # rootElement.attrib["assertions"] = f"{self._assertionCount}"
311 self._xmlDocument = ElementTree(rootElement)
313 for testsuite in self._testsuites.values():
314 self._GenerateTestsuite(testsuite, rootElement)
316 def _GenerateTestsuite(self, testsuite: Testsuite, parentElement: _Element) -> None:
317 """
318 Generate the internal XML data structure for a test suite.
320 This method generates the XML element (``<testsuite>``) and recursively calls other generated methods.
322 :param testsuite: The test suite to convert to an XML data structures.
323 :param parentElement: The parent XML data structure element, this data structure part will be added to.
324 """
325 testsuiteElement = SubElement(parentElement, "testsuite")
326 testsuiteElement.attrib["name"] = testsuite._name
327 if testsuite._startTime is None:
328 raise UnittestException(
329 f"The {self._DIALECT} format requires a timestamp on <testsuite>, but the report has none."
330 )
331 testsuiteElement.attrib["timestamp"] = f"{testsuite._startTime.isoformat()}"
332 if testsuite._duration is not None: 332 ↛ 334line 332 didn't jump to line 334 because the condition on line 332 was always true
333 testsuiteElement.attrib["time"] = f"{testsuite._duration.total_seconds():.6f}"
334 testsuiteElement.attrib["tests"] = str(testsuite._tests)
335 testsuiteElement.attrib["failures"] = str(testsuite._failed)
336 testsuiteElement.attrib["errors"] = str(testsuite._errored)
337 testsuiteElement.attrib["skipped"] = str(testsuite._skipped)
338 testsuiteElement.attrib["disabled"] = "0" # TODO: find a value
339 # if testsuite._assertionCount is not None:
340 # testsuiteElement.attrib["assertions"] = f"{testsuite._assertionCount}"
341 # if testsuite._hostname is not None:
342 # testsuiteElement.attrib["hostname"] = testsuite._hostname
344 for testclass in testsuite._testclasses.values():
345 for tc in testclass._testcases.values():
346 self._GenerateTestcase(tc, testsuiteElement)
348 def _GenerateTestcase(self, testcase: Testcase, parentElement: _Element) -> None:
349 """
350 Generate the internal XML data structure for a test case.
352 This method generates the XML element (``<testcase>``) and recursively calls other generated methods.
354 :param testcase: The test case to convert to an XML data structures.
355 :param parentElement: The parent XML data structure element, this data structure part will be added to.
356 """
357 testcaseElement = SubElement(parentElement, "testcase")
358 if testcase.Classname is not None: 358 ↛ 360line 358 didn't jump to line 360 because the condition on line 358 was always true
359 testcaseElement.attrib["classname"] = testcase.Classname
360 testcaseElement.attrib["name"] = testcase._name
361 if testcase._duration is not None: 361 ↛ 363line 361 didn't jump to line 363 because the condition on line 361 was always true
362 testcaseElement.attrib["time"] = f"{testcase._duration.total_seconds():.6f}"
363 if testcase._assertionCount is not None: 363 ↛ 364line 363 didn't jump to line 364 because the condition on line 363 was never true
364 testcaseElement.attrib["assertions"] = f"{testcase._assertionCount}"
366 if testcase._parent._parent._startTime is None: 366 ↛ 367line 366 didn't jump to line 367 because the condition on line 366 was never true
367 raise UnittestException(
368 f"The {self._DIALECT} format requires a timestamp on <testcase>, but the report has none."
369 )
370 testcaseElement.attrib["timestamp"] = f"{testcase._parent._parent._startTime.isoformat()}"
371 testcaseElement.attrib["file"] = "" # TODO: find a value
372 testcaseElement.attrib["line"] = "0" # TODO: find a value
373 testcaseElement.attrib["status"] = "run" # TODO: find a value
374 testcaseElement.attrib["result"] = "completed" # TODO: find a value
376 if testcase._status is TestcaseStatus.Passed:
377 pass
378 elif testcase._status is TestcaseStatus.Failed: 378 ↛ 380line 378 didn't jump to line 380 because the condition on line 378 was always true
379 failureElement = SubElement(testcaseElement, "failure")
380 elif testcase._status is TestcaseStatus.Skipped:
381 skippedElement = SubElement(testcaseElement, "skipped")
382 else:
383 errorElement = SubElement(testcaseElement, "error")