Visual Studio Code, rebuilt in Rust
Rust
//! The testing service of the workbench: mainThreadTesting.ts (the extension host's side), testServiceImpl.ts
//! (runs by profile), testProfileService.ts and testResultService.ts (the live results, published to the host
//! when they complete).
use std::collections::HashMap;
use exthost::session::ForwardedRequest;
use gpui::{Context, Task, Window};
use serde_json::{Value, json};
use super::Workbench;
use crate::commands::Outcome;
use super::testing_item_menu::HAS_NON_DEFAULT_PROFILE;
use crate::testing::{GROUP_COVERAGE, GROUP_DEBUG, GROUP_RUN, Profile, ResultState, TestCollection, TestResult, default_profile};
/// testTypes.ts `TestControllerCapability`.
pub(super) const CAPABILITY_REFRESH: u64 = 1 << 1;
const CAPABILITY_CODE_RELATED_TO_TEST: u64 = 1 << 2;
const CAPABILITY_TEST_RELATED_TO_CODE: u64 = 1 << 3;
/// A `$registerTestController` registration: its label and `TestControllerCapability` bits.
#[derive(Clone, Debug)]
pub struct Controller {
pub label: String,
pub capabilities: u64,
}
#[derive(Default)]
pub struct TestingService {
pub controllers: HashMap<String, Controller>,
pub collection: TestCollection,
pub profiles: Vec<Profile>,
/// Newest first, as testResultService.ts keeps them.
pub results: Vec<TestResult>,
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,
subscribed: bool,
next_run: u64,
}
impl TestingService {
pub fn result_mut(&mut self, id: &str) -> Option<&mut TestResult> {
self.results.iter_mut().find(|result| result.id == id)
}
/// The state of a test in the newest result that ran it (`testResultService.getStateById`).
pub fn state_of(&self, id: &str) -> Option<ResultState> {
self.results.iter().find(|result| result.items.contains_key(id)).map(|result| result.computed_state(id))
}
/// Whether the newest result with the test has it retired (treeProjection.ts `item.retired`).
pub fn is_retired(&self, id: &str) -> bool {
self.results.iter().find(|result| result.items.contains_key(id)).is_some_and(|result| result.items[id].retired)
}
pub fn is_running(&self) -> bool {
self.results.iter().any(|result| result.completed_at.is_none())
}
/// `testResultService.createLiveResult`; testResultService.ts keeps the newest 128 results.
fn create_result(&mut self, id: Option<String>, request: Value) -> String {
let id = id.unwrap_or_else(|| {
self.next_run += 1;
format!("r{}-{}", std::process::id(), self.next_run)
});
self.results.insert(0, TestResult::new(id.clone(), request));
self.results.truncate(128);
id
}
}
fn now_millis() -> u64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |elapsed| elapsed.as_millis() as u64)
}
impl Workbench {
/// The workbench's testingContextKeys.ts keys of testServiceImpl.ts, testProfileService.ts `refreshContextKeys`
/// and testResultService.ts.
pub(super) fn testing_service_context(&self, context: &mut HashMap<String, Value>) {
let testing = &self.testing;
let any_controller = |capability: u64| json!(testing.controllers.values().any(|controller| controller.capabilities & capability != 0));
let mut profiles = 0;
for profile in &testing.profiles {
profiles |= if profiles & profile.group != 0 { HAS_NON_DEFAULT_PROFILE } else { profile.group };
}
let active_editor_has_tests = self.editors.active().is_some_and(|editor| testing.collection.tests_in_file(&editor.document().path.to_string_lossy()).next().is_some());
for (key, value) in [
("testing.providerCount", json!(testing.controllers.len())),
("testing.canRefresh", any_controller(CAPABILITY_REFRESH)),
("testing.canGoToRelatedCode", any_controller(CAPABILITY_CODE_RELATED_TO_TEST)),
("testing.canGoToRelatedTest", any_controller(CAPABILITY_TEST_RELATED_TO_CODE)),
("testing.isRefreshing", json!(!testing.refreshes.is_empty())),
("testing.activeEditorHasTests", json!(active_editor_has_tests)),
("testing.hasRunnableTests", json!(profiles & GROUP_RUN != 0)),
("testing.hasDebuggableTests", json!(profiles & GROUP_DEBUG != 0)),
("testing.hasCoverableTests", json!(profiles & GROUP_COVERAGE != 0)),
("testing.hasNonDefaultProfile", json!(profiles & HAS_NON_DEFAULT_PROFILE != 0)),
// `refreshContextKeys` never sets the `HasConfigurable` bit in 1.147.0.
("testing.hasConfigurableProfile", json!(false)),
("testing.hasAnyResults", json!(!testing.results.is_empty())),
("testing.isRunning", json!(testing.is_running())),
] {
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
/// they answer.
pub(super) fn refresh_tests(&mut self, controllers: &[String], cx: &mut Context<Self>) {
let all: Vec<String>;
let controllers = if controllers.is_empty() {
all = self.testing.controllers.keys().cloned().collect();
&all
} else {
controllers
};
let replies: Vec<_> = controllers.iter().map(|id| self.host.call_cancellable("ExtHostTesting", "$refreshTests", vec![json!(id)])).collect();
let id = self.testing.next_refresh;
self.testing.next_refresh += 1;
let task = cx.spawn(async move |this, cx| {
futures::future::join_all(replies).await;
let _ = this.update(cx, |workbench, cx| {
workbench.testing.refreshes.remove(&id);
cx.notify();
});
});
self.testing.refreshes.insert(id, task);
cx.notify();
}
/// MainThreadTesting's methods.
pub(crate) fn handle_testing_request(&mut self, request: ForwardedRequest, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
let args = request.args;
let arg = |index: usize| args.get(index).cloned().unwrap_or(Value::Null);
let text = |index: usize| args.get(index).and_then(Value::as_str).unwrap_or_default().to_owned();
let testing = &mut self.testing;
match request.method.as_str() {
"$registerTestController" => _ = testing.controllers.insert(text(0), Controller { label: text(1), capabilities: arg(2).as_u64().unwrap_or_default() }),
"$updateController" => {
if let Some(controller) = testing.controllers.get_mut(&text(0)) {
if let Some(label) = arg(1)["label"].as_str() {
controller.label = label.to_owned();
}
if let Some(capabilities) = arg(1)["capabilities"].as_u64() {
controller.capabilities = capabilities;
}
}
}
"$unregisterTestController" => {
let id = text(0);
testing.controllers.remove(&id);
testing.profiles.retain(|profile| profile.controller_id != id);
let diff = [json!({ "op": 3, "itemId": id })];
testing.collection.apply(&diff);
if testing.subscribed {
self.host.send("ExtHostTesting", "$acceptDiff", vec![json!(diff)]);
}
}
"$subscribeToDiffs" => {
testing.subscribed = true;
let diff = testing.collection.reviver_diff();
self.host.send("ExtHostTesting", "$acceptDiff", vec![json!(diff)]);
}
"$unsubscribeFromDiffs" => testing.subscribed = false,
"$publishDiff" => {
let diff = arg(1).as_array().cloned().unwrap_or_default();
for root in testing.collection.apply(&diff) {
// treeProjection.ts `storeItem`: a controller root expands at once, which resolves its children.
self.host.send("ExtHostTesting", "$expandTest", vec![json!(root), json!(0)]);
}
if testing.subscribed {
self.host.send("ExtHostTesting", "$acceptDiff", vec![json!(diff)]);
}
}
"$publishTestRunProfile" => {
let mut profile = Profile::from_value(&arg(0));
if let Some(is_default) = super::testing_profiles::stored_profile_default(&self.workspace_storage.lock().unwrap(), &profile) {
profile.is_default = is_default;
}
if testing.controllers.contains_key(&profile.controller_id) {
testing.profiles.retain(|existing| (existing.controller_id.as_str(), existing.profile_id) != (profile.controller_id.as_str(), profile.profile_id));
testing.profiles.push(profile);
self.send_default_profiles();
}
}
"$updateTestRunConfig" => {
let (controller, id) = (text(0), arg(1).as_i64());
if let Some(profile) = testing.profiles.iter_mut().find(|profile| profile.controller_id == controller && Some(profile.profile_id) == id) {
profile.update(&arg(2));
if arg(2)["isDefault"].is_boolean() {
super::testing_profiles::store_profile_default(&mut self.workspace_storage.lock().unwrap(), profile);
}
}
self.send_default_profiles();
}
"$removeTestProfile" => {
let (controller, id) = (text(0), arg(1).as_i64());
testing.profiles.retain(|profile| !(profile.controller_id == controller && Some(profile.profile_id) == id));
self.send_default_profiles();
}
"$runTests" => {
let id = self.run_resolved_tests(arg(0), window, cx);
return Outcome::Ready(Ok(json!(id)));
}
"$startedExtensionTestRun" => {
let request = arg(0);
let targets = json!({ "group": request["profile"]["group"].as_u64().unwrap_or(GROUP_RUN), "targets": [{ "testIds": request["include"], "controllerId": request["controllerId"], "profileId": request["profile"]["id"] }] });
testing.create_result(request["id"].as_str().map(str::to_owned), targets);
}
"$startedTestRunTask" => {
if let Some(result) = testing.result_mut(&text(0)) {
result.add_task(&arg(1));
}
}
"$finishedTestRunTask" => {
if let Some(result) = testing.result_mut(&text(0)) {
result.mark_task_complete(&text(1));
}
}
"$finishedExtensionTestRun" => self.finish_test_run(&text(0), cx),
"$applyTestRunUpdates" => {
let run = text(1);
for update in arg(2).as_array().into_iter().flatten() {
self.apply_test_run_update(&run, update);
}
}
"$addTestsToRun" => self.apply_test_run_update(&text(1), &json!({ "type": "tests", "tests": arg(2) })),
"$updateTestStateInRun" => self.apply_test_run_update(&text(0), &json!({ "type": "state", "taskId": arg(1), "testId": arg(2), "state": arg(3), "duration": arg(4) })),
"$appendTestMessagesInRun" => self.apply_test_run_update(&text(0), &json!({ "type": "messages", "taskId": arg(1), "testId": arg(2), "messages": arg(3) })),
"$appendOutputToRun" => self.apply_test_run_update(&text(0), &json!({ "type": "output", "taskId": arg(1), "output": arg(2), "location": arg(3), "testId": arg(4) })),
"$markTestRetired" => {
if let Ok(test_ids) = serde_json::from_value::<Option<Vec<String>>>(arg(0)) {
for result in &mut testing.results {
result.mark_retired(test_ids.as_deref());
}
}
}
"$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") {
self.continuous_profiles_changed(window, cx);
}
cx.notify();
Outcome::done()
}
/// `TestRunUpdate`s of a run: tests added, a state, messages or output.
fn apply_test_run_update(&mut self, run: &str, update: &Value) {
let Some(result) = self.testing.result_mut(run) else { return };
let text = |key: &str| update[key].as_str().unwrap_or_default();
match text("type") {
"tests" => result.add_chain(update["tests"].as_array().map_or(&[], Vec::as_slice)),
"state" => result.update_state(text("testId"), text("taskId"), ResultState::from_value(&update["state"]), update["duration"].as_f64()),
"messages" => {
for message in update["messages"].as_array().into_iter().flatten() {
result.append_message(text("testId"), text("taskId"), message.clone());
}
}
"output" => {
// A string, or a VSBuffer the session turned into its bytes.
let output = match &update["output"] {
Value::String(output) => output.clone(),
bytes => String::from_utf8_lossy(&bytes.as_array().into_iter().flatten().filter_map(|byte| byte.as_u64().map(|byte| byte as u8)).collect::<Vec<u8>>()).into_owned(),
};
let test = update["testId"].as_str();
result.append_output(text("taskId"), &output, (!update["location"].is_null()).then(|| update["location"].clone()), test);
self.test_output_changed(run);
}
_ => {}
}
}
/// `markComplete` and the `$publishTestResults` of testResultService.ts's `onResultsChanged`.
fn finish_test_run(&mut self, run: &str, cx: &mut Context<Self>) {
let Some(result) = self.testing.result_mut(run) else { return };
if result.completed_at.is_some() {
return;
}
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);
}
/// mainThreadTesting.ts `onDidChange` of the profiles: `$setDefaultRunProfiles`.
pub(super) fn send_default_profiles(&self) {
let mut defaults: HashMap<String, Vec<i64>> = HashMap::new();
for group in [GROUP_RUN, GROUP_DEBUG, GROUP_COVERAGE] {
for profile in self.testing.profiles.iter().filter(|profile| profile.group & group != 0 && profile.is_default) {
defaults.entry(profile.controller_id.clone()).or_default().push(profile.profile_id);
}
}
self.host.send("ExtHostTesting", "$setDefaultRunProfiles", vec![json!(defaults)]);
}
/// testServiceImpl.ts `runTests`: the tests grouped by the profile of the group that runs each of them.
/// Without `exclude`, the run excludes the hidden tests (`runResolvedTests`).
pub(crate) fn run_tests(&mut self, test_ids: &[String], exclude: Option<&[String]>, group: u64, window: &mut Window, cx: &mut Context<Self>) -> Option<String> {
let mut targets: Vec<(String, i64, Vec<String>)> = Vec::new();
for id in test_ids {
let Some(test) = self.testing.collection.items.get(id) else { continue };
let Some(profile) = default_profile(&self.testing.profiles, group, test) else { continue };
match targets.iter_mut().find(|(controller, profile_id, _)| *controller == profile.controller_id && *profile_id == profile.profile_id) {
Some((_, _, ids)) => ids.push(id.clone()),
None => targets.push((profile.controller_id.clone(), profile.profile_id, vec![id.clone()])),
}
}
if targets.is_empty() {
return None;
}
let targets: Vec<Value> = targets.into_iter().map(|(controller, profile, ids)| json!({ "controllerId": controller, "profileId": profile, "testIds": ids })).collect();
let mut request = json!({ "group": group, "targets": targets });
if let Some(exclude) = exclude {
request["exclude"] = json!(exclude);
}
Some(self.run_resolved_tests(request, window, cx))
}
/// `runResolvedTests`: a live result, the workspace trust request, then `$runControllerTests` for each
/// controller; the result completes when every controller answers, or at once without trust.
pub(super) fn run_resolved_tests(&mut self, mut request: Value, window: &mut Window, cx: &mut Context<Self>) -> String {
if request.get("exclude").is_none() {
request["exclude"] = json!(self.testing.excluded);
}
let run = self.testing.create_result(None, request.clone());
self.show_test_results_on_start(&run, cx);
let trust = match self.request_workspace_trust(&json!({ "message": "Running tests may execute code in your workspace." }), window, cx) {
Outcome::Ready(answer) => {
self.run_trusted_tests(&run, &request, matches!(answer, Ok(Value::Bool(true))), cx);
return run;
}
Outcome::Pending(answer) => answer,
};
let id = run.clone();
cx.spawn(async move |this, cx| {
let trusted = matches!(trust.await, Ok(Ok(Value::Bool(true))));
let _ = this.update(cx, |workbench, cx| workbench.run_trusted_tests(&id, &request, trusted, cx));
})
.detach();
run
}
fn run_trusted_tests(&mut self, run: &str, request: &Value, trusted: bool, cx: &mut Context<Self>) {
if !trusted {
self.finish_test_run(run, cx);
return;
}
let exclude = request["exclude"].as_array().cloned().unwrap_or_default();
let mut by_controller: HashMap<String, Vec<Value>> = HashMap::new();
for target in request["targets"].as_array().into_iter().flatten() {
let controller = target["controllerId"].as_str().unwrap_or_default().to_owned();
let ids = target["testIds"].as_array().cloned().unwrap_or_default();
let exclude: Vec<&Value> = exclude.iter().filter(|id| !ids.contains(id)).collect();
by_controller.entry(controller.clone()).or_default().push(json!({ "runId": run, "excludeExtIds": exclude, "profileId": target["profileId"], "controllerId": controller, "testIds": ids }));
}
let replies: Vec<_> = by_controller.into_values().map(|requests| self.host.call("ExtHostTesting", "$runControllerTests", vec![json!(requests)])).collect();
let finished = run.to_owned();
cx.spawn(async move |this, cx| {
let mut errors = Vec::new();
for reply in replies {
if let Ok(Ok(answers)) = reply.await {
errors.extend(answers.as_array().into_iter().flatten().filter_map(|answer| answer["error"].as_str().map(str::to_owned)));
}
}
let _ = this.update(cx, |workbench, cx| {
if !errors.is_empty() {
workbench.notify_error(format!("An error occurred attempting to run tests: {}", errors.join(" ")));
}
workbench.finish_test_run(&finished, cx);
cx.notify();
});
})
.detach();
}
/// `testing.cancelRun`: `$cancelExtensionTestRun` of the running results.
pub(crate) fn cancel_test_runs(&mut self) {
for result in self.testing.results.iter().filter(|result| result.completed_at.is_none()) {
self.host.send("ExtHostTesting", "$cancelExtensionTestRun", vec![json!(result.id), Value::Null]);
}
}
}
#[cfg(test)]
mod tests {
use std::path::Path;
use std::sync::{Arc, Mutex};
use gpui::TestAppContext;
use serde_json::json;
use crate::workbench::Workbench;
use crate::workspace_trust::{Startup, WorkspaceTrust};
#[gpui::test]
fn a_test_run_waits_for_workspace_trust_and_completes_when_it_is_refused(cx: &mut TestAppContext) {
let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
let theme = crate::theme::load_theme(&[exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "Dark Modern").unwrap();
let (sender, host) = std::sync::mpsc::channel();
let (workbench, cx) = cx.add_window_view(|_, cx| {
let mut workbench = Workbench::new(theme, app_root.clone(), None, crate::languages::Languages::new(&[]), crate::default_settings(), crate::host_sync::HostSync::new(sender), cx);
let mut storage = storage::Storage::in_memory();
let startup = Startup { enabled: true, workspace: None, empty_window_trusted: false, workspace_storage: &mut storage };
workbench.workspace_trust = WorkspaceTrust::new(Arc::new(Mutex::new(storage::Storage::in_memory())), startup);
workbench
});
let request = json!({ "group": 2, "targets": [{ "controllerId": "c", "profileId": 1, "testIds": ["t"] }] });
let mut runs = Vec::new();
for button in [2, 0] {
let run = workbench.update_in(cx, |workbench, window, cx| workbench.run_resolved_tests(request.clone(), window, cx));
cx.run_until_parked();
let asked_first = host.try_iter().all(|message| message.method != "$runControllerTests");
workbench.update(cx, |workbench, cx| workbench.close_custom_dialog(button, cx));
cx.run_until_parked();
let ran = host.try_iter().any(|message| message.method == "$runControllerTests");
let completed = workbench.read_with(cx, |workbench, _| workbench.testing.results.iter().any(|result| result.id == run && result.completed_at.is_some()));
runs.push((asked_first, ran, completed));
}
assert_eq!(runs, [(true, false, true), (true, true, false)]);
}
/// testingContextKeys.ts's workbench keys: testServiceImpl.ts's controllers and refreshes, testProfileService.ts
/// `refreshContextKeys`, testResultService.ts; `testing.providerCount > 0` shows the Test Explorer's commands.
#[gpui::test]
fn the_workbench_context_has_the_testing_service_keys(cx: &mut TestAppContext) {
let (workbench, cx, host) = crate::workbench::testing_gutter::tests::workbench_with_tests("testing-context", &[("c\0t", "t", 1)], cx);
const KEYS: [&str; 13] = [
"testing.providerCount",
"testing.canRefresh",
"testing.canGoToRelatedCode",
"testing.canGoToRelatedTest",
"testing.isRefreshing",
"testing.activeEditorHasTests",
"testing.hasRunnableTests",
"testing.hasDebuggableTests",
"testing.hasCoverableTests",
"testing.hasNonDefaultProfile",
"testing.hasConfigurableProfile",
"testing.hasAnyResults",
"testing.isRunning",
];
let state = |cx: &mut gpui::VisualTestContext| {
workbench.update_in(cx, |workbench, window, _| {
let context = workbench.key_context(window);
let focus_shown = crate::command_palette::enabled_commands(&workbench.quick_access.menu, &context, &workbench.commands).iter().any(|pick| pick.id == "workbench.view.testing.focus");
(KEYS.map(|key| context.get(key).cloned().unwrap_or_default()), focus_shown)
})
};
workbench.update(cx, |workbench, _| workbench.set_command_palette_menu(crate::command_palette::menu(&[])));
let (keys, focus_shown) = state(cx);
assert_eq!((keys[0].clone(), keys[1].clone(), focus_shown), (json!(0), json!(false), false));
workbench.update(cx, |workbench, _| {
workbench.testing.controllers.insert("c".into(), super::Controller { label: "c".into(), capabilities: super::CAPABILITY_REFRESH });
});
let (keys, focus_shown) = state(cx);
assert_eq!(keys, [json!(1), json!(true), json!(false), json!(false), json!(false), json!(true), json!(true), json!(true), json!(false), json!(true), json!(false), json!(false), json!(false)]);
assert!(focus_shown);
workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("testing.refreshTests", Vec::new(), window, cx)));
cx.run_until_parked();
let refreshes: Vec<_> = host.try_iter().filter(|message| message.method == "$refreshTests").collect();
assert_eq!(refreshes.iter().map(|message| (message.args.clone(), message.cancellable)).collect::<Vec<_>>(), [(vec![json!("c")], true)]);
assert_eq!(state(cx).0[4], json!(true), "isRefreshing holds until the controller answers");
workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("testing.cancelTestRefresh", Vec::new(), window, cx)));
cx.run_until_parked();
assert!(refreshes[0].reply.as_ref().unwrap().is_canceled());
assert_eq!(state(cx).0[4], json!(false));
workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("testing.refreshTests", Vec::new(), window, cx)));
cx.run_until_parked();
let refresh = host.try_iter().find(|message| message.method == "$refreshTests").unwrap();
refresh.reply.unwrap().send(Ok(serde_json::Value::Null)).unwrap();
cx.run_until_parked();
assert_eq!(state(cx).0[4], json!(false), "the answer ends the refresh");
workbench.update(cx, |workbench, _| drop(workbench.testing.create_result(None, json!({}))));
let (keys, _) = state(cx);
assert_eq!((keys[11].clone(), keys[12].clone()), (json!(true), json!(true)));
}
}