Coverage for pyEDAA/Reports/Unittesting/JUnit/PyTestJUnit.py: 91%

137 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.Decorators import export, InheritDocString, DocStringMergeStrategy 

42from pyTooling.Stopwatch import Stopwatch 

43 

44from pyEDAA.Reports.Unittesting import UnittestError, TestsuiteKind, TestsuiteSummary as ut_TestsuiteSummary, \ 

45 Testsuite as ut_Testsuite 

46from pyEDAA.Reports.Unittesting.JUnit import Testcase as ju_Testcase, Testclass as ju_Testclass, \ 

47 Testsuite as ju_Testsuite, TestsuiteSummary as ju_TestsuiteSummary, \ 

48 Document as ju_Document 

49 

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 pyTest JUnit 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 pyTest JUnit 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 pyTest JUnit 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 pyTest JUnit dialect. 

84 

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

86 :returns: Test suite from JUnit specific data model (pyTest JUnitdialect). 

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 pyTest JUnit 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 pyTest JUnit dialect. 

138 

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

140 :returns: Test suite summary from JUnit specific data model (pyTest JUnit 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 pyTest JUnit XML file format. 

155 

156 This class reads, validates and transforms an XML file in the pyTest JUnit 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 pyTest JUnit 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 pyTest JUnit dialect. 

177 """ 

178 xmlSchemaFile = "PyTest-JUnit.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 pyTest 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 for rootNode in rootElement.iterchildren(tag="testsuite"): # type: _Element 

245 self._ConvertTestsuite(self, rootNode) 

246 

247 self.Aggregate() 

248 

249 self._modelConversion = sw.Duration 

250 

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

252 """ 

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

254 

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

256 

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

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

259 """ 

260 newTestsuite = Testsuite( 

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

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

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

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

265 parent=parent 

266 ) 

267 

268 self._ConvertTestsuiteChildren(testsuitesNode, newTestsuite) 

269 

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

271 """ 

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

273 

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

275 

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

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

278 """ 

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

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

281 

282 rootElement = Element("testsuites") 

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

284 if self._startTime is not None: 

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

286 if self._duration is not None: 

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

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

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

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

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

292 # if self._assertionCount is not None: 

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

294 

295 self._xmlDocument = ElementTree(rootElement) 

296 

297 for testsuite in self._testsuites.values(): 

298 self._GenerateTestsuite(testsuite, rootElement) 

299 

300 def _GenerateTestsuite(self, testsuite: Testsuite, parentElement: _Element) -> None: 

301 """ 

302 Generate the internal XML data structure for a test suite. 

303 

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

305 

306 :param testsuite: The test suite to convert to an XML data structures. 

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

308 """ 

309 testsuiteElement = SubElement(parentElement, "testsuite") 

310 testsuiteElement.attrib["name"] = testsuite._name 

311 if testsuite._startTime is not None: 

312 testsuiteElement.attrib["timestamp"] = f"{testsuite._startTime.isoformat()}" 

313 if testsuite._duration is not None: 313 ↛ 315line 313 didn't jump to line 315 because the condition on line 313 was always true

314 testsuiteElement.attrib["time"] = f"{testsuite._duration.total_seconds():.6f}" 

315 testsuiteElement.attrib["tests"] = str(testsuite._tests) 

316 testsuiteElement.attrib["failures"] = str(testsuite._failed) 

317 testsuiteElement.attrib["errors"] = str(testsuite._errored) 

318 testsuiteElement.attrib["skipped"] = str(testsuite._skipped) 

319 # if testsuite._assertionCount is not None: 

320 # testsuiteElement.attrib["assertions"] = f"{testsuite._assertionCount}" 

321 if testsuite._hostname is not None: 

322 testsuiteElement.attrib["hostname"] = testsuite._hostname 

323 

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

325 self._GenerateTestcase(tc, testsuiteElement) 

326 

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

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

329 self._GenerateTestcase(tc, testsuiteElement) 

330 

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

332 """ 

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

334 

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

336 

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

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

339 """ 

340 testcaseElement = SubElement(parentElement, "testcase") 

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

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

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

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

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

346 if testcase._assertionCount is not None: 

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

348 

349 self._GenerateTestcaseChildren(testcase, testcaseElement)