Files
claude-config/bin/mutate_changes/mutmut_setup.py
T

59 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 os
import re
from failure import Failure
SUMMARY = re.compile(r"^=+ short test summary info =+$", re.MULTILINE)
# A test pytest's short summary reports as failed or erroring; its message, where one fits, follows " - ".
REPORTED = re.compile(r"^(?:ERROR|FAILED) (\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], left: list[str]) -> str | Failure:
"""The setup.cfg that has mutmut mutate the sources, copy the rest of the folder, which their tests import, and pass pytest the options that leave tests out.
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"] = "."
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 nodeid of each test, or test file that failed to collect, that a failed run's short summary reports."""
summary = SUMMARY.split(output)
return REPORTED.findall(summary[-1]) if len(summary) > 1 else []
def leaving_out(nodeids: list[str], copy: str) -> list[str]:
"""The pytest options that leave out each nodeid: --deselect for a test, --ignore for a file.
mutmut 3.8.1 runs pytest in copy's mutants/ folder, yet pytest 9.2 reports each nodeid from copy, as mutants/<path>. --deselect takes the
nodeid as reported, and --ignore an absolute path, built the same way whether or not the nodeid starts with mutants/."""
return [f"--deselect={nodeid}" if "::" in nodeid else f"--ignore={os.path.join(copy, 'mutants', nodeid.removeprefix('mutants/'))}" for nodeid in nodeids]