Coverage for pyEDAA/Reports/Unittesting/JUnit/AntJUnit4.py: 88%

131 statements  

« 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 

36 

37from pathlib import Path 

38from typing import Optional as Nullable, Tuple, TypeVar, Type, ClassVar 

39 

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 

44 

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 

50 

51TestsuiteType = TypeVar("TestsuiteType", bound="Testsuite") 

52TestcaseAggregateReturnType = Tuple[int, int, int] 

53TestsuiteAggregateReturnType = Tuple[int, int, int, int, int] 

54 

55 

56@export 

57@InheritDocString(ju_Testcase, DocStringMergeStrategy.BaseLast) 

58class Testcase(ju_Testcase): 

59 """ 

60 This is a derived implementation for the Ant + JUnit4 dialect. 

61 """ 

62 

63 

64@export 

65@InheritDocString(ju_Testclass, DocStringMergeStrategy.BaseLast) 

66class Testclass(ju_Testclass): 

67 """ 

68 This is a derived implementation for the Ant + JUnit4 dialect. 

69 """ 

70 

71 

72@export 

73@InheritDocString(ju_Testsuite, DocStringMergeStrategy.BaseLast) 

74class Testsuite(ju_Testsuite): 

75 """ 

76 This is a derived implementation for the Ant + JUnit4 dialect. 

77 """ 

78 

79 @classmethod 

80 def FromTestsuite(cls, testsuite: ut_Testsuite) -> Testsuite: 

81 """ 

82 Convert a test suite of the unified test entity data model to the JUnit specific data model's test suite object 

83 adhering to the Ant + JUnit4 dialect. 

84 

85 :param testsuite: Test suite from unified data model. 

86 :returns: Test suite from JUnit specific data model (Ant + JUnit4 dialect). 

87 """ 

88 juTestsuite = cls( 

89 testsuite._name, 

90 hostname=testsuite._hostname, 

91 startTime=testsuite._startTime, 

92 duration=testsuite._totalDuration, 

93 status= testsuite._status, 

94 ) 

95 

96 juTestsuite._tests = testsuite._tests 

97 juTestsuite._skipped = testsuite._skipped 

98 juTestsuite._errored = testsuite._errored 

99 juTestsuite._failed = testsuite._failed 

100 juTestsuite._passed = testsuite._passed 

101 

102 for tc in testsuite.IterateTestcases(): 

103 ts = tc._parent 

104 if ts is None: 104 ↛ 105line 104 didn't jump to line 105 because the condition on line 104 was never true

105 raise UnittestError(f"Testcase '{tc._name}' is not part of a hierarchy.") 

106 elif ts is testsuite: 

107 juTestsuite.AddTestcase(Testcase.FromTestcase(tc)) 

108 continue 

109 

110 classname = ts._name 

111 ts = ts._parent 

112 while ts is not None and ts._kind > TestsuiteKind.Logical: 

113 classname = f"{ts._name}.{classname}" 

114 ts = ts._parent 

115 

116 if classname in juTestsuite._testclasses: 

117 juClass = juTestsuite._testclasses[classname] 

118 else: 

119 juClass = Testclass(classname, parent=juTestsuite) 

120 

121 juClass.AddTestcase(Testcase.FromTestcase(tc)) 

122 

123 return juTestsuite 

124 

125 

126@export 

127@InheritDocString(ju_TestsuiteSummary, DocStringMergeStrategy.BaseLast) 

128class TestsuiteSummary(ju_TestsuiteSummary): 

129 """ 

130 This is a derived implementation for the Ant + JUnit4 dialect. 

131 """ 

132 

133 @classmethod 

134 def FromTestsuiteSummary(cls, testsuiteSummary: ut_TestsuiteSummary) -> TestsuiteSummary: 

135 """ 

136 Convert a test suite summary of the unified test entity data model to the JUnit specific data model's test suite 

137 summary object adhering to the Ant + JUnit4 dialect. 

138 

139 :param testsuiteSummary: Test suite summary from unified data model. 

140 :returns: Test suite summary from JUnit specific data model (Ant + JUnit4 dialect). 

141 """ 

142 return cls( 

143 testsuiteSummary._name, 

144 startTime=testsuiteSummary._startTime, 

145 duration=testsuiteSummary._totalDuration, 

146 status=testsuiteSummary._status, 

147 testsuites=(Testsuite.FromTestsuite(testsuite) for testsuite in testsuiteSummary._testsuites.values()) 

148 ) 

149 

150 

151@export 

152class Document(ju_Document): 

