editor_test_context.rs

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