Coverage for pyEDAA/Reports/Unittesting/JUnit/TestLoggerJUnit.py: 90%
156 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-21 23:49 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-21 23:49 +0000
1# ==================================================================================================================== #
2# _____ ____ _ _ ____ _ #
3# _ __ _ _| ____| _ \ / \ / \ | _ \ ___ _ __ ___ _ __| |_ ___ #
4# | '_ \| | | | _| | | | |/ _ \ / _ \ | |_) / _ \ '_ \ / _ \| '__| __/ __| #
5# | |_) | |_| | |___| |_| / ___ \ / ___ \ _| _ < __/ |_) | (_) | | | |_\__ \ #
6# | .__/ \__, |_____|____/_/ \_\/_/ \_(_)_| \_\___| .__/ \___/|_| \__|___/ #
7# |_| |___/ |_| #
8# ==================================================================================================================== #
9# Authors: #
10# Patrick Lehmann #
11# #
12# License: #
13# ==================================================================================================================== #
14# Copyright 2026-2026 Electronic Design Automation Abstraction (EDA²) #
15# #
16# Licensed under the Apache License, Version 2.0 (the "License"); #
17# you may not use this file except in compliance with the License. #
18# You may obtain a copy of the License at #
19# #
20# http://www.apache.org/licenses/LICENSE-2.0 #
21# #
22# Unless required by applicable law or agreed to in writing, software #
23# distributed under the License is distributed on an "AS IS" BASIS, #
24# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
25# See the License for the specific language governing permissions and #
26# limitations under the License. #
27# #
28# SPDX-License-Identifier: Apache-2.0 #
29# ==================================================================================================================== #
30#
31"""
32Reader and writer for the JUnit XML dialect of the .NET test logger ``JunitXml.TestLogger``.
34The logger writes it, when ``dotnet test`` is called with ``--logger junit``.
36.. seealso::
38 :ref:`UNITTEST/SpecificDataModel/JUnit/Dialect/TestLogger`
39 |rarr| How the logger's report is read into the unified data model.
40"""
41from __future__ import annotations
43from datetime import timezone
44from pathlib import Path
45from typing import Optional as Nullable, ClassVar, Type
47from lxml.etree import ElementTree, Element, SubElement, tostring, _Element
48from pyTooling.Common import firstValue
49from pyTooling.Decorators import export, InheritDocString, DocStringMergeStrategy
50from pyTooling.Stopwatch import Stopwatch
52from pyEDAA.Reports.Unittesting import UnittestError, TestcaseStatus, TestsuiteKind
53from pyEDAA.Reports.Unittesting import TestsuiteSummary as ut_TestsuiteSummary, Testsuite as ut_Testsuite
54from pyEDAA.Reports.Unittesting.JUnit import Testcase as ju_Testcase, Testclass as ju_Testclass
55from pyEDAA.Reports.Unittesting.JUnit import Testsuite as ju_Testsuite, TestsuiteSummary as ju_TestsuiteSummary
56from pyEDAA.Reports.Unittesting.JUnit import Document as ju_Document
59@export
60@InheritDocString(ju_Testcase, DocStringMergeStrategy.BaseLast)
61class Testcase(ju_Testcase):
62 """
63 This is a derived implementation for the JunitXml.TestLogger JUnit dialect.
64 """
67@export
68@InheritDocString(ju_Testclass, DocStringMergeStrategy.BaseLast)
69class Testclass(ju_Testclass):
70 """
71 This is a derived implementation for the JunitXml.TestLogger JUnit dialect.
72 """
75@export
76@InheritDocString(ju_Testsuite, DocStringMergeStrategy.BaseLast)
77class Testsuite(ju_Testsuite):
78 """
79 This is a derived implementation for the JunitXml.TestLogger JUnit dialect.
80 """
82 @classmethod
83 def FromTestsuite(cls, testsuite: ut_Testsuite) -> Testsuite:
84 """
85 Convert a test suite of the unified test entity data model to the JUnit specific data model's test suite object
86 adhering to the JunitXml.TestLogger JUnit dialect.
88 :param testsuite: Test suite from unified data model.
89 :returns: Test suite from JUnit specific data model (JunitXml.TestLogger JUnit dialect).
90 :raises UnittestError: If a test case is not part of a test suite hierarchy.
91 """
92 juTestsuite = cls(
93 testsuite._name,
94 hostname=testsuite._hostname,
95 startTime=testsuite._startTime,
96 duration=testsuite._totalDuration,
97 status=testsuite._status,
98 )
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 UnittestError(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
120 def ToTestsuite(self) -> ut_Testsuite:
121 """
122 Convert this test suite to a test suite of the unified test entity data model.
124 A test class' name is split into its namespace and its class at the last dot before the arguments of a
125 parameterized test class. Each part of the namespace becomes a test suite of kind
126 :attr:`~pyEDAA.Reports.Unittesting.TestsuiteKind.Namespace`, the class a test suite of kind
127 :attr:`~pyEDAA.Reports.Unittesting.TestsuiteKind.Class` holding the test cases. A nested class keeps the name .NET
128 gives it, e.g. ``Outer+Inner``.
130 :returns: Test suite of the unified test entity data model.
131 """
132 testsuite = ut_Testsuite(
133 self._name,
134 kind=TestsuiteKind.Logical,
135 hostname=self._hostname,
136 startTime=self._startTime,
137 totalDuration=self._duration,
138 status=self._status,
139 )
141 for testclass in self._testclasses.values():
142 namespace, separator, _ = testclass._name.partition("(")[0].rpartition(".")
144 suite = testsuite
145 if namespace != "":
146 for element in namespace.split("."):
147 if element in suite._testsuites:
148 suite = suite._testsuites[element]
149 else:
150 suite = ut_Testsuite(element, kind=TestsuiteKind.Namespace, parent=suite)
152 ut_Testsuite(
153 testclass._name[len(namespace) + len(separator):],
154 kind=TestsuiteKind.Class,
155 testcases=(tc.ToTestcase() for tc in testclass._testcases.values()),
156 parent=suite
157 )
159 return testsuite
162@export
163@InheritDocString(ju_TestsuiteSummary, DocStringMergeStrategy.BaseLast)
164class TestsuiteSummary(ju_TestsuiteSummary):
165 """
166 This is a derived implementation for the JunitXml.TestLogger JUnit dialect.
167 """
169 @classmethod
170 def FromTestsuiteSummary(cls, testsuiteSummary: ut_TestsuiteSummary) -> TestsuiteSummary:
171 """
172 Convert a test suite summary of the unified test entity data model to the JUnit specific data model's test suite
173 summary object adhering to the JunitXml.TestLogger JUnit dialect.
175 :param testsuiteSummary: Test suite summary from unified data model.
176 :returns: Test suite summary from JUnit specific data model (JunitXml.TestLogger JUnit dialect).
177 """
178 return cls(
179 testsuiteSummary._name,
180 startTime=testsuiteSummary._startTime,
181 duration=testsuiteSummary._totalDuration,
182 status=testsuiteSummary._status,
183 testsuites=(Testsuite.FromTestsuite(testsuite) for testsuite in testsuiteSummary._testsuites.values())
184 )
187@export
188class Document(ju_Document):
189 """
190 A document reader and writer for the JunitXml.TestLogger JUnit XML file format.
192 This class reads, validates and transforms an XML file in the JunitXml.TestLogger JUnit format into a JUnit data
193 model. It can then be converted into a unified test entity data model.
195 In reverse, a JUnit data model instance with the specific JunitXml.TestLogger JUnit file format can be created from a
196 unified test entity data model. This data model can be written as XML into a file.
197 """
199 _DIALECT: ClassVar[str] = "JunitXml.TestLogger JUnit" #: Name of the dialect in error messages.
200 _TESTCASE: ClassVar[Type[Testcase]] = Testcase #: Test case class of this dialect.
201 _TESTCLASS: ClassVar[Type[Testclass]] = Testclass #: Test class class of this dialect.
202 _TESTSUITE: ClassVar[Type[Testsuite]] = Testsuite #: Test suite class of this dialect.
204 def Analyze(self) -> None:
205 """
206 Analyze the XML file, parse the content into an XML data structure and validate the data structure using an XML
207 schema.
209 .. hint::
211 The time spend for analysis will be made available via property :data:`AnalysisDuration`.
213 The used XML schema definition is specific to the JunitXml.TestLogger JUnit dialect.
214 """
215 xmlSchemaFile = "TestLogger-JUnit.xsd"
216 self._Analyze(xmlSchemaFile)
218 def Write(self, path: Nullable[Path] = None, overwrite: bool = False, regenerate: bool = False) -> None:
219 """
220 Write the data model as XML into a file adhering to the JunitXml.TestLogger JUnit dialect.
222 :param path: Optional, path to the XML file, if internal path shouldn't be used.
223 :param overwrite: Optional, if true, overwrite an existing file.
224 :param regenerate: Optional, if true, regenerate the XML structure from data model.
225 :raises UnittestError: If the file cannot be overwritten.
226 :raises UnittestError: If the internal XML data structure wasn't generated. |br|
227 Call ``Document.Generate()`` or ``Document.Write(..., regenerate=True)``.
228 :raises UnittestError: If the file cannot be opened or written.
229 """
230 if path is None: 230 ↛ 233line 230 didn't jump to line 233 because the condition on line 230 was always true
231 path = self._path
233 if not overwrite and path.exists():
234 raise UnittestError(f"JUnit XML file '{path}' can not be overwritten.") \
235 from FileExistsError(f"File '{path}' already exists.")
237 if regenerate: 237 ↛ 240line 237 didn't jump to line 240 because the condition on line 237 was always true
238 self.Generate(overwrite=True)
240 if self._xmlDocument is None: 240 ↛ 241line 240 didn't jump to line 241 because the condition on line 240 was never true
241 ex = UnittestError("Internal XML document tree is empty and needs to be generated before write is possible.")
242 ex.add_note("Call 'Document.Generate()' or 'Document.Write(..., regenerate=True)'.")
243 raise ex
245 content = tostring(self._xmlDocument, encoding="utf-8", xml_declaration=True, pretty_print=True)
246 try:
247 with path.open("wb") as file:
248 file.write(content)
249 except OSError as ex:
250 raise UnittestError(f"JUnit XML file '{path}' can not be written.") from ex
252 def Convert(self) -> None:
253 """
254 Convert the parsed and validated XML data structure into a JUnit test entity hierarchy.
256 This method converts the root element. As ``<testsuites>`` has no attributes, the summary's start time is the one
257 of the first test suite: the logger writes the start of the test run into every ``<testsuite>``.
259 .. hint::
261 The time spend for model conversion will be made available via property :data:`ModelConversionDuration`.
263 :raises UnittestError: If XML was not read and parsed before. |br|
264 Call ``Document.Analyze()`` or create the document using
265 ``Document(path, analyzeAndConvert=True)``.
266 """
267 if self._xmlDocument is None: 267 ↛ 268line 267 didn't jump to line 268 because the condition on line 267 was never true
268 ex = UnittestError(f"JUnit XML file '{self._path}' needs to be read and analyzed by an XML parser.")
269 ex.add_note("Call 'Document.Analyze()' or create the document using 'Document(path, analyzeAndConvert=True)'.")
270 raise ex
272 with Stopwatch() as sw:
273 rootElement: _Element = self._xmlDocument.getroot()
275 self._name = self._ConvertName(rootElement, optional=True)
277 for rootNode in rootElement.iterchildren(tag="testsuite"): # type: _Element
278 self._ConvertTestsuite(self, rootNode)
280 if len(self._testsuites) > 0: 280 ↛ 283line 280 didn't jump to line 283 because the condition on line 280 was always true
281 self._startTime = firstValue(self._testsuites)._startTime
283 self.Aggregate()
285 self._modelConversion = sw.Duration
287 def _ConvertTestsuite(self, parent: TestsuiteSummary, testsuitesNode: _Element) -> None:
288 """
289 Convert the XML data structure of a ``<testsuite>`` to a test suite.
291 This method uses private helper methods provided by the base-class. The ``timestamp`` is read as UTC. The
292 attributes ``id`` (always ``0``) and ``package`` (the same as ``name``) are not read.
294 :param parent: The test suite summary as a parent element in the test entity hierarchy.
295 :param testsuitesNode: The current XML element node representing a test suite.
296 """
297 newTestsuite = self._TESTSUITE(
298 self._ConvertName(testsuitesNode, optional=False),
299 self._ConvertHostname(testsuitesNode, optional=False),
300 self._ConvertTimestamp(testsuitesNode, optional=False).replace(tzinfo=timezone.utc),
301 self._ConvertTime(testsuitesNode, optional=False),
302 parent=parent
303 )
305 self._ConvertTestsuiteChildren(testsuitesNode, newTestsuite)
307 def Generate(self, overwrite: bool = False) -> None:
308 """
309 Generate the internal XML data structure from test suites and test cases.
311 This method generates the XML root element (``<testsuites>``), without attributes, and recursively calls other
312 generated methods.
314 :param overwrite: Optional, overwrite the internal XML data structure.
315 :raises UnittestError: If overwrite is false and the internal XML data structure is not empty.
316 """
317 if not overwrite and self._xmlDocument is not None: 317 ↛ 318line 317 didn't jump to line 318 because the condition on line 317 was never true
318 raise UnittestError("Internal XML document is populated with data.")
320 rootElement = Element("testsuites")
322 self._xmlDocument = ElementTree(rootElement)
324 for testsuite in self._testsuites.values():
325 self._GenerateTestsuite(testsuite, rootElement)
327 def _GenerateTestsuite(self, testsuite: Testsuite, parentElement: _Element) -> None:
328 """
329 Generate the internal XML data structure for a test suite.
331 This method generates the XML element (``<testsuite>``) and recursively calls other generated methods. Errored
332 test cases are counted as failures, as the logger knows no errors. The start time is written in UTC. The
333 attributes ``id`` and ``package`` are written as the logger does: ``0`` and the test suite's name.
335 :param testsuite: The test suite to convert to an XML data structures.
336 :param parentElement: The parent XML data structure element, this data structure part will be added to.
337 :raises UnittestError: If the test suite has no test cases.
338 :raises UnittestError: If the test suite has no start time.
339 :raises UnittestError: If the test suite has no duration.
340 :raises UnittestError: If the test suite has no host name.
341 """
342 if testsuite.TestcaseCount == 0:
343 raise UnittestError(
344 f"The {self._DIALECT} format requires test cases in <testsuite>, but '{testsuite._name}' has none."
345 )
346 elif testsuite._startTime is None:
347 raise UnittestError(
348 f"The {self._DIALECT} format requires a timestamp on <testsuite>, but '{testsuite._name}' has none."
349 )
350 elif testsuite._duration is None: 350 ↛ 351line 350 didn't jump to line 351 because the condition on line 350 was never true
351 raise UnittestError(
352 f"The {self._DIALECT} format requires a time on <testsuite>, but '{testsuite._name}' has none."
353 )
354 elif testsuite._hostname is None: 354 ↛ 355line 354 didn't jump to line 355 because the condition on line 354 was never true
355 raise UnittestError(
356 f"The {self._DIALECT} format requires a hostname on <testsuite>, but '{testsuite._name}' has none."
357 )
359 startTime = testsuite._startTime
360 if startTime.tzinfo is not None:
361 startTime = startTime.astimezone(timezone.utc).replace(tzinfo=None)
363 testsuiteElement = SubElement(parentElement, "testsuite")
364 testsuiteElement.attrib["name"] = testsuite._name
365 testsuiteElement.attrib["tests"] = str(testsuite.TestcaseCount)
366 testsuiteElement.attrib["skipped"] = str(testsuite._skipped)
367 testsuiteElement.attrib["failures"] = str(testsuite._failed + testsuite._errored)
368 testsuiteElement.attrib["errors"] = "0"
369 testsuiteElement.attrib["time"] = f"{testsuite._duration.total_seconds():.6f}"
370 testsuiteElement.attrib["timestamp"] = startTime.isoformat(timespec="seconds")
371 testsuiteElement.attrib["hostname"] = testsuite._hostname
372 testsuiteElement.attrib["id"] = "0"
373 testsuiteElement.attrib["package"] = testsuite._name
375 SubElement(testsuiteElement, "properties")
377 for testclass in testsuite._testclasses.values():
378 for tc in testclass._testcases.values():
379 self._GenerateTestcase(tc, testsuiteElement)
381 def _GenerateTestcase(self, testcase: Testcase, parentElement: _Element) -> None:
382 """
383 Generate the internal XML data structure for a test case.
385 This method generates the XML element (``<testcase>``) and recursively calls other generated methods. The
386 duration is written with seven decimals and at least ``0.0000001`` seconds, as the logger does.
388 :param testcase: The test case to convert to an XML data structures.
389 :param parentElement: The parent XML data structure element, this data structure part will be added to.
390 :raises UnittestError: If the test case has no duration.
391 """
392 if testcase._duration is None: 392 ↛ 393line 392 didn't jump to line 393 because the condition on line 392 was never true
393 raise UnittestError(
394 f"The {self._DIALECT} format requires a time on <testcase>, but '{testcase._name}' has none."
395 )
397 testcaseElement = SubElement(parentElement, "testcase")
398 testcaseElement.attrib["classname"] = testcase.Classname
399 testcaseElement.attrib["name"] = testcase._name
400 testcaseElement.attrib["time"] = f"{max(testcase._duration.total_seconds(), 0.0000001):.7f}"
402 self._GenerateTestcaseChildren(testcase, testcaseElement)
404 def _GenerateTestcaseChildren(self, testcase: Testcase, testcaseElement: _Element) -> None:
405 """
406 Generate the child elements of a ``<testcase>`` from the test case's status, message, details and captured output.
408 A skipped test case gets an empty ``<skipped/>``: its message and details are not written. Every other test case,
409 which didn't pass, gets a ``<failure type="failure">`` carrying the message (``message`` attribute) and details
410 (text) - errored ones too. Captured standard output and standard error are written as ``<system-out>`` and
411 ``<system-err>`` elements.
413 :param testcase: The test case to convert to XML child elements.
414 :param testcaseElement: The ``<testcase>`` element, the child elements will be added to.
415 """
416 if testcase._status is TestcaseStatus.Skipped:
417 SubElement(testcaseElement, "skipped")
418 elif testcase._status is not TestcaseStatus.Passed:
419 failureElement = SubElement(testcaseElement, "failure")
420 failureElement.attrib["type"] = "failure"
422 if testcase._message is not None:
423 failureElement.attrib["message"] = testcase._message
425 if testcase._details is not None:
426 failureElement.text = testcase._details
428 if testcase._standardOutput is not None:
429 SubElement(testcaseElement, "system-out").text = testcase._standardOutput
431 if testcase._standardError is not None:
432 SubElement(testcaseElement, "system-err").text = testcase._standardError