153 """ 

154 A document reader and writer for the Ant + JUnit4 XML file format. 

155 

156 This class reads, validates and transforms an XML file in the Ant + JUnit4 format into a JUnit data model. It can then 

157 be converted into a unified test entity data model. 

158 

159 In reverse, a JUnit data model instance with the specific Ant + JUnit4 file format can be created from a unified test 

160 entity data model. This data model can be written as XML into a file. 

161 """ 

162 

163 _TESTCASE: ClassVar[Type[Testcase]] = Testcase 

164 _TESTCLASS: ClassVar[Type[Testclass]] = Testclass 

165 _TESTSUITE: ClassVar[Type[Testsuite]] = Testsuite 

166 

167 def Analyze(self) -> None: 

168 """ 

169 Analyze the XML file, parse the content into an XML data structure and validate the data structure using an XML 

170 schema. 

171 

172 .. hint:: 

173 

174 The time spend for analysis will be made available via property :data:`AnalysisDuration`.. 

175 

176 The used XML schema definition is specific to the Ant JUnit4 dialect. 

177 """ 

178 xmlSchemaFile = "Ant-JUnit4.xsd" 

179 self._Analyze(xmlSchemaFile) 

180 

181 def Write(self, path: Nullable[Path] = None, overwrite: bool = False, regenerate: bool = False) -> None: 

182 """ 

183 Write the data model as XML into a file adhering to the Ant + JUnit4 dialect. 

184 

185 :param path: Optional, path to the XML file, if internal path shouldn't be used. 

186 :param overwrite: Optional, if true, overwrite an existing file. 

187 :param regenerate: Optional, if true, regenerate the XML structure from data model. 

188 :raises UnittestError: If the file cannot be overwritten. 

189 :raises UnittestError: If the internal XML data structure wasn't generated. 

190 :raises UnittestError: If the file cannot be opened or written. 

191 """ 

192 if path is None: 

193 path = self._path 

194 

195 if not overwrite and path.exists(): 

196 raise UnittestError(f"JUnit XML file '{path}' can not be overwritten.") \ 

197 from FileExistsError(f"File '{path}' already exists.") 

198 

199 if regenerate: 199 ↛ 202line 199 didn't jump to line 202 because the condition on line 199 was always true

200 self.Generate(overwrite=True) 

201 

202 if self._xmlDocument is None: 202 ↛ 203line 202 didn't jump to line 203 because the condition on line 202 was never true

203 ex = UnittestError("Internal XML document tree is empty and needs to be generated before write is possible.") 

204 ex.add_note("Call 'JUnitDocument.Generate()' or 'JUnitDocument.Write(..., regenerate=True)'.") 

205 raise ex 

206 

207 content = tostring(self._xmlDocument, encoding="utf-8", xml_declaration=True, pretty_print=True) 

208 try: 

209 with path.open("wb") as file: 

210 file.write(content) 

211 except OSError as ex: 

212 raise UnittestError(f"JUnit XML file '{path}' can not be written.") from ex 

213 

214 def Convert(self) -> None: 

215 """ 

216 Convert the parsed and validated XML data structure into a JUnit test entity hierarchy. 

217 

218 This method converts the root element. 

219 

220 .. hint:: 

221 

222 The time spend for model conversion will be made available via property :data:`ModelConversionDuration`. 

223 

224 :raises UnittestError: If XML was not read and parsed before. 

225 """ 

226 if self._xmlDocument is None: 226 ↛ 227line 226 didn't jump to line 227 because the condition on line 226 was never true

227 ex = UnittestError(f"JUnit XML file '{self._path}' needs to be read and analyzed by an XML parser.") 

228 ex.add_note("Call 'JUnitDocument.Analyze()' or create the document using 'JUnitDocument(path, parse=True)'.") 

229 raise ex 

230 

231 with Stopwatch() as sw: 

232 rootElement: _Element = self._xmlDocument.getroot() 

233 

234 self._name = self._ConvertName(rootElement, optional=True) 

235 self._startTime =self._ConvertTimestamp(rootElement, optional=True) 

236 self._duration = self._ConvertTime(rootElement, optional=True) 

237 

238 # tests = rootElement.getAttribute("tests") 

239 # skipped = rootElement.getAttribute("skipped") 

240 # errors = rootElement.getAttribute("errors") 

241 # failures = rootElement.getAttribute("failures") 

242 # assertions = rootElement.getAttribute("assertions") 

243 

244 hostname = self._ConvertHostname(rootElement, optional=True, default=None) 

245 ts = Testsuite(self._name, hostname, startTime=self._startTime, duration=self._duration, parent=self) 

