diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b809919fa5..0688350912 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -148,8 +148,8 @@ jobs: fi - uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11 with: { tool: nextest } - # ide-sdk's .NET status test runs the real `dotnet` CLI; with CI set it fails, not skips, when - # it is missing. + # ide-sdk's .NET status test and crates/ide-coverage/tests/dotnet_cli.rs run the real `dotnet` + # CLI; with CI set they fail, not skip, when it is missing. - uses: actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1 # v5.4.0 with: dotnet-version: 10.0.x diff --git a/Cargo.lock b/Cargo.lock index 956cc235eb..3fb4608377 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4287,6 +4287,7 @@ dependencies = [ name = "ide-coverage" version = "0.1.57" dependencies = [ + "dunce", "ide-core", "ide-run", "quick-xml 0.42.0", diff --git a/crates/ide-coverage/Cargo.toml b/crates/ide-coverage/Cargo.toml index 62a6ad1f1d..5257cc6df8 100644 --- a/crates/ide-coverage/Cargo.toml +++ b/crates/ide-coverage/Cargo.toml @@ -14,4 +14,5 @@ serde_json.workspace = true specta.workspace = true [dev-dependencies] +dunce.workspace = true tempfile.workspace = true diff --git a/crates/ide-coverage/src/cobertura.rs b/crates/ide-coverage/src/cobertura.rs index 1d11344e4c..efa16c7928 100644 --- a/crates/ide-coverage/src/cobertura.rs +++ b/crates/ide-coverage/src/cobertura.rs @@ -51,8 +51,14 @@ fn resolve(filename: &str, sources: &[(PathBuf, bool)], base: &Path) -> PathBuf /// Relative sources (and filenames without sources) resolve against `base`. pub(crate) fn parse(xml: &str, base: &Path) -> Result { - let mut reader = Reader::from_str(xml); let mut acc = Accumulator::default(); + parse_into(xml, base, &mut acc)?; + Ok(acc) +} + +/// Like [`parse`], merging into the data of other reports. +pub(crate) fn parse_into(xml: &str, base: &Path, acc: &mut Accumulator) -> Result<(), quick_xml::Error> { + let mut reader = Reader::from_str(xml); let mut sources: Vec<(PathBuf, bool)> = Vec::new(); let mut source: Option = None; let mut file: Option = None; @@ -72,7 +78,8 @@ pub(crate) fn parse(xml: &str, base: &Path) -> Result().ok()) else { continue }; let line = number.saturating_sub(1); acc.line(path, line, attr(&e, "hits").and_then(|h| h.parse().ok()).unwrap_or(0)); - if attr(&e, "branch").as_deref() == Some("true") + // coverlet writes `True`. + if attr(&e, "branch").is_some_and(|b| b.eq_ignore_ascii_case("true")) && let Some((covered, total)) = attr(&e, "condition-coverage").as_deref().and_then(conditions) { acc.has_branches = true; @@ -115,7 +122,7 @@ pub(crate) fn parse(xml: &str, base: &Path) -> Result {} } } - Ok(acc) + Ok(()) } #[cfg(test)] @@ -162,6 +169,16 @@ mod tests { assert!(parse("", Path::new("/root")).is_err()); } + /// Written by `dotnet test --collect:"XPlat Code Coverage"` (coverlet.collector 6.0.4). + #[test] + fn reads_a_coverlet_report() { + let suite = + parse(include_str!("testdata/coverlet.cobertura.xml"), Path::new("/root")).unwrap().finish("coverlet"); + let [file] = suite.files.as_slice() else { panic!("{:?}", suite.files) }; + assert!((file.path.as_ref() as &Path).ends_with("home/dev/dn app/Calc/Calculator.cs")); + assert_eq!((file.lines_covered, file.lines_total, file.branches_covered, file.branches_total), (6, 7, 1, 2)); + } + #[test] fn filenames_without_sources_resolve_against_the_base() { let xml = r#""#; diff --git a/crates/ide-coverage/src/dotnet.rs b/crates/ide-coverage/src/dotnet.rs new file mode 100644 index 0000000000..e3f9829351 --- /dev/null +++ b/crates/ide-coverage/src/dotnet.rs @@ -0,0 +1,234 @@ +//! `dotnet test` with coverage: coverlet.collector under VSTest, +//! Microsoft.Testing.Extensions.CodeCoverage under Microsoft.Testing.Platform. +//! +//! The run gets its own results directory, so only this run's reports are read. + +use crate::plan::{missing, ready, unsupported}; +use crate::{CoveragePrepared, CoverageReportSpec}; +use ide_run::{RunConfig, wrap}; +use std::path::{Path, PathBuf}; + +const COLLECTOR: &str = "coverlet.collector"; +const CODE_COVERAGE: &str = "Microsoft.Testing.Extensions.CodeCoverage"; + +#[derive(Clone, Copy, PartialEq, Debug)] +enum Runner { + VsTest, + /// `global.json` selects the testing platform's `dotnet test`. + Mtp, + /// A testing-platform project run through the VSTest target: its options go after `--`. + MtpLegacy, +} + +/// What MSBuild says about a project: (testing-platform project, referenced packages). +fn evaluation(json: &str) -> Option<(bool, Vec)> { + let json: serde_json::Value = serde_json::from_str(&json[json.find('{')?..]).ok()?; + let packages: Vec = json["Items"]["PackageReference"] + .as_array()? + .iter() + .filter_map(|p| p["Identity"].as_str().map(str::to_ascii_lowercase)) + .collect(); + let mtp = json["Properties"] + .as_object() + .is_some_and(|p| p.values().any(|v| v.as_str().is_some_and(|v| v.eq_ignore_ascii_case("true")))) + || packages.iter().any(|p| p.starts_with("xunit.v3.mtp")); + Some((mtp, packages)) +} + +/// Whether the nearest `global.json` selects Microsoft.Testing.Platform. +fn global_mtp(dir: &Path) -> bool { + dir.ancestors().find_map(|d| std::fs::read_to_string(d.join("global.json")).ok()).is_some_and(|text| { + serde_json::from_str::(&ide_core::jsonc::strip(&text)) + .is_ok_and(|j| j["test"]["runner"] == "Microsoft.Testing.Platform") + }) +} + +/// The project file the configuration tests; none for a solution or a bare `dotnet test`. +fn project_file(config: &RunConfig, dir: &Path) -> Option { + config + .extras + .params + .get("project") + .into_iter() + .chain(config.args.iter().skip(1)) + .find(|a| Path::new(a).extension().is_some_and(|e| e.to_string_lossy().to_ascii_lowercase().ends_with("proj"))) + .map(|p| dir.join(p)) +} + +pub(crate) fn prepare(config: &RunConfig, dir: &Path, out: &Path) -> CoveragePrepared { + if config.args.first().is_none_or(|a| a != "test") { + return unsupported(".NET coverage runs `dotnet test` configurations."); + } + let project = project_file(config, dir); + let evaluated = project.as_ref().and_then(|project| { + let mut argv = vec![ + config.command.clone(), + "msbuild".into(), + project.to_string_lossy().into_owned(), + "-nologo".into(), + "-getProperty:IsTestingPlatformApplication,TestingPlatformDotnetTestSupport,EnableMSTestRunner".into(), + "-getItem:PackageReference".into(), + ]; + if let Some(framework) = config.extras.params.get("framework").filter(|f| !f.is_empty()) { + argv.push(format!("-p:TargetFramework={framework}")); + } + evaluation(&wrap::capture(&argv, dir, config)?) + }); + let project_dir = project.as_deref().and_then(Path::parent).unwrap_or(dir); + let runner = if global_mtp(project_dir) { + Runner::Mtp + } else if evaluated.as_ref().is_some_and(|(mtp, _)| *mtp) { + Runner::MtpLegacy + } else { + Runner::VsTest + }; + let package = if runner == Runner::VsTest { COLLECTOR } else { CODE_COVERAGE }; + if let Some((project, (_, packages))) = project.as_ref().zip(evaluated.as_ref()) + && !packages.iter().any(|p| p.eq_ignore_ascii_case(package)) + { + let target = project.strip_prefix(dir).unwrap_or(project).to_string_lossy(); + let add = [&config.command, "add", &target, "package", package].map(str::to_owned); + return missing( + package, + format!(".NET coverage needs the {package} package in the test project."), + Some((add.to_vec(), dir)), + ); + } + launch(config, dir, out, runner, package) +} + +fn launch(config: &RunConfig, dir: &Path, out: &Path, runner: Runner, package: &str) -> CoveragePrepared { + let results = out.to_string_lossy().into_owned(); + let mut extra: Vec = match runner { + Runner::VsTest => vec!["--collect:XPlat Code Coverage".into()], + _ => ["--coverage", "--coverage-output-format", "cobertura"].map(str::to_owned).to_vec(), + }; + extra.extend(["--results-directory".into(), results]); + let mut launch = config.clone(); + // A `dotnet test` configuration type rebuilds its command line from the parameters. + launch.extras.params.insert("coverageArgs".into(), serde_json::json!(extra).to_string()); + let boundary = launch.args.iter().position(|a| a == "--"); + match runner { + Runner::VsTest => { + let at = boundary.unwrap_or(launch.args.len()); + launch.args.splice(at..at, extra); + } + Runner::Mtp => launch.args.extend(extra), + Runner::MtpLegacy => { + if boundary.is_none() { + launch.args.push("--".into()); + } + launch.args.extend(extra); + } + } + let report = CoverageReportSpec::Cobertura { + runner: package.to_owned(), + dir: out.to_path_buf().into(), + base: dir.to_path_buf().into(), + hint: format!("Check the test output, and that every test project references {package}."), + }; + ready(package, &launch, launch.command.clone(), launch.args.clone(), report) +} + +/// VSTest writes `//coverage.cobertura.xml`, the testing platform +/// `/.cobertura.xml`. Deeper files are the TRX logger's copies of the same data. +pub(crate) fn reports(dir: &Path) -> Vec { + let is_report = |p: &Path| p.is_file() && p.to_string_lossy().ends_with(".cobertura.xml"); + let entries = |d: &Path| std::fs::read_dir(d).into_iter().flatten().flatten().map(|e| e.path()).collect::>(); + let mut found: Vec = entries(dir) + .into_iter() + .flat_map(|p| if p.is_dir() { entries(&p) } else { vec![p] }) + .filter(|p| is_report(p)) + .collect(); + found.sort(); + found +} + +#[cfg(test)] +mod tests { + use super::*; + + fn config(args: &[&str]) -> RunConfig { + serde_json::from_value(serde_json::json!({ + "id": "t", "name": "t", "kind": "shell", "command": "dotnet", "args": args, + "env": {}, "detected": true, "isTest": true, + })) + .unwrap() + } + + fn args(runner: Runner, base: &[&str]) -> Vec { + match launch(&config(base), Path::new("/p"), Path::new("/o"), runner, "x") { + CoveragePrepared::Ready { launch, .. } => launch.args, + other => panic!("{other:?}"), + } + } + + #[test] + fn options_go_where_each_runner_reads_them() { + assert_eq!( + args(Runner::VsTest, &["test", "--", "A=1"]), + ["test", "--collect:XPlat Code Coverage", "--results-directory", "/o", "--", "A=1"] + ); + let platform = ["--coverage", "--coverage-output-format", "cobertura", "--results-directory", "/o"]; + assert_eq!(args(Runner::Mtp, &["test"])[1..], platform); + let legacy = args(Runner::MtpLegacy, &["test"]); + assert_eq!((legacy[1].as_str(), &legacy[2..]), ("--", platform.map(str::to_owned).as_slice())); + } + + #[test] + fn msbuild_evaluation_names_packages_and_the_platform() { + let json = r#"noise {"Properties":{"IsTestingPlatformApplication":""},"Items":{"PackageReference":[{"Identity":"Coverlet.Collector"}]}}"#; + assert_eq!(evaluation(json), Some((false, vec!["coverlet.collector".into()]))); + let json = r#"{"Properties":{"EnableMSTestRunner":"true"},"Items":{"PackageReference":[]}}"#; + assert_eq!(evaluation(json), Some((true, vec![]))); + assert_eq!(evaluation("error MSB1009"), None); + } + + #[test] + fn project_files_and_global_json() { + let tmp = tempfile::tempdir().unwrap(); + let project = project_file(&config(&["test", "a/T.fsproj"]), tmp.path()).unwrap(); + assert_eq!(project, tmp.path().join("a/T.fsproj")); + assert_eq!(project_file(&config(&["test", "All.sln"]), tmp.path()), None); + assert!(!global_mtp(&tmp.path().join("a"))); + std::fs::write( + tmp.path().join("global.json"), + "{ // x\n\"test\":{\"runner\":\"Microsoft.Testing.Platform\"},}", + ) + .unwrap(); + assert!(global_mtp(&tmp.path().join("a"))); + } + + /// One report per test project is merged; the TRX logger's copies are not counted twice. + #[test] + fn merges_the_reports_of_one_run() { + let tmp = tempfile::tempdir().unwrap(); + let xml = include_str!("testdata/coverlet.cobertura.xml"); + for file in + ["guid-a/coverage.cobertura.xml", "guid-b/coverage.cobertura.xml", "t/In/host/coverage.cobertura.xml"] + { + let file = tmp.path().join(file); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(file, xml).unwrap(); + } + let spec = CoverageReportSpec::Cobertura { + runner: "coverlet.collector".into(), + dir: tmp.path().to_path_buf().into(), + base: tmp.path().to_path_buf().into(), + hint: "why".into(), + }; + let suite = crate::collect(&spec).unwrap(); + assert_eq!(suite.files[0].lines[0].hits, 2); + std::fs::write(tmp.path().join("direct.cobertura.xml"), xml).unwrap(); + assert_eq!(reports(tmp.path()).len(), 3); + // A cancelled or failed build leaves nothing: say why. + let empty = tempfile::tempdir().unwrap(); + let spec = CoverageReportSpec::Cobertura { + runner: "x".into(), + dir: empty.path().to_path_buf().into(), + base: empty.path().to_path_buf().into(), + hint: "why".into(), + }; + assert!(crate::collect(&spec).unwrap_err().to_string().contains("why")); + } +} diff --git a/crates/ide-coverage/src/lib.rs b/crates/ide-coverage/src/lib.rs index 898f155c5b..24c3143a17 100644 --- a/crates/ide-coverage/src/lib.rs +++ b/crates/ide-coverage/src/lib.rs @@ -14,11 +14,13 @@ //! | 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` | +//! | .NET (`dotnet test`) | coverlet.collector, or Microsoft.Testing.Extensions.CodeCoverage | Cobertura XML | //! //! Lines in the model are 0-based, like every IPC coordinate. mod cobertura; mod coveragepy; +mod dotnet; mod goprofile; mod import; mod jacoco; @@ -94,6 +96,9 @@ pub enum CoverageReportSpec { SimpleCov { path: IpcPath, base: IpcPath }, /// Every JaCoCo XML report (Maven `target/site/jacoco`, Gradle `build/reports/jacoco`) under `dir`. Jacoco { dir: IpcPath }, + /// The Cobertura reports `dotnet test` left in its results directory `dir`: one per test + /// project and target framework. `hint` explains why there might be none. + Cobertura { runner: String, dir: IpcPath, base: IpcPath, hint: String }, /// 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. @@ -218,6 +223,19 @@ pub fn collect(spec: &CoverageReportSpec) -> IdeResult { } Ok(acc.finish("JaCoCo")) } + CoverageReportSpec::Cobertura { runner, dir, base, hint } => { + let reports = dotnet::reports(dir); + if reports.is_empty() { + return Err(IdeError::not_found(format!("the run produced no coverage report. {hint}"))); + } + let mut acc = Accumulator::default(); + for report in reports { + let xml = std::fs::read_to_string(&report)?; + cobertura::parse_into(&xml, base, &mut acc) + .map_err(|e| IdeError::invalid(format!("{}: {e}", report.display())))?; + } + Ok(acc.finish(runner)) + } CoverageReportSpec::Exported { runner, argv, cwd, env, lcov } => { let (program, args) = argv.split_first().ok_or_else(|| IdeError::invalid("empty coverage export command"))?; diff --git a/crates/ide-coverage/src/plan.rs b/crates/ide-coverage/src/plan.rs index 4806c86769..336d4c1616 100644 --- a/crates/ide-coverage/src/plan.rs +++ b/crates/ide-coverage/src/plan.rs @@ -28,11 +28,15 @@ fn path(p: &Path) -> String { p.to_string_lossy().into_owned() } -fn unsupported(reason: impl Into) -> CoveragePrepared { +pub(crate) fn unsupported(reason: impl Into) -> CoveragePrepared { CoveragePrepared::Unsupported { reason: reason.into() } } -fn missing(tool: &str, message: impl Into, install: Option<(Vec, &Path)>) -> CoveragePrepared { +pub(crate) fn missing( + tool: &str, + message: impl Into, + install: Option<(Vec, &Path)>, +) -> CoveragePrepared { CoveragePrepared::MissingTool { tool: tool.to_owned(), message: message.into(), @@ -43,7 +47,7 @@ fn missing(tool: &str, message: impl Into, install: Option<(Vec, } } -fn ready( +pub(crate) fn ready( runner: &str, config: &RunConfig, command: String, @@ -69,6 +73,7 @@ pub fn prepare(root: &Path, config: &RunConfig, out: &Path) -> CoveragePrepared let first = config.args.first().map(String::as_str).unwrap_or_default(); match program.as_str() { "cargo" => cargo(config, &dir, out), + "dotnet" => crate::dotnet::prepare(config, &dir, out), "go" if first == "test" => go(config, &dir, out), "go" => unsupported("Go coverage is collected by `go test`; run a test configuration with coverage."), "mvn" | "mvnw" => maven(config, &dir), diff --git a/crates/ide-coverage/src/testdata/coverlet.cobertura.xml b/crates/ide-coverage/src/testdata/coverlet.cobertura.xml new file mode 100644 index 0000000000..71e51619a2 --- /dev/null +++ b/crates/ide-coverage/src/testdata/coverlet.cobertura.xml @@ -0,0 +1,48 @@ + + + + / + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/crates/ide-coverage/tests/dotnet_cli.rs b/crates/ide-coverage/tests/dotnet_cli.rs new file mode 100644 index 0000000000..bdddc033c0 --- /dev/null +++ b/crates/ide-coverage/tests/dotnet_cli.rs @@ -0,0 +1,101 @@ +//! Run with Coverage against the real `dotnet` CLI on `fixtures/dotnet-coverage`. +//! Skipped without a .NET 10 SDK, except in CI, where the workflow installs one. + +use ide_coverage::{CoveragePrepared, CoverageSuite, collect, prepare}; +use ide_run::RunConfig; +use std::path::Path; +use std::process::Command; + +fn has_sdk() -> bool { + let found = Command::new("dotnet") + .arg("--list-sdks") + .output() + .is_ok_and(|o| String::from_utf8_lossy(&o.stdout).lines().any(|l| l.starts_with("10."))); + assert!(found || std::env::var_os("CI").is_none(), "CI needs the .NET 10 SDK"); + found +} + +fn copy(from: &Path, to: &Path) { + std::fs::create_dir_all(to).unwrap(); + for entry in std::fs::read_dir(from).unwrap().flatten() { + let (name, path) = (entry.file_name(), entry.path()); + if path.is_dir() { + if name != "bin" && name != "obj" { + copy(&path, &to.join(name)); + } + } else { + std::fs::copy(&path, to.join(name)).unwrap(); + } + } +} + +fn config(args: &[&str]) -> RunConfig { + serde_json::from_value(serde_json::json!({ + "id": "t", "name": "t", "kind": "shell", "command": "dotnet", "args": args, + "env": {}, "detected": true, "isTest": true, + })) + .unwrap() +} + +/// Prepares, runs and collects like the IDE does; `out` has a space in its name. +fn covered(root: &Path, config: &RunConfig, out: &Path) -> CoverageSuite { + std::fs::create_dir_all(out).unwrap(); + let CoveragePrepared::Ready { launch, report, .. } = prepare(root, config, out) else { + panic!("{:?}", prepare(root, config, out)); + }; + let cwd = launch.cwd.as_deref().map_or_else(|| root.to_path_buf(), |c| root.join(c)); + let run = Command::new(&launch.command).args(&launch.args).current_dir(cwd).output().unwrap(); + assert!(run.status.success(), "{}{}", String::from_utf8_lossy(&run.stdout), String::from_utf8_lossy(&run.stderr)); + collect(&report).unwrap() +} + +/// (covered, total) lines of `Calculator.cs`, which must exist on this machine. +fn calculator(suite: &CoverageSuite) -> (u32, u32) { + let file = suite.files.iter().find(|f| (f.path.as_ref() as &Path).ends_with("Calc/Calculator.cs")); + let file = file.unwrap_or_else(|| panic!("{:?}", suite.files)); + assert!((file.path.as_ref() as &Path).is_file(), "{:?}", file.path); + (file.lines_covered, file.lines_total) +} + +#[test] +fn vstest_projects_solutions_and_missing_packages() { + if !has_sdk() { + return; + } + let tmp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(tmp.path()).unwrap(); + copy(&Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/dotnet-coverage"), &root); + + let project = config(&["test", "Add.Tests/Add.Tests.csproj"]); + let one = covered(&root, &project, &root.join("out one")); + assert_eq!(calculator(&one), (1, 7)); + // Both test projects of the solution are merged. + let all = covered(&root, &config(&["test", "Calc.slnx"]), &root.join("out all")); + assert_eq!(calculator(&all), (6, 7)); + + let csproj = root.join("Add.Tests/Add.Tests.csproj"); + let text = std::fs::read_to_string(&csproj).unwrap(); + let without: Vec<&str> = text.lines().filter(|l| !l.contains("coverlet")).collect(); + std::fs::write(&csproj, without.join("\n")).unwrap(); + match prepare(&root, &project, &root.join("out one")) { + CoveragePrepared::MissingTool { tool, install: Some(install), .. } => { + assert_eq!(tool, "coverlet.collector"); + assert_eq!(install.args, ["add", "Add.Tests/Add.Tests.csproj", "package", "coverlet.collector"]); + } + other => panic!("{other:?}"), + } +} + +#[test] +fn testing_platform_projects() { + if !has_sdk() { + return; + } + let tmp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(tmp.path()).unwrap(); + copy(&Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/dotnet-coverage"), &root); + // `global.json` is read from the working directory. + let mut config = config(&["test", "--project", "Mtp.Tests.csproj"]); + config.cwd = Some(root.join("mtp").into()); + assert_eq!(calculator(&covered(&root, &config, &root.join("out mtp"))), (1, 7)); +} diff --git a/crates/ide-run/src/wrap.rs b/crates/ide-run/src/wrap.rs index e2ed49df1d..d1282a7abe 100644 --- a/crates/ide-run/src/wrap.rs +++ b/crates/ide-run/src/wrap.rs @@ -115,6 +115,19 @@ pub fn probe(argv: &[String], dir: &Path, config: &RunConfig) -> bool { .is_ok_and(|s| s.success()) } +/// Like [`probe`], returning what a successful command printed. +pub fn capture(argv: &[String], dir: &Path, config: &RunConfig) -> Option { + let (program, args) = argv.split_first()?; + let program = resolve(program, config, dir); + let out = ide_core::process::prepare(Command::new(program).current_dir(dir)) + .args(args) + .envs(&config.env) + .stdin(Stdio::null()) + .output() + .ok()?; + out.status.success().then(|| ide_core::output_encoding::decode_tool_output(&out.stdout).to_string()) +} + /// `program` as spawnable: bare names through the configuration's search path. fn resolve(program: &str, config: &RunConfig, dir: &Path) -> PathBuf { let p = Path::new(program); diff --git a/docs/en/guide/coverage.mdx b/docs/en/guide/coverage.mdx index 01e071ae00..c13ecb53fc 100644 --- a/docs/en/guide/coverage.mdx +++ b/docs/en/guide/coverage.mdx @@ -29,17 +29,18 @@ If the coverage tool is missing, a notification names it and offers **Install**, ## Supported runtimes -| Runtime | Configurations | Coverage tool | -| ----------------------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -| Rust | `cargo test`, `cargo run`, `cargo nextest` | `cargo llvm-cov` (install `cargo-llvm-cov` and the `llvm-tools-preview` rustup component) | -| Go | `go test` | `go test -coverprofile` | -| Java / Kotlin (Maven) | Maven configurations that run tests (`test`, `verify`) | JaCoCo Maven plugin goals | -| Java / Kotlin (Gradle) | Gradle configurations that run tests (`test`, `check`) | JaCoCo, applied through an init script | -| JavaScript / TypeScript | `package.json` test scripts that run vitest or jest (npm, pnpm, yarn, bun) | The runner's own `--coverage` (vitest needs `@vitest/coverage-v8` or `@vitest/coverage-istanbul`) | -| 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` | +| Runtime | Configurations | Coverage tool | +| ----------------------- | -------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | +| Rust | `cargo test`, `cargo run`, `cargo nextest` | `cargo llvm-cov` (install `cargo-llvm-cov` and the `llvm-tools-preview` rustup component) | +| Go | `go test` | `go test -coverprofile` | +| .NET | `dotnet test` configurations | coverlet.collector or Microsoft.Testing.Extensions.CodeCoverage (see [C# and .NET](/en/languages/csharp)) | +| Java / Kotlin (Maven) | Maven configurations that run tests (`test`, `verify`) | JaCoCo Maven plugin goals | +| Java / Kotlin (Gradle) | Gradle configurations that run tests (`test`, `check`) | JaCoCo, applied through an init script | +| JavaScript / TypeScript | `package.json` test scripts that run vitest or jest (npm, pnpm, yarn, bun) | The runner's own `--coverage` (vitest needs `@vitest/coverage-v8` or `@vitest/coverage-istanbul`) | +| 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/csharp.mdx b/docs/en/languages/csharp.mdx index 2ceaaa1b1b..5647f241c6 100644 --- a/docs/en/languages/csharp.mdx +++ b/docs/en/languages/csharp.mdx @@ -133,6 +133,19 @@ Results appear in the test tree of the Run tool window. The IDE asks VSTest for See [Testing](/en/guide/testing) for the test tree and rerunning failed tests. +### Coverage + +**Run with Coverage** works for `dotnet test` configurations, including a single test started from the gutter, and shows the result in the [coverage views](/en/guide/coverage). Each test project needs a collector package: + +| Test runner | Package | +| -------------------------- | ------------------------------------------- | +| VSTest (the default) | `coverlet.collector` | +| Microsoft.Testing.Platform | `Microsoft.Testing.Extensions.CodeCoverage` | + +The xUnit, NUnit and MSTest templates already reference `coverlet.collector`. When the package is missing from the project a configuration tests, a notification offers **Install** (`dotnet add package …`). A configuration that tests a solution isn't checked: projects without the package are left out of the report. + +Each run writes its results to its own temporary directory, so older reports in `TestResults` are never mixed in, and the reports of several test projects are merged. A stopped run shows no coverage. Remove your own `--results-directory` from the test arguments for coverage runs. + ## Debugging Running a .NET Project configuration, or a project file from the Project view, with **Debug** builds the project, asks MSBuild for its output assembly (`TargetPath`, in the Debug configuration) and launches it under netcoredbg. If netcoredbg is missing, a notification offers to install it. diff --git a/docs/zh/guide/coverage.mdx b/docs/zh/guide/coverage.mdx index 0c06db4b40..a5d6355641 100644 --- a/docs/zh/guide/coverage.mdx +++ b/docs/zh/guide/coverage.mdx @@ -25,17 +25,18 @@ description: "使用覆盖率运行配置,在编辑器、项目视图和覆盖 ## 支持的运行时 -| 运行时 | 配置 | 覆盖率工具 | -| ----------------------- | ---------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | -| Rust | `cargo test`、`cargo run`、`cargo nextest` | `cargo llvm-cov`(需安装 `cargo-llvm-cov` 和 rustup 组件 `llvm-tools-preview`) | -| Go | `go test` | `go test -coverprofile` | -| Java / Kotlin(Maven) | 运行测试的 Maven 配置(`test`、`verify`) | JaCoCo Maven 插件目标 | -| Java / Kotlin(Gradle) | 运行测试的 Gradle 配置(`test`、`check`) | JaCoCo,通过 init 脚本应用 | -| JavaScript / TypeScript | 运行 vitest 或 jest 的 `package.json` 测试脚本(npm、pnpm、yarn、bun) | 测试框架自带的 `--coverage`(vitest 需要 `@vitest/coverage-v8` 或 `@vitest/coverage-istanbul`) | -| 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` 读取结果包 | +| 运行时 | 配置 | 覆盖率工具 | +| ----------------------- | ---------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | +| Rust | `cargo test`、`cargo run`、`cargo nextest` | `cargo llvm-cov`(需安装 `cargo-llvm-cov` 和 rustup 组件 `llvm-tools-preview`) | +| Go | `go test` | `go test -coverprofile` | +| .NET | `dotnet test` 配置 | coverlet.collector 或 Microsoft.Testing.Extensions.CodeCoverage(见 [C# 与 .NET](/zh/languages/csharp)) | +| Java / Kotlin(Maven) | 运行测试的 Maven 配置(`test`、`verify`) | JaCoCo Maven 插件目标 | +| Java / Kotlin(Gradle) | 运行测试的 Gradle 配置(`test`、`check`) | JaCoCo,通过 init 脚本应用 | +| JavaScript / TypeScript | 运行 vitest 或 jest 的 `package.json` 测试脚本(npm、pnpm、yarn、bun) | 测试框架自带的 `--coverage`(vitest 需要 `@vitest/coverage-v8` 或 `@vitest/coverage-istanbul`) | +| 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/csharp.mdx b/docs/zh/languages/csharp.mdx index 5a8ba856db..6f415e8aff 100644 --- a/docs/zh/languages/csharp.mdx +++ b/docs/zh/languages/csharp.mdx @@ -112,6 +112,19 @@ C# 在装了 Roslyn 语言服务器时用它,否则用 csharp-ls。Roslyn 是 测试树和重新运行失败测试等内容见[测试](/zh/guide/testing)。 +### 覆盖率 + +`dotnet test` 配置支持**带覆盖率运行**(包括从行号栏运行单个测试),结果显示在[覆盖率视图](/zh/guide/coverage)中。每个测试项目都需要一个收集器包: + +| 测试运行器 | 包 | +| -------------------------- | ------------------------------------------- | +| VSTest(默认) | `coverlet.collector` | +| Microsoft.Testing.Platform | `Microsoft.Testing.Extensions.CodeCoverage` | + +xUnit、NUnit 和 MSTest 模板默认已引用 `coverlet.collector`。如果配置所测试的项目缺少对应的包,会弹出带**安装**按钮的通知(执行 `dotnet add <项目> package …`)。测试解决方案的配置不做检查:没有引用包的项目不会出现在报告中。 + +每次运行的结果写入单独的临时目录,因此不会混入 `TestResults` 里的旧报告;多个测试项目的报告会合并。中途停止的运行不显示覆盖率。带覆盖率运行前,请从测试参数中去掉自己指定的 `--results-directory`。 + ## 调试 以 **调试** 方式运行 .NET 项目配置或项目视图中的项目文件时,IDE 会先构建项目,再向 MSBuild 查询输出程序集(Debug 配置下的 `TargetPath`),然后在 netcoredbg 下启动。缺少 netcoredbg 时会弹出通知提供安装。 diff --git a/fixtures/README.md b/fixtures/README.md index a2c4f0f670..cc85c22a14 100644 --- a/fixtures/README.md +++ b/fixtures/README.md @@ -29,6 +29,7 @@ something to show. | `python-profiling/` | Python 3.10+ (standard library only) | `python cpu_heavy.py` (Run › Profile) | — | — | — | | `tailwind-app/` | Node 22+, pnpm/npm, Tailwind CSS 4, React | `pnpm dev` | — | — | `flex` conflicting with `block` in `src/App.tsx` | | `zig-app/` | Zig 0.17 | `zig build run` | `zig build test` | — | — | +| `dotnet-coverage/` | .NET 10 SDK | — | `dotnet test Calc.slnx` | — | — (Run with Coverage; `mtp/` is Microsoft.Testing.Platform) | | `swiftpm-app/` | Swift 6+ (Xcode or a swift.org toolchain) | — | `swift test` (XCTest and Swift Testing) | `OPENIDEA_FAIL=1 swift test` | — | | `biome-app/` | Node 22+, `@biomejs/biome` (`npm install`) | `npm start` | — | — | `let` never reassigned, `==` and a duplicate CSS `color` (Biome) | | `dprint-app/` | Node 22+, `dprint` (`npm install`) | `npm start` | — | — | unformatted `src/index.ts` / `src/data.json` (dprint); `README.md` keeps Prettier | diff --git a/fixtures/dotnet-coverage/.gitignore b/fixtures/dotnet-coverage/.gitignore new file mode 100644 index 0000000000..62d1e7994c --- /dev/null +++ b/fixtures/dotnet-coverage/.gitignore @@ -0,0 +1,3 @@ +bin/ +obj/ +TestResults/ diff --git a/fixtures/dotnet-coverage/Add.Tests/Add.Tests.csproj b/fixtures/dotnet-coverage/Add.Tests/Add.Tests.csproj new file mode 100644 index 0000000000..c1eb2806c8 --- /dev/null +++ b/fixtures/dotnet-coverage/Add.Tests/Add.Tests.csproj @@ -0,0 +1,14 @@ + + + net10.0 + + + + + + + + + + + diff --git a/fixtures/dotnet-coverage/Add.Tests/Tests.cs b/fixtures/dotnet-coverage/Add.Tests/Tests.cs new file mode 100644 index 0000000000..f1fa1eee13 --- /dev/null +++ b/fixtures/dotnet-coverage/Add.Tests/Tests.cs @@ -0,0 +1,8 @@ +using Calc; +using Xunit; + +public class AddTests +{ + [Fact] + public void Adds() => Assert.Equal(3, Calculator.Add(1, 2)); +} diff --git a/fixtures/dotnet-coverage/Calc.slnx b/fixtures/dotnet-coverage/Calc.slnx new file mode 100644 index 0000000000..1b19a74bd4 --- /dev/null +++ b/fixtures/dotnet-coverage/Calc.slnx @@ -0,0 +1,5 @@ + + + + + diff --git a/fixtures/dotnet-coverage/Calc/Calc.csproj b/fixtures/dotnet-coverage/Calc/Calc.csproj new file mode 100644 index 0000000000..555ae434a7 --- /dev/null +++ b/fixtures/dotnet-coverage/Calc/Calc.csproj @@ -0,0 +1,5 @@ + + + net10.0 + + diff --git a/fixtures/dotnet-coverage/Calc/Calculator.cs b/fixtures/dotnet-coverage/Calc/Calculator.cs new file mode 100644 index 0000000000..f2e566a67d --- /dev/null +++ b/fixtures/dotnet-coverage/Calc/Calculator.cs @@ -0,0 +1,15 @@ +namespace Calc; + +public static class Calculator +{ + public static int Add(int a, int b) => a + b; + + public static string Sign(int n) + { + if (n > 0) + { + return "positive"; + } + return "other"; + } +} diff --git a/fixtures/dotnet-coverage/Sign.Tests/Sign.Tests.csproj b/fixtures/dotnet-coverage/Sign.Tests/Sign.Tests.csproj new file mode 100644 index 0000000000..c1eb2806c8 --- /dev/null +++ b/fixtures/dotnet-coverage/Sign.Tests/Sign.Tests.csproj @@ -0,0 +1,14 @@ + + + net10.0 + + + + + + + + + + + diff --git a/fixtures/dotnet-coverage/Sign.Tests/Tests.cs b/fixtures/dotnet-coverage/Sign.Tests/Tests.cs new file mode 100644 index 0000000000..bbb966f8ca --- /dev/null +++ b/fixtures/dotnet-coverage/Sign.Tests/Tests.cs @@ -0,0 +1,8 @@ +using Calc; +using Xunit; + +public class SignTests +{ + [Fact] + public void Positive() => Assert.Equal("positive", Calculator.Sign(1)); +} diff --git a/fixtures/dotnet-coverage/mtp/Mtp.Tests.csproj b/fixtures/dotnet-coverage/mtp/Mtp.Tests.csproj new file mode 100644 index 0000000000..4bc3645b29 --- /dev/null +++ b/fixtures/dotnet-coverage/mtp/Mtp.Tests.csproj @@ -0,0 +1,14 @@ + + + Exe + net10.0 + true + + + + + + + + + diff --git a/fixtures/dotnet-coverage/mtp/Tests.cs b/fixtures/dotnet-coverage/mtp/Tests.cs new file mode 100644 index 0000000000..a3db32f6c2 --- /dev/null +++ b/fixtures/dotnet-coverage/mtp/Tests.cs @@ -0,0 +1,8 @@ +using Calc; +using Xunit; + +public class MtpTests +{ + [Fact] + public void Adds() => Assert.Equal(3, Calculator.Add(1, 2)); +} diff --git a/fixtures/dotnet-coverage/mtp/global.json b/fixtures/dotnet-coverage/mtp/global.json new file mode 100644 index 0000000000..7a61fa3925 --- /dev/null +++ b/fixtures/dotnet-coverage/mtp/global.json @@ -0,0 +1 @@ +{ "test": { "runner": "Microsoft.Testing.Platform" } } diff --git a/src/bindings.ts b/src/bindings.ts index 180c03ba30..087017482d 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -7319,6 +7319,11 @@ export type CoverageReportSpec = { kind: "simpleCov"; path: IpcPath; base: IpcPath } | /** Every JaCoCo XML report (Maven `target/site/jacoco`, Gradle `build/reports/jacoco`) under `dir`. */ { kind: "jacoco"; dir: IpcPath } | +/** + * The Cobertura reports `dotnet test` left in its results directory `dir`: one per test + * project and target framework. `hint` explains why there might be none. + */ +{ kind: "cobertura"; runner: string; dir: IpcPath; base: IpcPath; hint: string } | /** 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 } | /** An Xcode result bundle, read with `xcrun xccov`; only files under `root` are kept. */ diff --git a/src/features/coverage/coverage.test.ts b/src/features/coverage/coverage.test.ts index 122a5f6880..e5e7b94c76 100644 --- a/src/features/coverage/coverage.test.ts +++ b/src/features/coverage/coverage.test.ts @@ -46,6 +46,8 @@ const suite = (files: FileCoverage[]): CoverageSuite => ({ runner: "t", hasBranc describe("coverageSupports", () => { it("knows the coverage runners", () => { expect(coverageSupports(cfg("cargo", ["test"]))).toBe(true); + expect(coverageSupports(cfg("dotnet", ["test", "T.csproj"]))).toBe(true); + expect(coverageSupports(cfg("dotnet", ["run"]))).toBe(false); expect(coverageSupports(cfg("cargo", ["+nightly", "run"]))).toBe(true); expect(coverageSupports(cfg("cargo", ["build"]))).toBe(false); expect(coverageSupports(cfg("go", ["test", "./..."]))).toBe(true); diff --git a/src/features/coverage/model.ts b/src/features/coverage/model.ts index 349894a3ab..3894755436 100644 --- a/src/features/coverage/model.ts +++ b/src/features/coverage/model.ts @@ -29,6 +29,8 @@ export function coverageSupports(config: Pick { expect(line.args.indexOf("--no-build")).toBeLessThan(line.args.indexOf("--")); expect(line.args.slice(line.args.indexOf("--") + 1)).toEqual(["--filter", "FullyQualifiedName=A.Tests.Two"]); }); + it.each([ + ["vstest", ["--cov", "--", "A=1"]], + ["mtp", ["--", "A=1", "--cov"]], + ])("places %s coverage arguments", (runner, tail) => { + const p = { project: project.path, runner, programArgs: "-- A=1", coverageArgs: '["--cov"]' }; + expect(dotnetTestType.commandLine(p)!.args.slice(-3)).toEqual(tail); + }); it("resolves solution projects, XML entities and external references", () => { expect( solutionPaths(