Skip to content

Visual Studio Code, rebuilt in Rust

Rust
12.9 KB
Raw Blame
use std::cell::RefCell;
use std::path::Path;
use std::rc::Rc;
use std::sync::mpsc::Receiver;
use std::sync::{Arc, Mutex};

use gpui::{TestAppContext, VisualTestContext, point, px};
use serde_json::{Value, json};

use crate::commands::Outcome;
use crate::host_sync::HostMessage;
use crate::menus::{Entry, MenuAction, MenuId, MenuItem};
use crate::testing::{GROUP_DEBUG, GROUP_RUN, Profile};
use crate::workbench::Workbench;
use crate::workspace_trust::{Startup, WorkspaceTrust};

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

pub(in crate::workbench) fn contributed(menu: MenuId, command: &str, title: &str) -> MenuItem {
    MenuItem { menu, entry: Entry::Command { id: command.into(), precondition: None, toggled: None, alt: None }, title: title.into(), group: String::new(), order: 0., when: None }
}

/// A workbench with `test.js` open and the tests `(id, label, line)` of controller `c` in it.
pub(in crate::workbench) fn workbench_with_tests<'a>(name: &str, tests: &[(&str, &str, u32)], cx: &'a mut TestAppContext) -> (gpui::Entity<Workbench>, &'a mut VisualTestContext, Receiver<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 dir = std::env::temp_dir().join(format!("code-gpui-{name}-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("test.js");
    std::fs::write(&file, "test('t', () => {});\n\ntest('u', () => {});\n").unwrap();
    let (sender, host) = std::sync::mpsc::channel();
    let tests: Vec<(String, String, u32)> = tests.iter().map(|(id, label, line)| (id.to_string(), label.to_string(), *line)).collect();
    let (workbench, cx) = cx.add_window_view(|window, 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.open_file(file.clone(), true, window, cx);
        let uri = workbench.editors.active().unwrap().document().uri();
        let mut ops = vec![json!({ "op": 0, "item": { "expand": 0, "item": { "extId": "c", "label": "c", "tags": [] } } })];
        for (id, label, line) in &tests {
            let range = json!({ "startLineNumber": line, "startColumn": 1, "endLineNumber": line, "endColumn": 2 });
            let item = if *line == 0 { json!({ "extId": id, "label": label, "tags": [] }) } else { json!({ "extId": id, "label": label, "tags": [], "uri": uri, "range": range }) };
            ops.push(json!({ "op": 0, "item": { "expand": 0, "item": item } }));
        }
        workbench.testing.collection.apply(&ops);
        workbench.testing.profiles = vec![profile(1, "Run", GROUP_RUN, true), profile(2, "Run Slow", GROUP_RUN, false), profile(3, "Debug", GROUP_DEBUG, true)];
        workbench
    });
    cx.run_until_parked();
    std::fs::remove_dir_all(dir).unwrap();
    (workbench, cx, host)
}

pub(in crate::workbench) fn titles(actions: &[MenuAction]) -> Vec<String> {
    actions
        .iter()
        .map(|action| match action {
            MenuAction::Command { title, .. } => title.clone(),
            MenuAction::Submenu { title, .. } => format!("{title} >"),
            MenuAction::Separator => "---".into(),
        })
        .collect()
}

pub(in crate::workbench) fn command_titled(actions: &[MenuAction], wanted: &str) -> String {
    actions.iter().find_map(|action| match action {
        MenuAction::Command { id, title, .. } if title == wanted => Some(id.clone()),
        _ => None,
    }).unwrap_or_else(|| panic!("no {wanted} in {:?}", titles(actions)))
}

