editor_test_context.rs

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