editor_test_context.rs

  1use crate::{
  2    AnchorRangeExt, Autoscroll, DisplayPoint, Editor, MultiBuffer, RowExt,
  3    display_map::ToDisplayPoint,
  4};
  5use buffer_diff::DiffHunkStatusKind;
  6use collections::BTreeMap;
  7use futures::Future;
  8
  9use gpui::{
 10    AnyWindowHandle, App, Context, Entity, Focusable as _, Keystroke, Pixels, Point,
 11    VisualTestContext, Window, WindowHandle, prelude::*,
 12};
 13use itertools::Itertools;
 14use language::{Buffer, BufferSnapshot, LanguageRegistry};
 15use multi_buffer::{Anchor, ExcerptRange, MultiBufferRow};
 16use parking_lot::RwLock;
 17use project::{FakeFs, Project};
 18use std::{
 19    any::TypeId,
 20    ops::{Deref, DerefMut, Range},
 21    path::Path,
 22    sync::{
 23        Arc,
 24        atomic::{AtomicUsize, Ordering},
 25    },
 26};
 27use util::{
 28    assert_set_eq,
 29    test::{generate_marked_text, marked_text_ranges},
 30};
 31
 32use super::{build_editor, build_editor_with_project};
 33
 34pub struct EditorTestContext {
 35    pub cx: gpui::VisualTestContext,
 36    pub window: AnyWindowHandle,
 37    pub editor: Entity<Editor>,
 38    pub assertion_cx: AssertionContextManager,
 39}
 40
 41impl EditorTestContext {
 42    pub async fn new(cx: &mut gpui::TestAppContext) -> EditorTestContext {
 43        let fs = FakeFs::new(cx.executor());
 44        let root = Self::root_path();
 45        fs.insert_tree(
 46            root,
 47            serde_json::json!({
 48                ".git": {},
 49                "file": "",
 50            }),
 51        )
 52        .await;
 53        let project = Project::test(fs.clone(), [root], cx).await;
 54        let buffer = project
 55            .update(cx, |project, cx| {
 56                project.open_local_buffer(root.join("file"), cx)
 57            })
 58            .await
 59            .unwrap();
 60        let editor = cx.add_window(|window, cx| {
 61            let editor = build_editor_with_project(
 62                project,
 63                MultiBuffer::build_from_buffer(buffer, cx),
 64                window,
 65                cx,
 66            );
 67
 68            window.focus(&editor.focus_handle(cx));
 69            editor
 70        });
 71        let editor_view = editor.root(cx).unwrap();
 72
 73        cx.run_until_parked();
 74        Self {
 75            cx: VisualTestContext::from_window(*editor.deref(), cx),
 76            window: editor.into(),
 77            editor: editor_view,
 78            assertion_cx: AssertionContextManager::new(),
 79        }
 80    }
 81
 82    #[cfg(target_os = "windows")]
 83    fn root_path() -> &'static Path {
 84        Path::new("C:\\root")
 85    }
 86
 87    #[cfg(not(target_os = "windows"))]
 88    fn root_path() -> &'static Path {
 89        Path::new("/root")
 90    }
 91
 92    pub async fn for_editor_in(editor: Entity<Editor>, cx: &mut gpui::VisualTestContext) -> Self {
 93        cx.focus(&editor);
 94        Self {
 95            window: cx.windows()[0],
 96            cx: cx.clone(),
 97            editor,
 98            assertion_cx: AssertionContextManager::new(),
 99        }
100    }
101
102    pub async fn for_editor(editor: WindowHandle<Editor>, cx: &mut gpui::TestAppContext) -> Self {
103        let editor_view = editor.root(cx).unwrap();
104        Self {
105            cx: VisualTestContext::from_window(*editor.deref(), cx),
106            window: editor.into(),
107            editor: editor_view,
108            assertion_cx: AssertionContextManager::new(),
109        }
110    }
111
112    pub fn new_multibuffer<const COUNT: usize>(
113        cx: &mut gpui::TestAppContext,
114        excerpts: [&str; COUNT],
115    ) -> EditorTestContext {
116        let mut multibuffer = MultiBuffer::new(language::Capability::ReadWrite);
117        let buffer = cx.new(|cx| {
118            for excerpt in excerpts.into_iter() {
119                let (text, ranges) = marked_text_ranges(excerpt, false);
120                let buffer = cx.new(|cx| Buffer::local(text, cx));
121                multibuffer.push_excerpts(
122                    buffer,
123                    ranges
124                        .into_iter()
125                        .map(|range| ExcerptRange::new(range.clone())),
126                    cx,
127                );
128            }
129            multibuffer
130        });
131
132        let editor = cx.add_window(|window, cx| {
133            let editor = build_editor(buffer, window, cx);
134            window.focus(&editor.focus_handle(cx));
135
136            editor
137        });
138
139        let editor_view = editor.root(cx).unwrap();
140        Self {
141            cx: VisualTestContext::from_window(*editor.deref(), cx),
142            window: editor.into(),
143            editor: editor_view,
144            assertion_cx: AssertionContextManager::new(),
145        }
146    }
147
148    pub fn condition(
149        &self,
150        predicate: impl FnMut(&Editor, &App) -> bool,
151    ) -> impl Future<Output = ()> {
152        self.editor
153            .condition::<crate::EditorEvent>(&self.cx, predicate)
154    }
155
156    #[track_caller]
157    pub fn editor<F, T>(&mut self, read: F) -> T
158    where
159        F: FnOnce(&Editor, &Window, &mut Context<Editor>) -> T,
160    {
161        self.editor
162            .update_in(&mut self.cx, |this, window, cx| read(this, window, cx))
163    }
164
165    #[track_caller]
166    pub fn update_editor<F, T>(&mut self, update: F) -> T
167    where
168        F: FnOnce(&mut Editor, &mut Window, &mut Context<Editor>) -> T,
169    {
170        self.editor.update_in(&mut self.cx, update)
171    }
172
173    pub fn multibuffer<F, T>(&mut self, read: F) -> T
174    where
175        F: FnOnce(&MultiBuffer, &App) -> T,
176    {
177        self.editor(|editor, _, cx| read(editor.buffer().read(cx), cx))
178    }
179
180    pub fn update_multibuffer<F, T>(&mut self, update: F) -> T
181    where
182        F: FnOnce(&mut MultiBuffer, &mut Context<MultiBuffer>) -> T,
183    {
184        self.update_editor(|editor, _, cx| editor.buffer().update(cx, update))
185    }
186
187    pub fn buffer_text(&mut self) -> String {
188        self.multibuffer(|buffer, cx| buffer.snapshot(cx).text())
189    }
190
191    pub fn display_text(&mut self) -> String {
192        self.update_editor(|editor, _, cx| editor.display_text(cx))
193    }
194
195    pub fn buffer<F, T>(&mut self, read: F) -> T
196    where
197        F: FnOnce(&Buffer, &App) -> T,
198    {
199        self.multibuffer(|multibuffer, cx| {
200            let buffer = multibuffer.as_singleton().unwrap().read(cx);
201            read(buffer, cx)
202        })
203    }
204
205    pub fn language_registry(&mut self) -> Arc<LanguageRegistry> {
206        self.editor(|editor, _, cx| {
207            editor
208                .project
209                .as_ref()
210                .unwrap()
211                .read(cx)
212                .languages()
213                .clone()
214        })
215    }
216
217    pub fn update_buffer<F, T>(&mut self, update: F) -> T
218    where
219        F: FnOnce(&mut Buffer, &mut Context<Buffer>) -> T,
220    {
221        self.update_multibuffer(|multibuffer, cx| {
222            let buffer = multibuffer.as_singleton().unwrap();
223            buffer.update(cx, update)
224        })
225    }
226
227    pub fn buffer_snapshot(&mut self) -> BufferSnapshot {
228        self.buffer(|buffer, _| buffer.snapshot())
229    }
230
231    pub fn add_assertion_context(&self, context: String) -> ContextHandle {
232        self.assertion_cx.add_context(context)
233    }
234
235    pub fn assertion_context(&self) -> String {
236        self.assertion_cx.context()
237    }
238
239    // unlike cx.simulate_keystrokes(), this does not run_until_parked
240    // so you can use it to test detailed timing
241    pub fn simulate_keystroke(&mut self, keystroke_text: &str) {
242        let keystroke = Keystroke::parse(keystroke_text).unwrap();
243        self.cx.dispatch_keystroke(self.window, keystroke);
244    }
245
246    pub fn run_until_parked(&mut self) {
247        self.cx.background_executor.run_until_parked();
248    }
249
250    #[track_caller]
251    pub fn ranges(&mut self, marked_text: &str) -> Vec<Range<usize>> {
252        let (unmarked_text, ranges) = marked_text_ranges(marked_text, false);
253        assert_eq!(self.buffer_text(), unmarked_text);
254        ranges
255    }
256
257    pub fn display_point(&mut self, marked_text: &str) -> DisplayPoint {
258        let ranges = self.ranges(marked_text);
259        let snapshot = self.editor.update_in(&mut self.cx, |editor, window, cx| {
260            editor.snapshot(window, cx)
261        });
262        ranges[0].start.to_display_point(&snapshot)
263    }
264
265    pub fn pixel_position(&mut self, marked_text: &str) -> Point<Pixels> {
266        let display_point = self.display_point(marked_text);
267        self.pixel_position_for(display_point)
268    }
269
270    pub fn pixel_position_for(&mut self, display_point: DisplayPoint) -> Point<Pixels> {
271        self.update_editor(|editor, window, cx| {
272            let newest_point = editor.selections.newest_display(cx).head();
273            let pixel_position = editor.pixel_position_of_newest_cursor.unwrap();
274            let line_height = editor
275                .style()
276                .unwrap()
277                .text
278                .line_height_in_pixels(window.rem_size());
279            let snapshot = editor.snapshot(window, cx);
280            let details = editor.text_layout_details(window);
281
282            let y = pixel_position.y
283                + line_height * (display_point.row().as_f32() - newest_point.row().as_f32());
284            let x = pixel_position.x + snapshot.x_for_display_point(display_point, &details)
285                - snapshot.x_for_display_point(newest_point, &details);
286            Point::new(x, y)
287        })
288    }
289
290    // Returns anchors for the current buffer using `«` and `»`
291    pub fn text_anchor_range(&mut self, marked_text: &str) -> Range<language::Anchor> {
292        let ranges = self.ranges(marked_text);
293        let snapshot = self.buffer_snapshot();
294        snapshot.anchor_before(ranges[0].start)..snapshot.anchor_after(ranges[0].end)
295    }
296
297    pub fn set_head_text(&mut self, diff_base: &str) {
298        self.cx.run_until_parked();
299        let fs = self.update_editor(|editor, _, cx| {
300            editor.project.as_ref().unwrap().read(cx).fs().as_fake()
301        });
302        let path = self.update_buffer(|buffer, _| buffer.file().unwrap().path().clone());
303        fs.set_head_for_repo(
304            &Self::root_path().join(".git"),
305            &[(path.into(), diff_base.to_string())],
306        );
307        self.cx.run_until_parked();
308    }
309
310    pub fn clear_index_text(&mut self) {
311        self.cx.run_until_parked();
312        let fs = self.update_editor(|editor, _, cx| {
313            editor.project.as_ref().unwrap().read(cx).fs().as_fake()
314        });
315        fs.set_index_for_repo(&Self::root_path().join(".git"), &[]);
316        self.cx.run_until_parked();
317    }
318
319    pub fn set_index_text(&mut self, diff_base: &str) {
320        self.cx.run_until_parked();
321        let fs = self.update_editor(|editor, _, cx| {
322            editor.project.as_ref().unwrap().read(cx).fs().as_fake()
323        });
324        let path = self.update_buffer(|buffer, _| buffer.file().unwrap().path().clone());
325        fs.set_index_for_repo(
326            &Self::root_path().join(".git"),
327            &[(path.into(), diff_base.to_string())],
328        );
329        self.cx.run_until_parked();
330    }
331
332    #[track_caller]
333    pub fn assert_index_text(&mut self, expected: Option<&str>) {
334        let fs = self.update_editor(|editor, _, cx| {
335            editor.project.as_ref().unwrap().read(cx).fs().as_fake()
336        });
337        let path = self.update_buffer(|buffer, _| buffer.file().unwrap().path().clone());
338        let mut found = None;
339        fs.with_git_state(&Self::root_path().join(".git"), false, |git_state| {
340            found = git_state.index_contents.get(path.as_ref()).cloned();
341        })
342        .unwrap();
343        assert_eq!(expected, found.as_deref());
344    }
345
346    /// Change the editor's text and selections using a string containing
347    /// embedded range markers that represent the ranges and directions of
348    /// each selection.
349    ///
350    /// Returns a context handle so that assertion failures can print what
351    /// editor state was needed to cause the failure.
352    ///
353    /// See the `util::test::marked_text_ranges` function for more information.
354    pub fn set_state(&mut self, marked_text: &str) -> ContextHandle {
355        let state_context = self.add_assertion_context(format!(
356            "Initial Editor State: \"{}\"",
357            marked_text.escape_debug()
358        ));
359        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
360        self.editor.update_in(&mut self.cx, |editor, window, cx| {
361            editor.set_text(unmarked_text, window, cx);
362            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
363                s.select_ranges(selection_ranges)
364            })
365        });
366        state_context
367    }
368
369    /// Only change the editor's selections
370    pub fn set_selections_state(&mut self, marked_text: &str) -> ContextHandle {
371        let state_context = self.add_assertion_context(format!(
372            "Initial Editor State: \"{}\"",
373            marked_text.escape_debug()
374        ));
375        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
376        self.editor.update_in(&mut self.cx, |editor, window, cx| {
377            assert_eq!(editor.text(cx), unmarked_text);
378            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
379                s.select_ranges(selection_ranges)
380            })
381        });
382        state_context
383    }
384
385    /// Assert about the text of the editor, the selections, and the expanded
386    /// diff hunks.
387    ///
388    /// Diff hunks are indicated by lines starting with `+` and `-`.
389    #[track_caller]
390    pub fn assert_state_with_diff(&mut self, expected_diff_text: String) {
391        assert_state_with_diff(&self.editor, &mut self.cx, &expected_diff_text);
392    }
393
394    #[track_caller]
395    pub fn assert_excerpts_with_selections(&mut self, marked_text: &str) {
396        let expected_excerpts = marked_text
397            .strip_prefix("[EXCERPT]\n")
398            .unwrap()
399            .split("[EXCERPT]\n")
400            .collect::<Vec<_>>();
401
402        let (multibuffer_snapshot, selections, excerpts) = self.update_editor(|editor, _, cx| {
403            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
404
405            let selections = editor.selections.disjoint_anchors();
406            let excerpts = multibuffer_snapshot
407                .excerpts()
408                .map(|(e_id, snapshot, range)| (e_id, snapshot.clone(), range))
409                .collect::<Vec<_>>();
410
411            (multibuffer_snapshot, selections, excerpts)
412        });
413
414        assert!(
415            excerpts.len() == expected_excerpts.len(),
416            "should have {} excerpts, got {}",
417            expected_excerpts.len(),
418            excerpts.len()
419        );
420
421        for (ix, (excerpt_id, snapshot, range)) in excerpts.into_iter().enumerate() {
422            let is_folded = self
423                .update_editor(|editor, _, cx| editor.is_buffer_folded(snapshot.remote_id(), cx));
424            let (expected_text, expected_selections) =
425                marked_text_ranges(expected_excerpts[ix], true);
426            if expected_text == "[FOLDED]\n" {
427                assert!(is_folded, "excerpt {} should be folded", ix);
428                let is_selected = selections.iter().any(|s| s.head().excerpt_id == excerpt_id);
429                if expected_selections.len() > 0 {
430                    assert!(
431                        is_selected,
432                        "excerpt {ix} should be selected. got {:?}",
433                        self.editor_state(),
434                    );
435                } else {
436                    assert!(
437                        !is_selected,
438                        "excerpt {ix} should not be selected, got: {selections:?}",
439                    );
440                }
441                continue;
442            }
443            assert!(!is_folded, "excerpt {} should not be folded", ix);
444            assert_eq!(
445                multibuffer_snapshot
446                    .text_for_range(Anchor::range_in_buffer(
447                        excerpt_id,
448                        snapshot.remote_id(),
449                        range.context.clone()
450                    ))
451                    .collect::<String>(),
452                expected_text
453            );
454
455            let selections = selections
456                .iter()
457                .filter(|s| s.head().excerpt_id == excerpt_id)
458                .map(|s| {
459                    let head = text::ToOffset::to_offset(&s.head().text_anchor, &snapshot)
460                        - text::ToOffset::to_offset(&range.context.start, &snapshot);
461                    let tail = text::ToOffset::to_offset(&s.head().text_anchor, &snapshot)
462                        - text::ToOffset::to_offset(&range.context.start, &snapshot);
463                    tail..head
464                })
465                .collect::<Vec<_>>();
466            // todo: selections that cross excerpt boundaries..
467            assert_eq!(
468                selections, expected_selections,
469                "excerpt {} has incorrect selections",
470                ix,
471            );
472        }
473    }
474
475    /// Make an assertion about the editor's text and the ranges and directions
476    /// of its selections using a string containing embedded range markers.
477    ///
478    /// See the `util::test::marked_text_ranges` function for more information.
479    #[track_caller]
480    pub fn assert_editor_state(&mut self, marked_text: &str) {
481        let (expected_text, expected_selections) = marked_text_ranges(marked_text, true);
482        pretty_assertions::assert_eq!(self.buffer_text(), expected_text, "unexpected buffer text");
483        self.assert_selections(expected_selections, marked_text.to_string())
484    }
485
486    /// Make an assertion about the editor's text and the ranges and directions
487    /// of its selections using a string containing embedded range markers.
488    ///
489    /// See the `util::test::marked_text_ranges` function for more information.
490    #[track_caller]
491    pub fn assert_display_state(&mut self, marked_text: &str) {
492        let (expected_text, expected_selections) = marked_text_ranges(marked_text, true);
493        pretty_assertions::assert_eq!(self.display_text(), expected_text, "unexpected buffer text");
494        self.assert_selections(expected_selections, marked_text.to_string())
495    }
496
497    pub fn editor_state(&mut self) -> String {
498        generate_marked_text(self.buffer_text().as_str(), &self.editor_selections(), true)
499    }
500
501    #[track_caller]
502    pub fn assert_editor_background_highlights<Tag: 'static>(&mut self, marked_text: &str) {
503        let expected_ranges = self.ranges(marked_text);
504        let actual_ranges: Vec<Range<usize>> = self.update_editor(|editor, window, cx| {
505            let snapshot = editor.snapshot(window, cx);
506            editor
507                .background_highlights
508                .get(&TypeId::of::<Tag>())
509                .map(|h| h.1.clone())
510                .unwrap_or_default()
511                .iter()
512                .map(|range| range.to_offset(&snapshot.buffer_snapshot))
513                .collect()
514        });
515        assert_set_eq!(actual_ranges, expected_ranges);
516    }
517
518    #[track_caller]
519    pub fn assert_editor_text_highlights<Tag: ?Sized + 'static>(&mut self, marked_text: &str) {
520        let expected_ranges = self.ranges(marked_text);
521        let snapshot = self.update_editor(|editor, window, cx| editor.snapshot(window, cx));
522        let actual_ranges: Vec<Range<usize>> = snapshot
523            .text_highlight_ranges::<Tag>()
524            .map(|ranges| ranges.as_ref().clone().1)
525            .unwrap_or_default()
526            .into_iter()
527            .map(|range| range.to_offset(&snapshot.buffer_snapshot))
528            .collect();
529        assert_set_eq!(actual_ranges, expected_ranges);
530    }
531
532    #[track_caller]
533    pub fn assert_editor_selections(&mut self, expected_selections: Vec<Range<usize>>) {
534        let expected_marked_text =
535            generate_marked_text(&self.buffer_text(), &expected_selections, true);
536        self.assert_selections(expected_selections, expected_marked_text)
537    }
538
539    #[track_caller]
540    fn editor_selections(&mut self) -> Vec<Range<usize>> {
541        self.editor
542            .update(&mut self.cx, |editor, cx| {
543                editor.selections.all::<usize>(cx)
544            })
545            .into_iter()
546            .map(|s| {
547                if s.reversed {
548                    s.end..s.start
549                } else {
550                    s.start..s.end
551                }
552            })
553            .collect::<Vec<_>>()
554    }
555
556    #[track_caller]
557    fn assert_selections(
558        &mut self,
559        expected_selections: Vec<Range<usize>>,
560        expected_marked_text: String,
561    ) {
562        let actual_selections = self.editor_selections();
563        let actual_marked_text =
564            generate_marked_text(&self.buffer_text(), &actual_selections, true);
565        if expected_selections != actual_selections {
566            pretty_assertions::assert_eq!(
567                actual_marked_text,
568                expected_marked_text,
569                "{}Editor has unexpected selections",
570                self.assertion_context(),
571            );
572        }
573    }
574}
575
576#[track_caller]
577pub fn assert_state_with_diff(
578    editor: &Entity<Editor>,
579    cx: &mut VisualTestContext,
580    expected_diff_text: &str,
581) {
582    let (snapshot, selections) = editor.update_in(cx, |editor, window, cx| {
583        (
584            editor.snapshot(window, cx).buffer_snapshot.clone(),
585            editor.selections.ranges::<usize>(cx),
586        )
587    });
588
589    let actual_marked_text = generate_marked_text(&snapshot.text(), &selections, true);
590
591    // Read the actual diff.
592    let line_infos = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
593    let has_diff = line_infos.iter().any(|info| info.diff_status.is_some());
594    let actual_diff = actual_marked_text
595        .split('\n')
596        .zip(line_infos)
597        .map(|(line, info)| {
598            let mut marker = match info.diff_status.map(|status| status.kind) {
599                Some(DiffHunkStatusKind::Added) => "+ ",
600                Some(DiffHunkStatusKind::Deleted) => "- ",
601                Some(DiffHunkStatusKind::Modified) => unreachable!(),
602                None => {
603                    if has_diff {
604                        "  "
605                    } else {
606                        ""
607                    }
608                }
609            };
610            if line.is_empty() {
611                marker = marker.trim();
612            }
613            format!("{marker}{line}")
614        })
615        .collect::<Vec<_>>()
616        .join("\n");
617
618    pretty_assertions::assert_eq!(actual_diff, expected_diff_text, "unexpected diff state");
619}
620
621impl Deref for EditorTestContext {
622    type Target = gpui::VisualTestContext;
623
624    fn deref(&self) -> &Self::Target {
625        &self.cx
626    }
627}
628
629impl DerefMut for EditorTestContext {
630    fn deref_mut(&mut self) -> &mut Self::Target {
631        &mut self.cx
632    }
633}
634
635/// Tracks string context to be printed when assertions fail.
636/// Often this is done by storing a context string in the manager and returning the handle.
637#[derive(Clone)]
638pub struct AssertionContextManager {
639    id: Arc<AtomicUsize>,
640    contexts: Arc<RwLock<BTreeMap<usize, String>>>,
641}
642
643impl Default for AssertionContextManager {
644    fn default() -> Self {
645        Self::new()
646    }
647}
648
649impl AssertionContextManager {
650    pub fn new() -> Self {
651        Self {
652            id: Arc::new(AtomicUsize::new(0)),
653            contexts: Arc::new(RwLock::new(BTreeMap::new())),
654        }
655    }
656
657    pub fn add_context(&self, context: String) -> ContextHandle {
658        let id = self.id.fetch_add(1, Ordering::Relaxed);
659        let mut contexts = self.contexts.write();
660        contexts.insert(id, context);
661        ContextHandle {
662            id,
663            manager: self.clone(),
664        }
665    }
666
667    pub fn context(&self) -> String {
668        let contexts = self.contexts.read();
669        format!("\n{}\n", contexts.values().join("\n"))
670    }
671}
672
673/// Used to track the lifetime of a piece of context so that it can be provided when an assertion fails.
674/// For example, in the EditorTestContext, `set_state` returns a context handle so that if an assertion fails,
675/// the state that was set initially for the failure can be printed in the error message
676pub struct ContextHandle {
677    id: usize,
678    manager: AssertionContextManager,
679}
680
681impl Drop for ContextHandle {
682    fn drop(&mut self) {
683        let mut contexts = self.manager.contexts.write();
684        contexts.remove(&self.id);
685    }
686}