Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# mutator

Mutation testing for Clojure, Java, Go, TypeScript, Rust, Python, and Swift. One run detects the language of each source file, applies that language's mutation rules, and writes the snapshot [uml-viewer](https://github.com/unclebob/uml-viewer) already reads.
Mutation testing for Clojure, Java, Go, TypeScript, Rust, Python, Dart, and Swift. One run detects the language of each source file, applies that language's mutation rules, and writes the snapshot [uml-viewer](https://github.com/unclebob/uml-viewer) already reads.

Clojure follows [clj-mutate](https://github.com/unclebob/clj-mutate). Go follows [mutate4go](https://github.com/unclebob/mutate4go). Java follows [mutate4java](https://github.com/unclebob/mutate4java). TypeScript, Rust, and Python use the same decisions as Java, spelled in that language. Function names and namespaces come from [crapper](https://github.com/unclebob/crapper), which is what uml-viewer joins to `.metrics/crap.edn`.
Clojure follows [clj-mutate](https://github.com/unclebob/clj-mutate). Go follows [mutate4go](https://github.com/unclebob/mutate4go). Java follows [mutate4java](https://github.com/unclebob/mutate4java). TypeScript, Rust, Python, and Dart use the same decisions as Java, spelled in that language. Function names and namespaces come from [crapper](https://github.com/unclebob/crapper), which is what uml-viewer joins to `.metrics/crap.edn`.

A mutant is killed when the tests fail or time out. It survives when the tests still pass. A worker that cannot run the tests on the unmutated source is not a kill. That run stops the way a failed baseline does, and the snapshot is left as it was. A site on a line the coverage report does not hit is uncovered and is not run. The score uml-viewer paints is killed / (killed + survived).

Expand Down Expand Up @@ -85,9 +85,10 @@ uml-viewer loads every `*.edn` file under `.metrics/mutate`. Each file is one na
| TypeScript | the dotted module path, or `module.Class` | the function or method name |
| Rust | `crate::module`, or `crate::module::Type` | the function or method name |
| Python | the dotted module path, or `module.Class` | the function or method name |
| Dart | the package name plus the path under `lib/`, or `module.Type` | the function or method name; `size` / `size=` for a getter / setter, `operator +`, a factory's name |
| Swift | the module, or `Module.Type` | the function, method, initializer, or stored closure |

`defn-` is Clojure's private form. Elsewhere a private method, an unexported Go function, a Python name that starts with `_`, a Rust function that is not `pub`, a TypeScript `private` / `#` name, or a Swift `private` / `fileprivate` declaration uses `defn-/`. A closure that crapper does not report as its own entry, including a closure stored in a local `let`, is attributed to the enclosing function.
`defn-` is Clojure's private form. Elsewhere a private method, an unexported Go function, a Python or Dart name that starts with `_`, a Rust function that is not `pub`, a TypeScript `private` / `#` name, or a Swift `private` / `fileprivate` declaration uses `defn-/`. A closure that crapper does not report as its own entry, including a closure stored in a local `let`, is attributed to the enclosing function.

## What each language mutates

Expand All @@ -101,6 +102,7 @@ Tokens inside strings, comments, and quoted Clojure forms are left alone. A repl
| TypeScript | the Java set, plus `===`/`!==`, `??` to `||`, and `?.` to `.`. A call or index drops `?.` (`a?.()` becomes `a()`). `.js`, `.jsx`, `.mjs`, and `.cjs` use these rules. |
| Rust | the Java set (`&&`/`||`, `!`, unary `-`). |
| Python | the Java set, spelled `and`/`or`, `not`, and `True`/`False`. |
| Dart | the Java set. Null safety (`?.`, `??`, the `x!` assertion), `%`, `~/`, `is`, and `as` are left alone. Types, annotations, and string text are skipped; code inside `${}` is mutated. Generative constructors are not entries; factory constructors are, matching crapper. |
| Swift | the Java set, plus `===`/`!==` and `??` to `||`. A boolean condition of `if`, `guard`, `while`, or `repeat-while` is wrapped in `!()`. Comma-separated conditions are each negated. A `let` or `var` binding is not. Logical `!` and unary `-` are deleted. Force-unwrap `!` is left alone. Statements and `return`s are not deleted; the other languages do not delete them either. |

Swift does not mutate `?.`. The `?` on an optional type is not an operator. `if case` is not split by the grammar crapper uses, so that statement contributes no sites.
Expand All @@ -117,8 +119,11 @@ The baseline command has to pass before any mutant runs. A mutant's timeout is t
| TypeScript | `npm test` | nearest `package.json` |
| Rust | `cargo test` | nearest `Cargo.toml` |
| Python | the project's `.venv` or `venv` Python running `pytest`, or `unittest discover` | nearest project file |
| Dart | `flutter test` when `pubspec.yaml` depends on `sdk: flutter`, otherwise `dart test` | nearest `pubspec.yaml` |
| Swift | `swift test` when a `Package.swift` contains the file. Otherwise `xcodebuild test` for the nearest `.xcworkspace` or `.xcodeproj` | the package directory, or the directory that holds the Xcode project |

Dart coverage is LCOV from `flutter test --coverage` or `dart test --coverage-path`, read the way crapper reads it, including each package's `coverage/lcov.info`. The Dart VM records a function's first line and its calls, not every statement: `return 1;` usually has no hit count. A line with no record takes the hit of the closest recorded line above it, so a mutant inside a function that ran is run. A branch that never ran in a function that did is run too and survives; read Dart survivors with that in mind. Each mutant reruns the package's tests, and a Flutter test run takes seconds even for a small package, so start with one file. `flutter` must be on `PATH`; when it is not, the baseline fails and no mutant runs.

`--xcode-scheme` sets the Xcode scheme. Without it, the run uses the first shared scheme, or the project name when the project has no shared scheme. `--xcode-destination` is the `xcodebuild -destination` value, passed as one argument. An iOS run needs it, for example `platform=iOS Simulator,name=iPhone 16`. iOS and Xcode tests run only on a Mac with Xcode. A file inside a SwiftPM package is tested with `swift test` even when an Xcode project is also in the tree.

```bash
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[project]
name = "mutator"
version = "0.1.0"
description = "Mutation testing for Clojure, Java, Go, TypeScript, Rust, Python, and Swift, in the snapshot uml-viewer reads."
description = "Mutation testing for Clojure, Java, Go, TypeScript, Rust, Python, Dart, and Swift, in the snapshot uml-viewer reads."
readme = "README.md"
license = { file = "LICENSE" }
classifiers = ["License :: OSI Approved :: Zero-Clause BSD (0BSD)"]
Expand Down
5 changes: 3 additions & 2 deletions src/mutator/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@ def _test_directory_text() -> str:
HELP = f"""\
Usage: mutator [options] [path-or-filter ...]

Discover mutation sites in Clojure, Java, Go, TypeScript, Rust, Python, and Swift,
run the project's tests against each one, and write `.metrics/mutate` for
Discover mutation sites in Clojure, Java, Go, TypeScript, Rust, Python, Dart,
and Swift, run the project's tests against each one, and write `.metrics/mutate` for
uml-viewer. Namespaces and function names are the ones crapper writes into
`.metrics/crap.edn`.

Expand Down Expand Up @@ -153,6 +153,7 @@ def _test_directory_text() -> str:
TypeScript npm run coverage, Vitest, or c8
Rust cargo llvm-cov or cargo tarpaulin
Python coverage.py LCOV
Dart flutter test --coverage, or dart test --coverage-path
Swift swift test --enable-code-coverage, then llvm-cov JSON;
or xcodebuild test and xcrun xccov view --report --json

Expand Down
55 changes: 55 additions & 0 deletions src/mutator/coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,59 @@ def _go_lines(root: Path, profile, source_path: str) -> set[int] | None:
return covered


def _dart_ranges(source: str) -> tuple[list[tuple[int, int]], list[tuple[int, int]]]:
"""Line spans of function bodies and of the blocks inside them."""

crapper = ensure_crapper()
_data, tree = crapper.languages.treesitter.parse(source, "dart")
bodies, blocks = [], []
stack = [tree.root_node]
while stack:
node = stack.pop()
span = (node.start_point[0] + 1, node.end_point[0] + 1)
if node.type == "function_body":
bodies.append(span)
elif node.type == "block":
blocks.append(span)
stack.extend(node.children)
return bodies, blocks


def _borrowed_hit(line: int, records: dict[int, tuple[int, int]], bodies, blocks) -> bool:
"""The closest record above `line` in its function body, skipping records
inside blocks that closed before `line`."""

body = next(((start, end) for start, end in bodies if start <= line <= end), None)
if body is None:
return False
closed = [(start, end) for start, end in blocks if end < line]
for number in range(line - 1, body[0] - 1, -1):
if number in records and not any(start < number <= end for start, end in closed):
return records[number][0] > 0
return False


def _dart_lines(lines: dict[int, tuple[int, int]] | None, source_path: Path) -> set[int] | None:
"""The Dart VM marks a function's first line and its calls, not `return 1;`.
A line with no record borrows the hit of the closest record above it in the
same function, never one from a block that already closed. An `else` block
with no record of its own borrows its `if` line."""

if lines is None:
return None
source = source_path.read_text(encoding="utf-8", errors="replace")
bodies, blocks = _dart_ranges(source)
covered: set[int] = set()
for number in range(1, len(source.splitlines()) + 1):
if number in lines:
hit = lines[number][0] > 0
else:
hit = _borrowed_hit(number, lines, bodies, blocks)
if hit:
covered.add(number)
return covered


def covered_lines(root: Path, source_path: Path, language: str) -> set[int] | None:
"""Lines with a hit, or None when this file is absent from coverage."""

Expand All @@ -256,6 +309,8 @@ def covered_lines(root: Path, source_path: Path, language: str) -> set[int] | No
bundle = crapper.coverage.load_bundle(root)
if language == "go":
return _go_lines(root, bundle.go_profile, path)
if language == "dart":
return _dart_lines(_lookup(bundle.lcov, path), source_path)
if language == "swift":
return _swift_lines(bundle, path)
if language == "clojure":
Expand Down
1 change: 1 addition & 0 deletions src/mutator/crapper_link.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ def ensure_crapper():
sys.path.insert(0, str(sibling))
import crapper
import crapper.coverage
import crapper.dart_coverage
import crapper.discover
import crapper.languages
import crapper.languages.treesitter
Expand Down
2 changes: 2 additions & 0 deletions src/mutator/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ def is_private(language: str, name: str, source: str, start: int, end: int) -> b
return re.match(r"pub\s", header) is None
if language == "typescript":
return _typescript_private(name, header)
if language == "dart":
return name.startswith("_")
if language == "swift":
return _swift_private(header)
return False
Expand Down
7 changes: 7 additions & 0 deletions src/mutator/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,12 @@ def _python_plan(root: Path, source: Path) -> tuple[Command, Path]:
return _python_command(directory), directory


def _dart_plan(root: Path, source: Path) -> tuple[Command, Path]:
directory = _nearest_marker(source, root, ("pubspec.yaml",))
flutter = ensure_crapper().dart_coverage.is_flutter(directory)
return ["flutter" if flutter else "dart", "test"], directory


def _xcode_flag(project: Path) -> str:
if project.suffix == ".xcworkspace":
return "-workspace"
Expand Down Expand Up @@ -286,6 +292,7 @@ def _swift_plan(
"typescript": _typescript_plan,
"rust": _rust_plan,
"python": _python_plan,
"dart": _dart_plan,
}


Expand Down
83 changes: 75 additions & 8 deletions src/mutator/sites.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
"""Find mutation sites.

Clojure follows clj-mutate's symbol rules. Go follows mutate4go, including
one-way `*` to `/`. Java follows mutate4java. TypeScript, Rust, Python, and
Swift use the same decisions as Java, spelled in that language. TypeScript
also mutates `??` to `||` and `?.` to `.` (removed on a call or index).
Swift mutates `??` to `||` and wraps a boolean condition of `if`, `guard`,
`while`, or `repeat-while` in `!()`. JavaScript files use the TypeScript rules.
one-way `*` to `/`. Java follows mutate4java. TypeScript, Rust, Python, Dart,
and Swift use the same decisions as Java, spelled in that language. Dart
leaves null safety (`?.`, `??`, `x!`), `%`, `~/`, `is`, and `as` alone. Swift
mutates `??` to `||` and wraps a boolean condition of `if`, `guard`, `while`,
or `repeat-while` in `!()`. TypeScript also mutates `??` to `||` and `?.` to
`.` (removed on a call or index). JavaScript files use the TypeScript rules.
"""

from __future__ import annotations
Expand Down Expand Up @@ -41,13 +42,25 @@
"multiplicative_expression",
"comparison_expression",
"equality_expression",
"infix_expression",
"conjunction_expression",
"disjunction_expression",
"infix_expression",
"nil_coalescing_expression",
# Dart wraps some operator tokens in their own node.
"multiplicative_operator",
"relational_operator",
"logical_and_operator",
"logical_or_operator",
}

_UNARY_PARENTS = {"unary_expression", "unary_operator", "not_operator", "prefix_expression"}
_UNARY_PARENTS = {
"unary_expression",
"unary_operator",
"not_operator",
"prefix_expression",
"negation_operator",
"prefix_operator",
}

# Boolean conditions. A `let` binding is not one of them. `repeat-while` puts
# the condition after the body; the others put it before.
Expand Down Expand Up @@ -228,6 +241,54 @@ def _statement_line(node) -> int:
}


# Dart types, annotations, and type tests never run. Code inside `${}` does.
_DART_SKIPPED = {"type_arguments", "annotation", "type_test", "type_cast"}


def _has_operator(expression, token: bytes, following: str | None = None) -> bool:
for child in expression.children:
if child.type != "relational_operator" or child.text != token:
continue
after = child.next_sibling
if following is None or (after is not None and after.type == following):
return True
return False


def _misread_generic(expression) -> bool:
"""tree-sitter reads `Future<void>.delayed(d)` as `Future < void > .delayed(d)`:
a `<` on the left, then `>` followed by `.name`."""

if expression is None or expression.type != "relational_expression":
return False
left = expression.children[0]
if left.type != "relational_expression" or not _has_operator(left, b"<"):
return False
return _has_operator(expression, b">", "dot_shorthand")


def _generic_type(node) -> bool:
operator = node.parent
if operator is None or operator.type != "relational_operator":
return False
return _misread_generic(operator.parent) or _misread_generic(operator.parent.parent)


def _dart_skipped(node) -> bool:
if _generic_type(node):
return True
current = node.parent
while current is not None:
if current.type in _DART_SKIPPED:
return True
if current.type == "template_substitution":
return False
if current.type == "string_literal":
return True
current = current.parent
return False


def _in_type(node) -> bool:
current = node.parent
while current is not None:
Expand All @@ -237,6 +298,12 @@ def _in_type(node) -> bool:
return False


def _skipped(node, language: str) -> bool:
if language == "typescript":
return _in_type(node)
return language == "dart" and _dart_skipped(node)


def _clojure_head(node, data: bytes) -> str | None:
for child in node.children:
if child.type == "sym_lit":
Expand Down Expand Up @@ -407,7 +474,7 @@ def _visit_swift_conditions(node, data: bytes, found: list[RawSite]) -> None:


def _visit_node(node, data: bytes, language: str, found: list[RawSite]) -> None:
if language == "typescript" and _in_type(node):
if _skipped(node, language):
return
if language == "swift":
_visit_swift_conditions(node, data, found)
Expand Down
16 changes: 16 additions & 0 deletions src/mutator/sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
(``Tests``, ``AppTests``) is a test target at any depth, and so is a file
named ``*Tests.swift``. ``.build``, ``.swiftpm``, and ``DerivedData`` are
crapper SKIP_DIRS.

Dart skips ``integration_test`` and ``test_driver`` at any depth for ``.dart``
files (from crapper's DART_TEST_DIRS), along with ``*_test.dart``, generated
Dart suffixes, and ``.dart_tool``.
"""

from __future__ import annotations
Expand Down Expand Up @@ -46,6 +50,14 @@ def _swift_test_relative(relative: Path) -> bool:
return any(part.endswith("Tests") for part in relative.parts[:-1])


def _dart_test_relative(relative: Path, dart_test_dirs: set[str]) -> bool:
"""Dart integration and driver test directories apply only to `.dart` files."""

if relative.suffix != ".dart":
return False
return any(part in dart_test_dirs for part in relative.parts[:-1])


def _relative_to(path: Path, root: Path) -> Path | None:
try:
return path.resolve().relative_to(root.resolve())
Expand All @@ -65,6 +77,8 @@ def is_mutable_source(path: Path, root: Path, crapper) -> bool:
return False
if _swift_test_relative(relative):
return False
if _dart_test_relative(relative, set(crapper.discover.DART_TEST_DIRS)):
return False
return not crapper.discover.is_test_file(path.name)


Expand All @@ -76,6 +90,8 @@ def is_skipped_test(path: Path, root: Path, crapper) -> bool:
return True
if relative is not None and _swift_test_relative(relative):
return True
if relative is not None and _dart_test_relative(relative, set(crapper.discover.DART_TEST_DIRS)):
return True
return crapper.discover.is_test_file(path.name)


Expand Down
Loading