Merge Swift mutation testing.

Swift uses the same operator decisions as Java, plus ?? and negation of
boolean conditions. swift test runs a package. xcodebuild runs an Xcode
or iOS project from the working directory, and the worker keeps a real
copy of the project so the mutant is what gets compiled.

Co-authored-by: Robert C. Martin <[email protected]>
This commit is contained in:
Cursor Agent
2026-11-26 01:04:35 +00:00
co-authored by Robert C. Martin
14 changed files with 1046 additions and 24 deletions
+15 -4
View File
@@ -1,6 +1,6 @@
# mutator
Mutation testing for Clojure, Java, Go, TypeScript, Rust, and Python. 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, 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`.
@@ -14,7 +14,7 @@ A mutant is killed when the tests fail or time out. It survives when the tests s
The first run creates `.venv` and installs the tool. crapper has to be checked out next to this directory (`../crapper`), because that is where the namespace and function names come from. From a project root the tool walks the tree and writes `.metrics/mutate/<namespace>.edn`.
Directories such as `vendor`, `node_modules`, `target`, `build`, and `testdata` are skipped at any depth. A test directory (`test`, `tests`, `spec`, `specs`, or `__tests__`) is skipped when it is the first component of the path, and so is `src/test` and `src/tests`. A deeper directory with one of those names, such as `src/pkg/test`, is mutated. Files whose names mark them as tests, such as `test_foo.py`, `foo_test.go`, or `foo.test.ts`, are also skipped.
Directories such as `vendor`, `node_modules`, `target`, `build`, `.build`, `.swiftpm`, `DerivedData`, and `testdata` are skipped at any depth. A test directory (`test`, `tests`, `spec`, `specs`, or `__tests__`) is skipped when it is the first component of the path, and so is `src/test` and `src/tests`. A deeper directory with one of those names, such as `src/pkg/test`, is mutated. Files whose names mark them as tests, such as `test_foo.py`, `foo_test.go`, or `foo.test.ts`, are also skipped. Swift also skips a directory whose name ends with `Tests` (`Tests`, `AppTests`) at any depth, and a file named `*Tests.swift`.
The first run of a tree executes every covered mutant. Start with the file you are working on.
@@ -85,8 +85,9 @@ 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 |
| 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`, or a TypeScript `private` / `#` name uses `defn-/`.
`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.
## What each language mutates
@@ -100,6 +101,9 @@ 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`. |
| 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.
## Tests and coverage
@@ -113,8 +117,15 @@ 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 |
| 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 |
Coverage is generated with crapper's commands unless `--use-existing-coverage` or `--no-coverage` is set. A file missing from the report is treated as uncovered, and the run says so.
`--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
./mutator --xcode-scheme App --xcode-destination 'platform=iOS Simulator,name=iPhone 16'
```
Coverage is generated with crapper's commands unless `--use-existing-coverage` or `--no-coverage` is set. A file missing from the report is treated as uncovered, and the run says so. Swift coverage is the JSON crapper writes under `target/coverage/swift/`: llvm-cov export after `swift test --enable-code-coverage`, or `xcrun xccov view --report --json` after `xcodebuild test -enableCodeCoverage YES`. A hit region marks that line. An xccov summary has no regions, so the function's line is covered when that function has covered lines.
## Development
+1 -1
View File
@@ -1,7 +1,7 @@
[project]
name = "mutator"
version = "0.1.0"
description = "Mutation testing for Clojure, Java, Go, TypeScript, Rust, and Python, in the snapshot uml-viewer reads."
description = "Mutation testing for Clojure, Java, Go, TypeScript, Rust, Python, and Swift, in the snapshot uml-viewer reads."
readme = "README.md"
license = { file = "LICENSE" }
classifiers = ["License :: OSI Approved :: Zero-Clause BSD (0BSD)"]
+25 -2
View File
@@ -68,7 +68,7 @@ def _test_directory_text() -> str:
HELP = f"""\
Usage: mutator [options] [path-or-filter ...]
Discover mutation sites in Clojure, Java, Go, TypeScript, Rust, and Python,
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
uml-viewer. Namespaces and function names are the ones crapper writes into
`.metrics/crap.edn`.
@@ -102,6 +102,11 @@ Options:
--test-command <cmd> Run this command for the baseline and every
mutant. The working directory is the project
root.
--xcode-scheme <name> Scheme for an Xcode or iOS test run. Default:
the first shared scheme, or the project name.
--xcode-destination <dest> xcodebuild -destination value. iOS needs this,
and a Mac with Xcode. Example:
platform=iOS Simulator,name=iPhone 16.
--timeout-factor <number> Mutant timeout, as a multiple of the baseline
duration. Default: 10. The timeout is at least
2 seconds.
@@ -123,7 +128,8 @@ named {_skip_directory_text()} are skipped at any depth. A test directory
({_test_directory_text()}) is skipped when it is the first component of the
path, and so is src/test and src/tests. A deeper directory with one of those
names, such as src/pkg/test, is mutated. Files whose names mark them as tests
are also skipped.
are also skipped. Swift also skips a directory whose name ends with Tests
(Tests, AppTests) at any depth, and a file named *Tests.swift.
The default, once a snapshot exists, reruns survivors and sites in functions
whose text changed. Killed mutants in unchanged functions are kept.
@@ -147,6 +153,11 @@ Coverage, when it is produced, uses the same commands as crapper:
TypeScript npm run coverage, Vitest, or c8
Rust cargo llvm-cov or cargo tarpaulin
Python coverage.py LCOV
Swift swift test --enable-code-coverage, then llvm-cov JSON;
or xcodebuild test and xcrun xccov view --report --json
SwiftPM tests are `swift test`. Xcode and iOS tests are `xcodebuild test`.
iOS runs only on a Mac with Xcode.
A site on a line the report does not mark as hit is uncovered and is not run.
"""
@@ -168,6 +179,8 @@ class Options:
use_existing_coverage: bool = False
coverage_command: str | None = None
test_command: str | None = None
xcode_scheme: str | None = None
xcode_destination: str | None = None
timeout_factor: float = 10.0
mutation_warning: int = 50
max_workers: int | None = None
@@ -231,6 +244,14 @@ def parse_args(argv: list[str] | None = None) -> Options:
options.test_command = _take(args, index, arg)
index += 2
continue
if arg == "--xcode-scheme":
options.xcode_scheme = _take(args, index, arg)
index += 2
continue
if arg == "--xcode-destination":
options.xcode_destination = _take(args, index, arg)
index += 2
continue
if arg == "--timeout-factor":
options.timeout_factor = float(_take(args, index, arg))
if options.timeout_factor <= 0:
@@ -548,6 +569,8 @@ def _mutate_files(options: Options, root: Path, files: list[Path]) -> int:
mutation_warning=options.mutation_warning,
baselines=baselines,
max_workers=options.max_workers,
xcode_scheme=options.xcode_scheme,
xcode_destination=options.xcode_destination,
)
outcome = _record(result, forms, written)
if outcome == "baseline":
+22 -2
View File
@@ -2,8 +2,10 @@
Java uses JaCoCo source lines. Go uses statement profiles, which name a
file by its module import path, the way crapper names it. Clojure prefers
Cloverage's per-line form counts, then LCOV. The other languages use LCOV.
A file that does not appear in a report has no coverage data.
Cloverage's per-line form counts, then LCOV. Swift uses the regions crapper
reads from llvm-cov JSON, or an xccov function summary when the report has
no regions. The other languages use LCOV. A file that does not appear in a
report has no coverage data.
"""
from __future__ import annotations
@@ -199,6 +201,22 @@ def _jacoco_index(root: Path) -> dict[str, set[int]]:
return found
def _swift_hits(record) -> set[int]:
"""Lines crapper counted. A region is one line; an xccov summary is the function line."""
if record.regions:
return {line for line, count in record.regions if count > 0}
return {line for line, covered, _executable in record.summaries if covered > 0}
def _swift_lines(bundle, source_path: str) -> set[int] | None:
crapper = ensure_crapper()
record = crapper.coverage._lookup(bundle.swift, source_path, bundle.source_parts)
if record is None:
return None
return _swift_hits(record)
def _go_lines(root: Path, profile, source_path: str) -> set[int] | None:
if not profile:
return None
@@ -226,6 +244,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 == "swift":
return _swift_lines(bundle, path)
if language == "clojure":
html = _covered_from_pairs(_lookup(bundle.form_html, path))
if html is not None:
+14 -1
View File
@@ -219,10 +219,19 @@ def _apply_selected(
baselines,
outcomes,
max_workers,
xcode_scheme,
xcode_destination,
) -> RunResult | None:
if not selected:
return None
command, cwd = test_plan(root, path, language, test_command)
command, cwd = test_plan(
root,
path,
language,
test_command,
xcode_scheme=xcode_scheme,
xcode_destination=xcode_destination,
)
cache_key = (_command_key(command), str(cwd))
_remember_baseline(baselines, cache_key, runner, command, cwd)
ok, seconds, tail = baselines[cache_key]
@@ -274,6 +283,8 @@ def mutate_file(
mutation_warning: int,
baselines: dict[tuple[tuple[str, ...], str], tuple[bool, float, str]],
max_workers: int | None = None,
xcode_scheme: str | None = None,
xcode_destination: str | None = None,
) -> RunResult:
"""Mutate one file and write its namespaces into `.metrics/mutate`."""
@@ -309,6 +320,8 @@ def mutate_file(
baselines,
outcomes,
max_workers,
xcode_scheme,
xcode_destination,
)
if failure is not None:
return failure
+6
View File
@@ -46,6 +46,10 @@ def _typescript_private(name: str, header: str) -> bool:
return name.startswith("#") or bool(re.search(r"\bprivate\b", header))
def _swift_private(header: str) -> bool:
return re.search(r"\b(?:fileprivate|private)\b", header) is not None
def is_private(language: str, name: str, source: str, start: int, end: int) -> bool:
"""True when uml-viewer should treat the operation as private."""
@@ -62,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 == "swift":
return _swift_private(header)
return False
+71 -2
View File
@@ -11,6 +11,8 @@ import time
from dataclasses import dataclass
from pathlib import Path
from mutator.crapper_link import ensure_crapper
Command = str | list[str]
@@ -222,6 +224,61 @@ def _python_plan(root: Path, source: Path) -> tuple[Command, Path]:
return _python_command(directory), directory
def _xcode_flag(project: Path) -> str:
if project.suffix == ".xcworkspace":
return "-workspace"
return "-project"
def _xcode_scheme(project: Path, requested: str | None) -> str:
if requested:
return requested
schemes = ensure_crapper().runners.xcode_schemes(project)
if schemes:
return schemes[0]
return project.stem
def _xcode_command(project: Path, scheme: str | None, destination: str | None) -> list[str]:
"""The project path is relative to the working directory, which is ``project.parent``.
An absolute path would name the original tree. The worker maps the working
directory and would then compile the unmutated project.
"""
command = [
"xcodebuild",
"test",
_xcode_flag(project),
project.name,
"-scheme",
_xcode_scheme(project, scheme),
]
if destination:
command.extend(["-destination", destination])
return command
def _swift_plan(
root: Path, source: Path, scheme: str | None, destination: str | None
) -> tuple[Command, Path]:
"""SwiftPM uses ``swift test``. An Xcode or iOS project uses ``xcodebuild``.
A file inside a package is not also sent to xcodebuild. Coverage stays
with crapper; this command only decides whether the tests pass.
"""
crapper = ensure_crapper()
packages = crapper.runners.swift_packages(root, [source])
if packages:
return ["swift", "test"], packages[0]
projects = crapper.runners.xcode_projects(root, [source])
if not projects:
return ["swift", "test"], root
project = projects[0]
return _xcode_command(project, scheme, destination), project.parent
_PLANS = {
"clojure": _clojure_plan,
"java": _java_plan,
@@ -232,16 +289,28 @@ _PLANS = {
}
def test_plan(root: Path, source: Path, language: str, override: str | None) -> tuple[Command, Path]:
def test_plan(
root: Path,
source: Path,
language: str,
override: str | None,
*,
xcode_scheme: str | None = None,
xcode_destination: str | None = None,
) -> tuple[Command, Path]:
"""The test command and the directory it runs in.
A user override stays a shell string. Every generated command is an
argument vector, so a package path is one argument.
argument vector, so a package path or an Xcode destination is one argument.
``xcode_scheme`` and ``xcode_destination`` apply to an Xcode or iOS project.
iOS needs a destination and a Mac with Xcode.
"""
root = root.resolve()
if override:
return override, root
if language == "swift":
return _swift_plan(root, source.resolve(), xcode_scheme, xcode_destination)
plan = _PLANS.get(language)
if plan is None:
return ["false"], root
+81 -9
View File
@@ -1,10 +1,11 @@
"""Find mutation sites.
Clojure follows clj-mutate's symbol rules. Go follows mutate4go, including
one-way `*` to `/`. Java follows mutate4java. TypeScript, Rust, and Python
use the same decisions as Java, spelled in that language. TypeScript also
mutates `??` to `||` and `?.` to `.` (removed on a call or index). JavaScript
files use the TypeScript rules.
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.
"""
from __future__ import annotations
@@ -36,9 +37,38 @@ _BINARY_PARENTS = {
"binary_operator",
"comparison_operator",
"boolean_operator",
"additive_expression",
"multiplicative_expression",
"comparison_expression",
"equality_expression",
"infix_expression",
"conjunction_expression",
"disjunction_expression",
"nil_coalescing_expression",
}
_UNARY_PARENTS = {"unary_expression", "unary_operator", "not_operator"}
_UNARY_PARENTS = {"unary_expression", "unary_operator", "not_operator", "prefix_expression"}
# Boolean conditions. A `let` binding is not one of them. `repeat-while` puts
# the condition after the body; the others put it before.
_SWIFT_CONDITIONS = {
"if_statement",
"guard_statement",
"while_statement",
"repeat_while_statement",
}
_SWIFT_SKIP = {
"if",
"else",
"guard",
"while",
"repeat",
"{",
"}",
"statements",
"if_statement",
"comment",
}
_BOOLEANS = {"true": "false", "false": "true", "True": "False", "False": "True"}
@@ -94,7 +124,7 @@ _CLOJURE_HEAD = {
class RawSite:
def __init__(
self, line: int, start: int, end: int, original: str, mutant: str, category: str, anchor_line: int = 0
self, line: int, start: int, end: int, original: str, mutant: str, category: str, anchor_line: int
):
self.line = line
# The line its statement starts on. LCOV marks only that line of a multi-line statement.
@@ -137,7 +167,7 @@ def _category(token: str) -> str:
def _binary_mutant(language: str, token: str) -> str | None:
if language == "go" and token == "/":
return None
if token == "??" and language != "typescript":
if token == "??" and language not in {"typescript", "swift"}:
return None
return _BINARY.get(token)
@@ -218,10 +248,10 @@ def _is_head(node) -> bool:
parent = node.parent
if parent is None or parent.type != "list_lit":
return False
# The symbol is one of these children, so this loop returns.
for child in parent.children:
if child.type == "sym_lit":
return child.id == node.id
return False
def _clojure_skipped(node, data: bytes) -> bool:
@@ -238,7 +268,7 @@ def _clojure_skipped(node, data: bytes) -> bool:
def _clojure_text(node, data: bytes) -> str:
if node.child_count == 0 or node.type in {"sym_lit", "bool_lit", "num_lit"}:
if node.type in {"sym_lit", "bool_lit", "num_lit"}:
return _text(data, node)
return ""
@@ -336,9 +366,51 @@ def _visit_leaf(node, data: bytes, language: str, found: list[RawSite]) -> None:
_visit_constant(node, token, found)
def _ends_swift_conditions(node, child) -> bool:
if node.type == "repeat_while_statement":
return False
return child.type in {"{", "statements"}
def _swift_conditions(node):
if node.type not in _SWIFT_CONDITIONS:
return []
found = []
binding = False
for child in node.children:
if _ends_swift_conditions(node, child):
break
if child.type == ",":
binding = False
continue
if child.type in _SWIFT_SKIP:
continue
if child.type == "value_binding_pattern":
binding = True
continue
if binding:
continue
found.append(child)
return found
def _negate_condition(node, data: bytes, found: list[RawSite]) -> None:
original = _text(data, node)
if not original.strip():
return
_add(found, node, original, f"!({original})", "conditional")
def _visit_swift_conditions(node, data: bytes, found: list[RawSite]) -> None:
for condition in _swift_conditions(node):
_negate_condition(condition, data, found)
def _visit_node(node, data: bytes, language: str, found: list[RawSite]) -> None:
if language == "typescript" and _in_type(node):
return
if language == "swift":
_visit_swift_conditions(node, data, found)
if node.child_count == 0:
_visit_leaf(node, data, language, found)
else:
+21
View File
@@ -10,6 +10,11 @@ under src/test or src/tests, the Maven and Gradle test layout. SKIP_DIRS are
skipped at any depth. Filename-based test files are still detected by
crapper.discover.is_test_file, applied to the filename so the any-depth
directory check is not reused.
Swift adds its own names. A directory component that ends with ``Tests``
(``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.
"""
from __future__ import annotations
@@ -29,6 +34,18 @@ def is_test_path(relative: Path, test_dirs: set[str]) -> bool:
return len(parts) >= 2 and parts[0] == "src" and parts[1] in SRC_TEST_DIRS
def _swift_test_relative(relative: Path) -> bool:
"""A Swift directory named ``Tests`` or ending in ``Tests`` is a test target.
``*Tests.swift`` is crapper's filename rule, applied to the file name.
``test`` at any depth stays a production path. Swift's name is ``Tests``.
"""
if relative.suffix != ".swift":
return False
return any(part.endswith("Tests") for part in relative.parts[:-1])
def _relative_to(path: Path, root: Path) -> Path | None:
try:
return path.resolve().relative_to(root.resolve())
@@ -46,6 +63,8 @@ def is_mutable_source(path: Path, root: Path, crapper) -> bool:
return False
if is_test_path(relative, set(crapper.discover.TEST_DIRS)):
return False
if _swift_test_relative(relative):
return False
return not crapper.discover.is_test_file(path.name)
@@ -55,6 +74,8 @@ def is_skipped_test(path: Path, root: Path, crapper) -> bool:
relative = _relative_to(path, root)
if relative is not None and is_test_path(relative, set(crapper.discover.TEST_DIRS)):
return True
if relative is not None and _swift_test_relative(relative):
return True
return crapper.discover.is_test_file(path.name)
+32 -3
View File
@@ -1,9 +1,10 @@
"""Run mutants in symlink overlays, the way clj-mutate runs its workers.
Each worker is a directory under target/mutation-workers. Project files are
linked in. The file under test is a private copy, so workers can mutate it at
the same time without touching the original tree. The overlay is removed when
the file's mutants finish.
linked in. An Xcode project or workspace is copied instead, because xcodebuild
realpaths a symlink and would compile the original tree. The file under test
is a private copy, so workers can mutate it at the same time without touching
the original tree. The overlay is removed when the file's mutants finish.
"""
from __future__ import annotations
@@ -43,6 +44,9 @@ SKIP_LINK = frozenset(
".mypy_cache",
".clj-kondo",
".gradle",
".build",
".swiftpm",
"DerivedData",
}
)
@@ -139,6 +143,28 @@ def _copy_configs(worker: Path, root: Path, relative: str) -> None:
(worker / name).write_bytes(source.read_bytes())
def _xcode_bundle(path: Path) -> bool:
"""An Xcode project or workspace. xcodebuild realpaths it before compiling."""
return path.suffix in {".xcodeproj", ".xcworkspace"} and path.is_dir()
def _copy_bundle(source: Path, destination: Path) -> None:
"""A real directory tree, so realpath stays inside the worker."""
destination.mkdir(parents=True)
for child in source.iterdir():
_place_bundle_entry(destination, child)
def _place_bundle_entry(destination: Path, child: Path) -> None:
target = destination / child.name
if child.is_dir():
_copy_bundle(child, target)
return
target.write_bytes(child.read_bytes())
def _link_children(worker_dir: Path, real_dir: Path, skip: set[str]) -> None:
if not real_dir.is_dir():
return
@@ -148,6 +174,9 @@ def _link_children(worker_dir: Path, real_dir: Path, skip: set[str]) -> None:
destination = worker_dir / child.name
if destination.exists() or destination.is_symlink():
continue
if _xcode_bundle(child):
_copy_bundle(child, destination)
continue
symlink(destination, child)
+84
View File
@@ -1,3 +1,6 @@
import json
from pathlib import Path
from mutator.coverage import covered_lines
@@ -112,6 +115,87 @@ def _go_source(path):
return path
def _swift_report(root: Path, payload: dict) -> None:
report = root / "target" / "coverage" / "swift" / "llvm-cov.json"
report.parent.mkdir(parents=True)
report.write_text(json.dumps(payload), encoding="utf-8")
def test_swift_llvm_cov_regions_mark_hit_lines(tmp_path):
source = tmp_path / "Sources" / "Demo" / "Box.swift"
source.parent.mkdir(parents=True)
source.write_text("func choose(x: Int) -> Int { 1 }\n", encoding="utf-8")
_swift_report(
tmp_path,
{
"type": "llvm.coverage.json.export",
"data": [
{
"files": [{"filename": str(source)}],
"functions": [
{
"regions": [
[2, 1, 2, 2, 1, 0, 0, 0],
[4, 1, 4, 2, 0, 0, 0, 0],
[3, 9, 3, 18, 0, 0, 0, 4],
]
}
],
}
],
},
)
assert covered_lines(tmp_path, source, "swift") == {2}
assert covered_lines(tmp_path, tmp_path / "Sources" / "Demo" / "Missing.swift", "swift") is None
def test_swift_xccov_summaries_mark_a_covered_function_line(tmp_path):
source = tmp_path / "Sources" / "Demo" / "Box.swift"
source.parent.mkdir(parents=True)
source.write_text("func choose(x: Int) -> Int { 1 }\n", encoding="utf-8")
_swift_report(
tmp_path,
{
"targets": [
{
"files": [
{
"path": "Sources/Demo/Box.swift",
"functions": [
{"lineNumber": 1, "coveredLines": 1, "executableLines": 2},
{"lineNumber": 9, "coveredLines": 0, "executableLines": 1},
],
}
]
}
]
},
)
assert covered_lines(tmp_path, source, "swift") == {1}
def test_swift_regions_with_no_hits_are_present_and_empty(tmp_path):
source = tmp_path / "Sources" / "Demo" / "Box.swift"
source.parent.mkdir(parents=True)
source.write_text("func choose(x: Int) -> Int { 1 }\n", encoding="utf-8")
_swift_report(
tmp_path,
{
"type": "llvm.coverage.json.export",
"data": [
{
"files": [{"filename": str(source)}],
"functions": [{"regions": [[2, 1, 2, 2, 0, 0, 0, 0]]}],
}
],
},
)
assert covered_lines(tmp_path, source, "swift") == set()
empty = tmp_path / "other"
empty.mkdir()
assert covered_lines(empty, source, "swift") is None
def test_go_profile_keyed_by_import_path_marks_hit_lines(tmp_path):
# `go test -coverprofile` names files by module import path, not by disk path.
_go_module(
+15
View File
@@ -29,6 +29,8 @@ def test_clojure_rules_follow_clj_mutate_and_mark_private_defns(tmp_path):
assert ("defn/place", "1", "0") in described
assert ("defn-/hide", "false", "true") in described
assert {site.namespace for site in sites} == {"demo.core"}
plus = [site for site in sites if site.original == "+"]
assert [site.anchor_line for site in plus] == [4]
functions = project_functions(source, tmp_path / "src/demo/core.clj", tmp_path)
assert form_id("hide", True) == "defn-/hide"
assert is_private("clojure", "hide", source, 6, 7)
@@ -40,12 +42,25 @@ def test_clojure_ignores_strings_comments_and_quotes(tmp_path):
(defn place []
(comment (+ 1 0))
(quote (+ 1 0))
'(+ 1 0)
(str "true + 1"))
"""
sites = _sites(tmp_path, "src/demo/core.clj", source)
assert sites == []
def test_a_clojure_vector_and_a_capitalized_symbol_are_not_calls(tmp_path):
source = """(defn place []
[+ 1]
True)
"""
sites = _sites(tmp_path, "src/demo/core.clj", source)
described = {(site.original, site.mutant) for site in sites}
assert ("+", "-") not in described
assert ("True", "False") not in described
assert ("1", "0") in described
def test_java_rules_follow_mutate4java(tmp_path):
source = """package demo;
class Board {
+9
View File
@@ -48,6 +48,15 @@ CASES = {
"src/pkg/foo.test.ts": False,
"src/pkg/foo.spec.ts": False,
"src/pkg/conftest.py": False,
"Tests/DemoTests/Board.swift": False,
"AppTests/Board.swift": False,
"Sources/Demo/BoxTests.swift": False,
"Sources/Demo/Box.swift": True,
".build/debug/Generated.swift": False,
".swiftpm/cache/Generated.swift": False,
"DerivedData/App.swift": False,
"src/pkg/Tests/Hidden.swift": False,
"src/pkg/test/Kept.swift": True,
}
+650
View File
@@ -0,0 +1,650 @@
"""Swift mutation sites join the functions crapper reports."""
import os
import shutil
import sys
from pathlib import Path
import pytest
from mutator.cli import parse_args, run, select_files
from mutator.functions import sites_in_file
from mutator.runner import test_plan as plan_command
SOURCE = """func place(x: Int, ready: Bool, name: String?) -> Int {
guard x > 0, ready else { return 0 }
if x >= 1 && ready || !ready {
return x + 1
} else if x != 0 {
return x - 1
}
while x < 2 {
x = x * 2 / 1
}
let value = name ?? "guest"
let flag = true
let n = -x
let forced = name!
let same = name === nil
let other = name !== nil
return value.count
}
struct Box {
private func hide() -> Bool { false }
fileprivate func seal() -> Bool { true }
func open() -> Int { 1 }
}
let stored = { (n: Int) -> Int in n + 1 }
func mount() -> Int {
let handler = { (n: Int) -> Int in
n > 0 ? n : 0
}
return handler(1)
}
func quote() -> String {
// x > 0 && true ?? name!
return "x > 0 && true ?? name!"
}
func bind(name: String?) -> Int {
if let name, name.count > 1 {
return name.count
}
repeat {
return 0
} while name == nil
}
"""
def _sites(tmp_path: Path, source: str = SOURCE, relative: str = "Sources/Demo/Box.swift"):
path = tmp_path / relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(source, encoding="utf-8")
return sites_in_file(source, path, tmp_path, relative)
def _pairs(sites):
return {(site.original, site.mutant) for site in sites}
def test_swift_operators_match_the_other_languages_and_negate_conditions(tmp_path):
sites = _sites(tmp_path)
pairs = _pairs(sites)
assert ("+", "-") in pairs
assert ("-", "+") in pairs
assert ("-", "") in pairs
assert ("*", "/") in pairs
assert ("/", "*") in pairs
assert (">", ">=") in pairs
assert (">=", ">") in pairs
assert ("<", "<=") in pairs
assert ("!=", "==") in pairs
assert ("==", "!=") in pairs
assert ("===", "!==") in pairs
assert ("!==", "===") in pairs
assert ("&&", "||") in pairs
assert ("||", "&&") in pairs
assert ("??", "||") in pairs
assert ("true", "false") in pairs
assert ("false", "true") in pairs
assert ("0", "1") in pairs
assert ("1", "0") in pairs
assert ("!", "") in pairs
negated = {site.original for site in sites if site.mutant == f"!({site.original})"}
assert negated == {
"x > 0",
"ready",
"x >= 1 && ready || !ready",
"x != 0",
"x < 2",
"name.count > 1",
"name == nil",
}
assert all(site.original != "?" for site in sites)
assert all(site.original != "?." for site in sites)
assert all(site.original != "%" for site in sites)
def test_a_nested_closure_stays_on_the_parent_and_a_stored_closure_is_its_own(tmp_path):
sites = _sites(tmp_path)
mount = [site for site in sites if site.name == "mount"]
assert (">", ">=") in _pairs(mount)
assert ("0", "1") in _pairs(mount)
assert {site.namespace for site in mount} == {"Demo"}
assert all(site.name != "handler" for site in sites)
stored = [site for site in sites if site.name == "stored"]
assert _pairs(stored) == {("+", "-"), ("1", "0")}
assert {site.namespace for site in stored} == {"Demo"}
def test_strings_comments_and_force_unwrap_are_left_alone(tmp_path):
sites = _sites(tmp_path)
assert all(site.name != "quote" for site in sites)
deleted = [site for site in sites if site.original == "!" and site.mutant == ""]
assert len(deleted) == 1
assert deleted[0].name == "place"
def test_private_and_fileprivate_join_the_type_namespace(tmp_path):
sites = _sites(tmp_path)
by_name = {site.name: site for site in sites if site.name in {"hide", "seal", "open"}}
assert by_name["hide"].form_id == "defn-/hide"
assert by_name["seal"].form_id == "defn-/seal"
assert by_name["open"].form_id == "defn/open"
assert {site.namespace for site in by_name.values()} == {"Demo.Box"}
assert by_name["hide"].mutant == "true"
assert by_name["seal"].mutant == "false"
assert (by_name["open"].original, by_name["open"].mutant) == ("1", "0")
def test_swift_test_files_are_skipped_and_production_sources_are_kept(tmp_path, capsys):
source = tmp_path / "Sources" / "Demo" / "Box.swift"
source.parent.mkdir(parents=True)
source.write_text("func open() -> Int { 1 }\n", encoding="utf-8")
test_file = tmp_path / "Tests" / "DemoTests" / "Box.swift"
test_file.parent.mkdir(parents=True)
test_file.write_text("func check() {}\n", encoding="utf-8")
named = tmp_path / "Sources" / "Demo" / "BoxTests.swift"
named.write_text("func check() {}\n", encoding="utf-8")
chosen = select_files(
parse_args(["--root", str(tmp_path), str(source), str(test_file), str(named)])
)
captured = capsys.readouterr()
assert chosen == [source.resolve()]
assert "Skipping test file" in captured.err
assert "Tests/DemoTests/Box.swift" in captured.err
assert "BoxTests.swift" in captured.err
def _write(path: Path, text: str) -> Path:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
return path
def test_xcode_options_require_a_value():
options = parse_args(
["--xcode-scheme", "App", "--xcode-destination", "platform=iOS Simulator,name=iPhone 16"]
)
assert options.xcode_scheme == "App"
assert options.xcode_destination == "platform=iOS Simulator,name=iPhone 16"
help_text = parse_args(["--help"]).message
assert "--xcode-scheme" in help_text
assert "--xcode-destination" in help_text
assert "swift test" in help_text
assert "xcodebuild" in help_text
assert "*Tests.swift" in help_text
assert parse_args(["--xcode-scheme"]).exit_code == 1
def test_a_swift_file_without_a_package_or_xcode_project_uses_swift_test(tmp_path):
root = tmp_path / "loose"
source = _write(root / "Place.swift", "func place() -> Int { 1 }\n")
command, directory = plan_command(root, source, "swift", None)
assert command == ["swift", "test"]
assert directory == root.resolve()
def test_a_swift_package_runs_swift_test(tmp_path):
root = tmp_path / "pkg"
_write(root / "Package.swift", "// swift-tools-version:5.9\n")
source = _write(root / "Sources" / "Demo" / "Box.swift", "func open() -> Int { 1 }\n")
command, directory = plan_command(root, source, "swift", None)
assert command == ["swift", "test"]
assert directory == root.resolve()
override, override_dir = plan_command(root, source, "swift", "swift test --filter open")
assert override == "swift test --filter open"
assert override_dir == root.resolve()
def test_an_xcode_project_runs_xcodebuild_with_scheme_and_destination(tmp_path):
root = tmp_path / "ios"
project = root / "App.xcodeproj"
_write(project / "xcshareddata" / "xcschemes" / "App.xcscheme", "<Scheme/>\n")
_write(project / "xcshareddata" / "xcschemes" / "Zed.xcscheme", "<Scheme/>\n")
source = _write(root / "App" / "ContentView.swift", "func body() -> Int { 1 }\n")
destination = "platform=iOS Simulator,name=iPhone 16"
command, directory = plan_command(root, source, "swift", None, xcode_destination=destination)
assert command == [
"xcodebuild",
"test",
"-project",
project.name,
"-scheme",
"App",
"-destination",
destination,
]
assert directory == root.resolve()
chosen, _directory = plan_command(
root, source, "swift", None, xcode_scheme="Zed", xcode_destination=destination
)
assert chosen[chosen.index("-scheme") + 1] == "Zed"
def test_a_workspace_uses_its_flag_and_a_missing_scheme_uses_the_project_name(tmp_path):
root = tmp_path / "ios"
workspace = root / "App.xcworkspace"
_write(workspace / "contents.xcworkspacedata", "<Workspace/>\n")
_write(root / "App.xcodeproj" / "project.pbxproj", "")
_write(workspace / "xcshareddata" / "xcschemes" / "App.xcscheme", "<Scheme/>\n")
source = _write(root / "App" / "ContentView.swift", "func body() -> Int { 1 }\n")
command, directory = plan_command(root, source, "swift", None)
assert command[:4] == ["xcodebuild", "test", "-workspace", workspace.name]
assert "-destination" not in command
assert directory == root.resolve()
bare = tmp_path / "bare"
project = bare / "Solo.xcodeproj"
_write(project / "project.pbxproj", "")
solo = _write(bare / "Solo" / "View.swift", "func body() -> Int { 1 }\n")
bare_command, _bare_dir = plan_command(bare, solo, "swift", None)
assert bare_command[bare_command.index("-scheme") + 1] == "Solo"
def test_a_package_is_tested_with_swift_and_an_app_outside_it_with_xcodebuild(tmp_path):
root = tmp_path / "repo"
_write(root / "libs" / "Demo" / "Package.swift", "// swift-tools-version:5.9\n")
package_source = _write(
root / "libs" / "Demo" / "Sources" / "Demo" / "Box.swift",
"func open() -> Int { 1 }\n",
)
project = root / "App.xcodeproj"
_write(project / "xcshareddata" / "xcschemes" / "App.xcscheme", "<Scheme/>\n")
app_source = _write(root / "App" / "ContentView.swift", "func body() -> Int { 1 }\n")
package_command, package_dir = plan_command(root, package_source, "swift", None)
app_command, app_dir = plan_command(root, app_source, "swift", None)
assert package_command == ["swift", "test"]
assert package_dir == (root / "libs" / "Demo").resolve()
assert app_command[2:6] == ["-project", project.name, "-scheme", "App"]
assert app_dir == root.resolve()
def test_a_worker_copies_an_xcode_bundle_and_links_a_file_with_that_suffix(tmp_path):
from mutator.workers import create_workers, new_run_dir
root = tmp_path / "ios"
source = _write(root / "App" / "ContentView.swift", "func body() -> Int { 1 }\n")
_write(root / "App.xcodeproj" / "project.pbxproj", "path = App/ContentView.swift;\n")
_write(root / "Notes.xcodeproj", "not a bundle\n")
worker = create_workers(
new_run_dir(root), root, "App/ContentView.swift", source.read_bytes(), 1
)[0]
bundle = worker / "App.xcodeproj"
assert bundle.is_dir() and not bundle.is_symlink()
assert (bundle / "project.pbxproj").read_text(encoding="utf-8").startswith("path =")
linked = worker / "Notes.xcodeproj"
assert linked.is_symlink()
assert linked.read_text(encoding="utf-8") == "not a bundle\n"
def test_a_worker_does_not_share_swift_build_directories(tmp_path):
from mutator.workers import create_workers, new_run_dir
root = tmp_path / "pkg"
source = _write(root / "Sources" / "Demo" / "Box.swift", "func open() -> Int { 1 }\n")
_write(root / "Package.swift", "// swift-tools-version:5.9\n")
for name in (".build", ".swiftpm", "DerivedData"):
_write(root / name / "marker", "x")
worker = create_workers(
new_run_dir(root), root, "Sources/Demo/Box.swift", source.read_bytes(), 1
)[0]
for name in (".build", ".swiftpm", "DerivedData"):
assert not (worker / name).exists()
assert (worker / "Package.swift").is_file()
copy = worker / "Sources" / "Demo" / "Box.swift"
assert copy.is_file() and not copy.is_symlink()
def _fake_tool(directory: Path, name: str, log: Path) -> None:
directory.mkdir(parents=True, exist_ok=True)
script = directory / name
script.write_text(
"#!/bin/sh\n"
f"printf '%s\\n' \"$PWD\" >> '{log}'\n"
f"printf '%s\\n' \"$@\" >> '{log}'\n"
f"printf '%s\\n' --- >> '{log}'\n"
"exit 0\n",
encoding="utf-8",
)
script.chmod(0o755)
def test_a_run_invokes_swift_test_and_xcodebuild_with_the_destination(tmp_path, monkeypatch):
bin_dir = tmp_path / "bin"
swift_log = tmp_path / "swift.log"
xcode_log = tmp_path / "xcode.log"
_fake_tool(bin_dir, "swift", swift_log)
_fake_tool(bin_dir, "xcodebuild", xcode_log)
monkeypatch.setenv("PATH", f"{bin_dir}{os.pathsep}{os.environ.get('PATH', '')}")
package = tmp_path / "pkg"
_write(package / "Package.swift", "// swift-tools-version:5.9\n")
_write(package / "Sources" / "Demo" / "Box.swift", "func open() -> Int { 1 }\n")
swift_code = run(["--no-coverage", "--root", str(package), "--max-workers", "1"])
swift_text = swift_log.read_text(encoding="utf-8")
assert swift_code == 3
assert "test\n" in swift_text
assert str(package.resolve()) in swift_text
app = tmp_path / "ios"
project = app / "My App.xcodeproj"
_write(project / "xcshareddata" / "xcschemes" / "App.xcscheme", "<Scheme/>\n")
_write(app / "App" / "ContentView.swift", "func body() -> Int { 1 }\n")
destination = "platform=iOS Simulator,name=iPhone 16"
xcode_code = run(
[
"--no-coverage",
"--root",
str(app),
"--max-workers",
"1",
"--xcode-scheme",
"App",
"--xcode-destination",
destination,
]
)
xcode_text = xcode_log.read_text(encoding="utf-8")
assert xcode_code == 3
assert "xcodebuild" not in xcode_text
assert "-project" in xcode_text
assert "My App.xcodeproj" in xcode_text.splitlines()
assert "-scheme" in xcode_text
assert "App" in xcode_text.splitlines()
assert destination in xcode_text.splitlines()
_IOS_BODY = "func body(x: Int) -> Int {\n if x > 0 {\n return x\n }\n return 0\n}\n"
# A stand-in for xcodebuild. It realpaths the project it was given, then reads
# the Swift file named in that project. A symlink, or an absolute path back to
# the original tree, compiles the unmutated source and cannot kill a mutant.
_XCODEBUILD = """#!/usr/bin/env python3
import os
import re
import sys
from pathlib import Path
def flag(argv, name):
if name not in argv:
return None
return argv[argv.index(name) + 1]
def resolved(start, value):
path = Path(value)
if not path.is_absolute():
path = start / path
return path.resolve()
argv = sys.argv[1:]
cwd = Path.cwd()
log = Path(os.environ["XCODE_LOG"])
project = flag(argv, "-project")
workspace = flag(argv, "-workspace")
scheme = flag(argv, "-scheme")
with log.open("a", encoding="utf-8") as handle:
handle.write(str(cwd) + "\\n")
for arg in argv:
handle.write(arg + "\\n")
handle.write("---\\n")
bundle_arg = project or workspace
if bundle_arg is None or scheme is None:
raise SystemExit(1)
bundle = resolved(cwd, bundle_arg)
scheme_file = bundle / "xcshareddata" / "xcschemes" / (scheme + ".xcscheme")
if not scheme_file.is_file():
raise SystemExit(1)
project_bundle = bundle
if workspace is not None:
data = (bundle / "contents.xcworkspacedata").read_text(encoding="utf-8")
named = re.search(r"[\\w./-]+\\.xcodeproj", data)
if named is None:
raise SystemExit(1)
project_bundle = resolved(bundle.parent, named.group(0))
pbx = project_bundle / "project.pbxproj"
if not pbx.is_file():
raise SystemExit(1)
sources = re.findall(r"[\\w./-]+\\.swift", pbx.read_text(encoding="utf-8"))
if not sources:
raise SystemExit(1)
body = ""
for relative in sources:
file = (project_bundle.parent / relative).resolve()
body += file.read_text(encoding="utf-8")
with log.open("a", encoding="utf-8") as handle:
handle.write("compiled " + str(project_bundle) + "\\n")
handle.write(body)
handle.write("===\\n")
if ">=" in body or "!(" in body:
raise SystemExit(1)
raise SystemExit(0)
"""
def _labels(output: str, description: str) -> list[str]:
return [line.split()[0] for line in output.splitlines() if description in line]
def _install_xcodebuild(bin_dir: Path, log: Path) -> None:
bin_dir.mkdir(parents=True, exist_ok=True)
script = bin_dir / "xcodebuild"
script.write_text(_XCODEBUILD, encoding="utf-8")
script.chmod(0o755)
def _ios_source(root: Path, project_name: str) -> Path:
project = root / project_name
_write(project / "project.pbxproj", "path = App/ContentView.swift;\n")
_write(project / "xcshareddata" / "xcschemes" / "App.xcscheme", "<Scheme/>\n")
_write(project / "xcshareddata" / "xcschemes" / "Zed.xcscheme", "<Scheme/>\n")
return _write(root / "App" / "ContentView.swift", _IOS_BODY)
def _assert_worker_saw_the_mutant(output: str, log_text: str, source: Path) -> None:
assert _labels(output, "> -> >=") == ["KILLED"]
assert _labels(output, "x > 0 -> !(x > 0)") == ["KILLED"]
assert _labels(output, "0 -> 1") == ["SURVIVED", "SURVIVED"]
compiled = log_text.split("compiled ")[1:]
worker = [chunk for chunk in compiled if "mutation-workers" in chunk.splitlines()[0]]
assert worker
assert any(">=" in chunk or "!(" in chunk for chunk in worker)
assert any("return 1" in chunk for chunk in worker)
assert source.read_text(encoding="utf-8") == _IOS_BODY
def test_xcodebuild_compiles_the_mutant_in_the_worker(tmp_path, monkeypatch, capsys):
bin_dir = tmp_path / "bin"
log = tmp_path / "xcode.log"
_install_xcodebuild(bin_dir, log)
monkeypatch.setenv("PATH", f"{bin_dir}{os.pathsep}{os.environ.get('PATH', '')}")
monkeypatch.setenv("XCODE_LOG", str(log))
root = tmp_path / "ios"
source = _ios_source(root, "My App.xcodeproj")
destination = "platform=iOS Simulator,name=iPhone 16"
code = run(
[
"--no-coverage",
"--root",
str(root),
"--max-workers",
"1",
"--xcode-destination",
destination,
]
)
captured = capsys.readouterr()
text = log.read_text(encoding="utf-8")
assert code == 3
assert destination in text.splitlines()
assert "My App.xcodeproj" in text.splitlines()
scheme_at = text.splitlines().index("-scheme")
assert text.splitlines()[scheme_at + 1] == "App"
_assert_worker_saw_the_mutant(captured.out, text, source)
snapshot = (root / ".metrics" / "mutate" / "My App.edn").read_text(encoding="utf-8")
assert ":killed" in snapshot
assert ":survived" in snapshot
def test_xcodebuild_workspace_compiles_the_mutant_in_the_worker(tmp_path, monkeypatch, capsys):
bin_dir = tmp_path / "bin"
log = tmp_path / "xcode.log"
_install_xcodebuild(bin_dir, log)
monkeypatch.setenv("PATH", f"{bin_dir}{os.pathsep}{os.environ.get('PATH', '')}")
monkeypatch.setenv("XCODE_LOG", str(log))
root = tmp_path / "ios"
_ios_source(root, "App.xcodeproj")
workspace = root / "App.xcworkspace"
_write(workspace / "contents.xcworkspacedata", '<FileRef location = "group:App.xcodeproj">\n')
_write(workspace / "xcshareddata" / "xcschemes" / "App.xcscheme", "<Scheme/>\n")
source = root / "App" / "ContentView.swift"
code = run(["--no-coverage", "--root", str(root), "--max-workers", "1"])
captured = capsys.readouterr()
text = log.read_text(encoding="utf-8")
assert code == 3
assert "App.xcworkspace" in text.splitlines()
assert "-workspace" in text.splitlines()
_assert_worker_saw_the_mutant(captured.out, text, source)
snapshot = (root / ".metrics" / "mutate" / "App.edn").read_text(encoding="utf-8")
assert ":killed" in snapshot
assert ":survived" in snapshot
def test_a_failing_xcodebuild_baseline_records_no_kills(tmp_path, monkeypatch, capsys):
bin_dir = tmp_path / "bin"
bin_dir.mkdir()
tool = bin_dir / "xcodebuild"
tool.write_text("#!/bin/sh\nexit 1\n", encoding="utf-8")
tool.chmod(0o755)
monkeypatch.setenv("PATH", f"{bin_dir}{os.pathsep}{os.environ.get('PATH', '')}")
root = tmp_path / "ios"
source = _ios_source(root, "App.xcodeproj")
code = run(["--no-coverage", "--root", str(root), "--max-workers", "1"])
captured = capsys.readouterr()
assert code == 2
assert "Baseline failed" in captured.err
assert "xcodebuild" in captured.err
assert source.read_text(encoding="utf-8") == _IOS_BODY
assert not (root / ".metrics" / "mutate").exists()
def test_scan_marks_a_swift_line_uncovered_when_llvm_cov_did_not_hit_it(tmp_path, capsys):
import json
source = tmp_path / "Sources" / "Demo" / "Box.swift"
source.parent.mkdir(parents=True)
source.write_text("func place(x: Int) -> Int {\n return x > 0 ? x : 0\n}\n", encoding="utf-8")
report = tmp_path / "target" / "coverage" / "swift" / "llvm-cov.json"
report.parent.mkdir(parents=True)
report.write_text(
json.dumps(
{
"type": "llvm.coverage.json.export",
"data": [
{
"files": [{"filename": str(source)}],
"functions": [{"regions": [[1, 1, 1, 2, 1, 0, 0, 0]]}],
}
],
}
),
encoding="utf-8",
)
code = run(["--scan", "--use-existing-coverage", "--root", str(tmp_path), str(source)])
captured = capsys.readouterr()
assert code == 0
assert "uncovered" in captured.out
assert "x > 0 -> !(x > 0)" in captured.out or "> -> >=" in captured.out
def _swift_on_path(monkeypatch) -> None:
if shutil.which("swift"):
return
toolchains = Path.home() / ".local" / "share" / "swiftly" / "toolchains"
binaries = sorted(toolchains.glob("*/usr/bin/swift")) if toolchains.is_dir() else []
if not binaries:
pytest.skip("swift is not installed")
monkeypatch.setenv("PATH", f"{binaries[-1].parent}{os.pathsep}{os.environ.get('PATH', '')}")
def test_swift_test_kills_and_survives_mutants_in_a_package(tmp_path, monkeypatch, capsys):
_swift_on_path(monkeypatch)
root = tmp_path / "pkg"
_write(
root / "Package.swift",
"// swift-tools-version:5.9\n"
"import PackageDescription\n"
"let package = Package(name: \"Demo\", targets: [\n"
" .target(name: \"Demo\"),\n"
" .testTarget(name: \"DemoTests\", dependencies: [\"Demo\"]),\n"
"])\n",
)
source = _write(
root / "Sources" / "Demo" / "Place.swift",
"func place(x: Int) -> Int {\n if x > 0 {\n return x\n }\n return 0\n}\n",
)
_write(
root / "Tests" / "DemoTests" / "PlaceTests.swift",
"import XCTest\n"
"@testable import Demo\n"
"final class PlaceTests: XCTestCase {\n"
" func testTwo() { XCTAssertEqual(place(x: 2), 2) }\n"
" func testOne() { XCTAssertEqual(place(x: 1), 1) }\n"
" func testZero() { XCTAssertEqual(place(x: 0), 0) }\n"
"}\n",
)
code = run(
["--no-coverage", "--mutate-all", "--max-workers", "1", "--root", str(root)]
)
captured = capsys.readouterr()
assert code == 3
assert "KILLED" in captured.out
assert "SURVIVED" in captured.out
text = (root / ".metrics" / "mutate" / "Demo.edn").read_text(encoding="utf-8")
assert ':namespace "Demo"' in text
assert ':id "defn/place"' in text
assert source.read_text(encoding="utf-8").startswith("func place")
def test_a_swift_run_records_killed_and_survived_on_the_crapper_namespace(tmp_path, capsys):
relative = "Sources/Demo/Place.swift"
path = tmp_path / relative
path.parent.mkdir(parents=True)
path.write_text(
"func place(x: Int) -> Int {\n guard x > 0 else { return x }\n return x\n}\n",
encoding="utf-8",
)
command = (
f"{sys.executable} -c \"from pathlib import Path; "
"text = Path('Sources/Demo/Place.swift').read_text(); "
"raise SystemExit(0 if 'x > 0' in text else 1)\""
)
code = run(
[
"--no-coverage",
"--mutate-all",
"--root",
str(tmp_path),
"--test-command",
command,
relative,
]
)
captured = capsys.readouterr()
assert code == 3
assert "KILLED" in captured.out
assert "SURVIVED" in captured.out
assert "Uncovered" in captured.out
snapshot = tmp_path / ".metrics" / "mutate" / "Demo.edn"
text = snapshot.read_text(encoding="utf-8")
assert ':namespace "Demo"' in text
assert ':source "Sources/Demo/Place.swift"' in text
assert ':id "defn/place"' in text
assert ":killed" in text
assert ":survived" in text
assert path.read_text(encoding="utf-8").startswith("func place")