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_diff_base(&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 assert_index_text(&mut self, expected: Option<&str>) {
302        let fs = self.update_editor(|editor, _, cx| {
303            editor.project.as_ref().unwrap().read(cx).fs().as_fake()
304        });
305        let path = self.update_buffer(|buffer, _| buffer.file().unwrap().path().clone());
306        let mut found = None;
307        fs.with_git_state(&Self::root_path().join(".git"), false, |git_state| {
308            found = git_state.index_contents.get(path.as_ref()).cloned();
309        });
310        assert_eq!(expected, found.as_deref());
311    }
312
313    /// Change the editor's text and selections using a string containing
314    /// embedded range markers that represent the ranges and directions of
315    /// each selection.
316    ///
317    /// Returns a context handle so that assertion failures can print what
318    /// editor state was needed to cause the failure.
319    ///
320    /// See the `util::test::marked_text_ranges` function for more information.
321    pub fn set_state(&mut self, marked_text: &str) -> ContextHandle {
322        let state_context = self.add_assertion_context(format!(
323            "Initial Editor State: \"{}\"",
324            marked_text.escape_debug()
325        ));
326        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
327        self.editor.update_in(&mut self.cx, |editor, window, cx| {
328            editor.set_text(unmarked_text, window, cx);
329            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
330                s.select_ranges(selection_ranges)
331            })
332        });
333        state_context
334    }
335
336    /// Only change the editor's selections
337    pub fn set_selections_state(&mut self, marked_text: &str) -> ContextHandle {
338        let state_context = self.add_assertion_context(format!(
339            "Initial Editor State: \"{}\"",
340            marked_text.escape_debug()
341        ));
342        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
343        self.editor.update_in(&mut self.cx, |editor, window, cx| {
344            assert_eq!(editor.text(cx), unmarked_text);
345            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
346                s.select_ranges(selection_ranges)
347            })
348        });
349        state_context
350    }
351
352    /// Assert about the text of the editor, the selections, and the expanded
353    /// diff hunks.
354    ///
355    /// Diff hunks are indicated by lines starting with `+` and `-`.
356    #[track_caller]
357    pub fn assert_state_with_diff(&mut self, expected_diff_text: String) {
358        assert_state_with_diff(&self.editor, &mut self.cx, &expected_diff_text);
359    }
360
361    /// Make an assertion about the editor's text and the ranges and directions
362    /// of its selections using a string containing embedded range markers.
363    ///
364    /// See the `util::test::marked_text_ranges` function for more information.
365    #[track_caller]
366    pub fn assert_editor_state(&mut self, marked_text: &str) {
367        let (expected_text, expected_selections) = marked_text_ranges(marked_text, true);
368        pretty_assertions::assert_eq!(self.buffer_text(), expected_text, "unexpected buffer text");
369        self.assert_selections(expected_selections, marked_text.to_string())
370    }
371
372    pub fn editor_state(&mut self) -> String {
373        generate_marked_text(self.buffer_text().as_str(), &self.editor_selections(), true)
374    }
375
376    #[track_caller]
377    pub fn assert_editor_background_highlights<Tag: 'static>(&mut self, marked_text: &str) {
378        let expected_ranges = self.ranges(marked_text);
379        let actual_ranges: Vec<Range<usize>> = self.update_editor(|editor, window, cx| {
380            let snapshot = editor.snapshot(window, cx);
381            editor
382                .background_highlights
383                .get(&TypeId::of::<Tag>())
384                .map(|h| h.1.clone())
385                .unwrap_or_default()
386                .iter()
387                .map(|range| range.to_offset(&snapshot.buffer_snapshot))
388                .collect()
389        });
390        assert_set_eq!(actual_ranges, expected_ranges);
391    }
392
393    #[track_caller]
394    pub fn assert_editor_text_highlights<Tag: ?Sized + 'static>(&mut self, marked_text: &str) {
395        let expected_ranges = self.ranges(marked_text);
396        let snapshot = self.update_editor(|editor, window, cx| editor.snapshot(window, cx));
397        let actual_ranges: Vec<Range<usize>> = snapshot
398            .text_highlight_ranges::<Tag>()
399            .map(|ranges| ranges.as_ref().clone().1)
400            .unwrap_or_default()
401            .into_iter()
402            .map(|range| range.to_offset(&snapshot.buffer_snapshot))
403            .collect();
404        assert_set_eq!(actual_ranges, expected_ranges);
405    }
406
407    #[track_caller]
408    pub fn assert_editor_selections(&mut self, expected_selections: Vec<Range<usize>>) {
409        let expected_marked_text =
410            generate_marked_text(&self.buffer_text(), &expected_selections, true);
411        self.assert_selections(expected_selections, expected_marked_text)
412    }
413
414    #[track_caller]
415    fn editor_selections(&mut self) -> Vec<Range<usize>> {
416        self.editor
417            .update(&mut self.cx, |editor, cx| {
418                editor.selections.all::<usize>(cx)
419            })
420            .into_iter()
421            .map(|s| {
422                if s.reversed {
423                    s.end..s.start
424                } else {
425                    s.start..s.end
426                }
427            })
428            .collect::<Vec<_>>()
429    }
430
431    #[track_caller]
432    fn assert_selections(
433        &mut self,
434        expected_selections: Vec<Range<usize>>,
435        expected_marked_text: String,
436    ) {
437        let actual_selections = self.editor_selections();
438        let actual_marked_text =
439            generate_marked_text(&self.buffer_text(), &actual_selections, true);
440        if expected_selections != actual_selections {
441            pretty_assertions::assert_eq!(
442                actual_marked_text,
443                expected_marked_text,
444                "{}Editor has unexpected selections",
445                self.assertion_context(),
446            );
447        }
448    }
449}
450
451#[track_caller]
452pub fn assert_state_with_diff(
453    editor: &Entity<Editor>,
454    cx: &mut VisualTestContext,
455    expected_diff_text: &str,
456) {
457    let (snapshot, selections) = editor.update_in(cx, |editor, window, cx| {
458        (
459            editor.snapshot(window, cx).buffer_snapshot.clone(),
460            editor.selections.ranges::<usize>(cx),
461        )
462    });
463
464    let actual_marked_text = generate_marked_text(&snapshot.text(), &selections, true);
465
466    // Read the actual diff.
467    let line_infos = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
468    let has_diff = line_infos.iter().any(|info| info.diff_status.is_some());
469    let actual_diff = actual_marked_text
470        .split('\n')
471        .zip(line_infos)
472        .map(|(line, info)| {
473            let mut marker = match info.diff_status.map(|status| status.kind) {
474                Some(DiffHunkStatusKind::Added) => "+ ",
475                Some(DiffHunkStatusKind::Deleted) => "- ",
476                Some(DiffHunkStatusKind::Modified) => unreachable!(),
477                None => {
478                    if has_diff {
479                        "  "
480                    } else {
481                        ""
482                    }
483                }
484            };
485            if line.is_empty() {
486                marker = marker.trim();
487            }
488            format!("{marker}{line}")
489        })
490        .collect::<Vec<_>>()
491        .join("\n");
492
493    pretty_assertions::assert_eq!(actual_diff, expected_diff_text, "unexpected diff state");
494}
495
496impl Deref for EditorTestContext {
497    type Target = gpui::VisualTestContext;
498
499    fn deref(&self) -> &Self::Target {
500        &self.cx
501    }
502}
503
504impl DerefMut for EditorTestContext {
505    fn deref_mut(&mut self) -> &mut Self::Target {
506        &mut self.cx
507    }
508}
509
510/// Tracks string context to be printed when assertions fail.
511/// Often this is done by storing a context string in the manager and returning the handle.
512#[derive(Clone)]
513pub struct AssertionContextManager {
514    id: Arc<AtomicUsize>,
515    contexts: Arc<RwLock<BTreeMap<usize, String>>>,
516}
517
518impl Default for AssertionContextManager {
519    fn default() -> Self {
520        Self::new()
521    }
522}
523
524impl AssertionContextManager {
525    pub fn new() -> Self {
526        Self {
527            id: Arc::new(AtomicUsize::new(0)),
528            contexts: Arc::new(RwLock::new(BTreeMap::new())),
529        }
530    }
531
532    pub fn add_context(&self, context: String) -> ContextHandle {
533        let id = self.id.fetch_add(1, Ordering::Relaxed);
534        let mut contexts = self.contexts.write();
535        contexts.insert(id, context);
536        ContextHandle {
537            id,
538            manager: self.clone(),
539        }
540    }
541
542    pub fn context(&self) -> String {
543        let contexts = self.contexts.read();
544        format!("\n{}\n", contexts.values().join("\n"))
545    }
546}
547
548/// Used to track the lifetime of a piece of context so that it can be provided when an assertion fails.
549/// For example, in the EditorTestContext, `set_state` returns a context handle so that if an assertion fails,
550/// the state that was set initially for the failure can be printed in the error message
551pub struct ContextHandle {
552    id: usize,
553    manager: AssertionContextManager,
554}
555
556impl Drop for ContextHandle {
557    fn drop(&mut self) {
558        let mut contexts = self.manager.contexts.write();
559        contexts.remove(&self.id);
560    }
561}