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                + f32::from(line_height)
279                    * Pixels::from(display_point.row().as_f64() - newest_point.row().as_f64());
280            let x = pixel_position.x + snapshot.x_for_display_point(display_point, &details)
281                - snapshot.x_for_display_point(newest_point, &details);
282            Point::new(x, y)
283        })
284    }
285
286    // Returns anchors for the current buffer using `«` and `»`
287    pub fn text_anchor_range(&mut self, marked_text: &str) -> Range<language::Anchor> {
288        let ranges = self.ranges(marked_text);
289        let snapshot = self.buffer_snapshot();
290        snapshot.anchor_before(ranges[0].start)..snapshot.anchor_after(ranges[0].end)
291    }
292
293    pub fn set_head_text(&mut self, diff_base: &str) {
294        self.cx.run_until_parked();
295        let fs =
296            self.update_editor(|editor, _, cx| editor.project().unwrap().read(cx).fs().as_fake());
297        let path = self.update_buffer(|buffer, _| buffer.file().unwrap().path().clone());
298        fs.set_head_for_repo(
299            &Self::root_path().join(".git"),
300            &[(path.as_unix_str(), diff_base.to_string())],
301            "deadbeef",
302        );
303        self.cx.run_until_parked();
304    }
305
306    pub fn clear_index_text(&mut self) {
307        self.cx.run_until_parked();
308        let fs =
309            self.update_editor(|editor, _, cx| editor.project().unwrap().read(cx).fs().as_fake());
310        fs.set_index_for_repo(&Self::root_path().join(".git"), &[]);
311        self.cx.run_until_parked();
312    }
313
314    pub fn set_index_text(&mut self, diff_base: &str) {
315        self.cx.run_until_parked();
316        let fs =
317            self.update_editor(|editor, _, cx| editor.project().unwrap().read(cx).fs().as_fake());
318        let path = self.update_buffer(|buffer, _| buffer.file().unwrap().path().clone());
319        fs.set_index_for_repo(
320            &Self::root_path().join(".git"),
321            &[(path.as_unix_str(), diff_base.to_string())],
322        );
323        self.cx.run_until_parked();
324    }
325
326    #[track_caller]
327    pub fn assert_index_text(&mut self, expected: Option<&str>) {
328        let fs =
329            self.update_editor(|editor, _, cx| editor.project().unwrap().read(cx).fs().as_fake());
330        let path = self.update_buffer(|buffer, _| buffer.file().unwrap().path().clone());
331        let mut found = None;
332        fs.with_git_state(&Self::root_path().join(".git"), false, |git_state| {
333            found = git_state.index_contents.get(&path.into()).cloned();
334        })
335        .unwrap();
336        assert_eq!(expected, found.as_deref());
337    }
338
339    /// Change the editor's text and selections using a string containing
340    /// embedded range markers that represent the ranges and directions of
341    /// each selection.
342    ///
343    /// Returns a context handle so that assertion failures can print what
344    /// editor state was needed to cause the failure.
345    ///
346    /// See the `util::test::marked_text_ranges` function for more information.
347    #[track_caller]
348    pub fn set_state(&mut self, marked_text: &str) -> ContextHandle {
349        let state_context = self.add_assertion_context(format!(
350            "Initial Editor State: \"{}\"",
351            marked_text.escape_debug()
352        ));
353        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
354        self.editor.update_in(&mut self.cx, |editor, window, cx| {
355            editor.set_text(unmarked_text, window, cx);
356            editor.change_selections(Default::default(), window, cx, |s| {
357                s.select_ranges(selection_ranges)
358            })
359        });
360        state_context
361    }
362
363    /// Only change the editor's selections
364    #[track_caller]
365    pub fn set_selections_state(&mut self, marked_text: &str) -> ContextHandle {
366        let state_context = self.add_assertion_context(format!(
367            "Initial Editor State: \"{}\"",
368            marked_text.escape_debug()
369        ));
370        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
371        self.editor.update_in(&mut self.cx, |editor, window, cx| {
372            assert_eq!(editor.text(cx), unmarked_text);
373            editor.change_selections(Default::default(), window, cx, |s| {
374                s.select_ranges(selection_ranges)
375            })
376        });
377        state_context
378    }
379
380    /// Assert about the text of the editor, the selections, and the expanded
381    /// diff hunks.
382    ///
383    /// Diff hunks are indicated by lines starting with `+` and `-`.
384    #[track_caller]
385    pub fn assert_state_with_diff(&mut self, expected_diff_text: String) {
386        assert_state_with_diff(&self.editor, &mut self.cx, &expected_diff_text);
387    }
388
389    #[track_caller]
390    pub fn assert_excerpts_with_selections(&mut self, marked_text: &str) {
391        let expected_excerpts = marked_text
392            .strip_prefix("[EXCERPT]\n")
393            .unwrap()
394            .split("[EXCERPT]\n")
395            .collect::<Vec<_>>();
396
397        let (multibuffer_snapshot, selections, excerpts) = self.update_editor(|editor, _, cx| {
398            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
399
400            let selections = editor.selections.disjoint_anchors_arc();
401            let excerpts = multibuffer_snapshot
402                .excerpts()
403                .map(|(e_id, snapshot, range)| (e_id, snapshot.clone(), range))
404                .collect::<Vec<_>>();
405
406            (multibuffer_snapshot, selections, excerpts)
407        });
408
409        assert!(
410            excerpts.len() == expected_excerpts.len(),
411            "should have {} excerpts, got {}",
412            expected_excerpts.len(),
413            excerpts.len()
414        );
415
416        for (ix, (excerpt_id, snapshot, range)) in excerpts.into_iter().enumerate() {
417            let is_folded = self
418                .update_editor(|editor, _, cx| editor.is_buffer_folded(snapshot.remote_id(), cx));
419            let (expected_text, expected_selections) =
420                marked_text_ranges(expected_excerpts[ix], true);
421            if expected_text == "[FOLDED]\n" {
422                assert!(is_folded, "excerpt {} should be folded", ix);
423                let is_selected = selections.iter().any(|s| s.head().excerpt_id == excerpt_id);
424                if !expected_selections.is_empty() {
425                    assert!(
426                        is_selected,
427                        "excerpt {ix} should be selected. got {:?}",
428                        self.editor_state(),
429                    );
430                } else {
431                    assert!(
432                        !is_selected,
433                        "excerpt {ix} should not be selected, got: {selections:?}",
434                    );
435                }
436                continue;
437            }
438            assert!(!is_folded, "excerpt {} should not be folded", ix);
439            assert_eq!(
440                multibuffer_snapshot
441                    .text_for_range(Anchor::range_in_buffer(
442                        excerpt_id,
443                        snapshot.remote_id(),
444                        range.context.clone()
445                    ))
446                    .collect::<String>(),
447                expected_text
448            );
449
450            let selections = selections
451                .iter()
452                .filter(|s| s.head().excerpt_id == excerpt_id)
453                .map(|s| {
454                    let head = text::ToOffset::to_offset(&s.head().text_anchor, &snapshot)
455                        - text::ToOffset::to_offset(&range.context.start, &snapshot);
456                    let tail = text::ToOffset::to_offset(&s.head().text_anchor, &snapshot)
457                        - text::ToOffset::to_offset(&range.context.start, &snapshot);
458                    tail..head
459                })
460                .collect::<Vec<_>>();
461            // todo: selections that cross excerpt boundaries..
462            assert_eq!(
463                selections, expected_selections,
464                "excerpt {} has incorrect selections",
465                ix,
466            );
467        }
468    }
469
470    /// Make an assertion about the editor's text and the ranges and directions
471    /// of its selections using a string containing embedded range markers.
472    ///
473    /// See the `util::test::marked_text_ranges` function for more information.
474    #[track_caller]
475    pub fn assert_editor_state(&mut self, marked_text: &str) {
476        let (expected_text, expected_selections) = marked_text_ranges(marked_text, true);
477        pretty_assertions::assert_eq!(self.buffer_text(), expected_text, "unexpected buffer text");
478        self.assert_selections(expected_selections, marked_text.to_string())
479    }
480
481    /// Make an assertion about the editor's text and the ranges and directions
482    /// of its selections using a string containing embedded range markers.
483    ///
484    /// See the `util::test::marked_text_ranges` function for more information.
485    #[track_caller]
486    pub fn assert_display_state(&mut self, marked_text: &str) {
487        let (expected_text, expected_selections) = marked_text_ranges(marked_text, true);
488        pretty_assertions::assert_eq!(self.display_text(), expected_text, "unexpected buffer text");
489        self.assert_selections(expected_selections, marked_text.to_string())
490    }
491
492    pub fn editor_state(&mut self) -> String {
493        generate_marked_text(self.buffer_text().as_str(), &self.editor_selections(), true)
494    }
495
496    #[track_caller]
497    pub fn assert_editor_background_highlights<Tag: 'static>(&mut self, marked_text: &str) {
498        let expected_ranges = self.ranges(marked_text);
499        let actual_ranges: Vec<Range<usize>> = self.update_editor(|editor, window, cx| {
500            let snapshot = editor.snapshot(window, cx);
501            editor
502                .background_highlights
503                .get(&HighlightKey::Type(TypeId::of::<Tag>()))
504                .map(|h| h.1.clone())
505                .unwrap_or_default()
506                .iter()
507                .map(|range| range.to_offset(&snapshot.buffer_snapshot()))
508                .collect()
509        });
510        assert_set_eq!(actual_ranges, expected_ranges);
511    }
512
513    #[track_caller]
514    pub fn assert_editor_text_highlights<Tag: ?Sized + 'static>(&mut self, marked_text: &str) {
515        let expected_ranges = self.ranges(marked_text);
516        let snapshot = self.update_editor(|editor, window, cx| editor.snapshot(window, cx));
517        let actual_ranges: Vec<Range<usize>> = snapshot
518            .text_highlight_ranges::<Tag>()
519            .map(|ranges| ranges.as_ref().clone().1)
520            .unwrap_or_default()
521            .into_iter()
522            .map(|range| range.to_offset(&snapshot.buffer_snapshot()))
523            .collect();
524        assert_set_eq!(actual_ranges, expected_ranges);
525    }
526
527    #[track_caller]
528    pub fn assert_editor_selections(&mut self, expected_selections: Vec<Range<usize>>) {
529        let expected_marked_text =
530            generate_marked_text(&self.buffer_text(), &expected_selections, true)
531                .replace(" \n", "\n");
532
533        self.assert_selections(expected_selections, expected_marked_text)
534    }
535
536    #[track_caller]
537    fn editor_selections(&mut self) -> Vec<Range<usize>> {
538        self.editor
539            .update(&mut self.cx, |editor, cx| {
540                editor.selections.all::<usize>(cx)
541            })
542            .into_iter()
543            .map(|s| {
544                if s.reversed {
545                    s.end..s.start
546                } else {
547                    s.start..s.end
548                }
549            })
550            .collect::<Vec<_>>()
551    }
552
553    #[track_caller]
554    fn assert_selections(
555        &mut self,
556        expected_selections: Vec<Range<usize>>,
557        expected_marked_text: String,
558    ) {
559        let actual_selections = self.editor_selections();
560        let actual_marked_text =
561            generate_marked_text(&self.buffer_text(), &actual_selections, true)
562                .replace(" \n", "\n");
563        if expected_selections != actual_selections {
564            pretty_assertions::assert_eq!(
565                actual_marked_text,
566                expected_marked_text,
567                "{}Editor has unexpected selections",
568                self.assertion_context(),
569            );
570        }
571    }
572}
573
574#[track_caller]
575pub fn assert_state_with_diff(
576    editor: &Entity<Editor>,
577    cx: &mut VisualTestContext,
578    expected_diff_text: &str,
579) {
580    let (snapshot, selections) = editor.update_in(cx, |editor, window, cx| {
581        (
582            editor.snapshot(window, cx).buffer_snapshot().clone(),
583            editor.selections.ranges::<usize>(cx),
584        )
585    });
586
587    let actual_marked_text = generate_marked_text(&snapshot.text(), &selections, true);
588
589    // Read the actual diff.
590    let line_infos = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
591    let has_diff = line_infos.iter().any(|info| info.diff_status.is_some());
592    let actual_diff = actual_marked_text
593        .split('\n')
594        .zip(line_infos)
595        .map(|(line, info)| {
596            let mut marker = match info.diff_status.map(|status| status.kind) {
597                Some(DiffHunkStatusKind::Added) => "+ ",
598                Some(DiffHunkStatusKind::Deleted) => "- ",
599                Some(DiffHunkStatusKind::Modified) => unreachable!(),
600                None => {
601                    if has_diff {
602                        "  "
603                    } else {
604                        ""
605                    }
606                }
607            };
608            if line.is_empty() {
609                marker = marker.trim();
610            }
611            format!("{marker}{line}")
612        })
613        .collect::<Vec<_>>()
614        .join("\n");
615
616    pretty_assertions::assert_eq!(actual_diff, expected_diff_text, "unexpected diff state");
617}
618
619impl Deref for EditorTestContext {
620    type Target = gpui::VisualTestContext;
621
622    fn deref(&self) -> &Self::Target {
623        &self.cx
624    }
625}
626
627impl DerefMut for EditorTestContext {
628    fn deref_mut(&mut self) -> &mut Self::Target {
629        &mut self.cx
630    }
631}
632
633/// Tracks string context to be printed when assertions fail.
634/// Often this is done by storing a context string in the manager and returning the handle.
635#[derive(Clone)]
636pub struct AssertionContextManager {
637    id: Arc<AtomicUsize>,
638    contexts: Arc<RwLock<BTreeMap<usize, String>>>,
639}
640
641impl Default for AssertionContextManager {
642    fn default() -> Self {
643        Self::new()
644    }
645}
646
647impl AssertionContextManager {
648    pub fn new() -> Self {
649        Self {
650            id: Arc::new(AtomicUsize::new(0)),
651            contexts: Arc::new(RwLock::new(BTreeMap::new())),
652        }
653    }
654
655    pub fn add_context(&self, context: String) -> ContextHandle {
656        let id = self.id.fetch_add(1, Ordering::Relaxed);
657        let mut contexts = self.contexts.write();
658        contexts.insert(id, context);
659        ContextHandle {
660            id,
661            manager: self.clone(),
662        }
663    }
664
665    pub fn context(&self) -> String {
666        let contexts = self.contexts.read();
667        format!("\n{}\n", contexts.values().join("\n"))
668    }
669}
670
671/// Used to track the lifetime of a piece of context so that it can be provided when an assertion fails.
672/// For example, in the EditorTestContext, `set_state` returns a context handle so that if an assertion fails,
673/// the state that was set initially for the failure can be printed in the error message
674pub struct ContextHandle {
675    id: usize,
676    manager: AssertionContextManager,
677}
678
679impl Drop for ContextHandle {
680    fn drop(&mut self) {
681        let mut contexts = self.manager.contexts.write();
682        contexts.remove(&self.id);
683    }
684}