/// testingDecorations.ts `getTestContextMenuActions` in editorLineNumberMenu.ts's menu: the test's actions, its
/// `testing/item/gutter` items with the test as argument, then the `editor/lineNumber/context` items. The test's items
/// run on it, not on the line's `{ lineNumber, uri }`.
#[gpui::test]
fn the_gutter_menu_shows_the_tests_actions_before_the_line_number_items(cx: &mut TestAppContext) {
    let (workbench, cx, host) = workbench_with_tests("test-gutter-menu", &[("c\0t", "t", 1)], cx);
    let received = Rc::new(RefCell::new(Vec::new()));
    let sink = received.clone();
    workbench.update(cx, |workbench, _| {
        workbench.menus.push(contributed(MenuId::TestItemGutter, "ext.gutter", "Ext Gutter"));
        workbench.menus.push(contributed(MenuId::EditorLineNumberContext, "ext.line", "Ext Line"));
        workbench.commands.register("ext.gutter", move |_, args, _, _| {
            sink.borrow_mut().push(args);
            Outcome::done()
        });
    });

    let actions = workbench.update_in(cx, |workbench, window, cx| {
        workbench.show_line_number_context_menu(0, point(px(10.), px(40.)), false, window, cx);
        workbench.context_menu.as_ref().expect("a context menu shows").levels[0].actions.clone()
    });
    assert_eq!(titles(&actions), ["Run Test", "Debug Test", "Execute Using Profile...", "Reveal in Test Explorer", "---", "Ext Gutter", "---", "Ext Line"]);

    workbench.update_in(cx, |workbench, window, cx| {
        workbench.hide_context_menu(window, cx);
        let line_arg = vec![json!({ "lineNumber": 1 })];
        drop(workbench.execute_command(&command_titled(&actions, "Ext Gutter"), line_arg.clone(), window, cx));
        drop(workbench.execute_command(&command_titled(&actions, "Run Test"), line_arg, window, cx));
    });
    cx.run_until_parked();
    let tests_of = |args: &Value| args["tests"].as_array().unwrap().iter().map(|test| test["item"]["extId"].clone()).collect::<Vec<_>>();
    assert_eq!(received.borrow().iter().map(|args| tests_of(&args[0])).collect::<Vec<_>>(), [vec![json!("c\0t")]]);
    let runs: Vec<_> = host.try_iter().filter(|message| message.method == "$runControllerTests").map(|message| message.args[0][0]["testIds"].clone()).collect();
    assert_eq!(runs, [json!(["c\0t"])]);
}

/// `MultiRunTestDecoration.getContextMenuActions`: the groups for all of the line's tests, then a submenu per test,
/// labeled with its parents while two labels are the same.
#[gpui::test]
fn a_line_with_two_tests_shows_run_all_and_a_submenu_per_test(cx: &mut TestAppContext) {
    let (workbench, cx, _host) = workbench_with_tests("test-gutter-multi", &[("c\0u", "u", 0), ("c\0s", "s", 0), ("c\0u\0t", "t", 3), ("c\0s\0t", "t", 3)], cx);
    let actions = workbench.update_in(cx, |workbench, window, _| workbench.test_gutter_actions(3, window));
    assert_eq!(titles(&actions), ["Run All Tests", "Debug All Tests", "---", "s > t >", "u > t >"]);
    let MenuAction::Submenu { actions: submenu, .. } = &actions[3] else { panic!("a submenu per test") };
    assert_eq!(titles(submenu), ["Run Test", "Debug Test", "Execute Using Profile...", "Reveal in Test Explorer"]);
}

/// testingDecorations.ts `MAX_TESTS_IN_SUBMENU`: past 30 tests the line's menu ends in "{0} more tests...", whose
/// `pickAndRun` picks one of all the tests, then one of its actions.
#[gpui::test]
fn a_line_with_more_than_30_tests_picks_the_rest_from_a_quick_pick(cx: &mut TestAppContext) {
    let ids: Vec<(String, String)> = (0..31).map(|index| (format!("c\0t{index:02}"), format!("t{index:02}"))).collect();
    let tests: Vec<(&str, &str, u32)> = ids.iter().map(|(id, label)| (id.as_str(), label.as_str(), 3)).collect();
    let (workbench, cx, host) = workbench_with_tests("test-gutter-overflow", &tests, cx);
    let actions = workbench.update_in(cx, |workbench, window, _| workbench.test_gutter_actions(3, window));
    assert_eq!(actions.len(), 3 + 30 + 1);
    assert_eq!(titles(&actions)[32..], ["t29 >", "1 more tests..."]);

    let accept = |handle: i64, cx: &mut VisualTestContext| {
        let shown = workbench.update_in(cx, |workbench, window, cx| {
            let input = workbench.quick_inputs.current().expect("a pick shows");
            let shown = (input.placeholder.clone(), input.items().iter().filter_map(|entry| match entry {
                crate::quick_input::Entry::Item(item) => Some(item.label.clone()),
                _ => None,
            }).collect::<Vec<_>>());
            let id = input.id;
            let input = workbench.quick_inputs.get_mut(id).unwrap();
            input.set_active_items(&[handle]);
            input.accept_from_ui();
            workbench.flush_quick_input_events(window, cx);
            shown
        });
        cx.run_until_parked();
        shown
    };
    workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command(&command_titled(&actions, "1 more tests..."), vec![json!({ "lineNumber": 3 })], window, cx)));
    cx.run_until_parked();
    let (placeholder, labels) = accept(30, cx);
    assert_eq!(placeholder.as_deref(), Some("Select a test to run"));
    assert_eq!(labels.len(), 31);
    assert_eq!(labels[30], "t30");
    let (placeholder, labels) = accept(0, cx);
    assert_eq!(placeholder.as_deref(), Some("t30"));
    assert_eq!(labels, ["Run Test", "Debug Test", "Execute Using Profile...", "Reveal in Test Explorer"]);
    let runs: Vec<_> = host.try_iter().filter(|message| message.method == "$runControllerTests").map(|message| message.args[0][0]["testIds"].clone()).collect();
    assert_eq!(runs, [json!(["c\0t30"])]);
}

