From b52159454de7163d41fca78dea17f9d16b8bd950 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 25 Nov 2026 23:58:11 +0000 Subject: [PATCH 1/8] Find Swift mutation sites and join them to crapper's functions. Swift needs the same operator decisions as Java, plus the ?? fallback TypeScript already flips, and a negation of boolean conditions so guard is covered. A logical ! and a unary - are deleted; a force-unwrap is not. Statements and returns are not removed, because the other languages do not remove them either. private and fileprivate declarations use defn-/. A closure crapper does not report stays on the enclosing function, and a stored closure is its own entry, so the snapshot namespace matches .metrics/crap.edn. Proved by tests/test_swift.py. Those tests failed first: only true/false and 0/1 were sites, private funcs were defn/, and a run exited 0 because the comparison and the guard negation were missing. They pass, and the existing suite still passes (101 tests). Co-authored-by: Robert C. Martin --- src/mutator/functions.py | 6 ++ src/mutator/sites.py | 85 +++++++++++++++++-- tests/test_swift.py | 176 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 261 insertions(+), 6 deletions(-) create mode 100644 tests/test_swift.py diff --git a/src/mutator/functions.py b/src/mutator/functions.py index 4d983b7..108b7ad 100644 --- a/src/mutator/functions.py +++ b/src/mutator/functions.py @@ -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 diff --git a/src/mutator/sites.py b/src/mutator/sites.py index 50d1b78..2fe715d 100644 --- a/src/mutator/sites.py +++ b/src/mutator/sites.py @@ -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,39 @@ _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"} @@ -137,7 +168,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) @@ -336,9 +367,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 child.type == "else": + return True + 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 in _SWIFT_SKIP: + binding = False + 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: diff --git a/tests/test_swift.py b/tests/test_swift.py new file mode 100644 index 0000000..8020b23 --- /dev/null +++ b/tests/test_swift.py @@ -0,0 +1,176 @@ +"""Swift mutation sites join the functions crapper reports.""" + +import sys +from pathlib import Path + +from mutator.cli import run +from mutator.functions import sites_in_file + +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_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") From 23b7d479367e0f9e316fad0d49e23557a236d02a Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 25 Nov 2026 23:58:57 +0000 Subject: [PATCH 2/8] Skip Swift test targets when choosing source files. crapper treats Tests, AppTests, and *Tests.swift as tests, but mutator only asked is_test_file about the filename. That kept a file such as Tests/DemoTests/Board.swift, so a run would mutate the test suite. .build, .swiftpm, and DerivedData were already SKIP_DIRS. A Swift path is now a test path when a directory component ends with Tests, or the file name ends with Tests.swift. A deeper directory named test, the Java fixture layout, is still mutated. Proved by the source walk and by selecting Sources/Demo/Box.swift next to Tests/DemoTests/Board.swift and BoxTests.swift. The walk failed first because those three Tests paths were still chosen. Both tests pass. Co-authored-by: Robert C. Martin --- src/mutator/sources.py | 22 ++++++++++++++++++++++ tests/test_sources.py | 9 +++++++++ tests/test_swift.py | 21 ++++++++++++++++++++- 3 files changed, 51 insertions(+), 1 deletion(-) diff --git a/src/mutator/sources.py b/src/mutator/sources.py index a11edd7..217cf8d 100644 --- a/src/mutator/sources.py +++ b/src/mutator/sources.py @@ -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,19 @@ 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: + """Swift test targets are ``Tests``, ``*Tests``, or ``*Tests.swift``. + + ``test`` at any depth stays a production path. Swift's name is ``Tests``. + """ + + if relative.suffix != ".swift": + return False + if relative.name.endswith("Tests.swift"): + return True + 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 +64,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 +75,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) diff --git a/tests/test_sources.py b/tests/test_sources.py index 9da1818..8a71763 100644 --- a/tests/test_sources.py +++ b/tests/test_sources.py @@ -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, } diff --git a/tests/test_swift.py b/tests/test_swift.py index 8020b23..42f7a11 100644 --- a/tests/test_swift.py +++ b/tests/test_swift.py @@ -3,7 +3,7 @@ import sys from pathlib import Path -from mutator.cli import run +from mutator.cli import parse_args, run, select_files from mutator.functions import sites_in_file SOURCE = """func place(x: Int, ready: Bool, name: String?) -> Int { @@ -137,6 +137,25 @@ def test_private_and_fileprivate_join_the_type_namespace(tmp_path): 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 test_a_swift_run_records_killed_and_survived_on_the_crapper_namespace(tmp_path, capsys): relative = "Sources/Demo/Place.swift" path = tmp_path / relative From 7c72d9deba5b897282ef4b4f45c0eea367542db2 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 26 Nov 2026 00:00:21 +0000 Subject: [PATCH 3/8] Run swift test or xcodebuild, and keep Swift build output private. A SwiftPM package is tested with swift test from the directory that holds Package.swift. An Xcode or iOS project is tested with xcodebuild test. The scheme is --xcode-scheme, otherwise the first shared scheme, otherwise the project name. --xcode-destination is one argument, so a simulator name with spaces is not split. A file inside a package is not also sent to xcodebuild. iOS still needs a Mac with Xcode; the command is only constructed here. Workers no longer link .build, .swiftpm, or DerivedData. A symlink would make swift test and xcodebuild write the real tree's build products, and parallel workers would share them. Proved by tests/test_swift.py. The command tests failed first because Swift returned false, xcode_destination was not a parameter, and a worker linked .build. A run with fake swift and xcodebuild on PATH then showed swift test and xcodebuild test -destination with the scheme. Co-authored-by: Robert C. Martin --- src/mutator/cli.py | 24 +++++- src/mutator/engine.py | 15 +++- src/mutator/runner.py | 67 +++++++++++++++- src/mutator/workers.py | 3 + tests/test_swift.py | 174 +++++++++++++++++++++++++++++++++++++++++ 5 files changed, 279 insertions(+), 4 deletions(-) diff --git a/src/mutator/cli.py b/src/mutator/cli.py index 5f574ed..6cb7d99 100644 --- a/src/mutator/cli.py +++ b/src/mutator/cli.py @@ -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 Run this command for the baseline and every mutant. The working directory is the project root. + --xcode-scheme Scheme for an Xcode or iOS test run. Default: + the first shared scheme, or the project name. + --xcode-destination xcodebuild -destination value. iOS needs this, + and a Mac with Xcode. Example: + platform=iOS Simulator,name=iPhone 16. --timeout-factor Mutant timeout, as a multiple of the baseline duration. Default: 10. The timeout is at least 2 seconds. @@ -147,6 +152,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 +178,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 +243,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 +568,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": diff --git a/src/mutator/engine.py b/src/mutator/engine.py index 0cc70d8..1930830 100644 --- a/src/mutator/engine.py +++ b/src/mutator/engine.py @@ -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 diff --git a/src/mutator/runner.py b/src/mutator/runner.py index e554c76..b1c2d9a 100644 --- a/src/mutator/runner.py +++ b/src/mutator/runner.py @@ -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,55 @@ 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]: + command = [ + "xcodebuild", + "test", + _xcode_flag(project), + str(project), + "-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 +283,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 diff --git a/src/mutator/workers.py b/src/mutator/workers.py index a3721f3..1212c21 100644 --- a/src/mutator/workers.py +++ b/src/mutator/workers.py @@ -43,6 +43,9 @@ SKIP_LINK = frozenset( ".mypy_cache", ".clj-kondo", ".gradle", + ".build", + ".swiftpm", + "DerivedData", } ) diff --git a/tests/test_swift.py b/tests/test_swift.py index 42f7a11..433aa98 100644 --- a/tests/test_swift.py +++ b/tests/test_swift.py @@ -1,10 +1,12 @@ """Swift mutation sites join the functions crapper reports.""" +import os import sys from pathlib import Path 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 } @@ -156,6 +158,178 @@ def test_swift_test_files_are_skipped_and_production_sources_are_kept(tmp_path, 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 parse_args(["--xcode-scheme"]).exit_code == 1 + + +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", "\n") + _write(project / "xcshareddata" / "xcschemes" / "Zed.xcscheme", "\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", + str(project.resolve()), + "-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", "\n") + _write(root / "App.xcodeproj" / "project.pbxproj", "") + _write(workspace / "xcshareddata" / "xcschemes" / "App.xcscheme", "\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", str(workspace.resolve())] + 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", "\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", str(project.resolve()), "-scheme", "App"] + assert app_dir == root.resolve() + + +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", "\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 str(project.resolve()) in xcode_text + assert "-scheme" in xcode_text + assert "App" in xcode_text.splitlines() + assert destination in xcode_text.splitlines() + + 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 From 3f6dc5bb7cd817bfecde856f190519c33f9a3af9 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 26 Nov 2026 00:00:50 +0000 Subject: [PATCH 4/8] Read Swift coverage from the reports crapper already parses. llvm-cov JSON and xccov JSON land in target/coverage/swift. crapper turns those into regions or function summaries. A region with a hit marks that line covered. An xccov summary has no lines, so the function line is covered when the summary's covered count is above zero. A file missing from the report stays uncovered and is not run. Proved by tests/test_coverage.py, which failed first because a Swift file with a report still returned no lines, and by a scan that marks an unhit line uncovered. The reports are the same JSON shapes crapper reads; mutator does not parse them itself. Co-authored-by: Robert C. Martin --- src/mutator/coverage.py | 24 +++++++++++- tests/test_coverage.py | 84 +++++++++++++++++++++++++++++++++++++++++ tests/test_swift.py | 29 ++++++++++++++ 3 files changed, 135 insertions(+), 2 deletions(-) diff --git a/src/mutator/coverage.py b/src/mutator/coverage.py index ab082e8..e8c083f 100644 --- a/src/mutator/coverage.py +++ b/src/mutator/coverage.py @@ -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: diff --git a/tests/test_coverage.py b/tests/test_coverage.py index 5f715ed..259eb4a 100644 --- a/tests/test_coverage.py +++ b/tests/test_coverage.py @@ -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( diff --git a/tests/test_swift.py b/tests/test_swift.py index 433aa98..6b4f42a 100644 --- a/tests/test_swift.py +++ b/tests/test_swift.py @@ -330,6 +330,35 @@ def test_a_run_invokes_swift_test_and_xcodebuild_with_the_destination(tmp_path, assert destination in xcode_text.splitlines() +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 test_a_swift_run_records_killed_and_survived_on_the_crapper_namespace(tmp_path, capsys): relative = "Sources/Demo/Place.swift" path = tmp_path / relative From 883a611b6891b8dc3b6d0c7e031549af9d101c5d Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 26 Nov 2026 00:01:19 +0000 Subject: [PATCH 5/8] Document Swift mutation, discovery, and the Mac test commands. The README and --help now name Swift with the other languages, list the operators (including which edits are not made), and say how Tests, *Tests.swift, .build, .swiftpm, and DerivedData are skipped. They also give swift test, xcodebuild test, --xcode-scheme, and --xcode-destination, and say an iOS run needs a Mac with Xcode. Proved by the help test, which checks that --help names swift test, xcodebuild, and *Tests.swift. Co-authored-by: Robert C. Martin --- README.md | 19 +++++++++++++++---- pyproject.toml | 2 +- src/mutator/cli.py | 3 ++- tests/test_swift.py | 1 + 4 files changed, 19 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 389457b..6533068 100644 --- a/README.md +++ b/README.md @@ -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/.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 diff --git a/pyproject.toml b/pyproject.toml index 818c4e1..d6bf0c0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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)"] diff --git a/src/mutator/cli.py b/src/mutator/cli.py index 6cb7d99..ff24a49 100644 --- a/src/mutator/cli.py +++ b/src/mutator/cli.py @@ -128,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. diff --git a/tests/test_swift.py b/tests/test_swift.py index 6b4f42a..d9b1da1 100644 --- a/tests/test_swift.py +++ b/tests/test_swift.py @@ -175,6 +175,7 @@ def test_xcode_options_require_a_value(): 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 From b9184399023f02c4820350f783a0dc78225d8418 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 26 Nov 2026 00:09:27 +0000 Subject: [PATCH 6/8] Kill equivalent Swift mutants and prove a SwiftPM run. Stopping a guard at else was the same as stopping at the following brace, and the binding flag started false only to be cleared by the keyword. Those edits survived because no test could see a difference, so the duplicate paths are gone. *Tests.swift stays crapper's filename rule; this check only adds Tests directories. A tiny package run with swift test records killed and survived on Demo.place and restores the source. The test skips when swift is not installed. The full suite, including that run on Swift 6.4.3, passed (115 tests). Co-authored-by: Robert C. Martin --- src/mutator/sites.py | 7 +++-- src/mutator/sources.py | 5 ++-- tests/test_swift.py | 60 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 65 insertions(+), 7 deletions(-) diff --git a/src/mutator/sites.py b/src/mutator/sites.py index 2fe715d..73161f0 100644 --- a/src/mutator/sites.py +++ b/src/mutator/sites.py @@ -65,7 +65,6 @@ _SWIFT_SKIP = { "repeat", "{", "}", - ",", "statements", "if_statement", "comment", @@ -368,8 +367,6 @@ def _visit_leaf(node, data: bytes, language: str, found: list[RawSite]) -> None: def _ends_swift_conditions(node, child) -> bool: - if child.type == "else": - return True if node.type == "repeat_while_statement": return False return child.type in {"{", "statements"} @@ -383,9 +380,11 @@ def _swift_conditions(node): for child in node.children: if _ends_swift_conditions(node, child): break - if child.type in _SWIFT_SKIP: + if child.type == ",": binding = False continue + if child.type in _SWIFT_SKIP: + continue if child.type == "value_binding_pattern": binding = True continue diff --git a/src/mutator/sources.py b/src/mutator/sources.py index 217cf8d..e066784 100644 --- a/src/mutator/sources.py +++ b/src/mutator/sources.py @@ -35,15 +35,14 @@ def is_test_path(relative: Path, test_dirs: set[str]) -> bool: def _swift_test_relative(relative: Path) -> bool: - """Swift test targets are ``Tests``, ``*Tests``, or ``*Tests.swift``. + """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 - if relative.name.endswith("Tests.swift"): - return True return any(part.endswith("Tests") for part in relative.parts[:-1]) diff --git a/tests/test_swift.py b/tests/test_swift.py index d9b1da1..9c1e645 100644 --- a/tests/test_swift.py +++ b/tests/test_swift.py @@ -1,9 +1,12 @@ """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 @@ -179,6 +182,14 @@ def test_xcode_options_require_a_value(): 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") @@ -360,6 +371,55 @@ def test_scan_marks_a_swift_line_uncovered_when_llvm_cov_did_not_hit_it(tmp_path 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 From b494411b07b2bfa031de6bed1d59b46b64b4e434 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 26 Nov 2026 00:26:05 +0000 Subject: [PATCH 7/8] Compile the Xcode mutant instead of the original project. xcodebuild was given the absolute path of the real project, and the worker only symlinked that bundle. The tool realpaths the project, so every mutant compiled the unmutated tree and survived. The command now names the project relative to the working directory, which the worker maps onto its overlay. The overlay copies an .xcodeproj or .xcworkspace instead of linking it, so realpath stays on the copy that holds the mutant. A file that only ends in .xcodeproj stays a link. Proved by a fake xcodebuild that realpaths the project and reads the Swift file the project names. The comparison and the negated condition are killed, and a constant survives. The same check uses a workspace. A baseline that exits 1 records no kills. The tests failed first on an absolute path, then on a symlink that escaped the worker. The suite passes (118 tests, and the SwiftPM run is skipped because swift is not installed). Co-authored-by: Robert C. Martin --- src/mutator/runner.py | 8 +- src/mutator/workers.py | 32 ++++++- tests/test_swift.py | 199 ++++++++++++++++++++++++++++++++++++++++- 3 files changed, 231 insertions(+), 8 deletions(-) diff --git a/src/mutator/runner.py b/src/mutator/runner.py index b1c2d9a..153e362 100644 --- a/src/mutator/runner.py +++ b/src/mutator/runner.py @@ -240,11 +240,17 @@ def _xcode_scheme(project: Path, requested: str | None) -> str: 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), - str(project), + project.name, "-scheme", _xcode_scheme(project, scheme), ] diff --git a/src/mutator/workers.py b/src/mutator/workers.py index 1212c21..a397abb 100644 --- a/src/mutator/workers.py +++ b/src/mutator/workers.py @@ -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 @@ -142,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 @@ -151,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) diff --git a/tests/test_swift.py b/tests/test_swift.py index 9c1e645..4f0ac98 100644 --- a/tests/test_swift.py +++ b/tests/test_swift.py @@ -214,7 +214,7 @@ def test_an_xcode_project_runs_xcodebuild_with_scheme_and_destination(tmp_path): "xcodebuild", "test", "-project", - str(project.resolve()), + project.name, "-scheme", "App", "-destination", @@ -235,7 +235,7 @@ def test_a_workspace_uses_its_flag_and_a_missing_scheme_uses_the_project_name(tm _write(workspace / "xcshareddata" / "xcschemes" / "App.xcscheme", "\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", str(workspace.resolve())] + assert command[:4] == ["xcodebuild", "test", "-workspace", workspace.name] assert "-destination" not in command assert directory == root.resolve() @@ -261,10 +261,28 @@ def test_a_package_is_tested_with_swift_and_an_app_outside_it_with_xcodebuild(tm 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", str(project.resolve()), "-scheme", "App"] + 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 @@ -336,12 +354,185 @@ def test_a_run_invokes_swift_test_and_xcodebuild_with_the_destination(tmp_path, assert xcode_code == 3 assert "xcodebuild" not in xcode_text assert "-project" in xcode_text - assert str(project.resolve()) 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", "\n") + _write(project / "xcshareddata" / "xcschemes" / "Zed.xcscheme", "\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", '\n') + _write(workspace / "xcshareddata" / "xcschemes" / "App.xcscheme", "\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 From 811859050338b383850a5a38e740b211b78bc3e8 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 26 Nov 2026 01:04:26 +0000 Subject: [PATCH 8/8] Kill the Clojure site survivors instead of leaving them. A reader quote is a quoting_lit, so '(+ 1 0) was not covered by the (quote ...) test. The skip returned True there and the mutant survived. A + inside a vector is not a call, a symbol True is not a boolean, and the anchor of a Clojure site is its own line. _clojure_text repeated its type check with a child-count clause, and _is_head's final return never ran because the symbol is a child of its list. Both are gone. Proved by the Clojure site tests. mutator on src/mutator/sites.py then scored 66 killed, 0 survived, 0 uncovered. The suite passes (119 tests, and the SwiftPM run is skipped because swift is not installed). Co-authored-by: Robert C. Martin --- src/mutator/sites.py | 6 +++--- tests/test_sites.py | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/mutator/sites.py b/src/mutator/sites.py index 73161f0..146d683 100644 --- a/src/mutator/sites.py +++ b/src/mutator/sites.py @@ -124,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. @@ -248,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: @@ -268,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 "" diff --git a/tests/test_sites.py b/tests/test_sites.py index bae3e62..32ccf32 100644 --- a/tests/test_sites.py +++ b/tests/test_sites.py @@ -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 {