Skip to content

Mutation testing

mutate_module runs a module's tests against every mutant of its rules, lexical entries, and constants and reports the mutants no test rejects.

mutation

Mutation testing: perturb a module and see whether its tests notice.

A test suite proves what it rejects. mutate_module makes small changes to a module's code, one at a time, each a mutant, and runs the module's tests against every mutant:

  • drop-rule: remove one inference rule (a deduction's rule, or a top-level rule);
  • drop-entry: remove one lexical entry;
  • swap-category: give one lexical entry the category of the next entry in its lexicon with a different one;
  • constant: replace one literal in a computation, handler, or program by another value (an integer n by n + 1 and n - 1, a real c by 0 and 2c, or 1 when c is zero; a truth value by its negation).

A mutant is killed when some test fails or errs against it, survives when every test still passes, and is invalid when the compiler rejects it, so no test needs to. A surviving mutant is a change to the code that no test can tell apart from the original: either the suite misses a behavior, or the mutant is equivalent to the original.

The tests themselves are never mutated, and the module must pass its tests before any mutant runs. A module is mutated as it runs, its module graph interpreted into one flat program; the mutants change the root module's code, or the code of the imported modules named instead, so a library's rules are mutated under the tests of a module that imports it.

OPERATORS module-attribute

OPERATORS: tuple[Operator, ...] = ('drop-rule', 'drop-entry', 'swap-category', 'constant')

Every mutation operator, in the order mutants are made.

Operator

Operator = Literal['drop-rule', 'drop-entry', 'swap-category', 'constant']

How a mutant changes the code.

MutantStatus

MutantStatus = Literal['killed', 'survived', 'invalid']

What the tests made of a mutant.

Step

Step = tuple[str, int | None]

One step into an AST: a field, and an index when the field is a tuple.

Location

Location = tuple[Step, ...]

Where a node sits in a module's AST.

Mutant didactic-model

Mutant(*, index: int, operator: Operator, description: str, line: int = 0, col: int = 0, file: str = '', status: MutantStatus = 'survived', killed_by: str = '', message: str = '')

Bases: Model

One change to a module and what the tests made of it.

PARAMETER DESCRIPTION
index

Its position among the module's mutants.

TYPE: int

operator

The kind of change.

TYPE: Operator

description

The change, in words.

TYPE: str

line

The source line of the changed node, in its own file.

TYPE: int DEFAULT: 0

col

Its source column.

TYPE: int DEFAULT: 0

file

The file of the changed node.

TYPE: str DEFAULT: ''

status

killed, survived, or invalid.

TYPE: MutantStatus DEFAULT: 'survived'

killed_by

The first test that failed against it, when killed.

TYPE: str DEFAULT: ''

message

Why the test failed, or why the compiler rejected the mutant.

TYPE: str DEFAULT: ''

to_data

to_data() -> dict[str, str | int]

The mutant as JSON data.

RETURNS DESCRIPTION
dict[str, str | int]

Every field.

Source code in src/quivers/testing/mutation.py
def to_data(self) -> dict[str, str | int]:
    """The mutant as JSON data.

    Returns
    -------
    dict[str, str | int]
        Every field.
    """
    return {
        "index": self.index,
        "operator": self.operator,
        "description": self.description,
        "line": self.line,
        "col": self.col,
        "file": self.file,
        "status": self.status,
        "killed_by": self.killed_by,
        "message": self.message,
    }

MutationReport didactic-model

MutationReport(*, path: str, baseline: ModuleReport, mutants: tuple[Mutant, ...] = (), error: str = '')

Bases: Model

A module's mutants and how its tests fared against them.

PARAMETER DESCRIPTION
path

The module.

TYPE: str

baseline

The tests' report on the unmutated module.

TYPE: ModuleReport

mutants

Every mutant, in the order made.

TYPE: tuple[Mutant, ...] DEFAULT: ()

error

Why no mutant ran: the module failed to load, has no tests, or its tests do not pass as written; empty otherwise.

TYPE: str DEFAULT: ''

survivors property

survivors: tuple[Mutant, ...]

The mutants no test rejected.

RETURNS DESCRIPTION
tuple[Mutant, ...]

The survivors.

ok property

ok: bool

Whether every valid mutant was killed.

RETURNS DESCRIPTION
bool

The verdict; False when no mutant ran.

to_data

to_data() -> dict[str, str | bool | int | dict | list]

The report as JSON data.

RETURNS DESCRIPTION
dict

The counts by status, the survivors, every mutant, and the baseline.

Source code in src/quivers/testing/mutation.py
def to_data(self) -> dict[str, str | bool | int | dict | list]:
    """The report as JSON data.

    Returns
    -------
    dict
        The counts by status, the survivors, every mutant, and the
        baseline.
    """
    counts = {
        status: sum(item.status == status for item in self.mutants)
        for status in ("killed", "survived", "invalid")
    }
    valid = counts["killed"] + counts["survived"]
    data: dict[str, str | bool | int | dict | list] = {
        "path": self.path,
        "ok": self.ok,
        "counts": counts,
        "score": f"{counts['killed']}/{valid}",
        "survivors": [item.to_data() for item in self.survivors],
        "mutants": [item.to_data() for item in self.mutants],
        "baseline": self.baseline.to_data(),
    }
    if self.error:
        data["error"] = self.error
    return data

mutants_of

mutants_of(module: Module, targets: Callable[[Statement], bool] | None = None) -> Iterator[tuple[Operator, str, int, int, Module]]

Every mutant of a module's code, in source order by operator.

PARAMETER DESCRIPTION
module

The parsed module; its tests are kept unchanged in every mutant.

TYPE: Module

targets

Which top-level statements are mutated; all when None.

TYPE: Callable[[Statement], bool] | None DEFAULT: None

RETURNS DESCRIPTION
Iterator[tuple[Operator, str, int, int, Module]]

The operator, a description, the line and column, and the mutated module.

Source code in src/quivers/testing/mutation.py
def mutants_of(
    module: Module, targets: Callable[[Statement], bool] | None = None
) -> Iterator[tuple[Operator, str, int, int, Module]]:
    """Every mutant of a module's code, in source order by operator.

    Parameters
    ----------
    module : Module
        The parsed module; its tests are kept unchanged in every mutant.
    targets : Callable[[Statement], bool] | None
        Which top-level statements are mutated; all when ``None``.

    Returns
    -------
    Iterator[tuple[Operator, str, int, int, Module]]
        The operator, a description, the line and column, and the mutated
        module.
    """
    code = Module(statements=module.statements)
    nodes = [
        (location, node)
        for location, node in _walk(code)
        if targets is None
        or (
            location
            and location[0][1] is not None
            and targets(module.statements[location[0][1]])
        )
    ]
    for location, node in nodes:
        operator = _DROPPABLE.get(type(node))
        if operator is None or not location or location[-1][1] is None:
            continue
        line, col = _position(node)
        mutated = _replace(code, location, None)
        yield (
            operator,
            f"remove {_label(node)}",
            line,
            col,
            _with_code(module, mutated),
        )
    for location, node in nodes:
        if not isinstance(node, LexiconEntry):
            continue
        parent_location, (field, index) = location[:-1], location[-1]
        parent = code
        for name, position in parent_location:
            value = getattr(parent, name)
            parent = value if position is None else value[position]
        siblings: tuple[LexiconEntry, ...] = getattr(parent, field)
        if index is None:
            continue
        replacement = next(
            (
                sibling.category
                for sibling in (*siblings[index + 1 :], *siblings[:index])
                if sibling.category != node.category
            ),
            None,
        )
        if replacement is None:
            continue
        line, col = _position(node)
        mutated = _replace(code, location, node.with_(category=replacement))
        yield (
            "swap-category",
            f"give {_label(node)} the category of another entry",
            line,
            col,
            _with_code(module, mutated),
        )
    for location, node in nodes:
        if not isinstance(node, LetExprLiteral | LetExprBool):
            continue
        line, col = _position(node)
        for replacement, description in _constant_variants(node):
            mutated = _replace(code, location, replacement)
            yield (
                "constant",
                description,
                line,
                col,
                _with_code(module, mutated),
            )

mutate_module

mutate_module(path: Path, operators: tuple[Operator, ...] = OPERATORS, modules: tuple[str, ...] = ()) -> MutationReport

Run a module's tests against every mutant of its code.

PARAMETER DESCRIPTION
path

The module file.

TYPE: Path

operators

The operators whose mutants run; every operator by default.

TYPE: tuple[Operator, ...] DEFAULT: OPERATORS

modules

The module paths whose code is mutated, among those the module imports; the module's own code when empty.

TYPE: tuple[str, ...] DEFAULT: ()

RETURNS DESCRIPTION
MutationReport

Every mutant's status, and the survivors.

Source code in src/quivers/testing/mutation.py
def mutate_module(
    path: Path,
    operators: tuple[Operator, ...] = OPERATORS,
    modules: tuple[str, ...] = (),
) -> MutationReport:
    """Run a module's tests against every mutant of its code.

    Parameters
    ----------
    path : Path
        The module file.
    operators : tuple[Operator, ...]
        The operators whose mutants run; every operator by default.
    modules : tuple[str, ...]
        The module paths whose code is mutated, among those the module
        imports; the module's own code when empty.

    Returns
    -------
    MutationReport
        Every mutant's status, and the survivors.
    """
    try:
        flat = load_program(path)
    except (OSError, ParseError, ModuleError, ValueError) as error:
        return MutationReport(
            path=str(path),
            baseline=ModuleReport(path=str(path), error=str(error)),
            error=str(error),
        )
    parsed = flat.module
    try:
        targets = _targets(flat, modules)
    except ValueError as error:
        return MutationReport(
            path=str(path),
            baseline=ModuleReport(path=str(path), error=str(error)),
            error=str(error),
        )
    try:
        checked = check_module(parsed, str(path))
    except Exception as error:  # noqa: BLE001 - every compile failure is reported
        message = f"{type(error).__name__}: {error}"
        return MutationReport(
            path=str(path),
            baseline=ModuleReport(path=str(path), error=message),
            error=message,
        )
    baseline = ModuleReport(
        path=str(path),
        digest=checked.digest,
        results=tuple(run_test(checked, test) for test in parsed.tests),
    )
    if not parsed.tests:
        return MutationReport(
            path=str(path), baseline=baseline, error="the module declares no tests"
        )
    if not baseline.ok:
        return MutationReport(
            path=str(path),
            baseline=baseline,
            error="the module's tests do not pass as written, so no mutant can be judged",
        )

    def chosen(statement: Statement) -> bool:
        line = getattr(statement, "line", 0)
        return flat.source_map.module_at(int(line)) in targets

    mutants: list[Mutant] = []
    selected = (item for item in mutants_of(parsed, chosen) if item[0] in operators)
    for index, (operator, description, line, col, mutated) in enumerate(selected):
        judged = _judge(index, operator, description, line, col, mutated, str(path))
        located = flat.source_map.locate(line, col)
        if located is not None:
            judged = judged.with_(file=located.file, line=located.line)
        mutants.append(judged)
    return MutationReport(path=str(path), baseline=baseline, mutants=tuple(mutants))