дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 09:41:34 +02:00
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]>
Цей коміт міститься в:
1 джерело
ccb73f4efd
коміт
cff33ee70d
31 files changed
+613
-30
No files matched your search
@@ -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
|
||||
|
||||
Створено
@@ -4287,6 +4287,7 @@ dependencies = [
|
||||
name = "ide-coverage"
|
||||
version = "0.1.57"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
"quick-xml 0.42.0",
|
||||
|
||||
@@ -14,4 +14,5 @@ serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
dunce.workspace = true
|
||||
tempfile.workspace = true
|
||||
@@ -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<Accumulator, quick_xml::Error> {
|
||||
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<String> = None;
|
||||
let mut file: Option<PathBuf> = None;
|
||||
@@ -72,7 +78,8 @@ pub(crate) fn parse(xml: &str, base: &Path) -> Result<Accumulator, quick_xml::Er
|
||||
let Some(number) = attr(&e, "number").and_then(|n| n.parse::<u32>().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<Accumulator, quick_xml::Er
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(acc)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -162,6 +169,16 @@ mod tests {
|
||||
assert!(parse("<coverage><packages></coverage>", 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#"<coverage><packages><package><classes><class filename="a/b.py"><lines><line number="1" hits="1"/></lines></class></classes></package></packages></coverage>"#;
|
||||
|
||||
@@ -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<String>)> {
|
||||
let json: serde_json::Value = serde_json::from_str(&json[json.find('{')?..]).ok()?;
|
||||
let packages: Vec<String> = 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::<serde_json::Value>(&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<PathBuf> {
|
||||
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<String> = 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 `<dir>/<guid>/coverage.cobertura.xml`, the testing platform
|
||||
/// `<dir>/<name>.cobertura.xml`. Deeper files are the TRX logger's copies of the same data.
|
||||
pub(crate) fn reports(dir: &Path) -> Vec<PathBuf> {
|
||||
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::<Vec<_>>();
|
||||
let mut found: Vec<PathBuf> = 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<String> {
|
||||
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"));
|
||||
}
|
||||
}
|
||||
@@ -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 <lcov>`).
|
||||
Exported { runner: String, argv: Vec<String>, cwd: IpcPath, env: BTreeMap<String, String>, 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<CoverageSuite> {
|
||||
}
|
||||
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"))?;
|
||||
|
||||
@@ -28,11 +28,15 @@ fn path(p: &Path) -> String {
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn unsupported(reason: impl Into<String>) -> CoveragePrepared {
|
||||
pub(crate) fn unsupported(reason: impl Into<String>) -> CoveragePrepared {
|
||||
CoveragePrepared::Unsupported { reason: reason.into() }
|
||||
}
|
||||
|
||||
fn missing(tool: &str, message: impl Into<String>, install: Option<(Vec<String>, &Path)>) -> CoveragePrepared {
|
||||
pub(crate) fn missing(
|
||||
tool: &str,
|
||||
message: impl Into<String>,
|
||||
install: Option<(Vec<String>, &Path)>,
|
||||
) -> CoveragePrepared {
|
||||
CoveragePrepared::MissingTool {
|
||||
tool: tool.to_owned(),
|
||||
message: message.into(),
|
||||
@@ -43,7 +47,7 @@ fn missing(tool: &str, message: impl Into<String>, install: Option<(Vec<String>,
|
||||
}
|
||||
}
|
||||
|
||||
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),
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<coverage line-rate="0.8571" branch-rate="0.5" version="1.9" timestamp="1796282470" lines-covered="6" lines-valid="7" branches-covered="1" branches-valid="2">
|
||||
<sources>
|
||||
<source>/</source>
|
||||
</sources>
|
||||
<packages>
|
||||
<package name="Calc" line-rate="0.8571" branch-rate="0.5" complexity="3">
|
||||
<classes>
|
||||
<class name="Calc.Calculator" filename="home/dev/dn app/Calc/Calculator.cs" line-rate="0.8571" branch-rate="0.5" complexity="3">
|
||||
<methods>
|
||||
<method name="Add" signature="(System.Int32,System.Int32)" line-rate="1" branch-rate="1" complexity="1">
|
||||
<lines>
|
||||
<line number="5" hits="1" branch="False" />
|
||||
</lines>
|
||||
</method>
|
||||
<method name="Sign" signature="(System.Int32)" line-rate="0.8332999999999999" branch-rate="0.5" complexity="2">
|
||||
<lines>
|
||||
<line number="8" hits="1" branch="False" />
|
||||
<line number="9" hits="1" branch="True" condition-coverage="50% (1/2)">
|
||||
<conditions>
|
||||
<condition number="7" type="jump" coverage="50%" />
|
||||
</conditions>
|
||||
</line>
|
||||
<line number="10" hits="1" branch="False" />
|
||||
<line number="11" hits="1" branch="False" />
|
||||
<line number="13" hits="0" branch="False" />
|
||||
<line number="14" hits="1" branch="False" />
|
||||
</lines>
|
||||
</method>
|
||||
</methods>
|
||||
<lines>
|
||||
<line number="5" hits="1" branch="False" />
|
||||
<line number="8" hits="1" branch="False" />
|
||||
<line number="9" hits="1" branch="True" condition-coverage="50% (1/2)">
|
||||
<conditions>
|
||||
<condition number="7" type="jump" coverage="50%" />
|
||||
</conditions>
|
||||
</line>
|
||||
<line number="10" hits="1" branch="False" />
|
||||
<line number="11" hits="1" branch="False" />
|
||||
<line number="13" hits="0" branch="False" />
|
||||
<line number="14" hits="1" branch="False" />
|
||||
</lines>
|
||||
</class>
|
||||
</classes>
|
||||
</package>
|
||||
</packages>
|
||||
</coverage>
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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<String> {
|
||||
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);
|
||||
|
||||
@@ -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:
|
||||
|
||||
|
||||
@@ -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 <project> 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.
|
||||
|
||||
@@ -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` 读取结果包 |
|
||||
|
||||
暂不支持:
|
||||
|
||||
|
||||
@@ -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 时会弹出通知提供安装。
|
||||
|
||||
@@ -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 |
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
bin/
|
||||
obj/
|
||||
TestResults/
|
||||
@@ -0,0 +1,14 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.4" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../Calc/Calc.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,8 @@
|
||||
using Calc;
|
||||
using Xunit;
|
||||
|
||||
public class AddTests
|
||||
{
|
||||
[Fact]
|
||||
public void Adds() => Assert.Equal(3, Calculator.Add(1, 2));
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<Solution>
|
||||
<Project Path="Calc/Calc.csproj" />
|
||||
<Project Path="Add.Tests/Add.Tests.csproj" />
|
||||
<Project Path="Sign.Tests/Sign.Tests.csproj" />
|
||||
</Solution>
|
||||
@@ -0,0 +1,5 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -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";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.4" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../Calc/Calc.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,8 @@
|
||||
using Calc;
|
||||
using Xunit;
|
||||
|
||||
public class SignTests
|
||||
{
|
||||
[Fact]
|
||||
public void Positive() => Assert.Equal("positive", Calculator.Sign(1));
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="xunit.v3.mtp-v2" Version="3.2.0" />
|
||||
<PackageReference Include="Microsoft.Testing.Extensions.CodeCoverage" Version="18.1.0" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../Calc/Calc.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,8 @@
|
||||
using Calc;
|
||||
using Xunit;
|
||||
|
||||
public class MtpTests
|
||||
{
|
||||
[Fact]
|
||||
public void Adds() => Assert.Equal(3, Calculator.Add(1, 2));
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{ "test": { "runner": "Microsoft.Testing.Platform" } }
|
||||
@@ -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 <lcov>`). */
|
||||
{ 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. */
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -29,6 +29,8 @@ export function coverageSupports(config: Pick<RunConfig, "command" | "args" | "k
|
||||
}
|
||||
case "go":
|
||||
return args[0] === "test";
|
||||
case "dotnet":
|
||||
return config.kind === "dotnet-test" || args[0] === "test";
|
||||
case "mvn":
|
||||
case "mvnw":
|
||||
case "gradle":
|
||||
|
||||
@@ -231,6 +231,11 @@ export const dotnetTestType: RunConfigTypeContribution = {
|
||||
const boundary = extra.indexOf("--");
|
||||
extra.splice(boundary < 0 ? extra.length : boundary, 0, ...selection);
|
||||
}
|
||||
// Run with Coverage: VSTest options go before `--` (RunSettings), testing-platform ones at the end.
|
||||
if (p.coverageArgs) {
|
||||
const boundary = !p.runner || p.runner === "vstest" ? extra.indexOf("--") : -1;
|
||||
extra.splice(boundary < 0 ? extra.length : boundary, 0, ...(JSON.parse(p.coverageArgs) as string[]));
|
||||
}
|
||||
return {
|
||||
...line,
|
||||
args: [...line.args, ...(p.runner === "mtp-legacy" && extra[0] !== "--" ? ["--"] : []), ...extra],
|
||||
|
||||
@@ -33,6 +33,13 @@ describe(".NET workspace formats and runners", () => {
|
||||
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(
|
||||
|
||||
Reference in new issue
Заблокувати користувача