Coverage for trlcdoc/testrun.py: 99%
144 statements
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-28 14:00 +0000
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-28 14:00 +0000
1"""Run the tests and convert the JUnit XML results into TRLC test result records."""
3# trlcdoc - A utility for producing project documentation from TRLC and LOBSTER contents.
4# Copyright (c) 2026 - 2026 Norbert Schulz github@schulznorbert.de
5#
6# This file is part of trlcdoc program.
7#
8# The trlcdoc program is free software: you can redistribute it and/or modify it under
9# the terms of the GNU General Public License as published by the Free Software Foundation,
10# either version 3 of the License, or (at your option) any later version.
11#
12# The trlcdoc program is distributed in the hope that it will be useful, but
13# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License along with pyTRLCConverter.
17# If not, see <https://www.gnu.org/licenses/>.
19# Imports **********************************************************************
21import logging
22import re
23import sys
24import time
25import xml.etree.ElementTree as ET
26from pathlib import Path
27from re import Pattern
28from typing import Any
30from .config import Config
31from .log import TRACE
32from .util import TrlcdocError, clean_dir, run_unchecked
34# Variables ********************************************************************
36RESULTS_FILE = "sw_test_result_report.trlc"
38LOG = logging.getLogger(__name__)
40# pytest exit codes: 0 = all passed, 1 = some tests failed.
41PYTEST_OK_CODES = (0, 1)
43# Qualified TRLC record id 'Package.record' for the {id} placeholder of tests.link.output.
44QUALIFIED_ID = r"(?P<id>[A-Za-z_][A-Za-z0-9_]*\.[A-Za-z_][A-Za-z0-9_]*)"
46# Unity test output line, e.g. 'test/test_a.c:12:test_a:INFO: lobster-trace: SwTests.tc_a'.
47UNITY_OUTPUT = re.compile(r"^(?P<file>.+?):(?P<line>\d+):(?P<test>[^:\s]+):(?P<level>[A-Z]+):\s*(?P<message>.*)$")
49# Seconds a coverage report written by the test command may seem older than its start,
50# for file systems with coarse modification times.
51MTIME_TOLERANCE = 2.0
53# Classes **********************************************************************
55# Functions ********************************************************************
58def run_tests(cfg: Config) -> bool:
59 # lobster-trace: SwRequirements.sw_req_test_run
60 """Run the tests and create the TRLC test result records.
62 Args:
63 cfg (Config): Project configuration with a tests section.
65 Returns:
66 bool: True if all tests passed.
68 Raises:
69 TrlcdocError: If the tests could not be executed.
70 """
71 tests = cfg.tests
72 clean_dir(cfg.tests_dir, cfg.output)
73 LOG.debug("Test runner %s, JUnit XML file %s", tests["runner"], cfg.junit_file)
75 match tests["runner"]:
76 case "pytest":
77 args = list(tests.get("args", []))
78 cmd = [sys.executable, "-m", "pytest", *args, "-o", "junit_family=xunit1", f"--junitxml={cfg.junit_file}"]
79 if any(arg.startswith("--cov") for arg in args):
80 cmd.extend(["--cov-report=term", f"--cov-report=html:{cfg.coverage_dir}"])
81 # Keep the coverage data file in the output folder instead of the project root.
82 returncode = run_unchecked(cmd, cfg.root, {"COVERAGE_FILE": str(cfg.tests_dir / ".coverage")})
83 if returncode not in PYTEST_OK_CODES:
84 raise TrlcdocError(f"pytest could not run the tests (exit code {returncode}).")
86 case "command":
87 # The exit code of a test command is ignored, so a command that fails must not leave the
88 # results of a previous run behind: they would be reported as the current ones.
89 cfg.junit_file.unlink(missing_ok=True)
90 started = time.time()
91 run_unchecked(tests["command"], cfg.root, source="tests.command")
92 coverage_index = cfg.coverage_dir / "index.html"
93 if "coverage" in tests and (
94 not coverage_index.is_file() or coverage_index.stat().st_mtime < started - MTIME_TOLERANCE
95 ):
96 raise TrlcdocError(f"Coverage report {coverage_index} was not created by the test command.")
98 if not cfg.junit_file.is_file():
99 raise TrlcdocError(f"Test result file {cfg.junit_file} was not created.")
101 results = read_junit(cfg.junit_file, tests["link"])
102 for name, passed, test_cases in results:
103 LOG.log(TRACE, "Test %s: %s, test cases %s", name, "passed" if passed else "failed", ", ".join(test_cases))
104 write_results(results, clean_dir(cfg.test_results_dir, cfg.output) / RESULTS_FILE, tests["link"])
106 failed = [name for name, passed, _ in results if not passed]
107 LOG.info("Tests: %d results, %d failed.", len(results), len(failed))
108 for name in failed:
109 LOG.info(" FAILED: %s", name)
110 return not failed
113def read_junit(junit_file: Path, link: dict[str, Any]) -> list[tuple[str, bool, list[str]]]:
114 # lobster-trace: SwRequirements.sw_req_test_results
115 """Read the test results and link them to their TRLC test cases.
117 Skipped tests have no result and are not part of the list.
119 Args:
120 junit_file (Path): JUnit XML file.
121 link (dict[str, Any]): The tests.link configuration.
123 Returns:
124 list[tuple[str, bool, list[str]]]: (test name, passed, qualified test case ids) per test.
126 Raises:
127 TrlcdocError: If a test cannot be linked to a test case, or to several
128 test cases while tests.link.array is not set.
129 """
130 results: list[tuple[str, bool, list[str]]] = []
131 unlinked: list[str] = []
132 ambiguous: list[str] = []
133 for suite in ET.parse(junit_file).getroot().iter("testsuite"):
134 suite_ids = _suite_output_ids(suite, link)
135 for testcase in suite.findall("testcase"):
136 name = testcase.get("name", "")
137 skipped = testcase.find("skipped") is not None
138 if not skipped:
139 passed = testcase.find("failure") is None and testcase.find("error") is None
140 test_case_ids = _linked_test_cases(testcase, link, suite_ids.get(name, []))
141 if not test_case_ids:
142 unlinked.append(name)
143 elif len(test_case_ids) > 1 and not link.get("array", False):
144 ambiguous.append(name)
145 else:
146 results.append((name, passed, test_case_ids))
148 if unlinked:
149 raise TrlcdocError(f"Tests without test case link ({_link_methods(link)}): {', '.join(unlinked)}")
150 if ambiguous:
151 raise TrlcdocError(f"Tests linked to several test cases, which needs tests.link.array: {', '.join(ambiguous)}")
152 return results
155def _link_methods(link: dict[str, Any]) -> str:
156 # lobster-trace: SwRequirements.sw_req_test_results
157 """Describe the configured link methods for an error message.
159 Args:
160 link (dict[str, Any]): The tests.link configuration.
162 Returns:
163 str: The link methods, e.g. "property 'lobster-trace', output 'lobster-trace: {id}'".
164 """
165 methods = [f"property '{link.get('property', 'lobster-trace')}'"]
166 if "output" in link:
167 methods.append(f"output '{link['output']}'")
168 if "from" in link:
169 methods.append(f"name pattern '{link['from']}'")
170 return ", ".join(methods)
173def _output_regex(link: dict[str, Any]) -> Pattern[str] | None:
174 # lobster-trace: SwRequirements.sw_req_test_results
175 """Compile the tests.link.output pattern.
177 Args:
178 link (dict[str, Any]): The tests.link configuration.
180 Returns:
181 Pattern[str] | None: Regular expression with the group 'id', None without output link.
182 """
183 result = None
184 if "output" in link:
185 result = re.compile(re.escape(link["output"]).replace(re.escape("{id}"), QUALIFIED_ID))
186 return result
189def _output_ids(lines: list[str], regex: Pattern[str]) -> list[str]:
190 # lobster-trace: SwRequirements.sw_req_test_results
191 """Find the test case ids in output lines.
193 Args:
194 lines (list[str]): Output lines.
195 regex (Pattern[str]): Compiled tests.link.output pattern.
197 Returns:
198 list[str]: The test case ids in order of appearance.
199 """
200 return [match.group("id") for match in (regex.search(line) for line in lines) if match is not None]
203def _system_out(element: ET.Element) -> list[str]:
204 # lobster-trace: SwRequirements.sw_req_test_results
205 """Get the lines of the system-out elements directly below an element.
207 Args:
208 element (ET.Element): JUnit testsuite or testcase element.
210 Returns:
211 list[str]: The output lines.
212 """
213 return [line.strip() for out in element.findall("system-out") for line in (out.text or "").splitlines()]
216def _suite_output_ids(suite: ET.Element, link: dict[str, Any]) -> dict[str, list[str]]:
217 # lobster-trace: SwRequirements.sw_req_test_results
218 """Get the test case ids of the suite output per test.
220 Only lines in Unity format '<file>:<line>:<test>:<level>: <message>' are used, the test name
221 assigns them to the test.
223 Args:
224 suite (ET.Element): JUnit testsuite element.
225 link (dict[str, Any]): The tests.link configuration.
227 Returns:
228 dict[str, list[str]]: Test case ids per test name, empty without output link.
229 """
230 result: dict[str, list[str]] = {}
231 regex = _output_regex(link)
232 if regex is not None:
233 for line in _system_out(suite):
234 unity = UNITY_OUTPUT.match(line)
235 if unity is not None:
236 result.setdefault(unity.group("test"), []).extend(_output_ids([unity.group("message")], regex))
237 return result
240def _linked_test_cases(testcase: ET.Element, link: dict[str, Any], suite_ids: list[str]) -> list[str]:
241 # lobster-trace: SwRequirements.sw_req_test_results
242 """Get the qualified TRLC test case ids of a JUnit test case.
244 The link methods are tried in this order: property, test output, name pattern.
246 Args:
247 testcase (ET.Element): JUnit testcase element.
248 link (dict[str, Any]): The tests.link configuration.
249 suite_ids (list[str]): Test case ids of this test in the suite output.
251 Returns:
252 list[str]: The test case ids without duplicates, empty if the test cannot be linked.
253 """
254 property_name = link.get("property", "lobster-trace")
255 result = [prop.get("value", "") for prop in testcase.iter("property") if prop.get("name") == property_name]
257 regex = _output_regex(link)
258 if not result and regex is not None:
259 result = _output_ids(_system_out(testcase), regex) + suite_ids
261 if not result and "from" in link:
262 # Remove pytest parametrization, e.g. test_foo[1-2] -> test_foo.
263 name = testcase.get("name", "").split("[")[0]
264 pattern = "^" + re.escape(link["from"]).replace(re.escape("{name}"), r"(?P<name>\w+)") + "$"
265 match = re.match(pattern, name)
266 if match is not None:
267 result = [link["to"].format(name=match.group("name"))]
268 return list(dict.fromkeys(result))
271def _results_package(results: list[tuple[str, bool, list[str]]]) -> str:
272 # lobster-trace: SwRequirements.sw_req_test_results
273 """Get the package of the linked test cases, which is the package of the result records.
275 Args:
276 results (list[tuple[str, bool, list[str]]]): (test name, passed, qualified test case ids) per test.
278 Returns:
279 str: The package name.
281 Raises:
282 TrlcdocError: If there is no linked test case, a test case id is not qualified, or the
283 test cases belong to several packages.
284 """
285 packages: dict[str, list[str]] = {}
286 unqualified: list[str] = []
287 for name, _, test_case_ids in results:
288 for test_case_id in test_case_ids:
289 if "." in test_case_id:
290 packages.setdefault(test_case_id.split(".")[0], []).append(name)
291 else:
292 unqualified.append(f"{name} ({test_case_id})")
294 if unqualified:
295 raise TrlcdocError(f"Tests linked to test case ids without package: {', '.join(unqualified)}")
296 if not packages:
297 raise TrlcdocError("No test linked to a test case, the package of the test results is unknown.")
298 if len(packages) > 1:
299 details = "; ".join(f"{package}: {', '.join(dict.fromkeys(names))}" for package, names in packages.items())
300 raise TrlcdocError(f"Tests linked to test cases of several packages: {details}")
301 return next(iter(packages))
304def write_results(results: list[tuple[str, bool, list[str]]], trlc_file: Path, link: dict[str, Any]) -> Path:
305 # lobster-trace: SwRequirements.sw_req_test_results
306 """Write the test results as TRLC SwTestCaseResult records.
308 The records are written into the package of the linked test cases.
310 Args:
311 results (list[tuple[str, bool, list[str]]]): (test name, passed, qualified test case ids) per test.
312 trlc_file (Path): TRLC file to write.
313 link (dict[str, Any]): The tests.link configuration. With 'array' the relates
314 component is written as list, otherwise as single reference.
316 Returns:
317 Path: The written file.
319 Raises:
320 TrlcdocError: If the package of the test cases cannot be determined.
321 """
322 package = _results_package(results)
323 used_ids: dict[str, int] = {}
324 with open(trlc_file, "w", encoding="utf-8") as file:
325 file.write(f"package {package}\n\n")
326 file.write('section "SW Test Results" {\n\n')
327 for name, passed, test_case_ids in results:
328 record_id = re.sub(r"\W", "_", name) + "_result"
329 used_ids[record_id] = used_ids.get(record_id, 0) + 1
330 if used_ids[record_id] > 1:
331 record_id += f"_{used_ids[record_id]}"
332 result = "PASSED" if passed else "FAILED"
333 file.write(f" SwTestCaseResult {record_id} {{\n")
334 file.write(f' name = "{name}"\n')
335 file.write(f" result = SwTestResult.{result}\n")
336 relates = f"[{', '.join(test_case_ids)}]" if link.get("array", False) else test_case_ids[0]
337 file.write(f" relates = {relates}\n")
338 file.write(" }\n\n")
339 file.write("}\n")
340 return trlc_file
343# Main *************************************************************************