Merge pull request #46 from unclebob/cursor/macos-swift-coverage-ea9f

Fix macOS Swift coverage lookup and record region end lines
This commit is contained in:
cursor[bot]
2026-11-26 01:52:06 +00:00
committed by GitHub
7 changed files with 689 additions and 39 deletions
+9 -4
View File
@@ -88,12 +88,14 @@ By default a run deletes the previous report for each language it is about to me
| TypeScript | `npm run coverage`, or Vitest `--coverage`, or `npx c8 ... npm test` | `coverage/lcov.info` or `target/coverage/typescript/lcov.info` | | TypeScript | `npm run coverage`, or Vitest `--coverage`, or `npx c8 ... npm test` | `coverage/lcov.info` or `target/coverage/typescript/lcov.info` |
| Rust | `cargo llvm-cov` or `cargo tarpaulin`, per Cargo package | `target/coverage/rust/lcov.info` | | Rust | `cargo llvm-cov` or `cargo tarpaulin`, per Cargo package | `target/coverage/rust/lcov.info` |
| Python | `coverage run` with pytest or unittest, then `coverage lcov` | `target/coverage/python/lcov.info` | | Python | `coverage run` with pytest or unittest, then `coverage lcov` | `target/coverage/python/lcov.info` |
| Swift | `swift test --enable-code-coverage`, then `llvm-cov export -format=json`; or `xcodebuild test -enableCodeCoverage YES` and `xcrun xccov view --report --json` | `target/coverage/swift/**/*.json` | | Swift | `swift test --enable-code-coverage`, then `llvm-cov export` (JSON by default); or `xcodebuild test -enableCodeCoverage YES` and `xcrun xccov view --report --json` | `target/coverage/swift/**/*.json` |
A missing tool or a failed test run scores that language at 0% and still writes the snapshot. Pass `--coverage-command` to replace those defaults with one command of your own. `--no-coverage` is the run that leaves coverage and CRAP as N/A. A missing tool or a failed test run scores that language at 0% and still writes the snapshot. Pass `--coverage-command` to replace those defaults with one command of your own. `--no-coverage` is the run that leaves coverage and CRAP as N/A.
Swift coverage is region coverage. llvm-cov code regions count; branch, gap, skipped, and expansion regions do not. A report with no function regions uses segments that carry a count. An xccov report joins a function on `lineNumber` and uses `coveredLines` / `executableLines`. A path in the report may be absolute; the file is matched by suffix, as the other languages are. Swift coverage is region coverage. llvm-cov code regions count; branch, gap, skipped, and expansion regions do not. A report with no function regions uses segments that carry a count. An xccov report joins a function on `lineNumber` and uses `coveredLines` / `executableLines`. A path in the report may be absolute; the file is matched by suffix, as the other languages are.
Each llvm-cov region is `(start_line, end_line, count)` on `SwiftFile.regions`. `SwiftFile.line_covered(line)` is true when the innermost region containing that line has a count greater than zero. A nested region with count zero leaves its lines uncovered, and a line in no region is uncovered. A segment is one line, so its start and end are the same. CRAP still counts each region once, and only when its start line lies in the function. An xccov summary stays `(line, covered, executable)` and is not a region, so `line_covered` does not read it.
## Swift coverage on a Mac ## Swift coverage on a Mac
iOS coverage is produced by Xcode on a Mac. crapper runs the commands below when `swift` or `xcodebuild` is on the path. To score a report that was produced on another machine, put the JSON under `target/coverage/swift/` and pass `--use-existing-coverage`. iOS coverage is produced by Xcode on a Mac. crapper runs the commands below when `swift` or `xcodebuild` is on the path. To score a report that was produced on another machine, put the JSON under `target/coverage/swift/` and pass `--use-existing-coverage`.
@@ -102,14 +104,17 @@ Swift package:
```bash ```bash
swift test --enable-code-coverage swift test --enable-code-coverage
bin="$(dirname "$(command -v swift)")/llvm-cov" bin="$(xcrun --find llvm-cov)"
profdata="$(find .build -path '*/codecov/default.profdata' -print -quit)" profdata="$(find .build -path '*/codecov/default.profdata' -print -quit)"
binary="$(find .build -type f \( -name '*PackageTests' -o -name '*PackageTests.xctest' \) ! -path '*.dSYM/*' -print -quit)" base="$(swift build --show-bin-path)"
binary="$(find "$base" -type f -path '*.xctest/Contents/MacOS/*Tests' ! -path '*.dSYM/*' -print -quit)"
mkdir -p target/coverage/swift mkdir -p target/coverage/swift
"$bin" export -format=json -instr-profile="$profdata" "$binary" \ "$bin" export -instr-profile="$profdata" "$binary" \
> target/coverage/swift/llvm-cov.json > target/coverage/swift/llvm-cov.json
``` ```
`llvm-cov export` writes JSON without `-format=json`. Apple LLVM 21 rejects that flag. On a current toolchain the test binary is `NameTests` inside `NameTests.xctest/Contents/MacOS`, under the directory `swift build --show-bin-path` prints. Older toolchains call it `PackageTests` (on Linux the `.xctest` file itself is the executable). When `xcrun` is missing, llvm-cov beside `swift` is the next place to look. crapper falls back to searching `.build` when `swift build --show-bin-path` prints nothing.
Xcode, including an iOS app. The scheme has to be shared (`xcshareddata/xcschemes`). Use `-workspace App.xcworkspace` when the app has a workspace. Xcode, including an iOS app. The scheme has to be shared (`xcshareddata/xcschemes`). Use `-workspace App.xcworkspace` when the app has a workspace.
```bash ```bash
+54 -14
View File
@@ -369,11 +369,30 @@ def _segments_percent(segments, start: int, end: int) -> float | None:
@dataclass @dataclass
class SwiftFile: class SwiftFile:
"""Regions `(line, count)` or xccov summaries `(line, covered, executable)`.""" """Code regions `(start_line, end_line, count)`, or xccov summaries.
regions: list[tuple[int, int]] = field(default_factory=list) `line_covered` is the line question. The innermost region containing the
line is covered when its count is greater than zero, so a nested region
with count zero leaves those lines uncovered. A line in no region is
uncovered. Summaries are not regions: they still score CRAP, and
`line_covered` does not read them.
CRAP counts each region once, and only when its start line lies in the
function. A segment, used when a file has no function regions, is one
line (`start_line == end_line`).
"""
regions: list[tuple[int, int, int]] = field(default_factory=list)
summaries: list[tuple[int, int, int]] = field(default_factory=list) summaries: list[tuple[int, int, int]] = field(default_factory=list)
def line_covered(self, line: int) -> bool:
"""True when the innermost region containing `line` has a count above zero."""
region = _innermost_region(self.regions, line)
if region is None:
return False
return region[2] > 0
def _is_llvm(data) -> bool: def _is_llvm(data) -> bool:
if not isinstance(data, dict): if not isinstance(data, dict):
@@ -383,21 +402,21 @@ def _is_llvm(data) -> bool:
return isinstance(data.get("data"), list) return isinstance(data.get("data"), list)
def _pair(line, count) -> tuple[int, int] | None: def _region_count(start, end, count) -> tuple[int, int, int] | None:
try: try:
return int(line), int(count) return int(start), int(end), int(count)
except (TypeError, ValueError): except (TypeError, ValueError):
return None return None
def _code_region(region) -> tuple[int, int] | None: def _code_region(region) -> tuple[int, int, int] | None:
"""A code region. Branch, gap, skipped, and expansion regions are not lines.""" """A code region. Branch, gap, skipped, and expansion regions are not lines."""
if not isinstance(region, list) or len(region) < 5: if not isinstance(region, list) or len(region) < 5:
return None return None
if len(region) >= 8 and region[7] not in (0, None): if len(region) >= 8 and region[7] not in (0, None):
return None return None
return _pair(region[0], region[4]) return _region_count(region[0], region[2], region[4])
def _segment_counts(segment) -> bool: def _segment_counts(segment) -> bool:
@@ -410,15 +429,15 @@ def _segment_counts(segment) -> bool:
return True return True
def _segment_region(segment) -> tuple[int, int] | None: def _segment_region(segment) -> tuple[int, int, int] | None:
if not isinstance(segment, list) or len(segment) < 4: if not isinstance(segment, list) or len(segment) < 4:
return None return None
if not _segment_counts(segment): if not _segment_counts(segment):
return None return None
return _pair(segment[0], segment[2]) return _region_count(segment[0], segment[0], segment[2])
def _regions_of(values, reader) -> list[tuple[int, int]]: def _regions_of(values, reader) -> list[tuple[int, int, int]]:
found = [] found = []
if not isinstance(values, list): if not isinstance(values, list):
return found return found
@@ -438,15 +457,15 @@ def _region_file(region: list) -> int:
return 0 return 0
def _add_function_region(found: dict[int, list[tuple[int, int]]], region) -> None: def _add_function_region(found: dict[int, list[tuple[int, int, int]]], region) -> None:
parsed = _code_region(region) parsed = _code_region(region)
if parsed is None or not isinstance(region, list): if parsed is None or not isinstance(region, list):
return return
found.setdefault(_region_file(region), []).append(parsed) found.setdefault(_region_file(region), []).append(parsed)
def _llvm_function_regions(unit: dict) -> dict[int, list[tuple[int, int]]]: def _llvm_function_regions(unit: dict) -> dict[int, list[tuple[int, int, int]]]:
found: dict[int, list[tuple[int, int]]] = {} found: dict[int, list[tuple[int, int, int]]] = {}
for function in unit.get("functions") or []: for function in unit.get("functions") or []:
if not isinstance(function, dict): if not isinstance(function, dict):
continue continue
@@ -540,11 +559,32 @@ def parse_swift_coverage(text: str) -> dict[str, SwiftFile]:
return _xccov_files(data) return _xccov_files(data)
def _contains_line(region: tuple[int, int, int], line: int) -> bool:
start, end, _count = region
return start <= line <= end
def _region_rank(region: tuple[int, int, int]) -> tuple[int, int]:
"""Smaller span first. The same span keeps the region that starts later."""
start, end, _count = region
return (end - start, -start)
def _innermost_region(regions, line: int) -> tuple[int, int, int] | None:
containing = [region for region in regions if _contains_line(region, line)]
if not containing:
return None
return min(containing, key=_region_rank)
def _covered_regions(regions, start: int, end: int) -> tuple[int, int]: def _covered_regions(regions, start: int, end: int) -> tuple[int, int]:
"""Each region counts once, and only when its start line lies in the function."""
total = 0 total = 0
covered = 0 covered = 0
for line, count in regions: for region_start, _region_end, count in regions:
if line < start or line > end: if region_start < start or region_start > end:
continue continue
total += 1 total += 1
if count > 0: if count > 0:
+112 -20
View File
@@ -555,7 +555,13 @@ def swift_test_command() -> list[str]:
def swift_export_command(tool: str, binary: Path, profdata: Path) -> list[str]: def swift_export_command(tool: str, binary: Path, profdata: Path) -> list[str]:
return [tool, "export", "-format=json", f"-instr-profile={profdata}", str(binary)] """argv for llvm-cov's default export, which is JSON.
Apple LLVM 21 rejects `-format=json` (`Cannot find option named 'json'`).
Its default export already writes `llvm.coverage.json.export`.
"""
return [tool, "export", f"-instr-profile={profdata}", str(binary)]
def xcode_export_command(result: Path) -> list[str]: def xcode_export_command(result: Path) -> list[str]:
@@ -581,37 +587,101 @@ def swift_profdata(package: Path) -> Path | None:
return _first_file(package, ".build/**/codecov/default.profdata") return _first_file(package, ".build/**/codecov/default.profdata")
def _part_ends_with(path: Path, suffix: str) -> bool:
return any(part.endswith(suffix) for part in path.parts)
def _in_dsym(path: Path) -> bool: def _in_dsym(path: Path) -> bool:
return any(part.endswith(".dSYM") for part in path.parts) return _part_ends_with(path, ".dSYM")
def _swift_binary(path: Path) -> bool: def _in_xctest(path: Path) -> bool:
return _part_ends_with(path, ".xctest")
def _named_test_file(path: Path) -> bool:
name = path.name
if name.endswith("PackageTests") or name.endswith("Tests.xctest"):
return True
return name.endswith("Tests") and _in_xctest(path)
def _test_executable(path: Path) -> bool:
if not path.is_file() or _in_dsym(path): if not path.is_file() or _in_dsym(path):
return False return False
return path.name.endswith("PackageTests") or path.name.endswith("PackageTests.xctest") return _named_test_file(path)
def _first_test_binary(base: Path) -> Path | None:
if not base.is_dir():
return None
found = sorted(path for path in base.rglob("*") if _test_executable(path))
if not found:
return None
return found[0]
def _tool_stdout(name: str, args: list[str], cwd: Path | None = None) -> str | None:
tool = shutil.which(name)
if not tool:
return None
return _command_stdout([tool, *args], cwd)
def _shown_directory(package: Path, text: str) -> Path | None:
stripped = text.strip()
if stripped == "":
return None
path = Path(stripped)
if not path.is_absolute():
path = package / path
return path
def _swift_bin_path(package: Path) -> Path | None:
text = _tool_stdout("swift", ["build", "--show-bin-path"], package)
if text is None:
return None
return _shown_directory(package, text)
def swift_test_binary(package: Path) -> Path | None: def swift_test_binary(package: Path) -> Path | None:
"""The test executable. macOS nests it in the .xctest bundle; Linux names the file .xctest. """The test executable.
A dSYM stores another file with the same name. That is debug info, not the executable. Prefer the directory `swift build --show-bin-path` prints. Otherwise
search `.build`. A current toolchain puts `NameTests` inside
`NameTests.xctest/Contents/MacOS`. On Linux the `.xctest` file is the
executable. Older toolchains call that file `PackageTests`. A dSYM is
debug info, not the executable.
""" """
found = [ base = _swift_bin_path(package)
path if base is not None:
for pattern in (".build/**/*PackageTests", ".build/**/*PackageTests.xctest") found = _first_test_binary(base)
for path in package.glob(pattern) if found is not None:
if _swift_binary(path)
]
if not found:
return None
return sorted(set(found))[0]
def llvm_cov_tool() -> str | None:
found = shutil.which("llvm-cov")
if found:
return found return found
return _first_test_binary(package / ".build")
def _command_stdout(command: list[str], cwd: Path | None = None) -> str | None:
"""Captured stdout, or None when the command cannot start or exits non-zero."""
try:
completed = subprocess.run(
command,
cwd=cwd,
capture_output=True,
text=True,
check=False,
)
except OSError:
return None
if completed.returncode != 0:
return None
return completed.stdout
def _llvm_cov_beside_swift() -> str | None:
swift = shutil.which("swift") swift = shutil.which("swift")
if not swift: if not swift:
return None return None
@@ -621,6 +691,28 @@ def llvm_cov_tool() -> str | None:
return None return None
def _llvm_cov_from_xcrun() -> str | None:
text = _tool_stdout("xcrun", ["--find", "llvm-cov"])
if text is None:
return None
path = Path(text.strip())
if path.is_file():
return str(path)
return None
def llvm_cov_tool() -> str | None:
"""llvm-cov on PATH, beside swift, or `xcrun --find llvm-cov` on a Mac."""
found = shutil.which("llvm-cov")
if found:
return found
sibling = _llvm_cov_beside_swift()
if sibling is not None:
return sibling
return _llvm_cov_from_xcrun()
def _xcode_bundle(directory: Path) -> Path | None: def _xcode_bundle(directory: Path) -> Path | None:
if not directory.is_dir(): if not directory.is_dir():
return None return None
+2
View File
@@ -165,6 +165,8 @@ def test_load_bundle_merges_each_report(tmp_path):
assert bundle.percent_for(function(start_line=3, end_line=4)) == 50.0 assert bundle.percent_for(function(start_line=3, end_line=4)) == 50.0
assert bundle.go_profile is not None assert bundle.go_profile is not None
assert bundle.jacoco is not None assert bundle.jacoco is not None
assert "src/demo/core.clj" in bundle.form_html
assert "index" not in bundle.form_html
def _go_module(module_dir, module_line, profile_text): def _go_module(module_dir, module_line, profile_text):
+35 -1
View File
@@ -54,6 +54,8 @@ def test_suffix_match_rejects_a_longer_suffix():
assert suffix_match("src/demo/core.clj", "demo/core.clj") is True assert suffix_match("src/demo/core.clj", "demo/core.clj") is True
assert suffix_match("core.clj", "src/demo/core.clj") is False assert suffix_match("core.clj", "src/demo/core.clj") is False
assert suffix_match("src/demo/core.clj", "") is False assert suffix_match("src/demo/core.clj", "") is False
assert suffix_match("", "") is False
assert suffix_match("src/a.go", "src/a.go") is True
def test_coverage_percent_is_zero_when_there_is_nothing_to_count(): def test_coverage_percent_is_zero_when_there_is_nothing_to_count():
@@ -74,13 +76,17 @@ def test_lcov_keeps_a_file_that_has_no_end_record():
def test_go_profile_rejects_a_broken_line(): def test_go_profile_rejects_a_broken_line():
with pytest.raises(ValueError, match="invalid coverage segment"): with pytest.raises(ValueError, match="invalid coverage segment on line 2"):
parse_go_profile("mode: set\nnot a segment\n") parse_go_profile("mode: set\nnot a segment\n")
with pytest.raises(ValueError, match="invalid coverage segment on line 1"):
parse_go_profile("not a segment\n")
def test_go_percent_is_zero_when_no_segment_overlaps_the_function(): def test_go_percent_is_zero_when_no_segment_overlaps_the_function():
profile = parse_go_profile("mode: set\nboard.go:1.1,2.2 1 1\n") profile = parse_go_profile("mode: set\nboard.go:1.1,2.2 1 1\n")
assert go_percent(profile, "board.go", 10, 12) == 0.0 assert go_percent(profile, "board.go", 10, 12) == 0.0
touching = parse_go_profile("mode: set\nboard.go:3.1,4.2 2 2\n")
assert go_percent(touching, "board.go", 1, 3) == 100.0
def test_go_percent_does_not_accept_the_first_unrelated_file(): def test_go_percent_does_not_accept_the_first_unrelated_file():
@@ -158,6 +164,34 @@ def test_a_shorter_file_does_not_take_a_longer_files_coverage():
assert bundle.percent_for(long) == 100.0 assert bundle.percent_for(long) == 100.0
def test_an_equal_report_key_blocks_a_longer_file():
bundle = CoverageBundle(
go_profile=parse_go_profile("mode: set\n/data/board.go:1.1,2.2 1 1\n")
)
bundle.bind_sources(["/proj/data/board.go", "/data/board.go"])
covered = function(path="/proj/data/board.go", start_line=1, end_line=2)
assert bundle.percent_for(covered) is None
def test_the_smaller_added_prefix_is_not_the_shorter_extra_prefix():
profile = parse_go_profile(
"mode: set\n"
"X/proj/src/demo/file.go:1.1,2.2 1 1\n"
"Y/Z/proj/demo/file.go:1.1,2.2 1 0\n"
)
assert go_percent(profile, "/proj/src/demo/file.go", 1, 2) == 100.0
def test_a_candidate_path_is_not_blank():
from crapper.coverage import _candidates, _key_has_suffix
assert "" not in _candidates("")
assert _key_has_suffix(["src", "a.go"], ["src", "a.go"]) is True
bundle = CoverageBundle()
bundle.bind_sources(["a.go", "a.go"])
assert bundle.source_parts.count(("a.go",)) == 1
def test_a_short_report_key_matches_one_longer_source(): def test_a_short_report_key_matches_one_longer_source():
bundle = CoverageBundle( bundle = CoverageBundle(
go_profile=parse_go_profile("mode: set\nboard.go:4.1,6.2 2 1\n") go_profile=parse_go_profile("mode: set\nboard.go:4.1,6.2 2 1\n")
+124
View File
@@ -17,8 +17,10 @@ from crapper.runners import (
_python_kind, _python_kind,
_record_python_lcov, _record_python_lcov,
_restore_manifests, _restore_manifests,
_cover_python,
_rust_kind, _rust_kind,
_vitest_version, _vitest_version,
write_command_output,
python_coverage_commands, python_coverage_commands,
python_roots, python_roots,
python_sources, python_sources,
@@ -567,3 +569,125 @@ def test_vitest_install_restores_manifests_when_install_changes_them(tmp_path, m
def test_python_sources_name_a_top_level_module_without_its_suffix(tmp_path): def test_python_sources_name_a_top_level_module_without_its_suffix(tmp_path):
module = tmp_path / "carddav.py" module = tmp_path / "carddav.py"
assert python_sources(tmp_path, [module, tmp_path / "test_carddav.py"]) == "carddav" assert python_sources(tmp_path, [module, tmp_path / "test_carddav.py"]) == "carddav"
def test_an_empty_language_directory_is_kept(tmp_path):
kept = tmp_path / "target" / "coverage" / "go"
kept.mkdir(parents=True)
_clean_clojure(tmp_path)
assert kept.is_dir()
def test_command_output_can_be_written_twice_under_nested_parents(tmp_path, monkeypatch):
def fake_run(command, cwd, stdout):
stdout.write("ok")
class Completed:
returncode = 0
return Completed()
monkeypatch.setattr("crapper.runners.subprocess.run", fake_run)
destination = tmp_path / "a" / "b" / "out.json"
assert write_command_output(["llvm-cov"], tmp_path, destination) == 0
assert write_command_output(["llvm-cov"], tmp_path, destination) == 0
assert destination.read_text(encoding="utf-8") == "ok"
def test_vitest_coverage_is_ready_only_after_a_real_install(tmp_path, monkeypatch):
provider = tmp_path / "node_modules" / "@vitest" / "coverage-v8"
def install(command, cwd):
provider.mkdir(parents=True)
return 0
monkeypatch.setattr("crapper.runners.run_shell", install)
assert _ensure_vitest_coverage(tmp_path) is True
other = tmp_path / "other"
other.mkdir()
monkeypatch.setattr("crapper.runners.run_shell", lambda command, cwd: 0)
assert _ensure_vitest_coverage(other) is False
def test_rustup_failure_is_reported_and_success_is_quiet(monkeypatch, capsys):
monkeypatch.setattr(
"crapper.runners.shutil.which",
lambda name: "/bin/rustup" if name == "rustup" else None,
)
monkeypatch.setattr("crapper.runners.run_shell", lambda command, cwd: 0)
assert _rust_kind() is None
assert "llvm-tools-preview failed" not in capsys.readouterr().err
monkeypatch.setattr("crapper.runners.run_shell", lambda command, cwd: 1)
assert _rust_kind() is None
assert "llvm-tools-preview failed" in capsys.readouterr().err
def test_a_failed_install_does_not_count_as_llvm_cov(monkeypatch):
installed = {"done": False}
def which(name):
if name == "cargo-llvm-cov" and installed["done"]:
return "/bin/cargo-llvm-cov"
return None
def shell(command, cwd):
installed["done"] = True
return 1
monkeypatch.setattr("crapper.runners.shutil.which", which)
monkeypatch.setattr("crapper.runners.run_shell", shell)
assert _rust_kind() is None
def test_java_and_go_success_are_quiet(tmp_path, monkeypatch, capsys):
java = _write(tmp_path, "src/Board.java", "class Board {}\n")
_write(tmp_path, "pom.xml", "<project></project>\n")
monkeypatch.setattr("crapper.runners.run_shell", lambda command, cwd: 0)
run_coverage(tmp_path, [java], None)
assert "exited" not in capsys.readouterr().err
monkeypatch.setattr("crapper.runners.run_shell", lambda command, cwd: 1)
run_coverage(tmp_path, [java], None)
assert "Java coverage exited 1" in capsys.readouterr().err
go_root = tmp_path / "go"
go_source = _write(go_root, "board.go", "package demo\nfunc Place() int { return 1 }\n")
_write(go_root, "go.mod", "module example.com/demo\n")
monkeypatch.setattr("crapper.runners.run_shell", lambda command, cwd: 0)
run_coverage(go_root, [go_source], None)
assert "Go coverage exited" not in capsys.readouterr().err
monkeypatch.setattr("crapper.runners.run_shell", lambda command, cwd: 1)
run_coverage(go_root, [go_source], None)
assert "Go coverage exited 1" in capsys.readouterr().err
def test_python_and_rust_reports_are_created_again(tmp_path, monkeypatch, capsys):
python = _write(tmp_path, "src/app.py", "def run():\n return 1\n")
_write(tmp_path, "pyproject.toml", "")
monkeypatch.setattr("crapper.runners._ensure_python_module", lambda *args: True)
monkeypatch.setattr("crapper.runners.run_shell", lambda *args: 0)
monkeypatch.setattr("crapper.runners._record_python_lcov", lambda *args: None)
_cover_python(tmp_path, [python])
_cover_python(tmp_path, [python])
assert (tmp_path / "target" / "coverage" / "python").is_dir()
rust_root = tmp_path / "rust"
rust = _write(rust_root, "src/lib.rs", "pub fn open() {}\n")
_write(rust_root, "Cargo.toml", '[package]\nname = "demo"\nversion = "0.1.0"\n')
monkeypatch.setattr(
"crapper.runners.shutil.which",
lambda name: "/bin/cargo-llvm-cov" if name == "cargo-llvm-cov" else None,
)
run_coverage(rust_root, [rust], None)
run_coverage(rust_root, [rust], None)
assert (rust_root / "target" / "coverage" / "rust").is_dir()
assert "exited" not in capsys.readouterr().err
monkeypatch.setattr("crapper.runners.run_shell", lambda *args: 1)
run_coverage(rust_root, [rust], None)
assert "Rust coverage exited 1" in capsys.readouterr().err
def test_a_successful_custom_coverage_command_is_quiet(tmp_path, capsys):
assert run_coverage(tmp_path, [], "true") == 0
assert "exited" not in capsys.readouterr().err
+355 -2
View File
@@ -1,11 +1,13 @@
"""Swift functions score the way a reader of the source would count branches.""" """Swift functions score the way a reader of the source would count branches."""
import json
from pathlib import Path from pathlib import Path
from crapper.cli import run from crapper.cli import run
from crapper.coverage import SwiftFile, parse_swift_coverage
from crapper.discover import is_test_file, iter_source_files from crapper.discover import is_test_file, iter_source_files
from crapper.languages.swift import functions_in_source from crapper.languages.swift import functions_in_source
from crapper.runners import run_coverage from crapper.runners import llvm_cov_tool, run_coverage, swift_export_command, swift_test_binary
_FIXTURES = Path(__file__).parent / "fixtures" / "swift" _FIXTURES = Path(__file__).parent / "fixtures" / "swift"
_BOX = (_FIXTURES / "Box.swift").read_text(encoding="utf-8") _BOX = (_FIXTURES / "Box.swift").read_text(encoding="utf-8")
@@ -322,6 +324,113 @@ def test_llvm_cov_regions_join_the_swift_snapshot(tmp_path):
assert ':name "open", :namespace "Demo.Box", :complexity 1, :coverage 100.0, :crap 1.0' in text assert ':name "open", :namespace "Demo.Box", :complexity 1, :coverage 100.0, :crap 1.0' in text
def _llvm_regions(filename: str, regions: list) -> str:
return json.dumps(
{
"type": "llvm.coverage.json.export",
"data": [
{
"files": [{"filename": filename}],
"functions": [{"regions": regions}],
}
],
}
)
def test_a_region_records_its_end_line_and_covers_that_span():
text = _llvm_regions(
"Sources/Demo/Box.swift",
[
[4, 9, 5, 2, 1, 0, 0, 0],
[2, 1, 2, 4, 0, 0, 0, 0],
[4, 1, "end", 2, 1, 0, 0, 0],
],
)
record = parse_swift_coverage(text)["Sources/Demo/Box.swift"]
assert record.regions == [(4, 5, 1), (2, 2, 0)]
assert record.line_covered(4)
assert record.line_covered(5)
assert not record.line_covered(2)
assert not record.line_covered(3)
assert not record.line_covered(6)
def test_the_innermost_region_decides_whether_a_line_is_covered():
nested = SwiftFile(regions=[(1, 6, 1), (4, 5, 0)])
assert nested.line_covered(1)
assert nested.line_covered(3)
assert not nested.line_covered(4)
assert not nested.line_covered(5)
assert nested.line_covered(6)
assert not nested.line_covered(7)
later = SwiftFile(regions=[(4, 5, 0), (5, 6, 1)])
assert not later.line_covered(4)
assert later.line_covered(5)
assert later.line_covered(6)
same = SwiftFile(regions=[(4, 5, 0), (4, 5, 1)])
assert not same.line_covered(4)
assert not same.line_covered(5)
def test_a_segment_region_is_a_single_line():
text = json.dumps(
{
"data": [
{
"files": [
{
"filename": "Short.swift",
"segments": ["nope", [1, 2], [2, 5, 1, True]],
}
],
"functions": [],
}
]
}
)
short = parse_swift_coverage(text)["Short.swift"]
assert short.regions == [(2, 2, 1)]
text = (_FIXTURES / "segments.json").read_text(encoding="utf-8")
record = parse_swift_coverage(text)["Sources/Demo/Box.swift"]
assert (2, 2, 1) in record.regions
assert (5, 5, 0) in record.regions
assert record.line_covered(2)
assert not record.line_covered(3)
assert not record.line_covered(5)
def test_an_xccov_summary_does_not_mark_a_line_covered():
record = SwiftFile(summaries=[(2, 1, 1)])
assert record.line_covered(2) is False
def test_a_spanning_region_still_counts_once_toward_crap(tmp_path):
source = tmp_path / "Sources" / "Demo" / "Box.swift"
source.parent.mkdir(parents=True)
source.write_text(_BOX, encoding="utf-8")
report = tmp_path / "target" / "coverage" / "swift" / "llvm-cov.json"
report.parent.mkdir(parents=True)
report.write_text(
_llvm_regions(
"Sources/Demo/Box.swift",
[
[2, 1, 2, 4, 0, 0, 0, 0],
[4, 1, 5, 2, 1, 0, 0, 0],
],
),
encoding="utf-8",
)
text = _snapshot(tmp_path)
assert ':name "choose", :namespace "Demo", :complexity 2, :coverage 50.0, :crap 2.5' in text
assert ':name "open", :namespace "Demo.Box", :complexity 1, :coverage 0.0, :crap 2.0' in text
record = parse_swift_coverage(report.read_text(encoding="utf-8"))["Sources/Demo/Box.swift"]
assert record.line_covered(5)
assert not record.line_covered(2)
def test_llvm_cov_segments_are_used_when_a_function_has_no_regions(tmp_path): def test_llvm_cov_segments_are_used_when_a_function_has_no_regions(tmp_path):
_swift_project(tmp_path, "segments.json") _swift_project(tmp_path, "segments.json")
text = _snapshot(tmp_path) text = _snapshot(tmp_path)
@@ -336,6 +445,16 @@ def _plant(root: Path, relative: str, source: str = "") -> Path:
return path return path
def test_swift_export_uses_the_default_json_format():
command = swift_export_command("llvm-cov", Path("DemoTests"), Path("default.profdata"))
assert command == [
"llvm-cov",
"export",
"-instr-profile=default.profdata",
"DemoTests",
]
def test_a_swift_package_exports_llvm_cov_json(tmp_path, monkeypatch, capsys): def test_a_swift_package_exports_llvm_cov_json(tmp_path, monkeypatch, capsys):
_plant(tmp_path, "Package.swift", "// swift-tools-version: 5.9\n") _plant(tmp_path, "Package.swift", "// swift-tools-version: 5.9\n")
source = _plant(tmp_path, "Sources/Demo/Box.swift", "func open() {}\n") source = _plant(tmp_path, "Sources/Demo/Box.swift", "func open() {}\n")
@@ -369,7 +488,6 @@ def test_a_swift_package_exports_llvm_cov_json(tmp_path, monkeypatch, capsys):
[ [
"/usr/bin/llvm-cov", "/usr/bin/llvm-cov",
"export", "export",
"-format=json",
f"-instr-profile={profdata}", f"-instr-profile={profdata}",
str(binary), str(binary),
] ]
@@ -574,6 +692,222 @@ def test_llvm_cov_beside_swift_is_used_when_it_is_not_on_the_path(tmp_path, monk
assert exports == [str(llvm)] assert exports == [str(llvm)]
def _program(path: Path, body: str) -> Path:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(body, encoding="utf-8")
path.chmod(0o755)
return path
def _which(found: dict[str, str]):
return lambda name: found.get(name)
def test_xcrun_finds_llvm_cov_when_it_is_not_beside_swift(tmp_path, monkeypatch):
llvm = tmp_path / "XcodeDefault.xctoolchain" / "usr" / "bin" / "llvm-cov"
llvm.parent.mkdir(parents=True)
llvm.write_text("", encoding="utf-8")
xcrun = _program(
tmp_path / "bin" / "xcrun",
"#!/bin/sh\n"
'if [ "$1" = "--find" ] && [ "$2" = "llvm-cov" ]; then\n'
f" printf '%s\\n' '{llvm}'\n"
" exit 0\n"
"fi\n"
"exit 1\n",
)
swift = tmp_path / "usr" / "bin" / "swift"
swift.parent.mkdir(parents=True)
swift.write_text("", encoding="utf-8")
_plant(tmp_path, "Package.swift", "")
source = _plant(tmp_path, "Sources/Demo/Box.swift", "func open() {}\n")
profdata = tmp_path / ".build" / "debug" / "codecov" / "default.profdata"
_plant_profdata(tmp_path)
binary = tmp_path / ".build" / "debug" / "DemoPackageTests"
binary.write_text("bin", encoding="utf-8")
exports = []
def export(command, cwd, destination):
exports.append(list(command))
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_text("{}", encoding="utf-8")
return 0
monkeypatch.setattr(
"crapper.runners.shutil.which",
_which({"swift": str(swift), "xcrun": str(xcrun)}),
)
monkeypatch.setattr("crapper.runners.run_shell", lambda command, cwd: 0)
monkeypatch.setattr("crapper.runners.write_command_output", export)
assert run_coverage(tmp_path, [source], None) == 0
assert exports == [
[str(llvm), "export", f"-instr-profile={profdata}", str(binary)]
]
def test_llvm_cov_beside_swift_wins_over_xcrun(tmp_path, monkeypatch):
swift = tmp_path / "tool" / "swift"
sibling = tmp_path / "tool" / "llvm-cov"
other = tmp_path / "xcode" / "llvm-cov"
swift.parent.mkdir()
sibling.write_text("", encoding="utf-8")
other.parent.mkdir()
other.write_text("", encoding="utf-8")
xcrun = _program(
tmp_path / "xcrun",
f"#!/bin/sh\nprintf '%s\\n' '{other}'\n",
)
monkeypatch.setattr(
"crapper.runners.shutil.which",
_which({"swift": str(swift), "xcrun": str(xcrun)}),
)
assert llvm_cov_tool() == str(sibling.resolve())
def test_a_missing_or_failing_xcrun_leaves_llvm_cov_unset(tmp_path, monkeypatch):
monkeypatch.setattr("crapper.runners.shutil.which", lambda name: None)
assert llvm_cov_tool() is None
broken = _program(tmp_path / "xcrun", "#!/bin/sh\nexit 1\n")
monkeypatch.setattr(
"crapper.runners.shutil.which",
_which({"xcrun": str(broken)}),
)
assert llvm_cov_tool() is None
blank = _program(tmp_path / "blank-xcrun", "#!/bin/sh\nexit 0\n")
monkeypatch.setattr(
"crapper.runners.shutil.which",
_which({"xcrun": str(blank)}),
)
assert llvm_cov_tool() is None
missing_file = _program(
tmp_path / "missing-file-xcrun",
"#!/bin/sh\nprintf '%s\\n' '/no/such/llvm-cov'\n",
)
monkeypatch.setattr(
"crapper.runners.shutil.which",
_which({"xcrun": str(missing_file)}),
)
assert llvm_cov_tool() is None
monkeypatch.setattr(
"crapper.runners.shutil.which",
_which({"xcrun": str(tmp_path / "not-there")}),
)
assert llvm_cov_tool() is None
def _xctest_binary(package: Path, directory: str, name: str) -> Path:
binary = package / directory / f"{name}.xctest" / "Contents" / "MacOS" / name
binary.parent.mkdir(parents=True, exist_ok=True)
binary.write_text("bin", encoding="utf-8")
return binary
def _swift_stub(path: Path) -> Path:
return _program(
path,
"#!/bin/sh\n"
'if [ "$1" = "build" ] && [ "$2" = "--show-bin-path" ]; then\n'
' printf "%s\\n" "$SHOW_BIN_PATH"\n'
' exit "${SHOW_BIN_STATUS:-0}"\n'
"fi\n"
"exit 1\n",
)
def test_the_current_toolchain_test_binary_is_inside_the_xctest_bundle(tmp_path):
binary = _xctest_binary(tmp_path, ".build/out/Products/Debug", "DemoTests")
dsym = tmp_path / ".build/out/Products/Debug/DemoTests.dSYM/Contents/MacOS/DemoTests"
dsym.parent.mkdir(parents=True)
dsym.write_text("dwarf", encoding="utf-8")
plist = binary.parents[1] / "Info.plist"
plist.write_text("plist", encoding="utf-8")
assert swift_test_binary(tmp_path) == binary
def test_a_linux_tests_xctest_file_is_the_test_binary(tmp_path):
binary = tmp_path / ".build" / "debug" / "DemoTests.xctest"
binary.parent.mkdir(parents=True)
binary.write_text("bin", encoding="utf-8")
assert swift_test_binary(tmp_path) == binary
def test_the_earliest_test_executable_is_chosen(tmp_path):
first = _xctest_binary(tmp_path, ".build/out/Products/Debug", "AAATests")
_xctest_binary(tmp_path, ".build/out/Products/Debug", "ZZZTests")
assert swift_test_binary(tmp_path) == first
def test_a_bare_tests_file_is_not_the_test_binary(tmp_path):
bare = tmp_path / ".build" / "debug" / "AAATests"
bare.parent.mkdir(parents=True)
bare.write_text("bin", encoding="utf-8")
packaged = tmp_path / ".build" / "debug" / "DemoPackageTests"
packaged.write_text("bin", encoding="utf-8")
assert swift_test_binary(tmp_path) == packaged
def test_show_bin_path_is_preferred_to_another_build_product(tmp_path, monkeypatch):
swift = _swift_stub(tmp_path / "swift")
chosen = _xctest_binary(tmp_path, "products", "ZedTests")
decoy = tmp_path / ".build" / "debug" / "AAAPackageTests"
decoy.parent.mkdir(parents=True)
decoy.write_text("bin", encoding="utf-8")
monkeypatch.setattr("crapper.runners.shutil.which", _which({"swift": str(swift)}))
monkeypatch.setenv("SHOW_BIN_PATH", str(tmp_path / "products"))
monkeypatch.setenv("SHOW_BIN_STATUS", "0")
assert swift_test_binary(tmp_path) == chosen
def test_a_relative_show_bin_path_is_inside_the_package(tmp_path, monkeypatch):
swift = _swift_stub(tmp_path / "swift")
chosen = _xctest_binary(tmp_path, "products", "ZedTests")
decoy = tmp_path / ".build" / "debug" / "AAAPackageTests"
decoy.parent.mkdir(parents=True)
decoy.write_text("bin", encoding="utf-8")
monkeypatch.setattr("crapper.runners.shutil.which", _which({"swift": str(swift)}))
monkeypatch.setenv("SHOW_BIN_PATH", "products")
monkeypatch.setenv("SHOW_BIN_STATUS", "0")
assert swift_test_binary(tmp_path) == chosen
def test_show_bin_path_falls_back_when_it_does_not_name_a_product(tmp_path, monkeypatch):
swift = _swift_stub(tmp_path / "swift")
chosen = tmp_path / ".build" / "debug" / "DemoPackageTests"
chosen.parent.mkdir(parents=True)
chosen.write_text("bin", encoding="utf-8")
_xctest_binary(tmp_path, "elsewhere", "AAATests")
monkeypatch.setattr("crapper.runners.shutil.which", _which({"swift": str(swift)}))
monkeypatch.setenv("SHOW_BIN_PATH", "")
monkeypatch.setenv("SHOW_BIN_STATUS", "0")
assert swift_test_binary(tmp_path) == chosen
monkeypatch.setenv("SHOW_BIN_PATH", str(tmp_path / "elsewhere"))
monkeypatch.setenv("SHOW_BIN_STATUS", "1")
assert swift_test_binary(tmp_path) == chosen
noted = tmp_path / "not-a-directory"
noted.write_text("notes", encoding="utf-8")
monkeypatch.setenv("SHOW_BIN_PATH", str(noted))
monkeypatch.setenv("SHOW_BIN_STATUS", "0")
assert swift_test_binary(tmp_path) == chosen
empty = tmp_path / "empty-products"
empty.mkdir()
monkeypatch.setenv("SHOW_BIN_PATH", str(empty))
assert swift_test_binary(tmp_path) == chosen
monkeypatch.setattr(
"crapper.runners.shutil.which",
_which({"swift": str(tmp_path / "missing-swift")}),
)
assert swift_test_binary(tmp_path) == chosen
def test_command_output_is_the_report_file(tmp_path, monkeypatch): def test_command_output_is_the_report_file(tmp_path, monkeypatch):
from crapper.runners import write_command_output from crapper.runners import write_command_output
@@ -685,6 +1019,25 @@ def test_a_failed_xcode_run_forgets_the_previous_report(tmp_path, monkeypatch):
assert ':name "choose", :namespace "Demo", :complexity 2, :coverage 0.0, :crap 6.0' in _snapshot(tmp_path) assert ':name "choose", :namespace "Demo", :complexity 2, :coverage 0.0, :crap 6.0' in _snapshot(tmp_path)
def test_swift_export_needs_the_profile_the_binary_and_llvm_cov(tmp_path, monkeypatch, capsys):
_plant(tmp_path, "Package.swift", "")
source = _plant(tmp_path, "Sources/Demo/Box.swift", "func open() {}\n")
_plant_profdata(tmp_path)
exports = []
monkeypatch.setattr(
"crapper.runners.shutil.which",
lambda name: f"/usr/bin/{name}" if name in {"swift", "llvm-cov"} else None,
)
monkeypatch.setattr("crapper.runners.run_shell", lambda command, cwd: 0)
monkeypatch.setattr(
"crapper.runners.write_command_output",
lambda command, cwd, destination: exports.append(command) or 0,
)
assert run_coverage(tmp_path, [source], None) == 0
assert exports == []
assert "Swift coverage data is missing" in capsys.readouterr().err
def test_swift_without_a_toolchain_does_not_run_a_command(tmp_path, monkeypatch, capsys): def test_swift_without_a_toolchain_does_not_run_a_command(tmp_path, monkeypatch, capsys):
_plant(tmp_path, "Package.swift", "") _plant(tmp_path, "Package.swift", "")
source = _plant(tmp_path, "Sources/Demo/Box.swift", "func open() {}\n") source = _plant(tmp_path, "Sources/Demo/Box.swift", "func open() {}\n")