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