test.rs

  1use crate::{
  2    display_map::{DisplayMap, DisplaySnapshot, ToDisplayPoint},
  3    multi_buffer::ToPointUtf16,
  4    AnchorRangeExt, Autoscroll, DisplayPoint, Editor, EditorMode, MultiBuffer, ToPoint,
  5};
  6use anyhow::Result;
  7use futures::{Future, StreamExt};
  8use gpui::{
  9    json, keymap::Keystroke, AppContext, ModelContext, ModelHandle, ViewContext, ViewHandle,
 10};
 11use indoc::indoc;
 12use language::{point_to_lsp, Buffer, BufferSnapshot, FakeLspAdapter, Language, LanguageConfig};
 13use lsp::{notification, request};
 14use project::Project;
 15use settings::Settings;
 16use std::{
 17    any::TypeId,
 18    ops::{Deref, DerefMut, Range},
 19    sync::Arc,
 20};
 21use util::{
 22    assert_set_eq, set_eq,
 23    test::{generate_marked_text, marked_text_offsets, marked_text_ranges},
 24};
 25use workspace::{pane, AppState, Workspace, WorkspaceHandle};
 26
 27#[cfg(test)]
 28#[ctor::ctor]
 29fn init_logger() {
 30    if std::env::var("RUST_LOG").is_ok() {
 31        env_logger::init();
 32    }
 33}
 34
 35// Returns a snapshot from text containing '|' character markers with the markers removed, and DisplayPoints for each one.
 36pub fn marked_display_snapshot(
 37    text: &str,
 38    cx: &mut gpui::MutableAppContext,
 39) -> (DisplaySnapshot, Vec<DisplayPoint>) {
 40    let (unmarked_text, markers) = marked_text_offsets(text);
 41
 42    let family_id = cx.font_cache().load_family(&["Helvetica"]).unwrap();
 43    let font_id = cx
 44        .font_cache()
 45        .select_font(family_id, &Default::default())
 46        .unwrap();
 47    let font_size = 14.0;
 48
 49    let buffer = MultiBuffer::build_simple(&unmarked_text, cx);
 50    let display_map =
 51        cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, None, 1, 1, cx));
 52    let snapshot = display_map.update(cx, |map, cx| map.snapshot(cx));
 53    let markers = markers
 54        .into_iter()
 55        .map(|offset| offset.to_display_point(&snapshot))
 56        .collect();
 57
 58    (snapshot, markers)
 59}
 60
 61pub fn select_ranges(editor: &mut Editor, marked_text: &str, cx: &mut ViewContext<Editor>) {
 62    let (umarked_text, text_ranges) = marked_text_ranges(marked_text, true);
 63    assert_eq!(editor.text(cx), umarked_text);
 64    editor.change_selections(None, cx, |s| s.select_ranges(text_ranges));
 65}
 66
 67pub fn assert_text_with_selections(
 68    editor: &mut Editor,
 69    marked_text: &str,
 70    cx: &mut ViewContext<Editor>,
 71) {
 72    let (unmarked_text, text_ranges) = marked_text_ranges(marked_text, true);
 73    assert_eq!(editor.text(cx), unmarked_text);
 74    assert_eq!(editor.selections.ranges(cx), text_ranges);
 75}
 76
 77pub(crate) fn build_editor(
 78    buffer: ModelHandle<MultiBuffer>,
 79    cx: &mut ViewContext<Editor>,
 80) -> Editor {
 81    Editor::new(EditorMode::Full, buffer, None, None, cx)
 82}
 83
 84pub struct EditorTestContext<'a> {
 85    pub cx: &'a mut gpui::TestAppContext,
 86    pub window_id: usize,
 87    pub editor: ViewHandle<Editor>,
 88}
 89
 90impl<'a> EditorTestContext<'a> {
 91    pub fn new(cx: &'a mut gpui::TestAppContext) -> EditorTestContext<'a> {
 92        let (window_id, editor) = cx.update(|cx| {
 93            cx.set_global(Settings::test(cx));
 94            crate::init(cx);
 95
 96            let (window_id, editor) = cx.add_window(Default::default(), |cx| {
 97                build_editor(MultiBuffer::build_simple("", cx), cx)
 98            });
 99
100            editor.update(cx, |_, cx| cx.focus_self());
101
102            (window_id, editor)
103        });
104
105        Self {
106            cx,
107            window_id,
108            editor,
109        }
110    }
111
112    pub fn condition(
113        &self,
114        predicate: impl FnMut(&Editor, &AppContext) -> bool,
115    ) -> impl Future<Output = ()> {
116        self.editor.condition(self.cx, predicate)
117    }
118
119    pub fn editor<F, T>(&self, read: F) -> T
120    where
121        F: FnOnce(&Editor, &AppContext) -> T,
122    {
123        self.editor.read_with(self.cx, read)
124    }
125
126    pub fn update_editor<F, T>(&mut self, update: F) -> T
127    where
128        F: FnOnce(&mut Editor, &mut ViewContext<Editor>) -> T,
129    {
130        self.editor.update(self.cx, update)
131    }
132
133    pub fn multibuffer<F, T>(&self, read: F) -> T
134    where
135        F: FnOnce(&MultiBuffer, &AppContext) -> T,
136    {
137        self.editor(|editor, cx| read(editor.buffer().read(cx), cx))
138    }
139
140    pub fn update_multibuffer<F, T>(&mut self, update: F) -> T
141    where
142        F: FnOnce(&mut MultiBuffer, &mut ModelContext<MultiBuffer>) -> T,
143    {
144        self.update_editor(|editor, cx| editor.buffer().update(cx, update))
145    }
146
147    pub fn buffer_text(&self) -> String {
148        self.multibuffer(|buffer, cx| buffer.snapshot(cx).text())
149    }
150
151    pub fn buffer<F, T>(&self, read: F) -> T
152    where
153        F: FnOnce(&Buffer, &AppContext) -> T,
154    {
155        self.multibuffer(|multibuffer, cx| {
156            let buffer = multibuffer.as_singleton().unwrap().read(cx);
157            read(buffer, cx)
158        })
159    }
160
161    pub fn update_buffer<F, T>(&mut self, update: F) -> T
162    where
163        F: FnOnce(&mut Buffer, &mut ModelContext<Buffer>) -> T,
164    {
165        self.update_multibuffer(|multibuffer, cx| {
166            let buffer = multibuffer.as_singleton().unwrap();
167            buffer.update(cx, update)
168        })
169    }
170
171    pub fn buffer_snapshot(&self) -> BufferSnapshot {
172        self.buffer(|buffer, _| buffer.snapshot())
173    }
174
175    pub fn simulate_keystroke(&mut self, keystroke_text: &str) {
176        let keystroke = Keystroke::parse(keystroke_text).unwrap();
177        self.cx.dispatch_keystroke(self.window_id, keystroke, false);
178    }
179
180    pub fn simulate_keystrokes<const COUNT: usize>(&mut self, keystroke_texts: [&str; COUNT]) {
181        for keystroke_text in keystroke_texts.into_iter() {
182            self.simulate_keystroke(keystroke_text);
183        }
184    }
185
186    pub fn ranges(&self, marked_text: &str) -> Vec<Range<usize>> {
187        let (unmarked_text, ranges) = marked_text_ranges(marked_text, false);
188        assert_eq!(self.buffer_text(), unmarked_text);
189        ranges
190    }
191
192    pub fn display_point(&mut self, marked_text: &str) -> DisplayPoint {
193        let ranges = self.ranges(marked_text);
194        let snapshot = self
195            .editor
196            .update(self.cx, |editor, cx| editor.snapshot(cx));
197        ranges[0].start.to_display_point(&snapshot)
198    }
199
200    // Returns anchors for the current buffer using `«` and `»`
201    pub fn text_anchor_range(&self, marked_text: &str) -> Range<language::Anchor> {
202        let ranges = self.ranges(marked_text);
203        let snapshot = self.buffer_snapshot();
204        snapshot.anchor_before(ranges[0].start)..snapshot.anchor_after(ranges[0].end)
205    }
206
207    /// Change the editor's text and selections using a string containing
208    /// embedded range markers that represent the ranges and directions of
209    /// each selection.
210    ///
211    /// See the `util::test::marked_text_ranges` function for more information.
212    pub fn set_state(&mut self, marked_text: &str) {
213        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
214        self.editor.update(self.cx, |editor, cx| {
215            editor.set_text(unmarked_text, cx);
216            editor.change_selections(Some(Autoscroll::Fit), cx, |s| {
217                s.select_ranges(selection_ranges)
218            })
219        })
220    }
221
222    /// Make an assertion about the editor's text and the ranges and directions
223    /// of its selections using a string containing embedded range markers.
224    ///
225    /// See the `util::test::marked_text_ranges` function for more information.
226    pub fn assert_editor_state(&mut self, marked_text: &str) {
227        let (unmarked_text, expected_selections) = marked_text_ranges(marked_text, true);
228        let buffer_text = self.buffer_text();
229        assert_eq!(
230            buffer_text, unmarked_text,
231            "Unmarked text doesn't match buffer text"
232        );
233        self.assert_selections(expected_selections, marked_text.to_string())
234    }
235
236    pub fn assert_editor_background_highlights<Tag: 'static>(&mut self, marked_text: &str) {
237        let expected_ranges = self.ranges(marked_text);
238        let actual_ranges: Vec<Range<usize>> = self.update_editor(|editor, cx| {
239            let snapshot = editor.snapshot(cx);
240            editor
241                .background_highlights
242                .get(&TypeId::of::<Tag>())
243                .map(|h| h.1.clone())
244                .unwrap_or_default()
245                .into_iter()
246                .map(|range| range.to_offset(&snapshot.buffer_snapshot))
247                .collect()
248        });
249        assert_set_eq!(actual_ranges, expected_ranges);
250    }
251
252    pub fn assert_editor_text_highlights<Tag: ?Sized + 'static>(&mut self, marked_text: &str) {
253        let expected_ranges = self.ranges(marked_text);
254        let snapshot = self.update_editor(|editor, cx| editor.snapshot(cx));
255        let actual_ranges: Vec<Range<usize>> = snapshot
256            .highlight_ranges::<Tag>()
257            .map(|ranges| ranges.as_ref().clone().1)
258            .unwrap_or_default()
259            .into_iter()
260            .map(|range| range.to_offset(&snapshot.buffer_snapshot))
261            .collect();
262        assert_set_eq!(actual_ranges, expected_ranges);
263    }
264
265    pub fn assert_editor_selections(&mut self, expected_selections: Vec<Range<usize>>) {
266        let expected_marked_text =
267            generate_marked_text(&self.buffer_text(), &expected_selections, true);
268        self.assert_selections(expected_selections, expected_marked_text)
269    }
270
271    fn assert_selections(
272        &mut self,
273        expected_selections: Vec<Range<usize>>,
274        expected_marked_text: String,
275    ) {
276        let actual_selections = self
277            .editor
278            .read_with(self.cx, |editor, cx| editor.selections.all::<usize>(cx))
279            .into_iter()
280            .map(|s| {
281                if s.reversed {
282                    s.end..s.start
283                } else {
284                    s.start..s.end
285                }
286            })
287            .collect::<Vec<_>>();
288        let actual_marked_text =
289            generate_marked_text(&self.buffer_text(), &actual_selections, true);
290        if expected_selections != actual_selections {
291            panic!(
292                indoc! {"
293                    Editor has unexpected selections.
294
295                    Expected selections:
296                    {}
297
298                    Actual selections:
299                    {}
300                "},
301                expected_marked_text, actual_marked_text,
302            );
303        }
304    }
305}
306
307impl<'a> Deref for EditorTestContext<'a> {
308    type Target = gpui::TestAppContext;
309
310    fn deref(&self) -> &Self::Target {
311        self.cx
312    }
313}
314
315impl<'a> DerefMut for EditorTestContext<'a> {
316    fn deref_mut(&mut self) -> &mut Self::Target {
317        &mut self.cx
318    }
319}
320
321pub struct EditorLspTestContext<'a> {
322    pub cx: EditorTestContext<'a>,
323    pub lsp: lsp::FakeLanguageServer,
324    pub workspace: ViewHandle<Workspace>,
325    pub buffer_lsp_url: lsp::Url,
326}
327
328impl<'a> EditorLspTestContext<'a> {
329    pub async fn new(
330        mut language: Language,
331        capabilities: lsp::ServerCapabilities,
332        cx: &'a mut gpui::TestAppContext,
333    ) -> EditorLspTestContext<'a> {
334        use json::json;
335
336        cx.update(|cx| {
337            crate::init(cx);
338            pane::init(cx);
339        });
340
341        let params = cx.update(AppState::test);
342
343        let file_name = format!(
344            "file.{}",
345            language
346                .path_suffixes()
347                .first()
348                .unwrap_or(&"txt".to_string())
349        );
350
351        let mut fake_servers = language
352            .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
353                capabilities,
354                ..Default::default()
355            }))
356            .await;
357
358        let project = Project::test(params.fs.clone(), [], cx).await;
359        project.update(cx, |project, _| project.languages().add(Arc::new(language)));
360
361        params
362            .fs
363            .as_fake()
364            .insert_tree("/root", json!({ "dir": { file_name: "" }}))
365            .await;
366
367        let (window_id, workspace) =
368            cx.add_window(|cx| Workspace::new(project.clone(), |_, _| unimplemented!(), cx));
369        project
370            .update(cx, |project, cx| {
371                project.find_or_create_local_worktree("/root", true, cx)
372            })
373            .await
374            .unwrap();
375        cx.read(|cx| workspace.read(cx).worktree_scans_complete(cx))
376            .await;
377
378        let file = cx.read(|cx| workspace.file_project_paths(cx)[0].clone());
379        let item = workspace
380            .update(cx, |workspace, cx| workspace.open_path(file, true, cx))
381            .await
382            .expect("Could not open test file");
383
384        let editor = cx.update(|cx| {
385            item.act_as::<Editor>(cx)
386                .expect("Opened test file wasn't an editor")
387        });
388        editor.update(cx, |_, cx| cx.focus_self());
389
390        let lsp = fake_servers.next().await.unwrap();
391
392        Self {
393            cx: EditorTestContext {
394                cx,
395                window_id,
396                editor,
397            },
398            lsp,
399            workspace,
400            buffer_lsp_url: lsp::Url::from_file_path("/root/dir/file.rs").unwrap(),
401        }
402    }
403
404    pub async fn new_rust(
405        capabilities: lsp::ServerCapabilities,
406        cx: &'a mut gpui::TestAppContext,
407    ) -> EditorLspTestContext<'a> {
408        let language = Language::new(
409            LanguageConfig {
410                name: "Rust".into(),
411                path_suffixes: vec!["rs".to_string()],
412                ..Default::default()
413            },
414            Some(tree_sitter_rust::language()),
415        );
416
417        Self::new(language, capabilities, cx).await
418    }
419
420    // Constructs lsp range using a marked string with '[', ']' range delimiters
421    pub fn lsp_range(&mut self, marked_text: &str) -> lsp::Range {
422        let ranges = self.ranges(marked_text);
423        self.to_lsp_range(ranges[0].clone())
424    }
425
426    pub fn to_lsp_range(&mut self, range: Range<usize>) -> lsp::Range {
427        let snapshot = self.update_editor(|editor, cx| editor.snapshot(cx));
428        let start_point = range.start.to_point(&snapshot.buffer_snapshot);
429        let end_point = range.end.to_point(&snapshot.buffer_snapshot);
430
431        self.editor(|editor, cx| {
432            let buffer = editor.buffer().read(cx);
433            let start = point_to_lsp(
434                buffer
435                    .point_to_buffer_offset(start_point, cx)
436                    .unwrap()
437                    .1
438                    .to_point_utf16(&buffer.read(cx)),
439            );
440            let end = point_to_lsp(
441                buffer
442                    .point_to_buffer_offset(end_point, cx)
443                    .unwrap()
444                    .1
445                    .to_point_utf16(&buffer.read(cx)),
446            );
447
448            lsp::Range { start, end }
449        })
450    }
451
452    pub fn to_lsp(&mut self, offset: usize) -> lsp::Position {
453        let snapshot = self.update_editor(|editor, cx| editor.snapshot(cx));
454        let point = offset.to_point(&snapshot.buffer_snapshot);
455
456        self.editor(|editor, cx| {
457            let buffer = editor.buffer().read(cx);
458            point_to_lsp(
459                buffer
460                    .point_to_buffer_offset(point, cx)
461                    .unwrap()
462                    .1
463                    .to_point_utf16(&buffer.read(cx)),
464            )
465        })
466    }
467
468    pub fn update_workspace<F, T>(&mut self, update: F) -> T
469    where
470        F: FnOnce(&mut Workspace, &mut ViewContext<Workspace>) -> T,
471    {
472        self.workspace.update(self.cx.cx, update)
473    }
474
475    pub fn handle_request<T, F, Fut>(
476        &self,
477        mut handler: F,
478    ) -> futures::channel::mpsc::UnboundedReceiver<()>
479    where
480        T: 'static + request::Request,
481        T::Params: 'static + Send,
482        F: 'static + Send + FnMut(lsp::Url, T::Params, gpui::AsyncAppContext) -> Fut,
483        Fut: 'static + Send + Future<Output = Result<T::Result>>,
484    {
485        let url = self.buffer_lsp_url.clone();
486        self.lsp.handle_request::<T, _, _>(move |params, cx| {
487            let url = url.clone();
488            handler(url, params, cx)
489        })
490    }
491
492    pub fn notify<T: notification::Notification>(&self, params: T::Params) {
493        self.lsp.notify::<T>(params);
494    }
495}
496
497impl<'a> Deref for EditorLspTestContext<'a> {
498    type Target = EditorTestContext<'a>;
499
500    fn deref(&self) -> &Self::Target {
501        &self.cx
502    }
503}
504
505impl<'a> DerefMut for EditorLspTestContext<'a> {
506    fn deref_mut(&mut self) -> &mut Self::Target {
507        &mut self.cx
508    }
509}