Files

55 lines
2.7 KiB
Python

"""The setup.cfg that has mutmut mutate a branch's changed files, and the tests left out because they fail before any mutant."""
import configparser
import io
import re
from failure import Failure
SUMMARY = re.compile(r"^=+ short test summary info =+$", re.MULTILINE)
# A line of pytest's short summary for a test that failed or errored; the test's message, where it fits, follows " - ". A failed subtest's line
# names its test after a description in [] or (), which may hold spaces, and pytest reports no line for the test itself.
REPORTED = re.compile(r"^(?:(?:ERROR|FAILED) (\S.*?)|SUBFAILED.*?[\])] (\S+::\S+))(?: - .*)?$", re.MULTILINE)
class CaseKept(configparser.ConfigParser):
"""Keeps each key as written, since the project's other sections are copied over unchanged."""
def optionxform(self, optionstr: str) -> str:
return optionstr
def mutmut_config(existing: str, sources: list[str], copied: list[str], left: list[str]) -> str | Failure:
"""The setup.cfg that has mutmut mutate the sources, copy every entry of the folder, which the sources' tests import, and pass pytest the options that leave tests out.
copied names each file and folder at the folder's top. Not ".": mutmut makes mutants/ before it copies, so "." would copy mutants/ into itself and
pytest would collect the tests twice. existing is the project's own setup.cfg, empty where it has none. Its settings stay, though its comments go, and its [mutmut] pytest_add_cli_args come before the options that leave tests out."""
config = CaseKept(interpolation=None)
try:
config.read_string(existing)
except configparser.Error as failure:
return Failure(f"could not read setup.cfg: {failure}")
if not config.has_section("mutmut"):
config.add_section("mutmut")
section = config["mutmut"]
section["source_paths"] = listed(sources)
section["also_copy"] = listed(copied)
if left:
section["pytest_add_cli_args"] = "\n".join(filter(None, [section.get("pytest_add_cli_args", ""), listed(left)]))
written = io.StringIO()
config.write(written)
return written.getvalue()
def listed(items: list[str]) -> str:
"""Items as a [mutmut] list, one per line, each % doubled: mutmut 3 reads setup.cfg with configparser's default interpolation."""
return "\n".join(item.replace("%", "%%") for item in items)
def left_out(output: str) -> list[str]:
"""The pytest options that leave out each test a failed run's short summary reports: --deselect for a test, --ignore for a file that failed to collect."""
summary = SUMMARY.split(output)
if len(summary) < 2:
return []
nodeids = dict.fromkeys(test or subtests_test for test, subtests_test in REPORTED.findall(summary[-1]))
return [f"--deselect={nodeid}" if "::" in nodeid else f"--ignore={nodeid}" for nodeid in nodeids]