Файли
openidea/crates/ide-coverage/tests/dotnet_cli.rs
T
LU XIANGRUIтаwildcatDownstairs cff33ee70d feat(dotnet): run .NET tests with coverage (#7736)
Run with Coverage now works for `dotnet test` configurations: VSTest projects collect with coverlet.collector, Microsoft.Testing.Platform projects with Microsoft.Testing.Extensions.CodeCoverage (Cobertura output). The runner is chosen from global.json's test.runner and an MSBuild evaluation of the project; a test project without the package gets an Install notification that runs `dotnet add <project> package …`. Each run writes to its own results directory and the reports of every test project are merged (the TRX logger's copies are not counted twice). Cobertura branch flags are read case-insensitively (coverlet writes `True`). The Rust CI job's .NET 10 SDK step now also serves ide-coverage's real-CLI test.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-05 09:51:24 +08:00

102 рядки
4.1 KiB
Rust

//! 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));
}