Skip to content

Visual Studio Code, rebuilt in Rust

Rust
11.3 KB
Raw Blame
use std::path::Path;
use std::sync::{Arc, Mutex};

use gpui::TestAppContext;
use serde_json::json;

use crate::menus::{MenuAction, MenuId, MenuItem};
use crate::quick_input::Entry;
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};

fn profile(profile_id: i64, label: &str, group: u64, is_default: bool, has_configuration_handler: bool) -> Profile {
    Profile { controller_id: "c".into(), profile_id, label: label.into(), group, is_default, tag: None, supports_continuous_run: false, has_configuration_handler }
}

/// A trusted workbench with controller "c" (labeled "Ctrl"), its root and one test, and the profiles.
fn workbench_with(profiles: Vec<Profile>, cx: &mut TestAppContext) -> (gpui::Entity<Workbench>, &mut gpui::VisualTestContext, std::sync::mpsc::Receiver<crate::host_sync::HostMessage>) {
    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: false, 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.testing.controllers.insert("c".into(), Controller { label: "Ctrl".into(), capabilities: 0 });
        workbench.testing.collection.apply(&[json!({ "op": 0, "item": { "expand": 0, "item": { "extId": "c", "label": "c", "tags": [] } } }), json!({ "op": 0, "item": { "expand": 0, "item": { "extId": "c\0t", "label": "t", "tags": [] } } })]);
        workbench.testing.profiles = profiles;
        workbench
    });
    (workbench, cx, host)
}

