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 async 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    pub fn set_state(&mut self, marked_text: &str) {
208        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
209        self.editor.update(self.cx, |editor, cx| {
210            editor.set_text(unmarked_text, cx);
211            editor.change_selections(Some(Autoscroll::Fit), cx, |s| {
212                s.select_ranges(selection_ranges)
213            })
214        })
215    }
216
217    pub fn assert_editor_state(&mut self, marked_text: &str) {
218        let (unmarked_text, expected_selections) = marked_text_ranges(marked_text, true);
219        let buffer_text = self.buffer_text();
220        assert_eq!(
221            buffer_text, unmarked_text,
222            "Unmarked text doesn't match buffer text"
223        );
224        self.assert_selections(expected_selections, marked_text.to_string())
225    }
226
227    pub fn assert_editor_background_highlights<Tag: 'static>(&mut self, marked_text: &str) {
228        let expected_ranges = self.ranges(marked_text);
229        let actual_ranges: Vec<Range<usize>> = self.update_editor(|editor, cx| {
230            let snapshot = editor.snapshot(cx);
231            editor
232                .background_highlights
233                .get(&TypeId::of::<Tag>())
234                .map(|h| h.1.clone())
235                .unwrap_or_default()
236                .into_iter()
237                .map(|range| range.to_offset(&snapshot.buffer_snapshot))
238                .collect()
239        });
240        assert_set_eq!(actual_ranges, expected_ranges);
241    }
242
243    pub fn assert_editor_text_highlights<Tag: ?Sized + 'static>(&mut self, marked_text: &str) {
244        let expected_ranges = self.ranges(marked_text);
245        let snapshot = self.update_editor(|editor, cx| editor.snapshot(cx));
246        let actual_ranges: Vec<Range<usize>> = snapshot
247            .highlight_ranges::<Tag>()
248            .map(|ranges| ranges.as_ref().clone().1)
249            .unwrap_or_default()
250            .into_iter()
251            .map(|range| range.to_offset(&snapshot.buffer_snapshot))
252            .collect();
253        assert_set_eq!(actual_ranges, expected_ranges);
254    }
255
256    pub fn assert_editor_selections(&mut self, expected_selections: Vec<Range<usize>>) {
257        let expected_marked_text =
258            generate_marked_text(&self.buffer_text(), &expected_selections, true);
259        self.assert_selections(expected_selections, expected_marked_text)
260    }
261
262    fn assert_selections(
263        &mut self,
264        expected_selections: Vec<Range<usize>>,
265        expected_marked_text: String,
266    ) {
267        let actual_selections = self
268            .editor
269            .read_with(self.cx, |editor, cx| editor.selections.all::<usize>(cx))
270            .into_iter()
271            .map(|s| {
272                if s.reversed {
273                    s.end..s.start
274                } else {
275                    s.start..s.end
276                }
277            })
278            .collect::<Vec<_>>();
279        let actual_marked_text =
280            generate_marked_text(&self.buffer_text(), &actual_selections, true);
281        if expected_selections != actual_selections {
282            panic!(
283                indoc! {"
284                    Editor has unexpected selections.
285
286                    Expected selections:
287                    {}
288
289                    Actual selections:
290                    {}
291                "},
292                expected_marked_text, actual_marked_text,
293            );
294        }
295    }
296}
297
298impl<'a> Deref for EditorTestContext<'a> {
299    type Target = gpui::TestAppContext;
300
301    fn deref(&self) -> &Self::Target {
302        self.cx
303    }
304}
305
306impl<'a> DerefMut for EditorTestContext<'a> {
307    fn deref_mut(&mut self) -> &mut Self::Target {
308        &mut self.cx
309    }
310}
311
312pub struct EditorLspTestContext<'a> {
313    pub cx: EditorTestContext<'a>,
314    pub lsp: lsp::FakeLanguageServer,
315    pub workspace: ViewHandle<Workspace>,
316    pub buffer_lsp_url: lsp::Url,
317}
318
319impl<'a> EditorLspTestContext<'a> {
320    pub async fn new(
321        mut language: Language,
322        capabilities: lsp::ServerCapabilities,
323        cx: &'a mut gpui::TestAppContext,
324    ) -> EditorLspTestContext<'a> {
325        use json::json;
326
327        cx.update(|cx| {
328            crate::init(cx);
329            pane::init(cx);
330        });
331
332        let params = cx.update(AppState::test);
333
334        let file_name = format!(
335            "file.{}",
336            language
337                .path_suffixes()
338                .first()
339                .unwrap_or(&"txt".to_string())
340        );
341
342        let mut fake_servers = language
343            .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
344                capabilities,
345                ..Default::default()
346            }))
347            .await;
348
349        let project = Project::test(params.fs.clone(), [], cx).await;
350        project.update(cx, |project, _| project.languages().add(Arc::new(language)));
351
352        params
353            .fs
354            .as_fake()
355            .insert_tree("/root", json!({ "dir": { file_name: "" }}))
356            .await;
357
358        let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project.clone(), cx));
359        project
360            .update(cx, |project, cx| {
361                project.find_or_create_local_worktree("/root", true, cx)
362            })
363            .await
364            .unwrap();
365        cx.read(|cx| workspace.read(cx).worktree_scans_complete(cx))
366            .await;
367
368        let file = cx.read(|cx| workspace.file_project_paths(cx)[0].clone());
369        let item = workspace
370            .update(cx, |workspace, cx| workspace.open_path(file, true, cx))
371            .await
372            .expect("Could not open test file");
373
374        let editor = cx.update(|cx| {
375            item.act_as::<Editor>(cx)
376                .expect("Opened test file wasn't an editor")
377        });
378        editor.update(cx, |_, cx| cx.focus_self());
379
380        let lsp = fake_servers.next().await.unwrap();
381
382        Self {
383            cx: EditorTestContext {
384                cx,
385                window_id,
386                editor,
387            },
388            lsp,
389            workspace,
390            buffer_lsp_url: lsp::Url::from_file_path("/root/dir/file.rs").unwrap(),
391        }
392    }
393
394    pub async fn new_rust(
395        capabilities: lsp::ServerCapabilities,
396        cx: &'a mut gpui::TestAppContext,
397    ) -> EditorLspTestContext<'a> {
398        let language = Language::new(
399            LanguageConfig {
400                name: "Rust".into(),
401                path_suffixes: vec!["rs".to_string()],
402                ..Default::default()
403            },
404            Some(tree_sitter_rust::language()),
405        );
406
407        Self::new(language, capabilities, cx).await
408    }
409
410    // Constructs lsp range using a marked string with '[', ']' range delimiters
411    pub fn lsp_range(&mut self, marked_text: &str) -> lsp::Range {
412        let ranges = self.ranges(marked_text);
413        self.to_lsp_range(ranges[0].clone())
414    }
415
416    pub fn to_lsp_range(&mut self, range: Range<usize>) -> lsp::Range {
417        let snapshot = self.update_editor(|editor, cx| editor.snapshot(cx));
418        let start_point = range.start.to_point(&snapshot.buffer_snapshot);
419        let end_point = range.end.to_point(&snapshot.buffer_snapshot);
420
421        self.editor(|editor, cx| {
422            let buffer = editor.buffer().read(cx);
423            let start = point_to_lsp(
424                buffer
425                    .point_to_buffer_offset(start_point, cx)
426                    .unwrap()
427                    .1
428                    .to_point_utf16(&buffer.read(cx)),
429            );
430            let end = point_to_lsp(
431                buffer
432                    .point_to_buffer_offset(end_point, cx)
433                    .unwrap()
434                    .1
435                    .to_point_utf16(&buffer.read(cx)),
436            );
437
438            lsp::Range { start, end }
439        })
440    }
441
442    pub fn to_lsp(&mut self, offset: usize) -> lsp::Position {
443        let snapshot = self.update_editor(|editor, cx| editor.snapshot(cx));
444        let point = offset.to_point(&snapshot.buffer_snapshot);
445
446        self.editor(|editor, cx| {
447            let buffer = editor.buffer().read(cx);
448            point_to_lsp(
449                buffer
450                    .point_to_buffer_offset(point, cx)
451                    .unwrap()
452                    .1
453                    .to_point_utf16(&buffer.read(cx)),
454            )
455        })
456    }
457
458    pub fn update_workspace<F, T>(&mut self, update: F) -> T
459    where
460        F: FnOnce(&mut Workspace, &mut ViewContext<Workspace>) -> T,
461    {
462        self.workspace.update(self.cx.cx, update)
463    }
464
465    pub fn handle_request<T, F, Fut>(
466        &self,
467        mut handler: F,
468    ) -> futures::channel::mpsc::UnboundedReceiver<()>
469    where
470        T: 'static + request::Request,
471        T::Params: 'static + Send,
472        F: 'static + Send + FnMut(lsp::Url, T::Params, gpui::AsyncAppContext) -> Fut,
473        Fut: 'static + Send + Future<Output = Result<T::Result>>,
474    {
475        let url = self.buffer_lsp_url.clone();
476        self.lsp.handle_request::<T, _, _>(move |params, cx| {
477            let url = url.clone();
478            handler(url, params, cx)
479        })
480    }
481
482    pub fn notify<T: notification::Notification>(&self, params: T::Params) {
483        self.lsp.notify::<T>(params);
484    }
485}
486
487impl<'a> Deref for EditorLspTestContext<'a> {
488    type Target = EditorTestContext<'a>;
489
490    fn deref(&self) -> &Self::Target {
491        &self.cx
492    }
493}
494
495impl<'a> DerefMut for EditorLspTestContext<'a> {
496    fn deref_mut(&mut self) -> &mut Self::Target {
497        &mut self.cx
498    }
499}