Skip to content

Visual Studio Code, rebuilt in Rust

Rust

feat(testing): port test coverage view, gutter and results rows

rokartur1db505910c0d
diff --git a/native/crates/app/src/main.rs b/native/crates/app/src/main.rs
index f1d6179f697..5ba43c55ebd 100644
--- a/native/crates/app/src/main.rs
+++ b/native/crates/app/src/main.rs
@@ -116,6 +116,7 @@ mod syntax;
mod tasks;
mod terminal;
mod testing;
+mod testing_coverage;
mod tf_idf;
mod theme;
mod timeline;
diff --git a/native/crates/app/src/testing.rs b/native/crates/app/src/testing.rs
index 220ae89784c..fb4cdfd5911 100644
--- a/native/crates/app/src/testing.rs
+++ b/native/crates/app/src/testing.rs
@@ -346,6 +346,8 @@ pub struct RunTask {
pub controller_id: String,
pub running: bool,
pub output: String,
+ /// `ITestRunTaskResults.coverage`, from the run's first `$appendCoverage`.
+ pub coverage: Option<crate::testing_coverage::TestCoverage>,
}
/// A `LiveTestResult`.
@@ -383,6 +385,7 @@ impl TestResult {
controller_id: task["ctrlId"].as_str().unwrap_or_default().to_owned(),
running: task["running"] != false,
output: String::new(),
+ coverage: None,
});
for item in self.items.values_mut() {
item.tasks.push(TaskState::default());
@@ -492,7 +495,7 @@ impl TestResult {
json!({ "expand": item.expand, "item": item.item, "tasks": tasks, "ownComputedState": item.own_state.to_value(), "computedState": self.computed_state(id).to_value() })
})
.collect();
- let tasks: Vec<Value> = self.tasks.iter().map(|task| json!({ "id": task.id, "name": task.name, "ctrlId": task.controller_id, "hasCoverage": false })).collect();
+ let tasks: Vec<Value> = self.tasks.iter().map(|task| json!({ "id": task.id, "name": task.name, "ctrlId": task.controller_id, "hasCoverage": task.coverage.is_some() })).collect();
json!({ "id": self.id, "completedAt": self.completed_at, "items": items, "tasks": tasks, "name": self.name(), "request": self.request })
}
}
diff --git a/native/crates/app/src/testing_coverage.rs b/native/crates/app/src/testing_coverage.rs
new file mode 100644
index 00000000000..7ce4b0e315d
--- /dev/null
+++ b/native/crates/app/src/testing_coverage.rs
@@ -0,0 +1,479 @@
+//! Test coverage of a run task: testCoverage.ts `TestCoverage` (the files' coverage in a prefix tree by URI path,
+//! computed for the folders above them), testTypes.ts `CoverageDetails`, codeCoverageDecorations.ts
+//! `CoverageDetailsModel` (the editor's non-overlapping ranges) and codeCoverageDisplayUtils.ts.
+
+use std::collections::{BTreeMap, BTreeSet, HashMap};
+
+use serde_json::Value;
+
+#[cfg(test)]
+mod tests;
+
+/// testTypes.ts `ICoverageCount`.
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct CoverageCount {
+ pub covered: u64,
+ pub total: u64,
+}
+
+impl CoverageCount {
+ fn from_value(value: &Value) -> Option<Self> {
+ Some(CoverageCount { covered: value["covered"].as_u64()?, total: value["total"].as_u64()? })
+ }
+
+ /// codeCoverageDisplayUtils.ts `percent`.
+ pub fn percent(self) -> f64 {
+ if self.total == 0 { 1. } else { (self.covered as f64 / self.total as f64).clamp(0., 1.) }
+ }
+}
+
+/// testCoverage.ts `getTotalCoveragePercent`.
+pub fn total_coverage_percent(statement: CoverageCount, branch: Option<CoverageCount>, declaration: Option<CoverageCount>) -> f64 {
+ let mut numerator = statement.covered;
+ let mut denominator = statement.total;
+ for count in [branch, declaration].into_iter().flatten() {
+ numerator += count.covered;
+ denominator += count.total;
+ }
+ if denominator == 0 { 1. } else { numerator as f64 / denominator as f64 }
+}
+
+/// A URI's `UriComponents` parts the tree keys on.
+#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct CoverageUri {
+ pub scheme: String,
+ pub authority: String,
+ pub path: String,
+}
+
+impl CoverageUri {
+ pub fn from_value(value: &Value) -> Self {
+ let text = |key: &str| value[key].as_str().unwrap_or_default().to_owned();
+ CoverageUri { scheme: text("scheme"), authority: text("authority"), path: text("path") }
+ }
+
+ #[cfg(test)]
+ pub fn file(path: &str) -> Self {
+ CoverageUri { scheme: "file".into(), authority: String::new(), path: path.to_owned() }
+ }
+
+ /// resources.ts `basenameOrAuthority`.
+ pub fn basename(&self) -> &str {
+ match self.path.rsplit('/').next() {
+ Some(name) if !name.is_empty() => name,
+ _ => &self.authority,
+ }
+ }
+
+ /// The `URI.toString()` the coverage view sorts files by (without its percent-encoding).
+ pub fn to_uri_string(&self) -> String {
+ format!("{}://{}{}", self.scheme, self.authority, self.path)
+ }
+}
+
+/// Which of testCoverage.ts's `AbstractFileCoverage` classes a tree node holds.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum CoverageKind {
+ /// `FileCoverage`: a file the extension reported.
+ File,
+ /// `ComputedFileCoverage`: a folder's sum of the files below it.
+ Computed,
+ /// `BypassedFileCoverage`: a node of `filterTreeForTest`, without counts.
+ Bypassed,
+}
+
+/// `AbstractFileCoverage`.
+#[derive(Clone, Debug, PartialEq)]
+pub struct FileCoverage {
+ pub kind: CoverageKind,
+ /// The extension host's id for `$getCoverageDetails`; a folder's is a counter.
+ pub id: String,
+ pub uri: CoverageUri,
+ pub statement: CoverageCount,
+ pub branch: Option<CoverageCount>,
+ pub declaration: Option<CoverageCount>,
+ /// `perTestData`: the tests that ran code in the file (or folder).
+ pub per_test: BTreeSet<String>,
+}
+
+impl FileCoverage {
+ /// `tpc`.
+ pub fn total_percent(&self) -> f64 {
+ total_coverage_percent(self.statement, self.branch, self.declaration)
+ }
+}
+
+/// An `IPrefixTreeNode` of a coverage tree: a path segment's node, keyed by the segment in its parent.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct CoverageNode {
+ pub value: Option<FileCoverage>,
+ pub children: BTreeMap<String, CoverageNode>,
+}
+
+impl CoverageNode {
+ /// `WellDefinedPrefixTree.values`.
+ pub fn values(&self) -> Vec<&FileCoverage> {
+ let mut values = Vec::new();
+ let mut stack: Vec<&CoverageNode> = vec![self];
+ while let Some(node) = stack.pop() {
+ values.extend(node.value.as_ref());
+ stack.extend(node.children.values());
+ }
+ values
+ }
+}
+
+/// `IFileCoverage.Serialized` from `$appendCoverage`.
+#[derive(Clone, Debug, PartialEq)]
+pub struct SerializedFileCoverage {
+ pub id: String,
+ pub uri: CoverageUri,
+ pub test_ids: Option<Vec<String>>,
+ pub statement: CoverageCount,
+ pub branch: Option<CoverageCount>,
+ pub declaration: Option<CoverageCount>,
+}
+
+impl SerializedFileCoverage {
+ pub fn from_value(value: &Value) -> Option<Self> {
+ Some(SerializedFileCoverage {
+ id: value["id"].as_str()?.to_owned(),
+ uri: CoverageUri::from_value(&value["uri"]),
+ test_ids: value["testIds"].as_array().map(|ids| ids.iter().filter_map(Value::as_str).map(str::to_owned).collect()),
+ statement: CoverageCount::from_value(&value["statement"])?,
+ branch: CoverageCount::from_value(&value["branch"]),
+ declaration: CoverageCount::from_value(&value["declaration"]),
+ })
+ }
+}
+
+/// The details of a file for the whole run (`None`) or one test, from `$getCoverageDetails`; `None` while loading.
+pub type DetailsKey = (CoverageUri, Option<String>);
+
+/// testCoverage.ts `TestCoverage`: one task's coverage.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct TestCoverage {
+ pub tree: CoverageNode,
+ pub details: HashMap<DetailsKey, Option<Vec<CoverageDetail>>>,
+ next_id: u64,
+}
+
+impl TestCoverage {
+ /// `allPerTestIDs`: the tests of the top nodes' per-test data, each once.
+ pub fn all_per_test_ids(&self) -> Vec<String> {
+ let mut seen = BTreeSet::new();
+ let mut ids = Vec::new();
+ for root in self.tree.children.values() {
+ for id in root.value.iter().flat_map(|value| &value.per_test) {
+ if seen.insert(id.clone()) {
+ ids.push(id.clone());
+ }
+ }
+ }
+ ids
+ }
+
+ /// `append`: sets the file's node and adds the change of its counts to every folder above it.
+ pub fn append(&mut self, coverage: &SerializedFileCoverage) {
+ let previous = self.computed_for_uri(&coverage.uri).cloned();
+ let canonical = tree_path(&coverage.uri, true);
+ let path = tree_path(&coverage.uri, false);
+ let mut node = &mut self.tree;
+ for (depth, segment) in path.iter().enumerate() {
+ node = node.children.entry(segment.clone()).or_default();
+ if depth + 1 == canonical.len() {
+ match &mut node.value {
+ Some(value) => {
+ value.id = coverage.id.clone();
+ value.statement = coverage.statement;
+ value.branch = coverage.branch;
+ value.declaration = coverage.declaration;
+ }
+ None => {
+ node.value = Some(FileCoverage { kind: CoverageKind::File, id: coverage.id.clone(), uri: coverage.uri.clone(), statement: coverage.statement, branch: coverage.branch, declaration: coverage.declaration, per_test: BTreeSet::new() });
+ }
+ }
+ } else {
+ match &mut node.value {
+ // The folder starts with a copy of the first file's counts.
+ None => {
+ let id = self.next_id.to_string();
+ self.next_id += 1;
+ let uri = tree_path_to_uri(&canonical[..=depth]);
+ node.value = Some(FileCoverage { kind: CoverageKind::Computed, id, uri, statement: coverage.statement, branch: coverage.branch, declaration: coverage.declaration, per_test: BTreeSet::new() });
+ }
+ Some(value) => {
+ let old = previous.as_ref();
+ add_delta(&mut value.statement, Some(coverage.statement), old.map(|old| old.statement));
+ apply_delta(&mut value.branch, coverage.branch, old.and_then(|old| old.branch));
+ apply_delta(&mut value.declaration, coverage.declaration, old.and_then(|old| old.declaration));
+ }
+ }
+ }
+ if let Some(ids) = &coverage.test_ids {
+ node.value.as_mut().expect("set above").per_test.extend(ids.iter().cloned());
+ }
+ }
+ }
+
+ /// `filterTreeForTest`: the paths of the files the test ran code in, without counts.
+ pub fn filter_tree_for_test(&self, test_id: &str) -> CoverageNode {
+ let mut tree = CoverageNode::default();
+ for file in self.tree.values().into_iter().filter(|value| value.kind == CoverageKind::File && value.per_test.contains(test_id)) {
+ let canonical = tree_path(&file.uri, true);
+ let mut node = &mut tree;
+ for (depth, segment) in tree_path(&file.uri, false).iter().enumerate() {
+ node = node.children.entry(segment.clone()).or_default();
+ if node.value.is_none() {
+ let uri = tree_path_to_uri(&canonical[..=depth]);
+ node.value = Some(FileCoverage { kind: CoverageKind::Bypassed, id: String::new(), uri, statement: CoverageCount::default(), branch: None, declaration: None, per_test: BTreeSet::new() });
+ }
+ }
+ }
+ tree
+ }
+
+ /// `getUri`: a file the extension reported.
+ pub fn file(&self, uri: &CoverageUri) -> Option<&FileCoverage> {
+ self.computed_for_uri(uri).filter(|value| value.kind == CoverageKind::File)
+ }
+
+ /// `getComputedForUri`.
+ pub fn computed_for_uri(&self, uri: &CoverageUri) -> Option<&FileCoverage> {
+ let mut node = &self.tree;
+ for segment in tree_path(uri, false) {
+ node = node.children.get(&segment)?;
+ }
+ node.value.as_ref()
+ }
+}
+
+/// `applyDelta`: a missing count takes the file's, a present one adds the change since the file's previous report.
+fn apply_delta(target: &mut Option<CoverageCount>, new: Option<CoverageCount>, old: Option<CoverageCount>) {
+ match target {
+ None => *target = new,
+ Some(count) => add_delta(count, new, old),
+ }
+}
+
+fn add_delta(count: &mut CoverageCount, new: Option<CoverageCount>, old: Option<CoverageCount>) {
+ let (new, old) = (new.unwrap_or_default(), old.unwrap_or_default());
+ count.covered = (count.covered + new.covered).saturating_sub(old.covered);
+ count.total = (count.total + new.total).saturating_sub(old.total);
+}
+
+/// `treePathForUri`: scheme, authority and the path's segments; the non-canonical path is lower case where the
+/// file system ignores case (`extUri.ignorePathCasing`, the macOS `file` scheme).
+fn tree_path(uri: &CoverageUri, canonical: bool) -> Vec<String> {
+ let path = if !canonical && uri.scheme == "file" && cfg!(target_os = "macos") { uri.path.to_lowercase() } else { uri.path.clone() };
+ let mut segments = vec![uri.scheme.clone(), uri.authority.clone()];
+ segments.extend(path.split('/').map(str::to_owned));
+ segments
+}
+
+fn tree_path_to_uri(path: &[String]) -> CoverageUri {
+ CoverageUri { scheme: path[0].clone(), authority: path.get(1).cloned().unwrap_or_default(), path: path.get(2..).map(|rest| rest.join("/")).unwrap_or_default() }
+}
+
+/// configuration.ts `TestingDisplayedCoveragePercent`, the `testing.displayedCoveragePercent` values.
+pub fn displayed_stat(file: &FileCoverage, method: &str) -> f64 {
+ match method {
+ "statement" => file.statement.percent(),
+ "minimum" => {
+ let mut value = file.statement.percent();
+ for count in [file.branch, file.declaration].into_iter().flatten() {
+ value = value.min(count.percent());
+ }
+ value
+ }
+ _ => file.total_percent(),
+ }
+}
+
+/// codeCoverageDisplayUtils.ts `displayPercent`: at precision 0, less than all shows 99%, not a rounded-up 100%.
+pub fn display_percent(value: f64, precision: usize) -> String {
+ let display = format!("{:.precision$}", value * 100.);
+ if value < 1. - 10e-8 && display == "100" {
+ return format!("{}%", 100. - 10f64.powi(-(precision as i32)));
+ }
+ format!("{display}%")
+}
+
+/// `getCoverageColor`: the closest `testing.coverageBarThresholds` threshold at or below the percent, red without one.
+pub fn coverage_color(percent: f64, thresholds: &Value) -> &'static str {
+ let mut best = "charts.red";
+ let mut distance = percent;
+ for (key, color) in [("red", "charts.red"), ("yellow", "charts.yellow"), ("green", "charts.green")] {
+ let threshold = thresholds[key].as_f64().unwrap_or(0.) / 100.;
+ if threshold != 0. && percent >= threshold && percent - threshold < distance {
+ best = color;
+ distance = percent - threshold;
+ }
+ }
+ best
+}
+
+/// A 1-based `IPosition`.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
+pub struct CoveragePosition {
+ pub line: u32,
+ pub column: u32,
+}
+
+/// An `IRange`, its ends in order as range.ts's constructor puts them.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct CoverageRange {
+ pub start: CoveragePosition,
+ pub end: CoveragePosition,
+}
+
+impl CoverageRange {
+ pub fn new(a: CoveragePosition, b: CoveragePosition) -> Self {
+ if a <= b { CoverageRange { start: a, end: b } } else { CoverageRange { start: b, end: a } }
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.start == self.end
+ }
+
+ pub fn contains(&self, position: CoveragePosition) -> bool {
+ self.start <= position && position <= self.end
+ }
+
+ /// `IRange` or `IPosition` from the wire; a position is codeCoverageDecorations.ts `tidyLocation`'s rest of its line.
+ fn from_location(value: &Value) -> Option<Self> {
+ let number = |key: &str| value[key].as_u64().map(|number| number as u32);
+ if let Some(line) = number("lineNumber") {
+ let start = CoveragePosition { line, column: number("column")? };
+ return Some(CoverageRange::new(start, CoveragePosition { line, column: 0x7FFF_FFFF }));
+ }
+ let start = CoveragePosition { line: number("startLineNumber")?, column: number("startColumn")? };
+ Some(CoverageRange::new(start, CoveragePosition { line: number("endLineNumber")?, column: number("endColumn")? }))
+ }
+}
+
+/// A detail's `count`: how often it ran, or whether.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum HitCount {
+ Times(u64),
+ Ran(bool),
+}
+
+impl HitCount {
+ fn from_value(value: &Value) -> Self {
+ match value {
+ Value::Bool(ran) => HitCount::Ran(*ran),
+ count => HitCount::Times(count.as_u64().unwrap_or(0)),
+ }
+ }
+
+ pub fn is_hit(self) -> bool {
+ self != HitCount::Times(0) && self != HitCount::Ran(false)
+ }
+}
+
+/// `IBranchCoverage`.
+#[derive(Clone, Debug, PartialEq)]
+pub struct BranchCoverage {
+ pub count: HitCount,
+ pub label: Option<String>,
+ pub location: Option<CoverageRange>,
+}
+
+/// testTypes.ts `DetailType`, the tie order of the details model.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
+pub enum DetailType {
+ Declaration,
+ Statement,
+ Branch,
+}
+
+/// `CoverageDetails.Serialized`: an `IDeclarationCoverage` (with a name) or an `IStatementCoverage`.
+#[derive(Clone, Debug, PartialEq)]
+pub struct CoverageDetail {
+ pub kind: DetailType,
+ pub name: String,
+ pub count: HitCount,
+ pub location: CoverageRange,
+ pub branches: Vec<BranchCoverage>,
+}
+
+impl CoverageDetail {
+ pub fn from_value(value: &Value) -> Option<Self> {
+ let kind = if value["type"].as_u64()? == 0 { DetailType::Declaration } else { DetailType::Statement };
+ let branches = value["branches"].as_array().into_iter().flatten().map(|branch| BranchCoverage {
+ count: HitCount::from_value(&branch["count"]),
+ label: branch["label"].as_str().map(str::to_owned),
+ location: CoverageRange::from_location(&branch["location"]),
+ });
+ Some(CoverageDetail { kind, name: value["name"].as_str().unwrap_or_default().to_owned(), count: HitCount::from_value(&value["count"]), location: CoverageRange::from_location(&value["location"])?, branches: branches.collect() })
+ }
+}
+
+/// codeCoverageDecorations.ts `DetailRange`: a detail (`branch` set for one of a statement's branches) over a range
+/// no other range overlaps; `primary` on the range's first piece.
+#[derive(Clone, Debug, PartialEq)]
+pub struct DetailRange {
+ pub range: CoverageRange,
+ pub primary: bool,
+ pub detail: usize,
+ pub branch: Option<usize>,
+}
+
+impl DetailRange {
+ pub fn kind(&self) -> DetailType {
+ if self.branch.is_some() { DetailType::Branch } else { DetailType::Statement }
+ }
+}
+
+/// `CoverageDetailsModel`'s ranges: nested details split into sequential, non-overlapping ranges.
+pub fn detail_ranges(details: &[CoverageDetail]) -> Vec<DetailRange> {
+ let mut ranges: Vec<(DetailRange, DetailType)> = details.iter().enumerate().map(|(index, detail)| (DetailRange { range: detail.location, primary: true, detail: index, branch: None }, detail.kind)).collect();
+ for (index, detail) in details.iter().enumerate() {
+ if detail.kind != DetailType::Statement {
+ continue;
+ }
+ for (branch, coverage) in detail.branches.iter().enumerate() {
+ let end = detail.location.end;
+ let range = coverage.location.unwrap_or(CoverageRange::new(end, end));
+ ranges.push((DetailRange { range, primary: true, detail: index, branch: Some(branch) }, DetailType::Branch));
+ }
+ }
+ // Declarations first on a tie, so single-statement functions (`() => foo()`) get inline decorations.
+ ranges.sort_by(|(a, a_kind), (b, b_kind)| (a.range.start, a.range.end, a_kind).cmp(&(b.range.start, b.range.end, b_kind)));
+ let mut stack: Vec<DetailRange> = Vec::new();
+ let mut result = Vec::new();
+ let pop = |stack: &mut Vec<DetailRange>, result: &mut Vec<DetailRange>| {
+ let next = stack.pop().expect("popped while not empty");
+ if let Some(previous) = stack.last_mut() {
+ previous.range = CoverageRange::new(next.range.end, previous.range.end);
+ }
+ result.push(next);
+ };
+ for (item, _) in ranges {
+ let start = item.range.start;
+ while stack.last().is_some_and(|top| !top.range.contains(start)) {
+ pop(&mut stack, &mut result);
+ }
+ if item.range.is_empty() {
+ result.push(item);
+ continue;
+ }
+ if let Some(previous) = stack.last_mut() {
+ let primary = previous.primary;
+ let before = CoverageRange::new(previous.range.start, start);
+ previous.range = CoverageRange::new(item.range.end, previous.range.end);
+ previous.primary = false;
+ let piece = DetailRange { range: before, primary, detail: previous.detail, branch: previous.branch };
+ if previous.range.is_empty() {
+ stack.pop();
+ }
+ result.push(piece);
+ }
+ stack.push(item);
+ }
+ while !stack.is_empty() {
+ pop(&mut stack, &mut result);
+ }
+ result
+}
diff --git a/native/crates/app/src/testing_coverage/tests.rs b/native/crates/app/src/testing_coverage/tests.rs
new file mode 100644
index 00000000000..0804c9911be
--- /dev/null
+++ b/native/crates/app/src/testing_coverage/tests.rs
@@ -0,0 +1,152 @@
+//! testCoverage.test.ts and codeCoverageDecorations.test.ts.
+
+use serde_json::json;
+
+use super::*;
+
+fn count(covered: u64, total: u64) -> CoverageCount {
+ CoverageCount { covered, total }
+}
+
+fn file(path: &str, statement: CoverageCount, branch: Option<CoverageCount>, declaration: Option<CoverageCount>) -> SerializedFileCoverage {
+ SerializedFileCoverage { id: "1".into(), uri: CoverageUri::file(path), test_ids: None, statement, branch, declaration }
+}
+
+fn add_tests(coverage: &mut TestCoverage) -> (SerializedFileCoverage, SerializedFileCoverage) {
+ let raw1 = file("/path/to/file", count(10, 20), Some(count(5, 10)), Some(count(2, 5)));
+ coverage.append(&raw1);
+ let raw2 = file("/path/to/file2", count(5, 10), Some(count(1, 5)), None);
+ coverage.append(&raw2);
+ (raw1, raw2)
+}
+
+#[test]
+fn looks_up_file_coverage() {
+ let mut coverage = TestCoverage::default();
+ let (raw1, _) = add_tests(&mut coverage);
+ let file = coverage.file(&raw1.uri).expect("the file's coverage");
+ assert_eq!((file.id.as_str(), file.statement, file.branch, file.declaration), ("1", raw1.statement, raw1.branch, raw1.declaration));
+ assert_eq!(coverage.computed_for_uri(&raw1.uri), Some(file));
+ assert_eq!(coverage.computed_for_uri(&CoverageUri::file("/path/to/x")), None);
+ assert_eq!(coverage.file(&CoverageUri::file("/path/to/x")), None);
+}
+
+#[test]
+fn computes_coverage_for_directories() {
+ let mut coverage = TestCoverage::default();
+ let (raw1, _) = add_tests(&mut coverage);
+ let folder = coverage.computed_for_uri(&CoverageUri::file("/path/to")).expect("the folder's coverage");
+ assert_eq!((folder.kind, folder.statement, folder.branch, folder.declaration), (CoverageKind::Computed, count(15, 30), Some(count(6, 15)), raw1.declaration));
+ assert_eq!(coverage.file(&CoverageUri::file("/path/to")), None, "a folder is not a reported file");
+}
+
+#[test]
+fn incrementally_diffs_updates_to_existing_files() {
+ let mut coverage = TestCoverage::default();
+ add_tests(&mut coverage);
+ let raw3 = file("/path/to/file", count(12, 24), Some(count(7, 10)), Some(count(2, 5)));
+ coverage.append(&raw3);
+ let file = coverage.file(&raw3.uri).expect("the file's coverage");
+ assert_eq!((file.statement, file.branch, file.declaration), (raw3.statement, raw3.branch, raw3.declaration));
+ let folder = coverage.computed_for_uri(&CoverageUri::file("/path/to")).expect("the folder's coverage");
+ assert_eq!((folder.statement, folder.branch, folder.declaration), (count(17, 34), Some(count(8, 15)), raw3.declaration));
+}
+
+#[test]
+fn folder_uris_are_the_canonical_path_prefixes() {
+ let mut coverage = TestCoverage::default();
+ add_tests(&mut coverage);
+ let mut uris: Vec<String> = coverage.tree.values().iter().map(|value| value.uri.to_uri_string()).collect();
+ uris.sort();
+ assert_eq!(uris, ["file://", "file://", "file://", "file:///path", "file:///path/to", "file:///path/to/file", "file:///path/to/file2"]);
+}
+
+#[test]
+fn per_test_ids_and_the_tree_filtered_to_a_test() {
+ let mut coverage = TestCoverage::default();
+ let mut a = file("/src/a.js", count(1, 2), None, None);
+ a.test_ids = Some(vec!["ctrl\0one".into()]);
+ let mut b = file("/src/lib/b.js", count(1, 1), None, None);
+ b.test_ids = Some(vec!["ctrl\0two".into(), "ctrl\0one".into()]);
+ coverage.append(&a);
+ coverage.append(&b);
+ assert_eq!(coverage.all_per_test_ids(), ["ctrl\0one", "ctrl\0two"]);
+ let filtered = coverage.filter_tree_for_test("ctrl\0two");
+ let paths: Vec<String> = filtered.values().iter().filter(|value| value.kind == CoverageKind::Bypassed).map(|value| value.uri.path.clone()).filter(|path| path.ends_with(".js")).collect();
+ assert_eq!(paths, ["/src/lib/b.js"], "only the files the test ran code in");
+}
+
+fn range(start: (u32, u32), end: (u32, u32)) -> Value {
+ json!({ "startLineNumber": start.0, "startColumn": start.1, "endLineNumber": end.0, "endColumn": end.1 })
+}
+
+fn statement(location: Value, count: u64) -> Value {
+ json!({ "type": 1, "location": location, "count": count })
+}
+
+/// The snapshot of `assertRanges`: each range and its count.
+fn ranges(details: Vec<Value>) -> Vec<String> {
+ let details: Vec<CoverageDetail> = details.iter().map(|detail| CoverageDetail::from_value(detail).expect("a detail")).collect();
+ detail_ranges(&details)
+ .iter()
+ .map(|piece| {
+ let detail = &details[piece.detail];
+ let count = match piece.branch {
+ Some(branch) => detail.branches[branch].count,
+ None => detail.count,
+ };
+ let HitCount::Times(count) = count else { panic!("a numeric count") };
+ format!("[{},{} -> {},{}] {count}", piece.range.start.line, piece.range.start.column, piece.range.end.line, piece.range.end.column)
+ })
+ .collect()
+}
+
+#[test]
+fn coverage_details_model_1() {
+ let mut branchy = statement(range((4, 0), (6, 0)), 4);
+ branchy["branches"] = json!([{ "location": range((3, 0), (7, 0)), "count": 3 }]);
+ let details = vec![statement(range((1, 0), (5, 0)), 1), statement(range((2, 0), (3, 0)), 2), branchy];
+ assert_eq!(ranges(details), ["[1,0 -> 2,0] 1", "[2,0 -> 3,0] 2", "[3,0 -> 4,0] 3", "[4,0 -> 6,0] 4", "[6,0 -> 7,0] 3", "[7,0 -> 7,0] 2", "[5,0 -> 7,0] 1"]);
+}
+
+#[test]
+fn coverage_details_model_2() {
+ let details = vec![statement(range((1, 0), (5, 0)), 1), statement(range((2, 0), (4, 0)), 2), statement(range((3, 0), (3, 5)), 3)];
+ assert_eq!(ranges(details), ["[1,0 -> 2,0] 1", "[2,0 -> 3,0] 2", "[3,0 -> 3,5] 3", "[3,5 -> 4,0] 2", "[4,0 -> 5,0] 1"]);
+}
+
+#[test]
+fn coverage_details_model_3() {
+ let details = vec![statement(range((1, 0), (5, 0)), 1), statement(range((2, 0), (3, 0)), 2), statement(range((4, 0), (5, 0)), 3)];
+ assert_eq!(ranges(details), ["[1,0 -> 2,0] 1", "[2,0 -> 3,0] 2", "[3,0 -> 4,0] 1", "[4,0 -> 5,0] 3"]);
+}
+
+#[test]
+fn coverage_details_model_4() {
+ let position = |line: u32, column: u32| json!({ "lineNumber": line, "column": column });
+ let details = vec![statement(range((1, 0), (5, 0)), 1), statement(position(2, 0), 2), statement(range((4, 0), (5, 0)), 3), statement(position(4, 3), 4)];
+ assert_eq!(ranges(details), ["[1,0 -> 2,0] 1", "[2,0 -> 2,2147483647] 2", "[2,2147483647 -> 4,0] 1", "[4,0 -> 4,3] 3", "[4,3 -> 4,2147483647] 4", "[4,2147483647 -> 5,0] 3"]);
+}
+
+#[test]
+fn has_inline_coverage_details() {
+ assert!(!detail_ranges(&[CoverageDetail::from_value(&statement(range((1, 0), (2, 0)), 1)).unwrap()]).is_empty());
+ assert!(detail_ranges(&[]).is_empty());
+}
+
+#[test]
+fn display_percent_keeps_a_rounded_up_whole_percent_below_100() {
+ assert_eq!(display_percent(0.5, 2), "50.00%");
+ // Upstream compares the display with "100", so only precision 0 is kept below it.
+ assert_eq!(display_percent(0.99999, 2), "100.00%");
+ assert_eq!(display_percent(0.996, 0), "99%");
+ assert_eq!(display_percent(1., 0), "100%");
+}
+
+#[test]
+fn coverage_color_takes_the_closest_threshold_below() {
+ let thresholds = json!({ "red": 0, "yellow": 60, "green": 90 });
+ assert_eq!(coverage_color(0.3, &thresholds), "charts.red");
+ assert_eq!(coverage_color(0.6, &thresholds), "charts.yellow");
+ assert_eq!(coverage_color(0.95, &thresholds), "charts.green");
+}
diff --git a/native/crates/app/src/theme.rs b/native/crates/app/src/theme.rs
index 1260651c2f7..2a24dadd458 100644
--- a/native/crates/app/src/theme.rs
+++ b/native/crates/app/src/theme.rs
@@ -374,7 +374,7 @@ impl Theme {
ColorValue::None => None,
ColorValue::Hex(hex) => Some(parse_hex(hex).expect("registry hex")),
ColorValue::Key(key) => self.resolve(key),
- ColorValue::Transparent(inner, factor) => self.evaluate(inner).map(|color| Rgba { a: color.a * factor, ..color }),
+ ColorValue::Transparent(inner, factor) => self.evaluate(inner).map(|color| Rgba { a: (color.a * factor).min(1.), ..color }),
ColorValue::Opacity(inner, opacity) => self.evaluate(inner).map(|color| Rgba { a: *opacity, ..color }),
ColorValue::Darken(inner, factor) => self.evaluate(inner).map(|color| darken(color, *factor)),
ColorValue::Lighten(inner, factor) => self.evaluate(inner).map(|color| lighten(color, *factor)),
diff --git a/native/crates/app/src/theme/debug_colors.rs b/native/crates/app/src/theme/debug_colors.rs
index 2bae1ce4101..33384586175 100644
--- a/native/crates/app/src/theme/debug_colors.rs
+++ b/native/crates/app/src/theme/debug_colors.rs
@@ -43,6 +43,15 @@ pub(super) fn debug_default(key: &str) -> Option<[ColorValue; 4]> {
}
"statusBar.debuggingForeground" => [Key("statusBar.foreground"), Key("statusBar.foreground"), Key("statusBar.foreground"), Hex("#FFFFFF")],
"testing.iconFailed" | "testing.iconErrored" => [Key("list.errorForeground"), Key("list.errorForeground"), Key("list.errorForeground"), Key("list.errorForeground")],
+ // testing/browser/theme.ts: the gutter of codeCoverageDecorations.ts.
+ "testing.coveredGutterBackground" => {
+ const COVERED: ColorValue = Transparent(&Key("diffEditor.insertedTextBackground"), 0.6);
+ [COVERED, COVERED, Key("charts.green"), Key("charts.green")]
+ }
+ "testing.uncoveredGutterBackground" => {
+ const UNCOVERED: ColorValue = Transparent(&Key("diffEditor.removedTextBackground"), 1.5);
+ [UNCOVERED, UNCOVERED, Key("charts.red"), Key("charts.red")]
+ }
"testing.iconPassed" | "testing.runAction" => [Hex("#73c991"), Hex("#73c991"), Hex("#73c991"), Hex("#007100")],
"testing.iconQueued" => [Key("list.warningForeground"), Key("list.warningForeground"), Key("list.warningForeground"), Key("list.warningForeground")],
"testing.iconUnset" | "testing.iconSkipped" => [Hex("#848484"), Hex("#848484"), Hex("#848484"), Hex("#848484")],
diff --git a/native/crates/app/src/workbench.rs b/native/crates/app/src/workbench.rs
index d8bfc5f02c7..d509baea658 100644
--- a/native/crates/app/src/workbench.rs
+++ b/native/crates/app/src/workbench.rs
@@ -46,6 +46,7 @@ mod testing_continuous;
mod testing_filter;
mod testing_gutter;
mod testing_peek;
+mod testing_coverage_view;
mod testing_results;
mod testing_item_menu;
mod testing_profiles;
@@ -1788,8 +1789,8 @@ impl Workbench {
return self.debug_side_bar(window, cx);
}
if self.side_bar_view == SideBarView::Testing {
- let testing = self.testing_view_pane(window, cx);
- return self.view_pane_container(view_panes::PaneContainer::Contributed(view_locations::TESTING_CONTAINER), "Testing", vec![testing], window, cx).child(div().h(px(5.)).flex_none());
+ let testing = vec![self.testing_view_pane(window, cx), self.test_coverage_view_pane(cx)];
+ return self.view_pane_container(view_panes::PaneContainer::Contributed(view_locations::TESTING_CONTAINER), "Testing", testing, window, cx).child(div().h(px(5.)).flex_none());
}
self.explorer_view_container(window, cx)
// The pane view is laid out 5px shorter than the side bar content.
diff --git a/native/crates/app/src/workbench/editor_view.rs b/native/crates/app/src/workbench/editor_view.rs
index 8de4a58efd5..6046cb3cafe 100644
--- a/native/crates/app/src/workbench/editor_view.rs
+++ b/native/crates/app/src/workbench/editor_view.rs
@@ -1903,6 +1903,7 @@ impl Workbench {
let edit_setting_line = settings_file.then(|| self.edit_setting_line(editor)).flatten();
let fold_control_color = self.color("editorGutter.foldingControlForeground");
let fold_background = self.color("editor.foldBackground");
+ let coverage = self.coverage_lines(&editor.document().uri(), editor.document().lines.len(), cx);
let fold_placeholder = self.color("editor.foldPlaceholderForeground");
let rounded_selection = self.setting("editor.roundedSelection") != json!(false);
let render_whitespace = self.setting("editor.renderWhitespace");
@@ -1954,6 +1955,8 @@ impl Workbench {
.text_color(if index == primary_line { colors.active_number } else { colors.number })
// lineNumbers.css `.relative-current-line-number`: the cursor's line number aligns left.
.when(metrics.line_numbers == LineNumbers::Relative && index == primary_line, |number| number.text_left())
+ // testing.css `.coverage-deco-gutter::before`: the fill sits under the number.
+ .when_some(coverage.get(&index).and_then(|line| self.coverage_gutter(*line)), |number, gutter| number.relative().child(gutter))
.children(line_number_label(metrics.line_numbers, index, primary_line, editor.document().lines.len()).filter(|_| segment.first));
let mut current_line = div().absolute().inset_0();
if line_highlight && all_empty && (0..selections.len()).any(|cursor_index| editor.head_view_line(cursor_index) == view_line) {
diff --git a/native/crates/app/src/workbench/editor_view/quick_diff.rs b/native/crates/app/src/workbench/editor_view/quick_diff.rs
index 717fb2b92e8..2051f4c3511 100644
--- a/native/crates/app/src/workbench/editor_view/quick_diff.rs
+++ b/native/crates/app/src/workbench/editor_view/quick_diff.rs
@@ -679,7 +679,7 @@ fn deleted_triangle(color: Rgba) -> Div {
/// `.dirty-diff-*.pattern`: a `width` square tile of a 45 degree `linear-gradient` (-45deg for a primary quick diff),
/// the color on its first and third quarters and the gutter background between, repeated down the line.
-fn stripes(color: Rgba, background: Rgba, width: f32, primary: bool) -> impl IntoElement {
+pub(in crate::workbench) fn stripes(color: Rgba, background: Rgba, width: f32, primary: bool) -> impl IntoElement {
canvas(
|_, _, _| (),
move |bounds, _, window, _| {
diff --git a/native/crates/app/src/workbench/panel.rs b/native/crates/app/src/workbench/panel.rs
index 0125b2d7def..b39e9f91f6e 100644
--- a/native/crates/app/src/workbench/panel.rs
+++ b/native/crates/app/src/workbench/panel.rs
@@ -509,6 +509,10 @@ impl Workbench {
if container == super::view_locations::TESTING_CONTAINER && !self.testing.controllers.is_empty() {
views.insert(0, super::testing_view::TESTING_VIEW);
}
+ if container == super::view_locations::TESTING_CONTAINER && self.selected_coverage().is_some() {
+ let after_explorer = usize::from(views.first() == Some(&super::testing_view::TESTING_VIEW));
+ views.insert(after_explorer, super::testing_coverage_view::TEST_COVERAGE_VIEW);
+ }
if let [view] = views[..] {
let pane = self.movable_view_pane(view, window, cx);
return (pane.body, pane.actions);
diff --git a/native/crates/app/src/workbench/testing_coverage_view.rs b/native/crates/app/src/workbench/testing_coverage_view.rs
new file mode 100644
index 00000000000..124db15aef3
--- /dev/null
+++ b/native/crates/app/src/workbench/testing_coverage_view.rs
@@ -0,0 +1,488 @@
+//! Test coverage in the workbench: testCoverageService.ts (the opened coverage and its test filter),
+//! testCoverageView.ts with testCoverageBars.ts (the Test Coverage view), the gutter of codeCoverageDecorations.ts and
+//! mainThreadTesting.ts `$appendCoverage`.
+
+use std::collections::{HashMap, HashSet};
+
+use gpui::{ClickEvent, Context, Div, InteractiveElement, IntoElement, ParentElement, Rgba, StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder, px};
+use serde_json::{Value, json};
+
+use super::Workbench;
+use crate::commands::Outcome;
+use crate::main_thread_quick_open::Owner;
+use crate::quick_input::{Entry, Item, Kind, QuickInput};
+use crate::testing::{RunTask, TestResult, parent_id};
+use crate::testing_coverage::{CoverageNode, CoverageUri, DetailType, FileCoverage, SerializedFileCoverage, TestCoverage, coverage_color, detail_ranges, display_percent, displayed_stat};
+
+#[cfg(test)]
+mod tests;
+
+/// constants.ts `Testing.CoverageViewId`.
+pub(super) const TEST_COVERAGE_VIEW: &str = "workbench.view.testCoverage";
+const ROW_HEIGHT: f32 = 22.;
+
+/// `ITestCoverageService` with the Test Coverage view's tree state.
+#[derive(Default)]
+pub struct CoverageService {
+ /// `selected`: the opened coverage's result id and `fromTaskId`.
+ pub selected: Option<(String, String)>,
+ /// `filterToTest`.
+ pub filter_to_test: Option<String>,
+ /// The view's `CoverageSortOrder`, stored as `testing.coverageSortOrder`.
+ pub sort_order: SortOrder,
+ /// The view's rows flipped from their default collapse state, and its selected row, by URI.
+ pub toggled: HashSet<String>,
+ pub selected_row: Option<String>,
+}
+
+/// testCoverageView.ts `CoverageSortOrder`.
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub enum SortOrder {
+ Coverage,
+ #[default]
+ Location,
+ Name,
+}
+
+/// A drawn row of the Test Coverage view: `CurrentlyFilteredTo`, or a file or folder node, folders with one folder
+/// child compressed into one row as `WorkbenchCompressibleObjectTree` does.
+#[derive(Clone, Debug, PartialEq)]
+pub struct CoverageRow {
+ pub label: String,
+ pub file: Option<FileCoverage>,
+ pub depth: usize,
+ pub folder: bool,
+ pub collapsed: bool,
+}
+
+/// codeCoverageDecorations.ts `CLASS_HIT` and `CLASS_MISS` of a line's `lineNumberClassName`s.
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct LineCoverage {
+ pub hit: bool,
+ pub miss: bool,
+}
+
+impl Workbench {
+ pub(super) fn register_testing_coverage_commands(&mut self) {
+ self.commands.register("testing.coverage.close", |workbench, _, _, cx| {
+ workbench.testing.coverage.selected = None;
+ cx.notify();
+ Outcome::done()
+ });
+ self.commands.register("testing.openCoverage", |workbench, _, _, cx| {
+ let task = workbench.testing.results.first().and_then(|result| result.tasks.iter().position(|task| task.coverage.is_some()).map(|task| (result.id.clone(), task)));
+ match task {
+ Some((result, task)) => workbench.open_coverage(&result, task, true, cx),
+ None => drop(workbench.notify(crate::notifications::Notification::new(crate::notifications::Severity::Info, "No coverage information available on the last test run."))),
+ }
+ cx.notify();
+ Outcome::done()
+ });
+ self.commands.register("testing.coverageFilterToTest", |workbench, _, window, cx| {
+ workbench.pick_coverage_test(window, cx);
+ Outcome::done()
+ });
+ self.commands.register("testing.coverageViewChangeSorting", |workbench, _, window, cx| {
+ workbench.pick_coverage_sort_order(window, cx);
+ Outcome::done()
+ });
+ self.commands.register("testing.coverageViewCollapseAll", |workbench, _, _, cx| {
+ let folders: Vec<String> = workbench.coverage_rows().into_iter().filter(|row| row.folder && !row.collapsed).filter_map(|row| row.file.map(|file| file.uri.to_uri_string())).collect();
+ for id in folders {
+ workbench.toggle_coverage_row(&id);
+ }
+ cx.notify();
+ Outcome::done()
+ });
+ }
+
+ /// mainThreadTesting.ts `$appendCoverage`: the task's coverage, made by its first report.
+ pub(super) fn append_coverage(&mut self, run: &str, task_id: &str, coverage: &Value, cx: &mut Context<Self>) {
+ let Some(file) = SerializedFileCoverage::from_value(coverage) else { return };
+ let Some(result) = self.testing.result_mut(run) else { return };
+ let completed = result.completed_at.is_some();
+ let Some(task) = result.tasks.iter_mut().find(|task| task.id == task_id) else { return };
+ let first = task.coverage.is_none();
+ task.coverage.get_or_insert_with(TestCoverage::default).append(&file);
+ // The `$runControllerTests` reply can complete the run before this queued report reaches the workbench.
+ if completed && first && self.testing.coverage.selected.is_none() {
+ self.coverage_result_completed(run, cx);
+ }
+ }
+
+ /// `selected`, gone with its result (testCoverageService.ts closes it on `removed`).
+ pub(super) fn selected_coverage(&self) -> Option<(&TestResult, &RunTask, &TestCoverage)> {
+ let (result_id, task_id) = self.testing.coverage.selected.as_ref()?;
+ let result = self.testing.results.iter().find(|result| &result.id == result_id)?;
+ let task = result.tasks.iter().find(|task| &task.id == task_id)?;
+ Some((result, task, task.coverage.as_ref()?))
+ }
+
+ /// `openCoverage`: the task's coverage unfiltered, and the Test Coverage view with `focus`.
+ pub(super) fn open_coverage(&mut self, result: &str, task: usize, focus: bool, cx: &mut Context<Self>) {
+ let Some(result) = self.testing.results.iter().find(|candidate| candidate.id == result) else { return };
+ if result.tasks[task].coverage.is_none() {
+ return;
+ }
+ self.testing.coverage.selected = Some((result.id.clone(), result.tasks[task].id.clone()));
+ self.testing.coverage.filter_to_test = None;
+ if focus {
+ self.show_view_container(super::view_locations::TESTING_CONTAINER, cx);
+ }
+ }
+
+ /// `onResultsChanged` with `completed`: the first task with coverage opens without focus, else coverage closes.
+ pub(super) fn coverage_result_completed(&mut self, run: &str, cx: &mut Context<Self>) {
+ let task = self.testing.results.iter().find(|result| result.id == run).and_then(|result| result.tasks.iter().position(|task| task.coverage.is_some()));
+ match task {
+ Some(task) => self.open_coverage(run, task, false, cx),
+ None => self.testing.coverage.selected = None,
+ }
+ }
+
+ /// The service's and codeCoverageDecorations.ts's testingContextKeys.ts keys.
+ pub(super) fn testing_coverage_context(&self, context: &mut HashMap<String, Value>) {
+ let selected = self.selected_coverage();
+ let file = self.editors.active().and_then(|editor| self.file_coverage(&editor.document().uri()));
+ let per_test = match &file {
+ Some(file) => !file.per_test.is_empty(),
+ None => selected.is_some_and(|(_, _, coverage)| !coverage.all_per_test_ids().is_empty()),
+ };
+ for (key, value) in [
+ ("testing.isTestCoverageOpen", selected.is_some()),
+ ("testing.hasPerTestCoverage", per_test),
+ ("testing.isCoverageFilteredToTest", self.testing.coverage.filter_to_test.is_some()),
+ ("testing.hasCoverageInFile", file.is_some()),
+ ("testing.inlineCoverageEnabled", false),
+ ("testing.coverageToolbarEnabled", self.setting("testing.coverageToolbarEnabled") != false),
+ ] {
+ context.insert(key.to_owned(), json!(value));
+ }
+ }
+
+ /// `report.getUri` of the opened coverage for an editor's document URI.
+ fn file_coverage(&self, uri: &Value) -> Option<FileCoverage> {
+ let (_, _, coverage) = self.selected_coverage()?;
+ coverage.file(&CoverageUri::from_value(uri)).cloned()
+ }
+
+ /// `TestCoverageChangePerTestFilterAction`: "Entire run", then each test with per-test data.
+ fn pick_coverage_test(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ let Some((result, _, coverage)) = self.selected_coverage() else { return };
+ let tests = coverage.all_per_test_ids();
+ let common_prefix = common_prefix_length(&tests);
+ let mut entries = vec![Entry::Item(Item { handle: 0, label: "Entire run".into(), ..Item::default() }), Entry::Separator(None)];
+ for (index, test) in tests.iter().enumerate() {
+ let (label, description) = label_for_item(result, test, common_prefix);
+ entries.push(Entry::Item(Item { handle: index as i64 + 1, label, description, ..Item::default() }));
+ }
+ let previous = self.testing.coverage.filter_to_test.as_ref().and_then(|test| tests.iter().position(|id| id == test)).map(|index| index as i64 + 1);
+ let (sender, receiver) = futures::channel::oneshot::channel();
+ let mut input = QuickInput::new(0, Kind::QuickPick);
+ input.placeholder = Some("Pick a test to show coverage for".into());
+ input.set_items(entries);
+ input.set_active_items(&previous.into_iter().collect::<Vec<_>>());
+ let id = self.quick_inputs.add(input, Owner::Debug(Some(sender)));
+ self.show_quick_input(id, window, cx);
+ self.flush_quick_input_events(window, cx);
+ cx.spawn(async move |this, cx| {
+ let Some(handle) = receiver.await.ok().flatten().and_then(|handle| handle.parse::<usize>().ok()) else { return };
+ let _ = this.update(cx, |workbench, cx| {
+ workbench.testing.coverage.filter_to_test = handle.checked_sub(1).map(|index| tests[index].clone());
+ cx.notify();
+ });
+ })
+ .detach();
+ }
+
+ /// `TestCoverageChangeSortingAction`.
+ fn pick_coverage_sort_order(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ let orders = [
+ (SortOrder::Location, "Sort by Location", "Files are sorted alphabetically, declarations are sorted by position"),
+ (SortOrder::Coverage, "Sort by Coverage", "Files and declarations are sorted by total coverage"),
+ (SortOrder::Name, "Sort by Name", "Files and declarations are sorted alphabetically"),
+ ];
+ let entries = orders.iter().enumerate().map(|(handle, (_, label, description))| Entry::Item(Item { handle: handle as i64, label: (*label).into(), description: Some((*description).into()), ..Item::default() })).collect();
+ let (sender, receiver) = futures::channel::oneshot::channel();
+ let mut input = QuickInput::new(0, Kind::QuickPick);
+ input.placeholder = Some("Sort the Test Coverage view...".into());
+ input.set_items(entries);
+ let id = self.quick_inputs.add(input, Owner::Debug(Some(sender)));
+ self.show_quick_input(id, window, cx);
+ self.flush_quick_input_events(window, cx);
+ cx.spawn(async move |this, cx| {
+ let Some(handle) = receiver.await.ok().flatten().and_then(|handle| handle.parse::<usize>().ok()) else { return };
+ let _ = this.update(cx, |workbench, cx| {
+ workbench.testing.coverage.sort_order = orders[handle].0;
+ cx.notify();
+ });
+ })
+ .detach();
+ }
+
+ fn toggle_coverage_row(&mut self, id: &str) {
+ let toggled = &mut self.testing.coverage.toggled;
+ if !toggled.remove(id) {
+ toggled.insert(id.to_owned());
+ }
+ }
+
+ /// `TestCoverageTree.setInput`: `CurrentlyFilteredTo`, then from each top node the first file or node with
+ /// several children, folders expanded and files collapsed.
+ pub(super) fn coverage_rows(&self) -> Vec<CoverageRow> {
+ let Some((result, _, coverage)) = self.selected_coverage() else { return Vec::new() };
+ let filtered;
+ let mut tree = &coverage.tree;
+ let mut rows = Vec::new();
+ if let Some(test) = &self.testing.coverage.filter_to_test {
+ filtered = coverage.filter_tree_for_test(test);
+ tree = &filtered;
+ if let Some(item) = result.items.get(test) {
+ rows.push(CoverageRow { label: format!("Showing coverage for \"{}\"", item.label()), file: None, depth: 0, folder: false, collapsed: false });
+ }
+ }
+ let mut tops = Vec::new();
+ for mut node in tree.children.values() {
+ while node.value.as_ref().is_none_or(|value| value.kind != crate::testing_coverage::CoverageKind::File) && node.children.len() == 1 {
+ node = node.children.values().next().expect("one child");
+ }
+ tops.push(node);
+ }
+ for node in self.sorted_coverage_nodes(tops) {
+ self.push_coverage_rows(node, 0, &mut rows);
+ }
+ rows
+ }
+
+ fn push_coverage_rows(&self, mut node: &CoverageNode, depth: usize, rows: &mut Vec<CoverageRow>) {
+ let mut label = node_label(node);
+ // A folder whose only child is a folder draws with it on one row.
+ while node.children.len() == 1 && node.children.values().next().is_some_and(|child| !child.children.is_empty()) {
+ node = node.children.values().next().expect("one child");
+ label = format!("{label}/{}", node_label(node));
+ }
+ let file = node.value.clone().expect("coverage nodes carry their value");
+ let folder = !node.children.is_empty();
+ let collapsed = folder == self.testing.coverage.toggled.contains(&file.uri.to_uri_string());
+ rows.push(CoverageRow { label, file: Some(file), depth, folder, collapsed: folder && collapsed });
+ if folder && !collapsed {
+ for child in self.sorted_coverage_nodes(node.children.values().collect()) {
+ self.push_coverage_rows(child, depth + 1, rows);
+ }
+ }
+ }
+
+ /// testCoverageView.ts `Sorter` of file nodes.
+ fn sorted_coverage_nodes<'a>(&self, mut nodes: Vec<&'a CoverageNode>) -> Vec<&'a CoverageNode> {
+ let value = |node: &&'a CoverageNode| node.value.clone().expect("coverage nodes carry their value");
+ match self.testing.coverage.sort_order {
+ SortOrder::Location | SortOrder::Name => nodes.sort_by_key(|node| value(node).uri.to_uri_string().to_lowercase()),
+ SortOrder::Coverage => nodes.sort_by(|a, b| value(b).total_percent().total_cmp(&value(a).total_percent())),
+ }
+ nodes
+ }
+
+ /// The Test Coverage view, laid out with the testing container's panes while coverage is open.
+ pub(super) fn test_coverage_view_pane(&self, cx: &mut Context<Self>) -> super::view_panes::ViewPane {
+ let per_test = self.selected_coverage().is_some_and(|(_, _, coverage)| !coverage.all_per_test_ids().is_empty());
+ // The `navigation` group: Change Sort Order (1), Collapse All (2), Clear Coverage (10), then the per-test filter
+ // without an order.
+ let filter_icon = if self.testing.coverage.filter_to_test.is_some() { "filter-filled" } else { "filter" };
+ let actions = div()
+ .flex()
+ .child(self.search_action("sort-precedence", "testing.coverageViewChangeSorting", true, cx))
+ .child(self.search_action("collapse-all", "testing.coverageViewCollapseAll", true, cx))
+ .child(self.search_action("close", "testing.coverage.close", true, cx))
+ .when(per_test, |actions| actions.child(self.search_action(filter_icon, "testing.coverageFilterToTest", true, cx)));
+ let mut body = div().id("test-coverage-tree").flex_1().min_h_0().overflow_y_scroll().flex().flex_col();
+ for row in self.coverage_rows() {
+ body = body.child(self.coverage_row(row, cx));
+ }
+ super::view_panes::ViewPane { id: TEST_COVERAGE_VIEW, title: "Test Coverage".into(), description: None, actions: Some(actions.into_any_element()), draws_more: false, show_actions: false, body: body.into_any_element() }
+ }
+
+ /// `FileCoverageRenderer` (twistie, resource label, `ManagedTestCoverageBars`) or `CurrentlyFilteredToRenderer`.
+ fn coverage_row(&self, row: CoverageRow, cx: &mut Context<Self>) -> gpui::Stateful<Div> {
+ let foreground = self.foreground_or("icon.foreground");
+ let id = row.file.as_ref().map_or_else(|| "filtered-to".to_owned(), |file| file.uri.to_uri_string());
+ let selected = self.testing.coverage.selected_row.as_ref() == Some(&id);
+ let element = div()
+ .id(gpui::SharedString::from(format!("coverage-row:{id}")))
+ .h(px(ROW_HEIGHT))
+ .flex_none()
+ .mx(px(self.pane_row_inset()))
+ .rounded(px(4.))
+ .pl(px(self.tree_indent() * row.depth as f32 + 11.))
+ .flex()
+ .items_center()
+ .cursor_pointer();
+ let element = self.list_row_selection(element, selected, false, false);
+ let Some(file) = row.file else {
+ let label = div().flex_1().min_w_0().overflow_hidden().text_ellipsis().whitespace_nowrap().child(row.label);
+ return element.child(div().w(px(19.)).flex_none()).child(label).on_click(cx.listener(|workbench, _: &ClickEvent, window, cx| {
+ workbench.execute_command("testing.coverageFilterToTest", Vec::new(), window, cx);
+ }));
+ };
+ let twistie_id = id.clone();
+ let twistie = div().id(gpui::SharedString::from(format!("coverage-twistie:{id}"))).w(px(19.)).h_full().flex().items_center().flex_none();
+ let twistie = match row.folder {
+ true => twistie.child(self.icon(if row.collapsed { "chevron-right" } else { "chevron-down" }, 16., 16., foreground)).on_click(cx.listener(move |workbench, _: &ClickEvent, _, cx| {
+ cx.stop_propagation();
+ workbench.toggle_coverage_row(&twistie_id);
+ cx.notify();
+ })),
+ false => twistie,
+ };
+ // testCoverageView.ts never sets `show-file-icons` on its tree, so the resource label draws no file icon.
+ let label = div().flex_1().min_w_0().overflow_hidden().text_ellipsis().whitespace_nowrap().child(row.label);
+ let bars = (file.kind != crate::testing_coverage::CoverageKind::Bypassed).then(|| self.coverage_bars(&file));
+ let open = (!row.folder).then(|| file.uri.clone());
+ element.child(twistie).child(label).children(bars).on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {
+ workbench.testing.coverage.selected_row = Some(id.clone());
+ if let Some(uri) = &open {
+ let uri = json!({ "scheme": uri.scheme, "authority": uri.authority, "path": uri.path });
+ if let Err(error) = workbench.try_show_text_document(&uri, &Value::Null, window, cx) {
+ workbench.notify_error(error["message"].as_str().unwrap_or("Unable to open the editor").to_owned());
+ }
+ }
+ cx.notify();
+ }))
+ }
+
+ /// testCoverageBars.ts `ManagedTestCoverageBars` without `compact`: the displayed percent at precision 2, then the
+ /// statement, function and branch bars (testing.css `.test-coverage-bars`).
+ fn coverage_bars(&self, file: &FileCoverage) -> Div {
+ let thresholds = self.setting("testing.coverageBarThresholds");
+ let method = self.setting("testing.displayedCoveragePercent");
+ let overall = display_percent(displayed_stat(file, method.as_str().unwrap_or("totalCoverage")), 2);
+ let mut bars = div().flex().flex_none().items_center().gap(px(4.)).text_size(px(11.)).mr(px(12.)).child(overall);
+ for count in [Some(file.statement), file.declaration, file.branch].into_iter().flatten() {
+ bars = bars.child(self.coverage_bar(count.percent(), count.total == 0, &thresholds));
+ }
+ bars
+ }
+
+ /// `renderBar`: 16px wide, filled to the floored percent, in the threshold's chart color or half the foreground
+ /// at a zero total.
+ fn coverage_bar(&self, percent: f64, zero: bool, thresholds: &Value) -> Div {
+ let color: Rgba = match zero {
+ true => Rgba { a: 0.5, ..self.color("foreground") },
+ false => self.color(coverage_color(percent, thresholds)),
+ };
+ let fill = Rgba { a: color.a * 0.7, ..color };
+ div().relative().w(px(16.)).h(px(8.)).border_1().border_color(color).rounded(px(2.)).overflow_hidden().child(div().absolute().left_0().top_0().bottom_0().w(px((percent * 16.).floor() as f32)).bg(fill))
+ }
+
+ /// codeCoverageDecorations.ts `apply` for the gutter: each line's `coverage-deco-hit` and `coverage-deco-miss`
+ /// from the statements and branches of the file's details, loaded once per file and test filter.
+ pub(super) fn coverage_lines(&self, uri: &Value, line_count: usize, cx: &mut Context<Self>) -> HashMap<usize, LineCoverage> {
+ let mut lines = HashMap::new();
+ let Some(file) = self.file_coverage(uri) else { return lines };
+ let (_, _, coverage) = self.selected_coverage().expect("file_coverage found it");
+ let key = (file.uri.clone(), self.testing.coverage.filter_to_test.clone());
+ let Some(details) = coverage.details.get(&key) else {
+ let (selected, file_id) = (self.testing.coverage.selected.clone().expect("open"), file.id.clone());
+ cx.spawn(async move |this, cx| this.update(cx, |workbench, cx| workbench.load_coverage_details(selected, key, file_id, cx))).detach();
+ return lines;
+ };
+ let Some(details) = details else { return lines };
+ for range in detail_ranges(details) {
+ let detail = &details[range.detail];
+ let hit = match (range.kind(), range.branch) {
+ (DetailType::Branch, Some(branch)) => detail.branches[branch].count.is_hit(),
+ (DetailType::Statement, _) => detail.count.is_hit(),
+ _ => continue,
+ };
+ // A report's lines are the extension's: the model's line range bounds them (`validateRange`).
+ let start = (range.range.start.line as usize).max(1);
+ let end = (range.range.end.line as usize).min(line_count);
+ for line in start..=end {
+ let marks: &mut LineCoverage = lines.entry(line - 1).or_default();
+ if hit { marks.hit = true } else { marks.miss = true }
+ }
+ }
+ lines
+ }
+
+ /// `FileCoverage.details` / `detailsForTest`: `$getCoverageDetails` of the file's id, cached on the coverage
+ /// with `None` while it loads.
+ fn load_coverage_details(&mut self, selected: (String, String), key: crate::testing_coverage::DetailsKey, file_id: String, cx: &mut Context<Self>) {
+ let Some(coverage) = self.coverage_of_mut(&selected) else { return };
+ if coverage.details.contains_key(&key) {
+ return;
+ }
+ coverage.details.insert(key.clone(), None);
+ let reply = self.host.call_cancellable("ExtHostTesting", "$getCoverageDetails", vec![json!(file_id), json!(key.1)]);
+ cx.spawn(async move |this, cx| {
+ let details = match reply.await {
+ Ok(Ok(Value::Array(details))) => details.iter().filter_map(crate::testing_coverage::CoverageDetail::from_value).collect(),
+ _ => Vec::new(),
+ };
+ let _ = this.update(cx, |workbench, cx| {
+ if let Some(coverage) = workbench.coverage_of_mut(&selected) {
+ coverage.details.insert(key, Some(details));
+ }
+ cx.notify();
+ });
+ })
+ .detach();
+ }
+
+ fn coverage_of_mut(&mut self, (result, task): &(String, String)) -> Option<&mut TestCoverage> {
+ let result = self.testing.result_mut(result)?;
+ result.tasks.iter_mut().find(|candidate| &candidate.id == task)?.coverage.as_mut()
+ }
+
+ /// The `coverage-deco-gutter` background of a line number: covered, uncovered, or both striped (testing.css).
+ pub(super) fn coverage_gutter(&self, line: LineCoverage) -> Option<Div> {
+ let (hit, miss) = (self.color("testing.coveredGutterBackground"), self.color("testing.uncoveredGutterBackground"));
+ let fill = div().absolute().inset_0();
+ match (line.hit, line.miss) {
+ (true, true) => Some(fill.child(super::editor_view::quick_diff::stripes(hit, miss, 6., true))),
+ (true, false) => Some(fill.bg(hit)),
+ (false, true) => Some(fill.bg(miss)),
+ (false, false) => None,
+ }
+ }
+}
+
+fn node_label(node: &CoverageNode) -> String {
+ node.value.as_ref().expect("coverage nodes carry their value").uri.basename().to_owned()
+}
+
+/// testId.ts `getLengthOfCommonPrefix`: bounded by the number of tests, not the paths' length, as upstream.
+fn common_prefix_length(tests: &[String]) -> usize {
+ if tests.is_empty() {
+ return 0;
+ }
+ let paths: Vec<Vec<&str>> = tests.iter().map(|test| test.split('\0').collect()).collect();
+ let mut common = 0;
+ while common < paths.len() - 1 {
+ for pair in paths.windows(2) {
+ if pair[0].get(common) != pair[1].get(common) {
+ return common;
+ }
+ }
+ common += 1;
+ }
+ common
+}
+
+/// codeCoverageDisplayUtils.ts `getLabelForItem`: the test's label, its parents past the common prefix described.
+fn label_for_item(result: &TestResult, test: &str, common_prefix: usize) -> (String, Option<String>) {
+ let mut ids = vec![test];
+ while let Some(parent) = parent_id(ids[ids.len() - 1]) {
+ ids.push(parent);
+ }
+ let mut parts = Vec::new();
+ for id in ids.into_iter().rev() {
+ let Some(item) = result.items.get(id) else { break };
+ parts.push(item.label().to_owned());
+ }
+ let relevant = parts.get(common_prefix..).unwrap_or_default();
+ match relevant {
+ [] => (String::new(), None),
+ [only] => (only.clone(), None),
+ [parents @ .., last] => (last.clone(), Some(parents.join(" \u{203A} "))),
+ }
+}
diff --git a/native/crates/app/src/workbench/testing_coverage_view/tests.rs b/native/crates/app/src/workbench/testing_coverage_view/tests.rs
new file mode 100644
index 00000000000..5f3639239d0
--- /dev/null
+++ b/native/crates/app/src/workbench/testing_coverage_view/tests.rs
@@ -0,0 +1,179 @@
+use gpui::TestAppContext;
+use serde_json::{Value, json};
+
+use crate::commands::Outcome;
+use crate::testing::{ResultState, TestResult};
+use crate::workbench::Workbench;
+use crate::workbench::testing_gutter::tests::workbench_with_tests;
+use crate::workbench::testing_results::ResultsElement;
+
+const TESTS: &[(&str, &str, u32)] = &[("c\0f", "math", 0), ("c\0f\0a", "adds", 1)];
+
+fn request(method: &str, args: Vec<Value>) -> exthost::session::ForwardedRequest {
+ exthost::session::ForwardedRequest { req: 1, proxy: "MainThreadTesting", method: method.into(), args }
+}
+
+fn file_coverage(id: &str, path: &str, covered: u64, total: u64) -> Value {
+ json!({ "id": id, "uri": { "scheme": "file", "path": path }, "statement": { "covered": covered, "total": total } })
+}
+
+/// A completed result `r1` of one task `t1` in which `adds` passed.
+fn add_result(workbench: &mut Workbench) {
+ let mut result = TestResult::new("r1".into(), json!({ "group": 2, "targets": [{ "testIds": ["c\0f"] }] }));
+ result.add_task(&json!({ "id": "t1", "name": "Task A", "ctrlId": "c", "running": false }));
+ let chain = ["c", "c\0f", "c\0f\0a"].map(|id| workbench.testing.collection.items[id].item.clone());
+ result.add_chain(&chain);
+ result.update_state("c\0f\0a", "t1", ResultState::Passed, Some(1.));
+ result.mark_complete(1);
+ workbench.testing.results = vec![result];
+}
+
+/// mainThreadTesting.ts `$appendCoverage`: the task's first report makes its coverage, later ones add files, and the
+/// serialized result says `hasCoverage`.
+#[gpui::test]
+fn appended_coverage_is_stored_on_its_task(cx: &mut TestAppContext) {
+ let (workbench, cx, _host) = workbench_with_tests("coverage-append", TESTS, cx);
+ workbench.update_in(cx, |workbench, window, cx| {
+ add_result(workbench);
+ assert_eq!(workbench.testing.results[0].to_json()["tasks"][0]["hasCoverage"], false);
+ drop(workbench.handle_testing_request(request("$appendCoverage", vec![json!("r1"), json!("t1"), file_coverage("f1", "/src/a.js", 1, 2)]), window, cx));
+ drop(workbench.handle_testing_request(request("$appendCoverage", vec![json!("r1"), json!("t1"), file_coverage("f2", "/src/b.js", 2, 2)]), window, cx));
+ let coverage = workbench.testing.results[0].tasks[0].coverage.as_ref().expect("the task's coverage");
+ let folder = coverage.computed_for_uri(&crate::testing_coverage::CoverageUri::file("/src")).expect("the folder's coverage");
+ assert_eq!((folder.statement.covered, folder.statement.total), (3, 4));
+ assert_eq!(workbench.testing.results[0].to_json()["tasks"][0]["hasCoverage"], true);
+ });
+}
+
+/// `$getCoverageDetails`: a reported file asks the extension host for its details by file id, any other answers `[]`.
+#[gpui::test]
+fn coverage_details_come_from_the_extension_host(cx: &mut TestAppContext) {
+ let (workbench, cx, host) = workbench_with_tests("coverage-details", TESTS, cx);
+ let (unknown, known) = workbench.update_in(cx, |workbench, window, cx| {
+ add_result(workbench);
+ drop(workbench.handle_testing_request(request("$appendCoverage", vec![json!("r1"), json!("t1"), file_coverage("f1", "/src/a.js", 1, 2)]), window, cx));
+ let ask = |workbench: &mut Workbench, path: &str, window: &mut gpui::Window, cx: &mut gpui::Context<Workbench>| workbench.handle_testing_request(request("$getCoverageDetails", vec![json!("r1"), json!(0), json!({ "scheme": "file", "path": path })]), window, cx);
+ (matches!(ask(workbench, "/src/x.js", window, cx), Outcome::Ready(Ok(Value::Array(ref details))) if details.is_empty()), matches!(ask(workbench, "/src/a.js", window, cx), Outcome::Pending(_)))
+ });
+ assert!(unknown && known);
+ let sent: Vec<_> = host.try_iter().filter(|message| message.method == "$getCoverageDetails").map(|message| message.args).collect();
+ assert_eq!(sent, vec![vec![json!("f1"), Value::Null]]);
+}
+
+/// testResultsTree.ts `CoverageElement`: the first child of a task with coverage, "View Test Coverage" opening it
+/// with the Test Coverage view, "Close Test Coverage" closing it.
+#[gpui::test]
+fn the_coverage_row_opens_and_closes_coverage(cx: &mut TestAppContext) {
+ let (workbench, cx, _host) = workbench_with_tests("coverage-results-row", TESTS, cx);
+ workbench.update_in(cx, |workbench, window, cx| {
+ add_result(workbench);
+ drop(workbench.handle_testing_request(request("$appendCoverage", vec![json!("r1"), json!("t1"), file_coverage("f1", "/src/a.js", 1, 2)]), window, cx));
+ drop(workbench.execute_command("testing.coverage.close", Vec::new(), window, cx));
+ let coverage = ResultsElement::Coverage { result: "r1".into(), task: 0 };
+ let rows = workbench.results_rows();
+ assert_eq!(rows.iter().map(|row| row.element.clone()).position(|element| element == coverage), Some(1), "after the task row");
+ let label = |workbench: &Workbench| workbench.results_row_label(&workbench.results_rows()[1]).0;
+ let open = |workbench: &Workbench, window: &gpui::Window| workbench.key_context(window)["testing.isTestCoverageOpen"] == true;
+ assert_eq!((label(workbench), open(workbench, window)), ("View Test Coverage".to_owned(), false));
+ workbench.open_coverage_element(&coverage, cx);
+ assert_eq!((label(workbench), open(workbench, window)), ("Close Test Coverage".to_owned(), true));
+ assert_eq!(workbench.side_bar_view, crate::workbench::view_locations::side_bar_view_of(crate::workbench::view_locations::TESTING_CONTAINER), "focus shows the Testing container");
+ });
+ cx.update(|window, cx| drop(window.draw(cx)));
+ workbench.update_in(cx, |workbench, window, cx| {
+ let coverage = ResultsElement::Coverage { result: "r1".into(), task: 0 };
+ let label = |workbench: &Workbench| workbench.results_row_label(&workbench.results_rows()[1]).0;
+ let open = |workbench: &Workbench, window: &gpui::Window| workbench.key_context(window)["testing.isTestCoverageOpen"] == true;
+ workbench.open_coverage_element(&coverage, cx);
+ assert_eq!((label(workbench), open(workbench, window)), ("View Test Coverage".to_owned(), false));
+ });
+}
+
+/// testCoverageService.ts: a completed run opens its first task's coverage.
+#[gpui::test]
+fn a_completed_run_opens_its_coverage(cx: &mut TestAppContext) {
+ let (workbench, cx, _host) = workbench_with_tests("coverage-completed", TESTS, cx);
+ workbench.update_in(cx, |workbench, window, cx| {
+ add_result(workbench);
+ drop(workbench.handle_testing_request(request("$appendCoverage", vec![json!("r1"), json!("t1"), file_coverage("f1", "/src/a.js", 1, 2)]), window, cx));
+ workbench.coverage_result_completed("r1", cx);
+ assert_eq!(workbench.testing.coverage.selected, Some(("r1".to_owned(), "t1".to_owned())));
+ });
+}
+
+/// The `$runControllerTests` reply can complete the run before the queued `$appendCoverage` that preceded it reaches
+/// the workbench; the reference's single channel keeps that order, so the coverage still opens.
+#[gpui::test]
+fn coverage_reported_just_before_the_run_completed_opens(cx: &mut TestAppContext) {
+ let (workbench, cx, _host) = workbench_with_tests("coverage-late", TESTS, cx);
+ workbench.update_in(cx, |workbench, window, cx| {
+ add_result(workbench);
+ workbench.coverage_result_completed("r1", cx);
+ assert_eq!(workbench.testing.coverage.selected, None);
+ drop(workbench.handle_testing_request(request("$appendCoverage", vec![json!("r1"), json!("t1"), file_coverage("f1", "/src/a.js", 1, 2)]), window, cx));
+ assert_eq!(workbench.testing.coverage.selected, Some(("r1".to_owned(), "t1".to_owned())));
+ });
+}
+
+/// testCoverageView.ts `setInput`: from the root the first folder with several children, then its files by
+/// location, each with its statement counts.
+#[gpui::test]
+fn the_coverage_view_lists_folders_and_files(cx: &mut TestAppContext) {
+ let (workbench, cx, _host) = workbench_with_tests("coverage-view", TESTS, cx);
+ workbench.update_in(cx, |workbench, window, cx| {
+ add_result(workbench);
+ for (id, path, covered) in [("f2", "/w/src/b.js", 2), ("f1", "/w/src/a.js", 1)] {
+ drop(workbench.handle_testing_request(request("$appendCoverage", vec![json!("r1"), json!("t1"), file_coverage(id, path, covered, 2)]), window, cx));
+ }
+ workbench.open_coverage("r1", 0, false, cx);
+ let rows: Vec<_> = workbench.coverage_rows().into_iter().map(|row| {
+ let file = row.file.expect("file rows");
+ (row.label, row.depth, file.statement.covered)
+ }).collect();
+ assert_eq!(rows, vec![("src".to_owned(), 0, 3), ("a.js".to_owned(), 1, 1), ("b.js".to_owned(), 1, 2)]);
+ });
+}
+
+/// paneview.css `.pane:focus-within`: beside the Test Coverage view, the Test Explorer's header keeps its actions while
+/// its filter has the focus, as the reference after Testing opens from the activity bar.
+#[gpui::test]
+fn the_test_explorer_header_shows_its_actions_while_its_filter_is_focused(cx: &mut TestAppContext) {
+ let (workbench, cx, _host) = workbench_with_tests("coverage-explorer-actions", TESTS, cx);
+ workbench.update_in(cx, |workbench, window, cx| {
+ workbench.testing.controllers.insert("c".into(), crate::workbench::testing_service::Controller { label: "Ctrl".into(), capabilities: 0 });
+ add_result(workbench);
+ drop(workbench.handle_testing_request(request("$appendCoverage", vec![json!("r1"), json!("t1"), file_coverage("f1", "/src/a.js", 1, 2)]), window, cx));
+ workbench.open_coverage("r1", 0, false, cx);
+ workbench.set_part_hidden(crate::workbench::layout::Part::SideBar, false, cx);
+ workbench.open_testing_view(true, window, cx);
+ });
+ cx.run_until_parked();
+ cx.update(|window, cx| drop(window.draw(cx)));
+ assert!(cx.debug_bounds("codicon-run-all").is_some(), "Run Tests draws in the Test Explorer's header");
+}
+
+/// codeCoverageDecorations.ts: a covered statement's lines are `coverage-deco-hit`, a missed one's
+/// `coverage-deco-miss`, from the details the extension host answered, within the document's lines.
+#[gpui::test]
+fn the_gutter_marks_covered_and_missed_lines(cx: &mut TestAppContext) {
+ let (workbench, cx, _host) = workbench_with_tests("coverage-gutter", TESTS, cx);
+ let lines = workbench.update_in(cx, |workbench, window, cx| {
+ add_result(workbench);
+ let uri = workbench.editors.active().expect("the test file").document().uri();
+ let coverage = json!({ "id": "f1", "uri": uri, "statement": { "covered": 1, "total": 2 } });
+ drop(workbench.handle_testing_request(request("$appendCoverage", vec![json!("r1"), json!("t1"), coverage]), window, cx));
+ workbench.open_coverage("r1", 0, false, cx);
+ assert!(workbench.coverage_lines(&uri, 3, cx).is_empty(), "nothing before the details load");
+ let range = |line: u32| json!({ "startLineNumber": line, "startColumn": 1, "endLineNumber": line, "endColumn": 10 });
+ let outside = json!({ "startLineNumber": 3, "startColumn": 1, "endLineNumber": u32::MAX, "endColumn": 1 });
+ let details = vec![json!({ "type": 1, "count": 1, "location": range(1) }), json!({ "type": 1, "count": 0, "location": outside })];
+ let file = workbench.selected_coverage().expect("open").2.file(&crate::testing_coverage::CoverageUri::from_value(&uri)).expect("the file").clone();
+ let task = &mut workbench.testing.results[0].tasks[0];
+ let details = details.iter().filter_map(crate::testing_coverage::CoverageDetail::from_value).collect();
+ task.coverage.as_mut().expect("coverage").details.insert((file.uri, None), Some(details));
+ let mut lines: Vec<_> = workbench.coverage_lines(&uri, 3, cx).into_iter().map(|(line, marks)| (line, marks.hit, marks.miss)).collect();
+ lines.sort();
+ lines
+ });
+ assert_eq!(lines, vec![(0, true, false), (2, false, true)]);
+}
diff --git a/native/crates/app/src/workbench/testing_profiles/tests.rs b/native/crates/app/src/workbench/testing_profiles/tests.rs
index ebb66a85501..94ad0bf0382 100644
--- a/native/crates/app/src/workbench/testing_profiles/tests.rs
+++ b/native/crates/app/src/workbench/testing_profiles/tests.rs
@@ -6,7 +6,7 @@ use serde_json::json;
use crate::menus::{MenuAction, MenuId, MenuItem};
use crate::quick_input::Entry;
-use crate::testing::{GROUP_DEBUG, GROUP_RUN, Profile};
+use crate::testing::{GROUP_COVERAGE, GROUP_DEBUG, GROUP_RUN, Profile};
use crate::workbench::Workbench;
use crate::workbench::testing_service::Controller;
use crate::workspace_trust::{Startup, WorkspaceTrust};
@@ -52,6 +52,23 @@ fn the_run_group_chevron_keeps_the_view_title_actions_in_the_side_bar(cx: &mut T
}
}
+/// testExplorerActions.ts `CoverageSelectedAction`: Run Tests with Coverage joins the view title once a coverage profile exists.
+#[gpui::test]
+fn a_coverage_profile_adds_run_tests_with_coverage_to_the_view_title(cx: &mut TestAppContext) {
+ let (workbench, cx, _host) = workbench_with(vec![profile(1, "Run", GROUP_RUN, true, false), profile(2, "Coverage", GROUP_COVERAGE, true, false)], cx);
+ workbench.update_in(cx, |workbench, window, cx| {
+ workbench.set_part_hidden(crate::workbench::layout::Part::SideBar, false, cx);
+ drop(workbench.execute_command("workbench.view.testing", Vec::new(), window, cx));
+ });
+ cx.run_until_parked();
+ cx.update(|window, _| window.refresh());
+ cx.run_until_parked();
+ let title = cx.debug_bounds("side-bar-title-label").expect("the side bar title draws");
+ let coverage = cx.debug_bounds("codicon-run-all-coverage").expect("Run Tests with Coverage draws");
+ let debug = cx.debug_bounds("codicon-debug-alt-small").expect("Debug Tests draws");
+ assert!(coverage.origin.y < title.bottom() && coverage.left() > debug.left(), "coverage at {coverage:?}, debug {debug:?}");
+}
+
/// style.css `.monaco-dropdown.active .action-label`: the chevron stays active while its own menu is open.
#[gpui::test]
fn the_run_group_chevron_is_active_while_its_menu_is_open(cx: &mut TestAppContext) {
diff --git a/native/crates/app/src/workbench/testing_results.rs b/native/crates/app/src/workbench/testing_results.rs
index 20d5be21dc7..7f8144cc1c6 100644
--- a/native/crates/app/src/workbench/testing_results.rs
+++ b/native/crates/app/src/workbench/testing_results.rs
@@ -32,6 +32,7 @@ pub enum ResultsElement {
Result { result: String },
Older { count: usize },
Task { result: String, task: usize },
+ Coverage { result: String, task: usize },
Test { result: String, task: usize, test: String },
Message { result: String, task: usize, test: String, message: usize },
}
@@ -42,6 +43,7 @@ impl ResultsElement {
ResultsElement::Result { result } => result.clone(),
ResultsElement::Older { count } => format!("older-{count}"),
ResultsElement::Task { result, task } => format!("{result}/{task}"),
+ ResultsElement::Coverage { result, task } => format!("coverage-{result}/{task}"),
ResultsElement::Test { result, test, .. } => format!("{result}/{test}"),
ResultsElement::Message { result, task, test, message } => format!("{result}/{task}/{test}/message/{message}"),
}
@@ -53,6 +55,7 @@ impl ResultsElement {
ResultsElement::Result { .. } => "result",
ResultsElement::Older { .. } => "older",
ResultsElement::Task { .. } => "task",
+ ResultsElement::Coverage { .. } => "coverage",
ResultsElement::Test { .. } => "test",
ResultsElement::Message { .. } => "message",
}
@@ -186,6 +189,10 @@ fn result_children(result: &TestResult) -> Vec<Node> {
}).collect();
tests.sort_by_key(|id| Reverse(result.items[*id].tasks[task].state.priority()));
let mut children = Vec::new();
+ if result.tasks[task].coverage.is_some() {
+ let element = ResultsElement::Coverage { result: result.id.clone(), task };
+ children.push(Node { element, incompressible: true, collapsed: false, children: Vec::new() });
+ }
for test in tests {
let messages = &result.items[test].tasks[task].messages;
let mut message_nodes = Vec::new();
@@ -340,6 +347,22 @@ impl Workbench {
rows
}
+ /// `CoverageElement.isOpen`.
+ fn is_coverage_open(&self, element: &ResultsElement) -> bool {
+ let ResultsElement::Coverage { result, task } = element else { return false };
+ let task_id = &self.result_by_id(result).expect("rows come from the results").tasks[*task].id;
+ self.testing.coverage.selected.as_ref().is_some_and(|(selected_result, selected_task)| selected_result == result && selected_task == task_id)
+ }
+
+ /// `onDidOpen` of a `CoverageElement`: closes the open coverage, else opens the task's with focus.
+ pub(super) fn open_coverage_element(&mut self, element: &ResultsElement, cx: &mut Context<Self>) {
+ let ResultsElement::Coverage { result, task } = element else { return };
+ match self.is_coverage_open(element) {
+ true => self.testing.coverage.selected = None,
+ false => self.open_coverage(result, *task, true, cx),
+ }
+ }
+
fn result_by_id(&self, id: &str) -> Option<&TestResult> {
self.testing.results.iter().find(|result| result.id == id)
}
@@ -361,6 +384,8 @@ impl Workbench {
let task = &self.result_by_id(result).expect("rows come from the results").tasks[*task];
(task.name.clone(), None, task.running.then_some(ResultState::Running))
}
+ ResultsElement::Coverage { .. } if self.is_coverage_open(element) => ("Close Test Coverage".into(), None, None),
+ ResultsElement::Coverage { .. } => ("View Test Coverage".into(), None, None),
ResultsElement::Test { result, task, test } => {
let result = self.result_by_id(result).expect("rows come from the results");
let item = &result.items[test];
@@ -421,7 +446,7 @@ impl Workbench {
fn results_element_args(&self, element: &ResultsElement) -> Vec<Value> {
match element {
ResultsElement::Result { result } => vec![json!(result)],
- ResultsElement::Older { .. } => Vec::new(),
+ ResultsElement::Older { .. } | ResultsElement::Coverage { .. } => Vec::new(),
ResultsElement::Task { result, task } => vec![self.result_task_context(result, *task)],
ResultsElement::Test { result, task, test } => vec![json!({ "$mid": TEST_ITEM_CONTEXT_MID, "tests": [self.result_test_arg(result, test)] }), self.result_task_context(result, *task)],
ResultsElement::Message { result, task, .. } => vec![self.message_args(element), self.result_task_context(result, *task)],
@@ -492,7 +517,7 @@ impl Workbench {
primary.push(ResultsAction::new("debug-alt-small", "Debug Test", "vscode.runTestsById", vec![json!(GROUP_DEBUG), json!(test)]));
}
}
- ResultsElement::Older { .. } => {}
+ ResultsElement::Older { .. } | ResultsElement::Coverage { .. } => {}
}
if let ResultsElement::Message { result, task, test, message } = element {
menu = MenuId::TestMessageContext;
@@ -602,6 +627,7 @@ impl Workbench {
let target = rows[index].target().clone();
self.testing_view.results_selected = Some(target.id());
self.open_results_element(&target);
+ self.open_coverage_element(&target, cx);
cx.notify();
return true;
}
@@ -948,12 +974,17 @@ impl Workbench {
true => twistie.child(self.icon(if row.collapsed { "chevron-right" } else { "chevron-down" }, 16., 16., twistie_color)),
false => twistie,
})
- .child(match state {
- Some(state) => {
+ .child(match (state, &row.element) {
+ (Some(state), _) => {
let (icon, color) = state_icon(state);
self.icon(icon, 16., 16., self.foreground_or(color)).mr(px(3.25))
}
- None => div().w(px(3.25)).flex_none(),
+ // testResultsTree.ts `CoverageElement.icon`: `widgetClose` while open, else `testingCoverageReport`.
+ (None, element @ ResultsElement::Coverage { .. }) => {
+ let icon = if self.is_coverage_open(element) { "close" } else { "coverage" };
+ self.icon(icon, 16., 16., twistie_color).mr(px(3.25))
+ }
+ (None, _) => div().w(px(3.25)).flex_none(),
})
.child(label_box)
.child(actions)
@@ -964,6 +995,7 @@ impl Workbench {
workbench.toggle_results_row(&toggle);
}
workbench.open_results_element(&open);
+ workbench.open_coverage_element(&open, cx);
cx.notify();
}))
.on_mouse_down(MouseButton::Right, cx.listener(move |workbench, event: &MouseDownEvent, window, cx| {
diff --git a/native/crates/app/src/workbench/testing_service.rs b/native/crates/app/src/workbench/testing_service.rs
index 601da8d2112..25dc1bd0568 100644
--- a/native/crates/app/src/workbench/testing_service.rs
+++ b/native/crates/app/src/workbench/testing_service.rs
@@ -35,6 +35,7 @@ pub struct TestingService {
pub continuous: Vec<super::testing_continuous::ContinuousRun>,
/// testExclusions.ts: the hidden tests' ids, in the order they were hidden.
pub excluded: Vec<String>,
+ pub coverage: super::testing_coverage_view::CoverageService,
/// testServiceImpl.ts `testRefreshCancellations`: dropping a refresh cancels its requests.
pub refreshes: HashMap<u64, Task<()>>,
next_refresh: u64,
@@ -106,6 +107,7 @@ impl Workbench {
] {
context.insert(key.to_owned(), value);
}
+ self.testing_coverage_context(context);
}
/// testServiceImpl.ts `refreshTests` of the controllers, or of all with none: `testing.isRefreshing` holds until
@@ -239,7 +241,15 @@ impl Workbench {
}
}
}
- "$appendCoverage" | "$getCoverageDetails" => return Outcome::Ready(Ok(json!([]))),
+ "$appendCoverage" => self.append_coverage(&text(0), &text(1), &arg(2), cx),
+ "$getCoverageDetails" => {
+ let task = testing.results.iter().find(|result| result.id == text(0)).and_then(|result| result.tasks.get(arg(1).as_u64().unwrap_or(u64::MAX) as usize));
+ let file = task.and_then(|task| task.coverage.as_ref()).and_then(|coverage| coverage.file(&crate::testing_coverage::CoverageUri::from_value(&arg(2))));
+ return match file {
+ Some(file) => Outcome::Pending(self.host.call_cancellable("ExtHostTesting", "$getCoverageDetails", vec![json!(file.id), Value::Null])),
+ None => Outcome::Ready(Ok(json!([]))),
+ };
+ }
_ => {}
}
if matches!(request.method.as_str(), "$unregisterTestController" | "$publishTestRunProfile" | "$updateTestRunConfig" | "$removeTestProfile") {
@@ -284,6 +294,7 @@ impl Workbench {
result.mark_complete(now_millis());
let serialized = result.to_json();
self.host.send("ExtHostTesting", "$publishTestResults", vec![json!([serialized])]);
+ self.coverage_result_completed(run, cx);
self.test_run_finished(run, cx);
}
diff --git a/native/crates/app/src/workbench/testing_view.rs b/native/crates/app/src/workbench/testing_view.rs
index 8fd86b3be59..356c4ab1cef 100644
--- a/native/crates/app/src/workbench/testing_view.rs
+++ b/native/crates/app/src/workbench/testing_view.rs
@@ -45,9 +45,10 @@ pub struct TestingView {
pub call_stack_collapsed: HashSet<usize>,
/// Where the continuous run dropdown's chevron last painted, to anchor its menu.
pub continuous_dropdown_bounds: std::rc::Rc<std::cell::Cell<gpui::Bounds<gpui::Pixels>>>,
- /// Where the run and the debug group dropdowns' chevrons last painted.
+ /// Where the run, debug and coverage group dropdowns' chevrons last painted.
pub run_dropdown_bounds: std::rc::Rc<std::cell::Cell<gpui::Bounds<gpui::Pixels>>>,
pub debug_dropdown_bounds: std::rc::Rc<std::cell::Cell<gpui::Bounds<gpui::Pixels>>>,
+ pub coverage_dropdown_bounds: std::rc::Rc<std::cell::Cell<gpui::Bounds<gpui::Pixels>>>,
/// The chevron whose menu showed, with that menu's `context_menus_shown` count.
pub open_dropdown: Option<(&'static str, usize)>,
pub filter: TestingFilter,
@@ -76,6 +77,7 @@ impl TestingView {
continuous_dropdown_bounds: Default::default(),
run_dropdown_bounds: Default::default(),
debug_dropdown_bounds: Default::default(),
+ coverage_dropdown_bounds: Default::default(),
open_dropdown: None,
filter: TestingFilter::new(cx),
selected: None,
@@ -139,9 +141,10 @@ impl Workbench {
self.register_test_item_commands();
self.register_testing_gutter_commands();
self.register_testing_results_commands();
+ self.register_testing_coverage_commands();
self.register_testing_filter_commands();
self.commands.register("workbench.view.extension.test", |workbench, args, window, cx| workbench.execute_command("workbench.view.testing", args, window, cx));
- for (id, group) in [("testing.runAll", GROUP_RUN), ("testing.debugAll", GROUP_DEBUG)] {
+ for (id, group) in [("testing.runAll", GROUP_RUN), ("testing.debugAll", GROUP_DEBUG), ("testing.coverageAll", GROUP_COVERAGE)] {
self.commands.register(id, move |workbench, _, window, cx| {
let roots = workbench.testing.collection.roots.clone();
workbench.run_or_notify(&roots, group, window, cx);
@@ -157,7 +160,7 @@ impl Workbench {
Outcome::done()
});
}
- for (id, group) in [("testing.runCurrentFile", GROUP_RUN), ("testing.debugCurrentFile", GROUP_DEBUG)] {
+ for (id, group) in [("testing.runCurrentFile", GROUP_RUN), ("testing.debugCurrentFile", GROUP_DEBUG), ("testing.coverageCurrentFile", GROUP_COVERAGE)] {
self.commands.register(id, move |workbench, _, window, cx| {
let Some(path) = workbench.editors.active().map(|editor| editor.document().path.to_string_lossy().into_owned()) else { return Outcome::done() };
let tests = workbench.top_tests_in_file(&path);
@@ -165,7 +168,7 @@ impl Workbench {
Outcome::done()
});
}
- for (id, group) in [("testing.runAtCursor", GROUP_RUN), ("testing.debugAtCursor", GROUP_DEBUG)] {
+ for (id, group) in [("testing.runAtCursor", GROUP_RUN), ("testing.debugAtCursor", GROUP_DEBUG), ("testing.coverageAtCursor", GROUP_COVERAGE)] {
self.commands.register(id, move |workbench, _, window, cx| {
let Some(editor) = workbench.editors.active() else { return Outcome::done() };
let line = editor.selections[0].head.line as u32 + 1;
@@ -344,6 +347,15 @@ impl Workbench {
let bounds = self.testing_view.debug_dropdown_bounds.clone();
actions = actions.child(self.dropdown_chevron("testing-debug-dropdown", bounds, |workbench, anchor, window, cx| workbench.show_run_group_dropdown(GROUP_DEBUG, anchor, window, cx), cx));
}
+ // `CoverageSelectedAction`, shown while idle once a coverage profile exists.
+ let coverage_profiles = self.testing.group_profile_count(GROUP_COVERAGE);
+ if !running && coverage_profiles > 0 {
+ actions = actions.child(self.search_action("run-all-coverage", "testing.coverageSelected", true, cx));
+ }
+ if !running && coverage_profiles > 1 {
+ let bounds = self.testing_view.coverage_dropdown_bounds.clone();
+ actions = actions.child(self.dropdown_chevron("testing-coverage-dropdown", bounds, |workbench, anchor, window, cx| workbench.show_run_group_dropdown(GROUP_COVERAGE, anchor, window, cx), cx));
+ }
// testExplorerActions.ts `continuousMenus`, ordered `RunUsing`.
if self.testing.profiles.iter().any(|profile| profile.supports_continuous_run) {
actions = actions.child(match self.testing.is_continuous_for("") {
diff --git a/native/crates/app/src/workbench/view_locations.rs b/native/crates/app/src/workbench/view_locations.rs
index 63457a33264..43b1461ee2f 100644
--- a/native/crates/app/src/workbench/view_locations.rs
+++ b/native/crates/app/src/workbench/view_locations.rs
@@ -157,7 +157,7 @@ impl Workbench {
match self.movable_view(id) {
Some(view) => view.icon,
// testing.contribution.ts `containerIcon: testingViewIcon`.
- None if id == super::testing_view::TESTING_VIEW => "beaker",
+ None if id == super::testing_view::TESTING_VIEW || id == super::testing_coverage_view::TEST_COVERAGE_VIEW => "beaker",
None => "window",
}
}
@@ -428,6 +428,7 @@ impl Workbench {
SEARCH_VIEW => self.search_view_pane(window, cx),
SCM_REPOSITORIES_VIEW => self.scm_repositories_pane(window, cx),
super::testing_view::TESTING_VIEW => self.testing_view_pane(window, cx),
+ super::testing_coverage_view::TEST_COVERAGE_VIEW => self.test_coverage_view_pane(cx),
SCM_CHANGES_VIEW => self.scm_changes_pane(window, cx),
SCM_HISTORY_VIEW => {
let provider = self.active_scm_provider().expect("Graph shows with a history provider");
diff --git a/native/crates/app/src/workbench/view_panes.rs b/native/crates/app/src/workbench/view_panes.rs
index fe4b66aa164..28f8621b11e 100644
--- a/native/crates/app/src/workbench/view_panes.rs
+++ b/native/crates/app/src/workbench/view_panes.rs
@@ -102,7 +102,7 @@ fn view_weight(id: &str) -> f32 {
"workbench.views.extensions.installed" => 100.,
"workbench.views.extensions.popular" => 60.,
VARIABLES_VIEW | SCM_CHANGES_VIEW | SCM_HISTORY_VIEW | "extensions.recommendedList" => 40.,
- TESTING_VIEW => 80.,
+ TESTING_VIEW | super::testing_coverage_view::TEST_COVERAGE_VIEW => 80.,
OUTLINE_VIEW | TIMELINE_VIEW | CALL_STACK_VIEW => 30.,
WATCH_VIEW => 10.,
LOADED_SCRIPTS_VIEW | NOTEBOOK_VARIABLES_VIEW => 5.,
@@ -405,6 +405,10 @@ impl Workbench {
self.layout_extensions_panes(height, cx);
// testing.contribution.ts: the Test Explorer's `when` is `testing.providerCount > 0`.
let mut testing = if self.testing.controllers.is_empty() { Vec::new() } else { vec![(TESTING_VIEW, false)] };
+ // The Test Coverage view's `when` is `testing.isTestCoverageOpen`, ordered after the Test Explorer.
+ if self.selected_coverage().is_some() {
+ testing.push((super::testing_coverage_view::TEST_COVERAGE_VIEW, false));
+ }
testing.extend(self.contributed_panes("test"));
self.layout_container(PaneContainer::Contributed(TESTING_CONTAINER), height, testing, cx);
let side_bar = self.tree_views.containers.iter().filter(|container| container.location == super::layout::Part::SideBar);
@@ -736,6 +740,7 @@ impl Workbench {
|| self.focused_action_bar(window) == Some(id)
|| (id == TIMELINE_VIEW && self.timeline_focus_within(window))
|| (id == OUTLINE_VIEW && self.outline_pane.focus.is_focused(window))
+ || (id == super::testing_view::TESTING_VIEW && (self.testing_view.tree_focus.is_focused(window) || self.testing_view.filter.focus.is_focused(window)))
|| self.setting("workbench.view.alwaysShowHeaderActions") == json!(true);
let foreground = self.foreground_or("sideBarSectionHeader.foreground");
// modernUI paneHeaders.css: in the panel the header takes the panel's background and separator colors.
diff --git a/port/fixtures/extensions/tests-provider/extension.js b/port/fixtures/extensions/tests-provider/extension.js
index 5c0bbe25f39..4b82163647d 100644
--- a/port/fixtures/extensions/tests-provider/extension.js
+++ b/port/fixtures/extensions/tests-provider/extension.js
@@ -1,6 +1,7 @@
// Each `test('name', ...)` line of a *.test.js file is one test; a test whose line says `fail` fails, with a
// diffable message when the line also has `expected "..." actual "..."` (JSON strings), a markdown one when it has
// `markdown "..."`, and a call stack when it has `stack`: a frame at the test's line and one without a source.
+// The Coverage profile reports each run file's test lines as statements, covered unless the line says `fail`.
const vscode = require('vscode');
exports.activate = async function (context) {
@@ -42,7 +43,8 @@ exports.activate = async function (context) {
}
});
};
- const runHandler = debug => async (request, token) => {
+ const statements = new Map();
+ const runHandler = (debug, coverage) => async (request, token) => {
const run = controller.createTestRun(request);
const queue = [];
const collect = item => item.children.size ? item.children.forEach(collect) : queue.push(item);
@@ -62,8 +64,23 @@ exports.activate = async function (context) {
if (debug) {
run.appendOutput('debug profile\r\n');
}
+ if (coverage) {
+ for (const uri of new Map(queue.map(test => [test.uri.toString(), test.uri])).values()) {
+ const lines = (await vscode.workspace.fs.readFile(uri)).toString().split('\n');
+ const covered = [];
+ lines.forEach((line, index) => {
+ if (/test\('/.test(line)) {
+ covered.push(new vscode.StatementCoverage(line.includes('fail') ? 0 : 1, new vscode.Range(index, 0, index, line.length)));
+ }
+ });
+ statements.set(uri.toString(), covered);
+ run.addCoverage(new vscode.FileCoverage(uri, new vscode.TestCoverageCount(covered.filter(statement => statement.executed).length, covered.length)));
+ }
+ }
run.end();
};
- controller.createRunProfile('Run', vscode.TestRunProfileKind.Run, runHandler(false), true);
- controller.createRunProfile('Debug', vscode.TestRunProfileKind.Debug, runHandler(true), true);
+ controller.createRunProfile('Run', vscode.TestRunProfileKind.Run, runHandler(false, false), true);
+ controller.createRunProfile('Debug', vscode.TestRunProfileKind.Debug, runHandler(true, false), true);
+ const coverage = controller.createRunProfile('Coverage', vscode.TestRunProfileKind.Coverage, runHandler(false, true), true);
+ coverage.loadDetailedCoverage = async (_run, file) => statements.get(file.uri.toString()) ?? [];
};
diff --git a/port/fixtures/ui-pair/m16/coverage.json b/port/fixtures/ui-pair/m16/coverage.json
new file mode 100644
index 00000000000..5bcca815807
--- /dev/null
+++ b/port/fixtures/ui-pair/m16/coverage.json
@@ -0,0 +1,19 @@
+[
+ { "wait": 12000 },
+ { "hotkey": ["cmd", "shift", "p"], "foreground": true },
+ { "wait": 800 },
+ { "type": "Run All Tests with Coverage" },
+ { "wait": 800 },
+ { "key": "return" },
+ { "wait": 6000 },
+ { "click": [25, 277] },
+ { "wait": 1500 },
+ { "shot": "coverage-open" },
+ { "hotkey": ["cmd", "shift", "p"], "foreground": true },
+ { "wait": 800 },
+ { "type": "Clear Coverage" },
+ { "wait": 800 },
+ { "key": "return" },
+ { "wait": 2000 },
+ { "shot": "coverage-closed" }
+]
diff --git a/port/ledger.md b/port/ledger.md
index f6e0ebccc7f..4b1e9f4b16a 100644
--- a/port/ledger.md
+++ b/port/ledger.md
@@ -602,7 +602,7 @@ One row per upstream unit, generated by `bun port/tools/gen-ledger.ts`; mileston
| workbench/contrib/telemetry | workbench contribution | M19 | verified | | the contribution logs to the NullTelemetryService and registers Show Telemetry only when supportsTelemetry, false in the built product: nothing to port; port/tools/telemetry-source-check no endpoint in 18370 shipped files (SELF_TEST finds 9 in the inert packages) |
| workbench/contrib/terminal | workbench contribution | M15 | verified | | workbench/terminal_view.rs, workbench/terminal_decorations.rs, terminal/marks.rs, terminal/serialize_html.rs, terminal/label.rs: cargo test -p app new_with_profile a_ctrl_d_exit_shows_no_exit_alert terminal::marks serialize_html terminal_decorations hover a_recording_keeps_each_kind_of_event toggle_visibility_writes_the_decorations_setting the_cwd_setting_resolves_its_variables terminal::label terminal_view::tests paths_are_quoted call_operator a_tab_row_is_inset_and_its_label_is_one_line_of_text panel_terminals_revive_in_their_groups_after_a_restart a_terminal_editor_revives_with_its_history_after_a_restart; ui-pair OSC 99, decorations, overview ruler, Copy as HTML, Record Terminal Session, terminal tabs (port/results/terminal.md), m12/folder-terminal.json (but the reference's Ports overflow, removed), m11/task-presentation.json (port/results/manage-menu.md) |
| workbench/contrib/terminalContrib | workbench contribution | M15 | verified | | terminal/link_parsing.rs, link_computer.rs, workbench/terminal_links.rs, terminal/auto_replies.rs, terminal/search.rs, workbench/terminal_find.rs, terminal/prompt_input.rs, workbench/terminal_suggest.rs, terminal/history.rs, workbench/terminal_quick_access.rs, terminal/sticky_scroll.rs, workbench/terminal_environment.rs, terminal/osc99.rs, terminal/quick_fix.rs, terminal/accessible_buffer.rs, workbench/terminal_initial_hint.rs: cargo test -p app link_ terminal::search prompt_input auto_replies terminal_contrib terminal_links terminal::history sticky_scroll quick_access environment_collection terminal::marks osc99 quick_fix accessible; ui-pair Run Recent Command, `term `, sticky scroll, the initial hint. No counterpart: Show Terminal Texture Atlas, Restart Pty Host. Removed: Copilot CLI, chat and voice (AI), wslRecommendation (Windows) (port/notes.md milestone 15) |
-| workbench/contrib/testing | workbench contribution | M16 | ported | [3 M] testing_results.rs `results_content`: a markdown message's text cannot be selected (`userSelect: text`); the content and tree split in half where the reference splits them about 2:1 (testResultsViewContent.ts `SplitView`); a plain text message's ANSI colors are stripped (`colorizeTestMessageInEditor`); a call stack frame's editor has no Cmd+click to the word's location (callStackWidget.ts `ClickToLocationContribution`); no `CoverageElement` rows | cargo test -p app testing:: testing_filter the_results_tree_shows_tasks_tests_and_messages_as_testresultstree the_results_tree_moves_its_focus_with_the_list_commands a_results_rows_menu_shows_its_actions_and_the_contributed_items an_opened_ the_gutter_menu_shows_the_tests_actions_before_the_line_number_items a_line_with_two_tests_shows_run_all_and_a_submenu_per_test reveal_in_test_explorer_expands_the_tests_parents the_run_group_dropdown_lists_its_profiles_and_runs_the_picked_one select_default_profile_stores_the_picked_defaults the_run_group_chevron_keeps_the_view_title_actions_in_the_side_bar runs_from_the_explorer_exclude_the_tests_the_filter_hides a_hidden_test_leaves_the_tree_and_runs_until_it_is_unhidden a_test_row_shows_the_test_item_menu_s_inline_group a_test_rows_context_menu_shows_and_runs_the_test_item_actions children_sort_by_line_then_by_file_name_order the_view_title_dropdown_starts_and_stops_one_profile_of_several continuous_run_using_picks_from_the_tests_controller_only a_continuous_run_holds_one_cancellable_request_per_profile_until_it_stops the_testing_item_spins view_as_list_shows_the_leaves_and_the_more_menu_checks_the_mode peek_error_opens_the_failed_childs_message_at_the_test a_test_run_waits_for_workspace_trust_and_completes_when_it_is_refused task_and_test_output_show_in_a_detached_terminal; ui-pair port/fixtures/debug-node with tests-provider (Testing tree, Run All, results tree, row menus, opened message, run glyphs and the gutter menu on port/fixtures/debug-node/math.test.js line 2, the run profile dropdown); ui-pair port/fixtures/testing-messages (diff message, markdown message output, stack trace); cargo test -p app a_contributed_inline_result_action_draws_its_icon retired_tests_take_test_result_outdated a_line_with_more_than_30_tests_picks_the_rest_from_a_quick_pick reveal_in_test_explorer_selects_and_scrolls_to_the_row the_run_group_chevron_is_active_while_its_menu_is_open the_workbench_context_has_the_testing_service_keys |
+| workbench/contrib/testing | workbench contribution | M16 | ported | [3 M] testing_results.rs `results_content`: a markdown message's text cannot be selected (`userSelect: text`); the content and tree split in half where the reference splits them about 2:1 (testResultsViewContent.ts `SplitView`); a plain text message's ANSI colors are stripped (`colorizeTestMessageInEditor`); a call stack frame's editor has no Cmd+click to the word's location (callStackWidget.ts `ClickToLocationContribution`)<br>[3 L] testing_coverage_view.rs: no inline coverage (codeCoverageDecorations.ts `CoverageToolbarWidget`, `testing.toggleInlineCoverage`, the line hover, `testing.coverage.goToNextMissedLine` and `goToPreviousMissedLine`), no Filter Coverage by Test or coverage actions in the editor title (`MenuId.EditorTitle`), no percent in the Explorer (`testing.showCoverageInExplorer`), no minimap or overview ruler marks (`testing.coverageMinimapEnabled`), no declaration rows under a file in the Test Coverage view (testCoverageView.ts `DeclarationCoverageNode`), the high-contrast gutter draws fills instead of testing.css's 3px/5px borders | cargo test -p app testing:: testing_filter coverage the_results_tree_shows_tasks_tests_and_messages_as_testresultstree the_results_tree_moves_its_focus_with_the_list_commands a_results_rows_menu_shows_its_actions_and_the_contributed_items an_opened_ the_gutter_menu_shows_the_tests_actions_before_the_line_number_items a_line_with_two_tests_shows_run_all_and_a_submenu_per_test reveal_in_test_explorer_expands_the_tests_parents the_run_group_dropdown_lists_its_profiles_and_runs_the_picked_one select_default_profile_stores_the_picked_defaults the_run_group_chevron_keeps_the_view_title_actions_in_the_side_bar runs_from_the_explorer_exclude_the_tests_the_filter_hides a_hidden_test_leaves_the_tree_and_runs_until_it_is_unhidden a_test_row_shows_the_test_item_menu_s_inline_group a_test_rows_context_menu_shows_and_runs_the_test_item_actions children_sort_by_line_then_by_file_name_order the_view_title_dropdown_starts_and_stops_one_profile_of_several continuous_run_using_picks_from_the_tests_controller_only a_continuous_run_holds_one_cancellable_request_per_profile_until_it_stops the_testing_item_spins view_as_list_shows_the_leaves_and_the_more_menu_checks_the_mode peek_error_opens_the_failed_childs_message_at_the_test a_test_run_waits_for_workspace_trust_and_completes_when_it_is_refused task_and_test_output_show_in_a_detached_terminal a_contributed_inline_result_action_draws_its_icon retired_tests_take_test_result_outdated a_line_with_more_than_30_tests_picks_the_rest_from_a_quick_pick reveal_in_test_explorer_selects_and_scrolls_to_the_row the_run_group_chevron_is_active_while_its_menu_is_open the_workbench_context_has_the_testing_service_keys; ui-pair port/fixtures/debug-node with tests-provider (Testing tree, Run All, results tree, row menus, opened message, run glyphs and the gutter menu on math.test.js line 2, the run profile dropdown); ui-pair port/fixtures/testing-messages (diff message, markdown message output, stack trace); ui-pair m16/coverage.json |
| workbench/contrib/themes | workbench contribution | M9 | verified | | Color Theme picker (`workbench.action.selectTheme`, Cmd+K Cmd+T): rows, order and descriptions as the reference, 200ms preview, Escape restores, accept writes `workbench.colorTheme`; File Icon Theme picker (`workbench.action.selectIconTheme`, Themes submenu): None and the installed themes, preview, Escape restores, accept writes `workbench.iconTheme` (null for None) (cargo test -p app themes); Product Icon Theme picker (`workbench.action.selectProductIconTheme`, Themes submenu): Default and the installed themes, writes `workbench.productIconTheme` (cargo test -p app product_icon; product-icons-pair `picker`: the same rows, except the reference's "Test Product Icon Theme" of vscode-colorize-tests, a test extension the port does not ship); no Marketplace browsing, no `window.autoDetectColorScheme` |
| workbench/contrib/timeline | workbench contribution | M14 | verified | | Timeline view (workbench/timeline_view.rs, timeline.rs): active editor and workspace timelines, paging, follow active editor, excluded sources in profile storage, compare selected, keyboard, `timeline/item/context` and title menus: cargo test -p app timeline; the title toolbar is a tab stop between the pane header and the tree (Shift+Tab focuses its first action with its hover, Left/Right, Enter): cargo test -p app shift_tab_reaches_the_title_toolbar; ui-pair m12/timeline.json header step matches; item labels draw their `$(icon)`s (cargo test -p app an_item_label_draws_its_icons); a `null` `timeline.pageSize` follows the view height (cargo test -p app a_null_page_size_follows_the_view_height) |
| workbench/contrib/typeHierarchy | workbench contribution | M13 | verified | | Peek Type Hierarchy in workbench/hierarchy_peek.rs: supertypes/subtypes toggle, layout `typeHierarchyPeekLayout`, the focused message of an empty answer, `_executePrepareTypeHierarchy`, `_executeProvideSupertypes`, `_executeProvideSubtypes`; cargo test -p app hierarchy; ui-pair port/results/language-features.md (Type hierarchy) |
diff --git a/port/notes.md b/port/notes.md
index 704a4d68f71..67eda1d75cd 100644
--- a/port/notes.md
+++ b/port/notes.md
@@ -891,7 +891,8 @@ Scope as in the M19 Work row of port/ledger.md.
- Extension host debugging (`extensionHost` launch type; rawDebugSession.ts `launchVsCode`, localProcessExtensionHost.ts `attachSession`, debugService.ts `onAttachSession`): js-debug's `launchVSCode` opens the Extension Development Host window (or reloads the one on the same extension path) with `--debugId`, `--inspect-brk-extensions` and `--extensionEnvironment`; the host it starts has the session attach to the inspector port on a new adapter. Decision: a host with an inspector port runs on Node, since Bun has no V8 inspector; a host without one stays on Bun, and there is no 5870 default port (environmentService.ts gives one to a build from source, which would put every checkout run on Node). The window closes with its current host's exit and at the end of a 'Run Without Debugging' session; a restart reloads it. Check: `cargo test -p app workbench::host::`, ui-pair `debug/extension-host.json` with `FOLDER=port/fixtures/debug-extension` (stops at the breakpoint in `activate`).
- Debug visualizers (`workbench/debug_visualizers.rs`): a visualizer contributed with a Uri `iconPath` draws an empty button in the reference too: variablesView.ts builds the action with `class: v.iconClass || 'debug-viz-icon'`, reads no `iconPath`, and no stylesheet of 1.147.0 names `debug-viz-icon` (cargo test -p app debug_visualizers).
- View Binary Data (`workbench/debug_memory.rs`; variablesView.ts `VIEW_MEMORY_ID`, debugMemory.ts): the `vscode-debug-memory` provider lives in the workbench, and `exthost/src/main_thread_files.rs` asks it through `ask_workbench`. The answer waits on the workbench's own `readMemory` to js-debug, so `Session::ask_workbench` flushes the workbench's queued host calls while it waits; before that the hex editor's read hung on its LOADING placeholders. The provider has only `FileOpenReadWriteClose`, so upstream's file service reads with `read`, which ends the file at the first unreadable byte; the port's `readFile` returns that prefix. The range comes from an extension: it must be ordered, end at most at 2^53-1 and span at most 16 MiB. Inline row buttons show on hover or focus through `hidden()`/`flex()`: a `group_hover` display change skips prepaint and panics. ui-pair `debug/memory.json` needs `ms-vscode.hexeditor` 1.11.1 from Open VSX in `<dir>`, `ARGS="--extensions-dir <dir>"` and `FOLDER=port/fixtures/debug-node`. The hex editor's breadcrumbs are `3 > memory.bin` (breadcrumbsControl.ts takes a custom editor's resource of any scheme with a file system provider, `custom_editor_resource`): a resource of a scheme other than `file` and `vscode-userdata` has no workspace folder or `~` item, and its pickers list nothing, as debugMemory.ts `stat` makes every folder a file (cargo test -p app a_custom_editor_on_a_debug_memory_resource_has_breadcrumbs). shortcut: Space on its file item opens the resource as a text file without the session authority, which cannot be read; upgrade when breadcrumb elements keep the URI.
-- Checks: `cargo test -p app debug` and `cargo test -p app testing::`; api-tests `MOCHA_GREP="vscode API - debug"`; `port/fixtures/debug-node` (app.js with launch.json, math.test.js) with `port/fixtures/extensions/tests-provider` through `port/tools/ui-pair`.
+- Test coverage (`testing_coverage.rs`, `workbench/testing_coverage_view.rs`): `$appendCoverage` keeps each task's `TestCoverage` (testCoverage.ts) on `RunTask.coverage`, a prefix tree keyed by scheme, authority and path segments (lower-cased `file` paths on macOS, `extUri.ignorePathCasing`) whose folder nodes sum their files' counts, and the result's `hasCoverage` follows it. `$getCoverageDetails(resultId, taskIndex, uri)` answers from the extension host by the file's id, `[]` for an unknown file. testCoverageService.ts: a completed run opens its first task's coverage without focus, else closes it; `selected` is the result id and task id, gone with the result. The results tree's `CoverageElement` is a task's first child ("View Test Coverage" opens with focus on the Testing container, "Close Test Coverage" closes), with no twistie (`hideTwistiesOfChildlessElements`). The Test Coverage view (`workbench.view.testCoverage`, `when` `testing.isTestCoverageOpen`, after the Test Explorer; the Test Explorer's title gains Run Tests with Coverage, `CoverageSelectedAction`, once a coverage profile exists) lists from the root the first node that is a file or has several children, folders with one folder child on one row, sorted by location, name or coverage, each with the displayed percent and the statement, declaration and branch bars of testCoverageBars.ts; its title has Change Sort Order, Collapse All, Clear Coverage and, with per-test data, Filter Coverage by Test. The gutter (codeCoverageDecorations.ts `lineNumberClassName`) fills a line number covered, uncovered or striped from the file's statement and branch details, loaded once per file and test filter; `Transparent` colors clamp alpha at 1 as `RGBA` does (`testing.uncoveredGutterBackground` is the removed-text color at 1.5). The tests-provider fixture's Coverage profile reports each test line as a statement, covered when the test passed, with `loadDetailedCoverage` and `loadDetailedCoverageForTest`. ui-pair `port/fixtures/ui-pair/m16/coverage.json` on `port/fixtures/debug-node`.
+- Checks: `cargo test -p app debug`, `cargo test -p app testing::` and `cargo test -p app coverage`; api-tests `MOCHA_GREP="vscode API - debug"`; `port/fixtures/debug-node` (app.js with launch.json, math.test.js) with `port/fixtures/extensions/tests-provider` through `port/tools/ui-pair`.
## Milestone 11 windows: dialogs, lifecycle, hot exit, windows, title bar