test.rs

  1use std::{
  2    any::TypeId,
  3    ops::{Deref, DerefMut, Range},
  4    sync::Arc,
  5};
  6
  7use anyhow::Result;
  8use futures::{Future, StreamExt};
  9use indoc::indoc;
 10
 11use collections::BTreeMap;
 12use gpui::{json, keymap::Keystroke, AppContext, ModelHandle, ViewContext, ViewHandle};
 13use language::{point_to_lsp, FakeLspAdapter, Language, LanguageConfig, Selection};
 14use lsp::request;
 15use project::Project;
 16use settings::Settings;
 17use util::{
 18    assert_set_eq, set_eq,
 19    test::{marked_text, marked_text_ranges, marked_text_ranges_by, SetEqError, TextRangeMarker},
 20};
 21use workspace::{pane, AppState, Workspace, WorkspaceHandle};
 22
 23use crate::{
 24    display_map::{DisplayMap, DisplaySnapshot, ToDisplayPoint},
 25    multi_buffer::ToPointUtf16,
 26    AnchorRangeExt, Autoscroll, DisplayPoint, Editor, EditorMode, MultiBuffer, ToPoint,
 27};
 28
 29#[cfg(test)]
 30#[ctor::ctor]
 31fn init_logger() {
 32    if std::env::var("RUST_LOG").is_ok() {
 33        env_logger::init();
 34    }
 35}
 36
 37// Returns a snapshot from text containing '|' character markers with the markers removed, and DisplayPoints for each one.
 38pub fn marked_display_snapshot(
 39    text: &str,
 40    cx: &mut gpui::MutableAppContext,
 41) -> (DisplaySnapshot, Vec<DisplayPoint>) {
 42    let (unmarked_text, markers) = marked_text(text);
 43
 44    let family_id = cx.font_cache().load_family(&["Helvetica"]).unwrap();
 45    let font_id = cx
 46        .font_cache()
 47        .select_font(family_id, &Default::default())
 48        .unwrap();
 49    let font_size = 14.0;
 50
 51    let buffer = MultiBuffer::build_simple(&unmarked_text, cx);
 52    let display_map =
 53        cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, None, 1, 1, cx));
 54    let snapshot = display_map.update(cx, |map, cx| map.snapshot(cx));
 55    let markers = markers
 56        .into_iter()
 57        .map(|offset| offset.to_display_point(&snapshot))
 58        .collect();
 59
 60    (snapshot, markers)
 61}
 62
 63pub fn select_ranges(editor: &mut Editor, marked_text: &str, cx: &mut ViewContext<Editor>) {
 64    let (umarked_text, text_ranges) = marked_text_ranges(marked_text);
 65    assert_eq!(editor.text(cx), umarked_text);
 66    editor.change_selections(None, cx, |s| s.select_ranges(text_ranges));
 67}
 68
 69pub fn assert_text_with_selections(
 70    editor: &mut Editor,
 71    marked_text: &str,
 72    cx: &mut ViewContext<Editor>,
 73) {
 74    let (unmarked_text, text_ranges) = marked_text_ranges(marked_text);
 75
 76    assert_eq!(editor.text(cx), unmarked_text);
 77    assert_eq!(editor.selections.ranges(cx), text_ranges);
 78}
 79
 80pub(crate) fn build_editor(
 81    buffer: ModelHandle<MultiBuffer>,
 82    cx: &mut ViewContext<Editor>,
 83) -> Editor {
 84    Editor::new(EditorMode::Full, buffer, None, None, cx)
 85}
 86
 87pub struct EditorTestContext<'a> {
 88    pub cx: &'a mut gpui::TestAppContext,
 89    pub window_id: usize,
 90    pub editor: ViewHandle<Editor>,
 91}
 92
 93impl<'a> EditorTestContext<'a> {
 94    pub async fn new(cx: &'a mut gpui::TestAppContext) -> EditorTestContext<'a> {
 95        let (window_id, editor) = cx.update(|cx| {
 96            cx.set_global(Settings::test(cx));
 97            crate::init(cx);
 98
 99            let (window_id, editor) = cx.add_window(Default::default(), |cx| {
100                build_editor(MultiBuffer::build_simple("", cx), cx)
101            });
102
103            editor.update(cx, |_, cx| cx.focus_self());
104
105            (window_id, editor)
106        });
107
108        Self {
109            cx,
110            window_id,
111            editor,
112        }
113    }
114
115    pub fn condition(
116        &self,
117        predicate: impl FnMut(&Editor, &AppContext) -> bool,
118    ) -> impl Future<Output = ()> {
119        self.editor.condition(self.cx, predicate)
120    }
121
122    pub fn editor<F, T>(&mut self, read: F) -> T
123    where
124        F: FnOnce(&Editor, &AppContext) -> T,
125    {
126        self.editor.read_with(self.cx, read)
127    }
128
129    pub fn update_editor<F, T>(&mut self, update: F) -> T
130    where
131        F: FnOnce(&mut Editor, &mut ViewContext<Editor>) -> T,
132    {
133        self.editor.update(self.cx, update)
134    }
135
136    pub fn buffer_text(&mut self) -> String {
137        self.editor.read_with(self.cx, |editor, cx| {
138            editor.buffer.read(cx).snapshot(cx).text()
139        })
140    }
141
142    pub fn simulate_keystroke(&mut self, keystroke_text: &str) {
143        let keystroke = Keystroke::parse(keystroke_text).unwrap();
144        self.cx.dispatch_keystroke(self.window_id, keystroke, false);
145    }
146
147    pub fn simulate_keystrokes<const COUNT: usize>(&mut self, keystroke_texts: [&str; COUNT]) {
148        for keystroke_text in keystroke_texts.into_iter() {
149            self.simulate_keystroke(keystroke_text);
150        }
151    }
152
153    pub fn display_point(&mut self, cursor_location: &str) -> DisplayPoint {
154        let (_, locations) = marked_text(cursor_location);
155        let snapshot = self
156            .editor
157            .update(self.cx, |editor, cx| editor.snapshot(cx));
158        locations[0].to_display_point(&snapshot.display_snapshot)
159    }
160
161    // Sets the editor state via a marked string.
162    // `|` characters represent empty selections
163    // `[` to `}` represents a non empty selection with the head at `}`
164    // `{` to `]` represents a non empty selection with the head at `{`
165    pub fn set_state(&mut self, text: &str) {
166        self.set_state_by(
167            vec![
168                '|'.into(),
169                ('[', '}').into(),
170                TextRangeMarker::ReverseRange('{', ']'),
171            ],
172            text,
173        );
174    }
175
176    pub fn set_state_by(&mut self, range_markers: Vec<TextRangeMarker>, text: &str) {
177        self.editor.update(self.cx, |editor, cx| {
178            let (unmarked_text, selection_ranges) = marked_text_ranges_by(&text, range_markers);
179            editor.set_text(unmarked_text, cx);
180
181            let selection_ranges: Vec<Range<usize>> = selection_ranges
182                .values()
183                .into_iter()
184                .flatten()
185                .cloned()
186                .collect();
187            editor.change_selections(Some(Autoscroll::Fit), cx, |s| {
188                s.select_ranges(selection_ranges)
189            })
190        })
191    }
192
193    // Asserts the editor state via a marked string.
194    // `|` characters represent empty selections
195    // `[` to `}` represents a non empty selection with the head at `}`
196    // `{` to `]` represents a non empty selection with the head at `{`
197    pub fn assert_editor_state(&mut self, text: &str) {
198        let (unmarked_text, mut selection_ranges) = marked_text_ranges_by(
199            &text,
200            vec!['|'.into(), ('[', '}').into(), ('{', ']').into()],
201        );
202        let buffer_text = self.buffer_text();
203        assert_eq!(
204            buffer_text, unmarked_text,
205            "Unmarked text doesn't match buffer text"
206        );
207
208        let expected_empty_selections = selection_ranges.remove(&'|'.into()).unwrap_or_default();
209        let expected_reverse_selections = selection_ranges
210            .remove(&('{', ']').into())
211            .unwrap_or_default();
212        let expected_forward_selections = selection_ranges
213            .remove(&('[', '}').into())
214            .unwrap_or_default();
215
216        self.assert_selections(
217            expected_empty_selections,
218            expected_reverse_selections,
219            expected_forward_selections,
220            Some(text.to_string()),
221        )
222    }
223
224    pub fn assert_editor_background_highlights<Tag: 'static>(&mut self, marked_text: &str) {
225        let (unmarked, mut ranges) = marked_text_ranges_by(marked_text, vec![('[', ']').into()]);
226        assert_eq!(unmarked, self.buffer_text());
227
228        let asserted_ranges = ranges.remove(&('[', ']').into()).unwrap();
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
241        assert_set_eq!(asserted_ranges, actual_ranges);
242    }
243
244    pub fn assert_editor_text_highlights<Tag: ?Sized + 'static>(&mut self, marked_text: &str) {
245        let (unmarked, mut ranges) = marked_text_ranges_by(marked_text, vec![('[', ']').into()]);
246        assert_eq!(unmarked, self.buffer_text());
247
248        let asserted_ranges = ranges.remove(&('[', ']').into()).unwrap();
249        let snapshot = self.update_editor(|editor, cx| editor.snapshot(cx));
250        let actual_ranges: Vec<Range<usize>> = snapshot
251            .display_snapshot
252            .highlight_ranges::<Tag>()
253            .map(|ranges| ranges.as_ref().clone().1)
254            .unwrap_or_default()
255            .into_iter()
256            .map(|range| range.to_offset(&snapshot.buffer_snapshot))
257            .collect();
258
259        assert_set_eq!(asserted_ranges, actual_ranges);
260    }
261
262    pub fn assert_editor_selections(&mut self, expected_selections: Vec<Selection<usize>>) {
263        let mut empty_selections = Vec::new();
264        let mut reverse_selections = Vec::new();
265        let mut forward_selections = Vec::new();
266
267        for selection in expected_selections {
268            let range = selection.range();
269            if selection.is_empty() {
270                empty_selections.push(range);
271            } else if selection.reversed {
272                reverse_selections.push(range);
273            } else {
274                forward_selections.push(range)
275            }
276        }
277
278        self.assert_selections(
279            empty_selections,
280            reverse_selections,
281            forward_selections,
282            None,
283        )
284    }
285
286    fn assert_selections(
287        &mut self,
288        expected_empty_selections: Vec<Range<usize>>,
289        expected_reverse_selections: Vec<Range<usize>>,
290        expected_forward_selections: Vec<Range<usize>>,
291        asserted_text: Option<String>,
292    ) {
293        let (empty_selections, reverse_selections, forward_selections) =
294            self.editor.read_with(self.cx, |editor, cx| {
295                let mut empty_selections = Vec::new();
296                let mut reverse_selections = Vec::new();
297                let mut forward_selections = Vec::new();
298
299                for selection in editor.selections.all::<usize>(cx) {
300                    let range = selection.range();
301                    if selection.is_empty() {
302                        empty_selections.push(range);
303                    } else if selection.reversed {
304                        reverse_selections.push(range);
305                    } else {
306                        forward_selections.push(range)
307                    }
308                }
309
310                (empty_selections, reverse_selections, forward_selections)
311            });
312
313        let asserted_selections = asserted_text.unwrap_or_else(|| {
314            self.insert_markers(
315                &expected_empty_selections,
316                &expected_reverse_selections,
317                &expected_forward_selections,
318            )
319        });
320        let actual_selections =
321            self.insert_markers(&empty_selections, &reverse_selections, &forward_selections);
322
323        let unmarked_text = self.buffer_text();
324        let all_eq: Result<(), SetEqError<String>> =
325            set_eq!(expected_empty_selections, empty_selections)
326                .map_err(|err| {
327                    err.map(|missing| {
328                        let mut error_text = unmarked_text.clone();
329                        error_text.insert(missing.start, '|');
330                        error_text
331                    })
332                })
333                .and_then(|_| {
334                    set_eq!(expected_reverse_selections, reverse_selections).map_err(|err| {
335                        err.map(|missing| {
336                            let mut error_text = unmarked_text.clone();
337                            error_text.insert(missing.start, '{');
338                            error_text.insert(missing.end, ']');
339                            error_text
340                        })
341                    })
342                })
343                .and_then(|_| {
344                    set_eq!(expected_forward_selections, forward_selections).map_err(|err| {
345                        err.map(|missing| {
346                            let mut error_text = unmarked_text.clone();
347                            error_text.insert(missing.start, '[');
348                            error_text.insert(missing.end, '}');
349                            error_text
350                        })
351                    })
352                });
353
354        match all_eq {
355            Err(SetEqError::LeftMissing(location_text)) => {
356                panic!(
357                    indoc! {"
358                        Editor has extra selection
359                        Extra Selection Location:
360                        {}
361                        Asserted selections:
362                        {}
363                        Actual selections:
364                        {}"},
365                    location_text, asserted_selections, actual_selections,
366                );
367            }
368            Err(SetEqError::RightMissing(location_text)) => {
369                panic!(
370                    indoc! {"
371                        Editor is missing empty selection
372                        Missing Selection Location:
373                        {}
374                        Asserted selections:
375                        {}
376                        Actual selections:
377                        {}"},
378                    location_text, asserted_selections, actual_selections,
379                );
380            }
381            _ => {}
382        }
383    }
384
385    fn insert_markers(
386        &mut self,
387        empty_selections: &Vec<Range<usize>>,
388        reverse_selections: &Vec<Range<usize>>,
389        forward_selections: &Vec<Range<usize>>,
390    ) -> String {
391        let mut editor_text_with_selections = self.buffer_text();
392        let mut selection_marks = BTreeMap::new();
393        for range in empty_selections {
394            selection_marks.insert(&range.start, '|');
395        }
396        for range in reverse_selections {
397            selection_marks.insert(&range.start, '{');
398            selection_marks.insert(&range.end, ']');
399        }
400        for range in forward_selections {
401            selection_marks.insert(&range.start, '[');
402            selection_marks.insert(&range.end, '}');
403        }
404        for (offset, mark) in selection_marks.into_iter().rev() {
405            editor_text_with_selections.insert(*offset, mark);
406        }
407
408        editor_text_with_selections
409    }
410}
411
412impl<'a> Deref for EditorTestContext<'a> {
413    type Target = gpui::TestAppContext;
414
415    fn deref(&self) -> &Self::Target {
416        self.cx
417    }
418}
419
420impl<'a> DerefMut for EditorTestContext<'a> {
421    fn deref_mut(&mut self) -> &mut Self::Target {
422        &mut self.cx
423    }
424}
425
426pub struct EditorLspTestContext<'a> {
427    pub cx: EditorTestContext<'a>,
428    pub lsp: lsp::FakeLanguageServer,
429    pub workspace: ViewHandle<Workspace>,
430    pub editor_lsp_url: lsp::Url,
431}
432
433impl<'a> EditorLspTestContext<'a> {
434    pub async fn new(
435        mut language: Language,
436        capabilities: lsp::ServerCapabilities,
437        cx: &'a mut gpui::TestAppContext,
438    ) -> EditorLspTestContext<'a> {
439        use json::json;
440
441        cx.update(|cx| {
442            crate::init(cx);
443            pane::init(cx);
444        });
445
446        let params = cx.update(AppState::test);
447
448        let file_name = format!(
449            "file.{}",
450            language
451                .path_suffixes()
452                .first()
453                .unwrap_or(&"txt".to_string())
454        );
455
456        let mut fake_servers = language
457            .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
458                capabilities,
459                ..Default::default()
460            }))
461            .await;
462
463        let project = Project::test(params.fs.clone(), [], cx).await;
464        project.update(cx, |project, _| project.languages().add(Arc::new(language)));
465
466        params
467            .fs
468            .as_fake()
469            .insert_tree("/root", json!({ "dir": { file_name: "" }}))
470            .await;
471
472        let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project.clone(), cx));
473        project
474            .update(cx, |project, cx| {
475                project.find_or_create_local_worktree("/root", true, cx)
476            })
477            .await
478            .unwrap();
479        cx.read(|cx| workspace.read(cx).worktree_scans_complete(cx))
480            .await;
481
482        let file = cx.read(|cx| workspace.file_project_paths(cx)[0].clone());
483        let item = workspace
484            .update(cx, |workspace, cx| workspace.open_path(file, true, cx))
485            .await
486            .expect("Could not open test file");
487
488        let editor = cx.update(|cx| {
489            item.act_as::<Editor>(cx)
490                .expect("Opened test file wasn't an editor")
491        });
492        editor.update(cx, |_, cx| cx.focus_self());
493
494        let lsp = fake_servers.next().await.unwrap();
495
496        Self {
497            cx: EditorTestContext {
498                cx,
499                window_id,
500                editor,
501            },
502            lsp,
503            workspace,
504            editor_lsp_url: lsp::Url::from_file_path("/root/dir/file.rs").unwrap(),
505        }
506    }
507
508    pub async fn new_rust(
509        capabilities: lsp::ServerCapabilities,
510        cx: &'a mut gpui::TestAppContext,
511    ) -> EditorLspTestContext<'a> {
512        let language = Language::new(
513            LanguageConfig {
514                name: "Rust".into(),
515                path_suffixes: vec!["rs".to_string()],
516                ..Default::default()
517            },
518            Some(tree_sitter_rust::language()),
519        );
520
521        Self::new(language, capabilities, cx).await
522    }
523
524    // Constructs lsp range using a marked string with '[', ']' range delimiters
525    pub fn lsp_range(&mut self, marked_text: &str) -> lsp::Range {
526        let (unmarked, mut ranges) = marked_text_ranges_by(marked_text, vec![('[', ']').into()]);
527        assert_eq!(unmarked, self.cx.buffer_text());
528        let offset_range = ranges.remove(&('[', ']').into()).unwrap()[0].clone();
529        self.to_lsp_range(offset_range)
530    }
531
532    pub fn to_lsp_range(&mut self, range: Range<usize>) -> lsp::Range {
533        let snapshot = self.update_editor(|editor, cx| editor.snapshot(cx));
534        let start_point = range.start.to_point(&snapshot.buffer_snapshot);
535        let end_point = range.end.to_point(&snapshot.buffer_snapshot);
536
537        self.editor(|editor, cx| {
538            let buffer = editor.buffer().read(cx);
539            let start = point_to_lsp(
540                buffer
541                    .point_to_buffer_offset(start_point, cx)
542                    .unwrap()
543                    .1
544                    .to_point_utf16(&buffer.read(cx)),
545            );
546            let end = point_to_lsp(
547                buffer
548                    .point_to_buffer_offset(end_point, cx)
549                    .unwrap()
550                    .1
551                    .to_point_utf16(&buffer.read(cx)),
552            );
553
554            lsp::Range { start, end }
555        })
556    }
557
558    pub fn to_lsp(&mut self, offset: usize) -> lsp::Position {
559        let snapshot = self.update_editor(|editor, cx| editor.snapshot(cx));
560        let point = offset.to_point(&snapshot.buffer_snapshot);
561
562        self.editor(|editor, cx| {
563            let buffer = editor.buffer().read(cx);
564            point_to_lsp(
565                buffer
566                    .point_to_buffer_offset(point, cx)
567                    .unwrap()
568                    .1
569                    .to_point_utf16(&buffer.read(cx)),
570            )
571        })
572    }
573
574    pub fn update_workspace<F, T>(&mut self, update: F) -> T
575    where
576        F: FnOnce(&mut Workspace, &mut ViewContext<Workspace>) -> T,
577    {
578        self.workspace.update(self.cx.cx, update)
579    }
580
581    pub fn handle_request<T, F, Fut>(
582        &self,
583        mut handler: F,
584    ) -> futures::channel::mpsc::UnboundedReceiver<()>
585    where
586        T: 'static + request::Request,
587        T::Params: 'static + Send,
588        F: 'static + Send + FnMut(lsp::Url, T::Params, gpui::AsyncAppContext) -> Fut,
589        Fut: 'static + Send + Future<Output = Result<T::Result>>,
590    {
591        let url = self.editor_lsp_url.clone();
592        self.lsp.handle_request::<T, _, _>(move |params, cx| {
593            let url = url.clone();
594            handler(url, params, cx)
595        })
596    }
597}
598
599impl<'a> Deref for EditorLspTestContext<'a> {
600    type Target = EditorTestContext<'a>;
601
602    fn deref(&self) -> &Self::Target {
603        &self.cx
604    }
605}
606
607impl<'a> DerefMut for EditorLspTestContext<'a> {
608    fn deref_mut(&mut self) -> &mut Self::Target {
609        &mut self.cx
610    }
611}