246 self._ConvertTestsuiteChildren(rootElement, ts) 

247 

248 self.Aggregate() 

249 

250 self._modelConversion = sw.Duration 

251 

252 def _ConvertTestsuite(self, parent: TestsuiteSummary, testsuitesNode: _Element) -> None: 

253 """ 

254 Convert the XML data structure of a ``<testsuite>`` to a test suite. 

255 

256 This method uses private helper methods provided by the base-class. 

257 

258 :param parent: The test suite summary as a parent element in the test entity hierarchy. 

259 :param testsuitesNode: The current XML element node representing a test suite. 

260 """ 

261 newTestsuite = Testsuite( 

262 self._ConvertName(testsuitesNode, optional=False), 

263 self._ConvertHostname(testsuitesNode, optional=False), 

264 self._ConvertTimestamp(testsuitesNode, optional=False), 

265 self._ConvertTime(testsuitesNode, optional=False), 

266 parent=parent 

267 ) 

268 

269 self._ConvertTestsuiteChildren(testsuitesNode, newTestsuite) 

270 

271 def Generate(self, overwrite: bool = False) -> None: 

272 """ 

273 Generate the internal XML data structure from test suites and test cases. 

274 

275 This method generates the XML root element (``<testsuite>``) and recursively calls other generated methods. 

276 

277 :param overwrite: Optional, overwrite the internal XML data structure. 

278 :raises UnittestError: If overwrite is false and the internal XML data structure is not empty. 

279 """ 

280 if not overwrite and self._xmlDocument is not None: 280 ↛ 281line 280 didn't jump to line 281 because the condition on line 280 was never true

281 raise UnittestError("Internal XML document is populated with data.") 

282 

283 if self.TestsuiteCount != 1: 

284 ex = UnittestError("The Ant + JUnit4 format requires exactly one test suite.") 

285 ex.add_note(f"Found {self.TestsuiteCount} test suites.") 

286 raise ex 

287 

288 testsuite = firstValue(self._testsuites) 

289 

290 rootElement = Element("testsuite") 

291 rootElement.attrib["name"] = self._name 

292 if self._startTime is not None: 

293 rootElement.attrib["timestamp"] = f"{self._startTime.isoformat()}" 

294 if self._duration is not None: 294 ↛ 296line 294 didn't jump to line 296 because the condition on line 294 was always true

295 rootElement.attrib["time"] = f"{self._duration.total_seconds():.6f}" 

296 rootElement.attrib["tests"] = str(self._tests) 

297 rootElement.attrib["failures"] = str(self._failed) 

298 rootElement.attrib["errors"] = str(self._errored) 

299 rootElement.attrib["skipped"] = str(self._skipped) 

300 # if self._assertionCount is not None: 

301 # rootElement.attrib["assertions"] = f"{self._assertionCount}" 

302 if testsuite._hostname is not None: 302 ↛ 305line 302 didn't jump to line 305 because the condition on line 302 was always true

303 rootElement.attrib["hostname"] = testsuite._hostname 

304 

305 self._xmlDocument = ElementTree(rootElement) 

306 

307 for tc in testsuite._testcases.values(): 

308 self._GenerateTestcase(tc, rootElement) 

309 

310 for testclass in testsuite._testclasses.values(): 

311 for tc in testclass._testcases.values(): 

312 self._GenerateTestcase(tc, rootElement) 

313 

314 def _GenerateTestcase(self, testcase: Testcase, parentElement: _Element) -> None: 

315 """ 

316 Generate the internal XML data structure for a test case. 

317 

318 This method generates the XML element (``<testcase>``) and recursively calls other generated methods. 

319 

320 :param testcase: The test case to convert to an XML data structures. 

321 :param parentElement: The parent XML data structure element, this data structure part will be added to. 

322 """ 

323 testcaseElement = SubElement(parentElement, "testcase") 

324 if testcase.Classname is not None: 324 ↛ 326line 324 didn't jump to line 326 because the condition on line 324 was always true

325 testcaseElement.attrib["classname"] = testcase.Classname 

326 testcaseElement.attrib["name"] = testcase._name 

327 if testcase._duration is not None: 327 ↛ 329line 327 didn't jump to line 329 because the condition on line 327 was always true

328 testcaseElement.attrib["time"] = f"{testcase._duration.total_seconds():.6f}" 

329 if testcase._assertionCount is not None: 329 ↛ 330line 329 didn't jump to line 330 because the condition on line 329 was never true

330 testcaseElement.attrib["assertions"] = f"{testcase._assertionCount}" 

331 

332 self._GenerateTestcaseChildren(testcase, testcaseElement)