editor_test_context.rs

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