/// testing.contribution.ts `_revealTestInExplorer`: the test's parents expand and the Testing view opens.
#[gpui::test]
fn reveal_in_test_explorer_expands_the_tests_parents(cx: &mut TestAppContext) {
    let (workbench, cx, _host) = workbench_with_tests("test-gutter-reveal", &[("c\0s", "s", 0), ("c\0s\0t", "t", 1)], cx);
    let expanded = workbench.update_in(cx, |workbench, window, cx| {
        drop(workbench.execute_command("_revealTestInExplorer", vec![json!("c\0s\0t")], window, cx));
        let mut expanded: Vec<String> = workbench.testing_view.expanded.iter().cloned().collect();
        expanded.sort();
        expanded
    });
    assert_eq!(expanded, ["c", "c\0s"]);
}

/// testingExplorerView.ts `revealById`: the revealed row is selected and scrolled to the middle of the tree.
#[gpui::test]
fn reveal_in_test_explorer_selects_and_scrolls_to_the_row(cx: &mut TestAppContext) {
    let ids: Vec<(String, String)> = (0..200).map(|index| (format!("c\0t{index:03}"), format!("t{index:03}"))).collect();
    let tests: Vec<(&str, &str, u32)> = ids.iter().map(|(id, label)| (id.as_str(), label.as_str(), 3)).collect();
    let (workbench, cx, _host) = workbench_with_tests("test-gutter-reveal-scroll", &tests, cx);
    workbench.update_in(cx, |workbench, window, cx| {
        workbench.testing.controllers.insert("c".into(), crate::workbench::testing_service::Controller { label: "c".into(), capabilities: 0 });
        workbench.set_part_hidden(crate::workbench::layout::Part::SideBar, false, cx);
        drop(workbench.execute_command("_revealTestInExplorer", vec![json!("c\0t100")], window, cx));
    });
    for _ in 0..2 {
        cx.run_until_parked();
        cx.update(|window, _| window.refresh());
    }
    cx.run_until_parked();
    let (selected, viewport, scroll_top) = workbench.read_with(cx, |workbench, _| {
        let view = &workbench.testing_view;
        (view.selected.clone(), f32::from(view.scroll.bounds().size.height), -f32::from(view.scroll.offset().y))
    });
    assert_eq!(selected.as_deref(), Some("c\0t100"));
    let focus = |cx: &mut VisualTestContext| cx.update(|window, cx| workbench.read_with(cx, |workbench, _| (workbench.testing_view.filter.focus.is_focused(window), workbench.testing_view.tree_focus.is_focused(window))));
    assert_eq!(focus(cx), (false, false), "a reveal without focus leaves the focus where it was");
    workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.view.testing", Vec::new(), window, cx)));
    assert_eq!(focus(cx), (true, false), "the opened view focuses its filter box");
    workbench.update_in(cx, |workbench, window, cx| window.focus(&workbench.testing_view.tree_focus.clone(), cx));
    cx.run_until_parked();
    cx.update(|window, _| window.refresh());
    cx.run_until_parked();
    workbench.update_in(cx, |workbench, window, cx| {
        window.blur(cx);
        drop(workbench.execute_command("workbench.view.testing", Vec::new(), window, cx));
    });
    assert_eq!(focus(cx), (false, true), "the tree gets the focus back once it had it last");
    // Row 101: a lone controller's root is not drawn.
    let middle = 22. * 100. - (viewport - 22.) / 2.;
    assert!(viewport > 0. && (scroll_top - middle).abs() < 1., "scroll top {scroll_top}, viewport {viewport}");
}