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