/// The view title's actions with a run group dropdown stay inside the side bar's title.
#[gpui::test]
fn the_run_group_chevron_keeps_the_view_title_actions_in_the_side_bar(cx: &mut TestAppContext) {
    let (workbench, cx, _host) = workbench_with(vec![profile(1, "Fast", GROUP_RUN, true, false), profile(2, "Slow", GROUP_RUN, false, 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 side_bar_right = cx.debug_bounds("testing-tree").expect("the tree draws").right();
    for selector in ["codicon-run-all", "codicon-chevron-down", "codicon-debug-alt-small", "codicon-terminal", "codicon-ellipsis"] {
        let bounds = cx.debug_bounds(selector).unwrap_or_else(|| panic!("{selector} draws"));
        assert!(bounds.origin.y < title.bottom() && bounds.right() < side_bar_right, "{selector} at {bounds:?}, title {title:?}");
    }
}

/// 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) {
    let (workbench, cx, _host) = workbench_with(vec![profile(1, "Fast", GROUP_RUN, true, false), profile(2, "Slow", GROUP_RUN, false, 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 chevron = cx.debug_bounds("codicon-chevron-down").expect("the chevron draws").center();
    cx.simulate_click(chevron, gpui::Modifiers::none());
    cx.run_until_parked();
    assert!(workbench.read_with(cx, |workbench, _| workbench.context_menu.is_some() && workbench.dropdown_open("testing-run-dropdown")));

    workbench.update_in(cx, |workbench, window, cx| {
        workbench.hide_context_menu(window, cx);
        workbench.show_run_group_dropdown(GROUP_RUN, gpui::Bounds::default(), window, cx);
    });
    assert!(!workbench.read_with(cx, |workbench, _| workbench.dropdown_open("testing-run-dropdown")), "a menu shown another way leaves the chevron inactive");
}

/// testingExplorerView.ts `getTestConfigGroupActions` for the run group of a controller with two run profiles,
/// one configurable, and a `testing/profiles/context` contribution for the run group only.
#[gpui::test]
fn the_run_group_dropdown_lists_its_profiles_and_runs_the_picked_one(cx: &mut TestAppContext) {
    let profiles = vec![profile(2, "Slow", GROUP_RUN, false, true), profile(1, "Fast", GROUP_RUN, true, false), profile(3, "Debug", GROUP_DEBUG, true, false)];
    let (workbench, cx, host) = workbench_with(profiles, cx);
    let contributed = |group: &str| MenuItem { menu: MenuId::TestProfilesContext, entry: crate::menus::Entry::Command { id: format!("ext.{group}"), precondition: None, toggled: None, alt: None }, title: format!("Ext {group}"), group: String::new(), order: 0., when: crate::contextkey::Expr::deserialize(&format!("testing.profile.context.group == {group}")) };
    workbench.update(cx, |workbench, _| workbench.menus.extend([contributed("run"), contributed("debug")]));

    let actions = workbench.update_in(cx, |workbench, window, cx| {
        workbench.show_run_group_dropdown(GROUP_RUN, gpui::Bounds::default(), window, cx);
        workbench.context_menu.as_ref().expect("the dropdown shows").levels[0].actions.clone()
    });
    let titles: Vec<(String, bool)> = actions.iter().map(|action| match action {
        MenuAction::Command { title, enabled, .. } => (title.to_string(), *enabled),
        _ => ("---".into(), true),
    }).collect();
    let item = |title: &str, enabled: bool| (title.to_owned(), enabled);
    assert_eq!(titles, [item("Ctrl", false), item("Fast (Default)", true), item("Slow", true), item("---", true), item("Ext run", true), item("---", true), item("Select Default Profile", true), item("Configure Test Profiles", true)]);

    let MenuAction::Command { id, .. } = &actions[2] else { unreachable!() };
    let id = id.clone();
    workbench.update_in(cx, |workbench, window, cx| {
        workbench.hide_context_menu(window, cx);
        drop(workbench.execute_command(&id, Vec::new(), window, cx));
    });
    cx.run_until_parked();
    let runs: Vec<_> = host.try_iter().filter(|message| message.method == "$runControllerTests").map(|message| message.args[0][0].clone()).collect();
    assert_eq!(runs.iter().map(|run| (run["profileId"].clone(), run["testIds"].clone())).collect::<Vec<_>>(), [(json!(2), json!(["c"]))]);
}

/// testExplorerActions.ts `SelectDefaultTestProfiles`: the group's profiles with its defaults picked; the accepted
/// ones become the defaults, a same-named profile of another group follows, and the choice is stored and outlives
/// the extension publishing the profile again (testProfileService.ts `addProfile`).
#[gpui::test]
fn select_default_profile_stores_the_picked_defaults(cx: &mut TestAppContext) {
    let profiles = vec![profile(1, "Fast", GROUP_RUN, true, false), profile(2, "Slow", GROUP_RUN, false, false), profile(3, "Slow", GROUP_DEBUG, false, false)];
    let (workbench, cx, host) = workbench_with(profiles, cx);
    workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("testing.selectDefaultTestProfiles", vec![json!(GROUP_RUN)], window, cx)));
    cx.run_until_parked();
    let shown = workbench.update_in(cx, |workbench, window, cx| {
        let input = workbench.quick_inputs.current().expect("the picker shows");
        let shown: Vec<(String, Option<String>, bool)> = input.items().iter().map(|entry| match entry {
            Entry::Item(item) => (item.label.clone(), item.description.clone(), input.selected_handles().contains(&item.handle)),
            other => (format!("{other:?}"), None, false),
        }).collect();
        let id = input.id;
        let input = workbench.quick_inputs.get_mut(id).unwrap();
        input.set_selected_items(&[1]);
        input.accept_from_ui();
        workbench.flush_quick_input_events(window, cx);
        shown
    });
    cx.run_until_parked();
    let item = |label: &str, picked: bool| (label.to_owned(), Some("Ctrl".to_owned()), picked);
    assert_eq!(shown, [item("Fast", true), item("Slow", false)], "one group shows without a header");

    let defaults = workbench.read_with(cx, |workbench, _| workbench.testing.profiles.iter().map(|profile| (profile.profile_id, profile.is_default)).collect::<Vec<_>>());
    assert_eq!(defaults, [(1, false), (2, true), (3, true)]);
    let stored = workbench.read_with(cx, |workbench, _| workbench.workspace_storage.lock().unwrap().get("testingPreferredProfiles2").map(str::to_owned));
    assert_eq!(stored.map(|stored| serde_json::from_str::<serde_json::Value>(&stored).unwrap()), Some(json!({ "c": { "1": false, "2": true, "3": true } })));
    let sent: Vec<_> = host.try_iter().filter(|message| message.method == "$setDefaultRunProfiles").map(|message| message.args[0].clone()).collect();
    assert_eq!(sent.last(), Some(&json!({ "c": [2, 3] })));

    workbench.update_in(cx, |workbench, window, cx| {
        workbench.testing.profiles.clear();
        let published = json!({ "controllerId": "c", "profileId": 1, "label": "Fast", "group": GROUP_RUN, "isDefault": true });
        let request = exthost::session::ForwardedRequest { req: 1, proxy: "MainThreadTesting", method: "$publishTestRunProfile".into(), args: vec![published] };
        drop(workbench.handle_testing_request(request, window, cx));
    });
    let republished = workbench.read_with(cx, |workbench, _| workbench.testing.profiles.iter().map(|profile| (profile.profile_id, profile.is_default)).collect::<Vec<_>>());
    assert_eq!(republished, [(1, false)]);
}