From 267a61c58148c8c268e01fb9fdd98ffbd2095660 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Mon, 30 Nov 2026 21:53:41 +0900 Subject: [PATCH] feat(coverage): run Xcode tests with coverage (#6944) Run with Coverage is offered for xcode-test configurations: it adds -enableCodeCoverage YES and names the run's result bundle, which xcode::prepare_test uses instead of its own, so there is still one test run and one bundle. Afterwards xcrun xccov view --report and --archive feed the shared coverage accumulator: files compiled only by .xctest targets, files outside the project and DerivedData/.build are left out, resolved paths map back to the project root, and lines with a missed subrange are partial. Closes #6941 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- crates/ide-coverage/Cargo.toml | 2 +- crates/ide-coverage/src/goprofile.rs | 2 +- crates/ide-coverage/src/lib.rs | 26 ++ crates/ide-coverage/src/plan.rs | 34 +++ crates/ide-coverage/src/xccov.rs | 188 +++++++++++++++ .../tests/fixtures/xccov-archive.json | 226 ++++++++++++++++++ .../tests/fixtures/xccov-report.json | 140 +++++++++++ crates/ide-run/src/xcode.rs | 13 +- docs/en/guide/coverage.mdx | 1 + docs/en/languages/swift.mdx | 4 + docs/zh/guide/coverage.mdx | 1 + docs/zh/languages/swift.mdx | 4 + src/bindings.ts | 4 +- src/features/coverage/coverage.test.ts | 2 + src/features/coverage/model.ts | 1 + 15 files changed, 644 insertions(+), 4 deletions(-) create mode 100644 crates/ide-coverage/src/xccov.rs create mode 100644 crates/ide-coverage/tests/fixtures/xccov-archive.json create mode 100644 crates/ide-coverage/tests/fixtures/xccov-report.json diff --git a/crates/ide-coverage/Cargo.toml b/crates/ide-coverage/Cargo.toml index be3d3c64cb..62a6ad1f1d 100644 --- a/crates/ide-coverage/Cargo.toml +++ b/crates/ide-coverage/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ide-coverage" -description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo) and report parsers (lcov, Go cover profiles, JaCoCo and Cobertura XML, SimpleCov, coverage.py data)" +description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo, xcodebuild) and report parsers (lcov, Go cover profiles, JaCoCo and Cobertura XML, SimpleCov, coverage.py data, xccov)" version.workspace = true edition.workspace = true license.workspace = true diff --git a/crates/ide-coverage/src/goprofile.rs b/crates/ide-coverage/src/goprofile.rs index 842e784afb..f2faeb894e 100644 --- a/crates/ide-coverage/src/goprofile.rs +++ b/crates/ide-coverage/src/goprofile.rs @@ -59,7 +59,7 @@ pub(crate) fn parse(text: &str, module: &str, module_dir: &Path) -> Accumulator impl Accumulator { /// Removes the branch data of lines whose branches are all taken or all missed. - fn drop_unanimous_branches(&mut self) { + pub(crate) fn drop_unanimous_branches(&mut self) { for lines in self.files.values_mut() { for acc in lines.values_mut() { let taken = acc.branches.values().filter(|t| **t).count(); diff --git a/crates/ide-coverage/src/lib.rs b/crates/ide-coverage/src/lib.rs index c890014147..898f155c5b 100644 --- a/crates/ide-coverage/src/lib.rs +++ b/crates/ide-coverage/src/lib.rs @@ -13,6 +13,7 @@ //! | Ruby (rspec, minitest, rake, scripts) | SimpleCov (`coverage/.resultset.json`) | SimpleCov resultset | //! | Go (`go test`) | `-coverprofile` | Go cover profile | //! | Maven / Gradle tests | JaCoCo (plugin goals / an init script) | JaCoCo XML | +//! | Xcode tests (`xcodebuild test`) | `-enableCodeCoverage YES` | the result bundle, read with `xccov` | //! //! Lines in the model are 0-based, like every IPC coordinate. @@ -24,6 +25,7 @@ mod jacoco; mod lcov; mod plan; mod simplecov; +mod xccov; pub use coveragepy::is_data_file; pub use import::{import, import_data}; @@ -94,6 +96,8 @@ pub enum CoverageReportSpec { Jacoco { dir: IpcPath }, /// The tool's raw data is exported to lcov by `argv` first (coverage.py: `… -m coverage lcov -o `). Exported { runner: String, argv: Vec, cwd: IpcPath, env: BTreeMap, lcov: IpcPath }, + /// An Xcode result bundle, read with `xcrun xccov`; only files under `root` are kept. + Xccov { bundle: IpcPath, root: IpcPath }, } /// A command line that installs a missing tool (run in the Run tool window). @@ -234,9 +238,31 @@ pub fn collect(spec: &CoverageReportSpec) -> IdeResult { let text = read_report(lcov)?; Ok(lcov::parse(&text, cwd).finish(runner)) } + CoverageReportSpec::Xccov { bundle, root } => { + if !bundle.exists() { + return Err(IdeError::not_found(format!("the run produced no result bundle ({})", bundle.display()))); + } + let report = xccov_json(&["--report", "--json"], bundle)?; + let archive = xccov_json(&["--archive", "--json"], bundle)?; + Ok(xccov::parse(&report, &archive, root) + .map_err(|e| IdeError::invalid(format!("unexpected xccov output: {e}")))? + .finish("xccov")) + } } } +/// `xcrun xccov view `'s output. +fn xccov_json(args: &[&str], bundle: &Path) -> IdeResult { + let out = ide_core::process::prepare(Command::new("xcrun").args(["xccov", "view"]).args(args).arg(bundle)) + .output() + .map_err(|e| IdeError::unavailable(format!("cannot run xcrun xccov: {e}")))?; + if !out.status.success() { + let text = ide_core::output_encoding::decode_tool_output(&out.stderr).trim().to_owned(); + return Err(IdeError::not_found(format!("the result bundle has no coverage data: {text}"))); + } + Ok(String::from_utf8_lossy(&out.stdout).into_owned()) +} + fn read_report(path: &Path) -> IdeResult { std::fs::read_to_string(path).map_err(|e| match e.kind() { std::io::ErrorKind::NotFound => { diff --git a/crates/ide-coverage/src/plan.rs b/crates/ide-coverage/src/plan.rs index 602fd1e86f..4806c86769 100644 --- a/crates/ide-coverage/src/plan.rs +++ b/crates/ide-coverage/src/plan.rs @@ -61,6 +61,9 @@ fn ready( /// data; it must exist (the Gradle init script is written there). Probes tools, /// so call it from a blocking thread. pub fn prepare(root: &Path, config: &RunConfig, out: &Path) -> CoveragePrepared { + if config.kind == "xcode-test" { + return xcode(root, config, out); + } let dir = wrap::run_dir(root, config); let program = program_name(&config.command); let first = config.args.first().map(String::as_str).unwrap_or_default(); @@ -336,6 +339,20 @@ fn python(config: &RunConfig, dir: &Path, out: &Path, py: wrap::PythonCommand) - ready("coverage.py", &config, command, args, report) } +/// `xcodebuild test` with coverage on, into a result bundle of its own (`xcode::prepare_test` +/// adds it at launch). +fn xcode(root: &Path, config: &RunConfig, out: &Path) -> CoveragePrepared { + let mut config = config.clone(); + if let Some(at) = config.args.iter().position(|a| a == "-enableCodeCoverage") { + config.args.drain(at..(at + 2).min(config.args.len())); + } + config.args.extend([s("-enableCodeCoverage"), s("YES")]); + let bundle = out.join("coverage.xcresult"); + config.extras.params.insert(s(ide_run::xcode::RESULT_BUNDLE_PARAM), path(&bundle)); + let report = CoverageReportSpec::Xccov { bundle: bundle.into(), root: root.to_path_buf().into() }; + ready("xccov", &config, config.command.clone(), config.args.clone(), report) +} + #[cfg(test)] mod tests { use super::*; @@ -535,6 +552,23 @@ mod tests { ); } + #[test] + fn xcode_tests_turn_coverage_on_into_their_own_bundle() { + let dir = tempfile::tempdir().unwrap(); + let config = cfg("xcode-test", "xcodebuild", &["test", "-scheme", "App", "-enableCodeCoverage", "NO"]); + let p = prepare(dir.path(), &config, dir.path()); + let (l, report) = launch(&p); + assert_eq!(l.args, ["test", "-scheme", "App", "-enableCodeCoverage", "YES"]); + let bundle = dir.path().join("coverage.xcresult"); + assert_eq!(l.extras.params[ide_run::xcode::RESULT_BUNDLE_PARAM], bundle.to_string_lossy()); + assert!(matches!(report, CoverageReportSpec::Xccov { bundle: b, .. } if (b.as_ref() as &Path) == bundle)); + + // A trailing flag without a value is replaced too. + let config = cfg("xcode-test", "xcodebuild", &["test", "-enableCodeCoverage"]); + let p = prepare(dir.path(), &config, dir.path()); + assert_eq!(launch(&p).0.args, ["test", "-enableCodeCoverage", "YES"]); + } + #[test] fn unknown_commands_are_unsupported() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/ide-coverage/src/xccov.rs b/crates/ide-coverage/src/xccov.rs new file mode 100644 index 0000000000..a95dc1f662 --- /dev/null +++ b/crates/ide-coverage/src/xccov.rs @@ -0,0 +1,188 @@ +//! Xcode coverage (`xcodebuild test -enableCodeCoverage YES`), read from the result bundle: +//! +//! - `xcrun xccov view --report --json `: the targets and their files. Files that only +//! test bundles (`*.xctest`) compile are left out. +//! - `xcrun xccov view --archive --json `: `{ "": [{ line, isExecutable, +//! executionCount, subranges? }] }` for every file. A subrange is a region of the line with its +//! own count; a covered line with a missed region is partial. + +use crate::Accumulator; +use serde::Deserialize; +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Component, Path, PathBuf}; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Report { + #[serde(default)] + targets: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Target { + #[serde(default)] + build_product_path: String, + #[serde(default)] + files: Vec, +} + +#[derive(Deserialize)] +struct ReportFile { + path: String, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Line { + line: u32, + is_executable: bool, + #[serde(default)] + execution_count: u64, + #[serde(default)] + subranges: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Subrange { + column: u32, + #[serde(default)] + length: u32, + #[serde(default)] + execution_count: u64, +} + +/// `path` inside the project as the project names it: the project and xccov may name it through +/// different symlinks (`/tmp` and `/private/tmp`). `None` outside the project and for DerivedData. +fn in_project(path: &Path, root: &Path, real_root: &Path) -> Option { + let real; + let rel = match path.strip_prefix(root) { + Ok(rel) => rel, + Err(_) => { + real = path.canonicalize().ok()?; + real.strip_prefix(real_root).ok()? + } + }; + let generated = rel.components().any(|c| matches!(c, Component::Normal(n) if n == "DerivedData" || n == ".build")); + (!generated).then(|| root.join(rel)) +} + +pub(crate) fn parse(report: &str, archive: &str, root: &Path) -> Result { + let report: Report = serde_json::from_str(report)?; + let archive: BTreeMap> = serde_json::from_str(archive)?; + // App and framework sources: a file listed by an app or framework target counts even when a test + // bundle compiles it too (sources added to the test target's membership instead of `@testable`). + let is_test_bundle = |t: &Target| { + Path::new(&t.build_product_path) + .components() + .any(|c| matches!(c, Component::Normal(n) if Path::new(n).extension().is_some_and(|e| e == "xctest"))) + }; + let real_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf()); + // Both views go through `in_project`, so they match however each spells the path. + let sources: BTreeSet = report + .targets + .iter() + .filter(|t| !is_test_bundle(t)) + .flat_map(|t| &t.files) + .filter_map(|f| in_project(Path::new(&f.path), root, &real_root)) + .collect(); + let mut acc = Accumulator::default(); + for (file, lines) in &archive { + let Some(path) = in_project(Path::new(file), root, &real_root).filter(|p| sources.contains(p)) else { + continue; + }; + acc.file(&path); + for l in lines.iter().filter(|l| l.is_executable && l.line > 0) { + let n = l.line - 1; + acc.line(&path, n, l.execution_count); + if !l.subranges.is_empty() { + acc.branch(&path, n, "line".into(), l.execution_count > 0); + for r in &l.subranges { + acc.branch(&path, n, format!("{}+{}", r.column, r.length), r.execution_count > 0); + } + } + } + } + // Regions are not branches: keep only the partial marks of lines with mixed regions. + acc.drop_unanimous_branches(); + Ok(acc) +} + +#[cfg(test)] +mod tests { + use super::*; + + // Captured from `xcodebuild test -enableCodeCoverage YES` (Xcode 27.1) on an app with a unit + // test target; paths rewritten to /Users/me. + const REPORT: &str = include_str!("../tests/fixtures/xccov-report.json"); + const ARCHIVE: &str = include_str!("../tests/fixtures/xccov-archive.json"); + + #[test] + fn reads_app_sources_and_leaves_out_test_bundles() { + let suite = parse(REPORT, ARCHIVE, Path::new("/Users/me/CovDemo")).unwrap().finish("xccov"); + assert!(!suite.has_branches); + let names: Vec<_> = suite.files.iter().map(|f| f.path.as_ref() as &Path).collect(); + assert_eq!( + names, + [Path::new("/Users/me/CovDemo/CovDemo/App.swift"), Path::new("/Users/me/CovDemo/CovDemo/Calculator.swift")] + ); + // xccov's own totals for Calculator.swift: 14 of 17 lines. + let calc = &suite.files[1]; + assert_eq!((calc.lines_total, calc.lines_covered), (17, 14)); + let at = |n: u32| calc.lines.iter().find(|l| l.line == n).unwrap(); + // `return nil` (line 8) never ran; `if b == 0 {` (line 7) ran with a missed region. + assert_eq!(at(7).hits, 0); + assert!(at(6).partial()); + assert!(!at(1).partial()); + } + + #[test] + fn files_outside_the_project_are_dropped() { + let suite = parse(REPORT, ARCHIVE, Path::new("/Users/me/Other")).unwrap().finish("xccov"); + assert!(suite.files.is_empty()); + let report = r#"{"targets":[{"buildProductPath":"/d/App.app/App","files":[{"path":"/p/DerivedData/G.swift"},{"path":"/p/A.swift"}]}]}"#; + let line = r#"[{"line":1,"isExecutable":true,"executionCount":2}]"#; + let archive = format!(r#"{{"/p/DerivedData/G.swift":{line},"/p/A.swift":{line}}}"#); + let suite = parse(report, &archive, Path::new("/p")).unwrap().finish("xccov"); + assert_eq!(suite.files.len(), 1); + assert_eq!(suite.files[0].lines[0].hits, 2); + } + + #[test] + fn a_file_of_an_app_and_a_test_bundle_counts() { + let report = r#"{"targets":[ + {"buildProductPath":"/d/App.app/App","files":[{"path":"/p/A.swift"}]}, + {"buildProductPath":"/d/AppTests.xctest/AppTests","files":[{"path":"/p/A.swift"},{"path":"/p/T.swift"}]}]}"#; + let line = r#"[{"line":1,"isExecutable":true,"executionCount":1}]"#; + let archive = format!(r#"{{"/p/A.swift":{line},"/p/T.swift":{line}}}"#); + let suite = parse(report, &archive, Path::new("/p")).unwrap().finish("xccov"); + let names: Vec<_> = suite.files.iter().map(|f| f.path.as_ref() as &Path).collect(); + assert_eq!(names, [Path::new("/p/A.swift")]); + } + + #[cfg(unix)] + #[test] + fn paths_through_another_symlink_map_to_the_project() { + let dir = tempfile::tempdir().unwrap(); + let real = dir.path().canonicalize().unwrap().join("real"); + std::fs::create_dir_all(&real).unwrap(); + std::fs::write(real.join("A.swift"), "").unwrap(); + let link = dir.path().join("link"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + let file = real.join("A.swift").to_string_lossy().into_owned(); + let report = + format!(r#"{{"targets":[{{"buildProductPath":"/d/App.app/App","files":[{{"path":"{file}"}}]}}]}}"#); + let archive = format!(r#"{{"{file}":[{{"line":1,"isExecutable":true,"executionCount":1}}]}}"#); + let suite = parse(&report, &archive, &link).unwrap().finish("xccov"); + assert_eq!(suite.files.len(), 1); + assert_eq!(suite.files[0].path.as_ref() as &Path, link.join("A.swift")); + + // The report names the file through the symlink, the archive by its real path. + let linked = link.join("A.swift").to_string_lossy().into_owned(); + let report = report.replace(&file, &linked); + let suite = parse(&report, &archive, &link).unwrap().finish("xccov"); + assert_eq!(suite.files.len(), 1); + assert_eq!(suite.files[0].lines[0].hits, 1); + } +} diff --git a/crates/ide-coverage/tests/fixtures/xccov-archive.json b/crates/ide-coverage/tests/fixtures/xccov-archive.json new file mode 100644 index 0000000000..6b1758b245 --- /dev/null +++ b/crates/ide-coverage/tests/fixtures/xccov-archive.json @@ -0,0 +1,226 @@ +{ + "/Users/me/CovDemo/CovDemo/App.swift": [ + { + "isExecutable": false, + "line": 1 + }, + { + "isExecutable": false, + "line": 2 + }, + { + "isExecutable": false, + "line": 3 + }, + { + "isExecutable": false, + "line": 4 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 5 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 6 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 7 + } + ], + "/Users/me/CovDemo/CovDemo/Calculator.swift": [ + { + "isExecutable": false, + "line": 1 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 2 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 3 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 4 + }, + { + "isExecutable": false, + "line": 5 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 6 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 7, + "subranges": [ + { + "column": 19, + "executionCount": 0, + "length": 0 + } + ] + }, + { + "executionCount": 0, + "isExecutable": true, + "line": 8 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 9, + "subranges": [ + { + "column": 1, + "executionCount": 0, + "length": 9 + } + ] + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 10 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 11 + }, + { + "isExecutable": false, + "line": 12 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 13 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 14, + "subranges": [ + { + "column": 18, + "executionCount": 0, + "length": 0 + } + ] + }, + { + "executionCount": 0, + "isExecutable": true, + "line": 15 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 16, + "subranges": [ + { + "column": 1, + "executionCount": 0, + "length": 9 + }, + { + "column": 26, + "executionCount": 0, + "length": 0 + } + ] + }, + { + "executionCount": 0, + "isExecutable": true, + "line": 17 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 18, + "subranges": [ + { + "column": 1, + "executionCount": 0, + "length": 9 + } + ] + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 19 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 20 + } + ], + "/Users/me/CovDemo/CovDemoTests/CalculatorTests.swift": [ + { + "isExecutable": false, + "line": 1 + }, + { + "isExecutable": false, + "line": 2 + }, + { + "isExecutable": false, + "line": 3 + }, + { + "isExecutable": false, + "line": 4 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 5 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 6 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 7 + }, + { + "isExecutable": false, + "line": 8 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 9 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 10 + }, + { + "executionCount": 1, + "isExecutable": true, + "line": 11 + } + ] +} \ No newline at end of file diff --git a/crates/ide-coverage/tests/fixtures/xccov-report.json b/crates/ide-coverage/tests/fixtures/xccov-report.json new file mode 100644 index 0000000000..4e308ef19e --- /dev/null +++ b/crates/ide-coverage/tests/fixtures/xccov-report.json @@ -0,0 +1,140 @@ +{ + "coveredLines": 28, + "executableLines": 31, + "lineCoverage": 0.9032258064516129, + "targets": [ + { + "buildProductPath": "/Users/me/Library/Developer/Xcode/DerivedData/CovDemo-abc/Build/Products/Debug-iphonesimulator/CovDemo.app/CovDemo", + "coveredLines": 18, + "executableLines": 21, + "files": [ + { + "coveredLines": 14, + "executableLines": 17, + "functions": [ + { + "coveredLines": 3, + "executableLines": 3, + "executionCount": 1, + "lineCoverage": 1, + "lineNumber": 2, + "name": "Calculator.add(_:_:)" + }, + { + "coveredLines": 5, + "executableLines": 6, + "executionCount": 1, + "lineCoverage": 0.8333333333333334, + "lineNumber": 6, + "name": "Calculator.divide(_:_:)" + }, + { + "coveredLines": 6, + "executableLines": 8, + "executionCount": 1, + "lineCoverage": 0.75, + "lineNumber": 13, + "name": "Calculator.describe(_:)" + } + ], + "lineCoverage": 0.8235294117647058, + "name": "Calculator.swift", + "path": "/Users/me/CovDemo/CovDemo/Calculator.swift" + }, + { + "coveredLines": 4, + "executableLines": 4, + "functions": [ + { + "coveredLines": 3, + "executableLines": 3, + "executionCount": 1, + "lineCoverage": 1, + "lineNumber": 5, + "name": "CovDemoApp.body.getter" + }, + { + "coveredLines": 1, + "executableLines": 1, + "executionCount": 1, + "lineCoverage": 1, + "lineNumber": 6, + "name": "closure #1 in CovDemoApp.body.getter" + } + ], + "lineCoverage": 1, + "name": "App.swift", + "path": "/Users/me/CovDemo/CovDemo/App.swift" + } + ], + "lineCoverage": 0.8571428571428571, + "name": "CovDemo.app" + }, + { + "buildProductPath": "/Users/me/Library/Developer/Xcode/DerivedData/CovDemo-abc/Build/Products/Debug-iphonesimulator/CovDemo.app/PlugIns/CovDemoTests.xctest/CovDemoTests", + "coveredLines": 10, + "executableLines": 10, + "files": [ + { + "coveredLines": 10, + "executableLines": 10, + "functions": [ + { + "coveredLines": 3, + "executableLines": 3, + "executionCount": 1, + "lineCoverage": 1, + "lineNumber": 5, + "name": "CalculatorTests.testAdd()" + }, + { + "coveredLines": 1, + "executableLines": 1, + "executionCount": 1, + "lineCoverage": 1, + "lineNumber": 6, + "name": "implicit closure #1 in CalculatorTests.testAdd()" + }, + { + "coveredLines": 1, + "executableLines": 1, + "executionCount": 1, + "lineCoverage": 1, + "lineNumber": 6, + "name": "implicit closure #2 in CalculatorTests.testAdd()" + }, + { + "coveredLines": 3, + "executableLines": 3, + "executionCount": 1, + "lineCoverage": 1, + "lineNumber": 9, + "name": "CalculatorTests.testDivide()" + }, + { + "coveredLines": 1, + "executableLines": 1, + "executionCount": 1, + "lineCoverage": 1, + "lineNumber": 10, + "name": "implicit closure #1 in CalculatorTests.testDivide()" + }, + { + "coveredLines": 1, + "executableLines": 1, + "executionCount": 1, + "lineCoverage": 1, + "lineNumber": 10, + "name": "implicit closure #2 in CalculatorTests.testDivide()" + } + ], + "lineCoverage": 1, + "name": "CalculatorTests.swift", + "path": "/Users/me/CovDemo/CovDemoTests/CalculatorTests.swift" + } + ], + "lineCoverage": 1, + "name": "CovDemoTests.xctest" + } + ] +} \ No newline at end of file diff --git a/crates/ide-run/src/xcode.rs b/crates/ide-run/src/xcode.rs index d40c2e7f51..d7a67d5c75 100644 --- a/crates/ide-run/src/xcode.rs +++ b/crates/ide-run/src/xcode.rs @@ -178,7 +178,8 @@ fn resolve(reference: &str, container: &Path) -> PathBuf { /// Completes an `xcodebuild test` launch: a simulator destination unless the configuration names /// one, and a fresh `-resultBundlePath` under `bundles` (xcodebuild refuses an existing one). The -/// bundles of this configuration's earlier runs are removed. +/// bundles of this configuration's earlier runs are removed. Run with Coverage names the bundle +/// itself in [`RESULT_BUNDLE_PARAM`]. pub fn prepare_test(config: &mut crate::RunConfig, dir: &Path, bundles: &Path) -> std::io::Result<()> { if !config.args.iter().any(|a| a == "-destination") && let Some(udid) = default_simulator(dir) @@ -188,6 +189,10 @@ pub fn prepare_test(config: &mut crate::RunConfig, dir: &Path, bundles: &Path) - if let Some(at) = config.args.iter().position(|a| a == "-resultBundlePath") { config.args.drain(at..(at + 2).min(config.args.len())); } + if let Some(bundle) = config.extras.params.get(RESULT_BUNDLE_PARAM).cloned() { + config.args.extend(["-resultBundlePath".to_owned(), bundle]); + return Ok(()); + } let prefix: String = config.id.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect(); fs::create_dir_all(bundles)?; for entry in fs::read_dir(bundles)?.flatten() { @@ -235,6 +240,8 @@ fn pick_simulator(json: &str) -> Option { /// [`default_simulator`]: the one place a device selector can feed its choice into. /// [`MAC`] runs an app that supports both on the Mac instead. pub const SIMULATOR_PARAM: &str = "simulator"; +/// The result bundle an `xcodebuild test` launch writes, when the caller reads it afterwards. +pub const RESULT_BUNDLE_PARAM: &str = "resultBundle"; /// Set (to anything but empty) by Debug: the app is launched suspended /// (`simctl launch --wait-for-debugger`) until the debugger attaches to the pid simctl prints. @@ -561,6 +568,10 @@ mod tests { assert!(config.args[4].contains("xcode_test_A-") && config.args[4].ends_with(".xcresult")); assert_eq!(config.args.len(), 5); assert!(!old.exists() && other.exists()); + + config.extras.params.insert(RESULT_BUNDLE_PARAM.into(), "/cov/r.xcresult".into()); + prepare_test(&mut config, dir.path(), dir.path()).unwrap(); + assert_eq!(config.args[3..], ["-resultBundlePath", "/cov/r.xcresult"]); } #[test] diff --git a/docs/en/guide/coverage.mdx b/docs/en/guide/coverage.mdx index 51bf5cd649..01e071ae00 100644 --- a/docs/en/guide/coverage.mdx +++ b/docs/en/guide/coverage.mdx @@ -39,6 +39,7 @@ If the coverage tool is missing, a notification names it and offers **Install**, | Node.js | `node`, `npx`, `tsx`, `ts-node` programs | `c8` | | Python | scripts, modules, pytest | coverage.py (`coverage run --branch`) in the project's interpreter | | Ruby | rspec, minitest, rake, rails and plain scripts | SimpleCov (in the Gemfile for Bundler projects) | +| Swift (Xcode) | Xcode test configurations (`xcodebuild test`) | `-enableCodeCoverage YES`, read from the result bundle with `xcrun xccov` | Not supported: diff --git a/docs/en/languages/swift.mdx b/docs/en/languages/swift.mdx index 7dc6d001b8..7c53b17bd2 100644 --- a/docs/en/languages/swift.mdx +++ b/docs/en/languages/swift.mdx @@ -108,6 +108,10 @@ Each scheme of a `.xcodeproj` or `.xcworkspace` in the project root gets an **Xc - **macOS apps** are built with `-destination 'platform=macOS'`, and the app's executable (`.app/Contents/MacOS/`) runs directly: its output shows in the Run console, and **Stop** quits it. No simulator is booted. - **Apps that support both** run on the simulator. Set **Simulator** to `macos` to run them on the Mac instead. +### Coverage of Xcode tests + +**Run › Run with Coverage** on an Xcode test configuration runs `xcodebuild test -enableCodeCoverage YES` and reads the result bundle with `xcrun xccov`. The [Coverage](/en/guide/coverage) tool window and the editor gutter show the app and framework sources of the project; files that only test targets (`.xctest` bundles) compile and files outside the project, such as the SDK and DerivedData, are left out. Covered lines with a region that never ran (an `if` whose `else` was skipped) are marked partial. + ### Debugging Debugging uses lldb-dap. On macOS the IDE finds Xcode's copy through `xcrun -f lldb-dap`; elsewhere it comes with the Swift toolchain on `PATH`. diff --git a/docs/zh/guide/coverage.mdx b/docs/zh/guide/coverage.mdx index 033438975f..0c06db4b40 100644 --- a/docs/zh/guide/coverage.mdx +++ b/docs/zh/guide/coverage.mdx @@ -35,6 +35,7 @@ description: "使用覆盖率运行配置,在编辑器、项目视图和覆盖 | Node.js | `node`、`npx`、`tsx`、`ts-node` 程序 | `c8` | | Python | 脚本、模块、pytest | 项目解释器中的 coverage.py(`coverage run --branch`) | | Ruby | rspec、minitest、rake、rails 和普通脚本 | SimpleCov(Bundler 项目需写在 Gemfile 中) | +| Swift(Xcode) | Xcode 测试配置(`xcodebuild test`) | `-enableCodeCoverage YES`,用 `xcrun xccov` 读取结果包 | 暂不支持: diff --git a/docs/zh/languages/swift.mdx b/docs/zh/languages/swift.mdx index faa187f0a8..79c0b4df0e 100644 --- a/docs/zh/languages/swift.mdx +++ b/docs/zh/languages/swift.mdx @@ -108,6 +108,10 @@ IDE 在项目中启动的所有进程都会以 `DEVELOPER_DIR` 得到它:sourc - **macOS App** 用 `-destination 'platform=macOS'` 构建,然后直接运行 App 的可执行文件(`.app/Contents/MacOS/`):输出显示在运行控制台里,**停止** 会退出 App。不会启动模拟器。 - **同时支持两者的 App** 在模拟器上运行。把 **模拟器** 设为 `macos` 就改在 Mac 上运行。 +### Xcode 测试的覆盖率 + +对 Xcode 测试配置使用 **运行 › 使用覆盖率运行**,IDE 会执行 `xcodebuild test -enableCodeCoverage YES`,再用 `xcrun xccov` 读取结果包。[覆盖率](/zh/guide/coverage)工具窗口和编辑器边栏只显示项目中 App 和框架的源文件;只由测试目标(`.xctest` 包)编译的文件和项目之外的文件(例如 SDK 和 DerivedData)不计入。已执行、但其中有一段代码没有执行的行(例如跳过了 `else` 的 `if`)标为部分覆盖。 + ### 调试 调试使用 lldb-dap。在 macOS 上,IDE 通过 `xcrun -f lldb-dap` 找到 Xcode 中的副本;其他平台使用 `PATH` 上 Swift 工具链自带的副本。 diff --git a/src/bindings.ts b/src/bindings.ts index 20c351da92..5af2c02e76 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -5882,7 +5882,9 @@ export type CoverageReportSpec = /** Every JaCoCo XML report (Maven `target/site/jacoco`, Gradle `build/reports/jacoco`) under `dir`. */ { kind: "jacoco"; dir: IpcPath } | /** The tool's raw data is exported to lcov by `argv` first (coverage.py: `… -m coverage lcov -o `). */ -{ kind: "exported"; runner: string; argv: string[]; cwd: IpcPath; env: { [key in string]: string }; lcov: IpcPath }; +{ kind: "exported"; runner: string; argv: string[]; cwd: IpcPath; env: { [key in string]: string }; lcov: IpcPath } | +/** An Xcode result bundle, read with `xcrun xccov`; only files under `root` are kept. */ +{ kind: "xccov"; bundle: IpcPath; root: IpcPath }; /** One coverage run's report. */ export type CoverageSuite = { diff --git a/src/features/coverage/coverage.test.ts b/src/features/coverage/coverage.test.ts index dff972c7b9..e04509ca9f 100644 --- a/src/features/coverage/coverage.test.ts +++ b/src/features/coverage/coverage.test.ts @@ -61,6 +61,8 @@ describe("coverageSupports", () => { expect(coverageSupports(cfg("bundle", ["exec", "rspec"], { isTest: true }))).toBe(true); expect(coverageSupports(cfg("bundle", ["exec", "rake", "db:migrate"]))).toBe(false); expect(coverageSupports(cfg("make", ["test"]))).toBe(false); + expect(coverageSupports(cfg("xcodebuild", ["test", "-scheme", "App"], { kind: "xcode-test" }))).toBe(true); + expect(coverageSupports(cfg("xcodebuild", ["build", "-scheme", "App"], { kind: "xcode" }))).toBe(false); }); }); diff --git a/src/features/coverage/model.ts b/src/features/coverage/model.ts index 472537edd4..df502630a5 100644 --- a/src/features/coverage/model.ts +++ b/src/features/coverage/model.ts @@ -19,6 +19,7 @@ const runsJvmTests = (args: readonly string[]) => * Node.js programs, Python and Ruby (scripts, rspec, test rake tasks). */ export function coverageSupports(config: Pick): boolean { + if (config.kind === "xcode-test") return true; const program = programName(config.command); const args = config.args; switch (program) {