editor_test_context.rs

  1use crate::{
  2    display_map::ToDisplayPoint, AnchorRangeExt, Autoscroll, DiffRowHighlight, DisplayPoint,
  3    Editor, MultiBuffer, RowExt,
  4};
  5use collections::BTreeMap;
  6use futures::Future;
  7use git::diff::DiffHunkStatus;
  8use gpui::{
  9    AnyWindowHandle, AppContext, Keystroke, ModelContext, Pixels, Point, View, ViewContext,
 10    VisualTestContext, WindowHandle,
 11};
 12use indoc::indoc;
 13use itertools::Itertools;
 14use language::{Buffer, BufferSnapshot, LanguageRegistry};
 15use multi_buffer::{ExcerptRange, ToPoint};
 16use parking_lot::RwLock;
 17use project::{FakeFs, Project};
 18use std::{
 19    any::TypeId,
 20    ops::{Deref, DerefMut, Range},
 21    sync::{
 22        atomic::{AtomicUsize, Ordering},
 23        Arc,
 24    },
 25};
 26
 27use ui::Context;
 28use util::{
 29    assert_set_eq,
 30    test::{generate_marked_text, marked_text_ranges},
 31};
 32
 33use super::{build_editor, build_editor_with_project};
 34
 35pub struct EditorTestContext {
 36    pub cx: gpui::VisualTestContext,
 37    pub window: AnyWindowHandle,
 38    pub editor: View<Editor>,
 39    pub assertion_cx: AssertionContextManager,
 40}
 41
 42impl EditorTestContext {
 43    pub async fn new(cx: &mut gpui::TestAppContext) -> EditorTestContext {
 44        let fs = FakeFs::new(cx.executor());
 45        // fs.insert_file("/file", "".to_owned()).await;
 46        fs.insert_tree(
 47            "/root",
 48            serde_json::json!({
 49                "file": "",
 50            }),
 51        )
 52        .await;
 53        let project = Project::test(fs, ["/root".as_ref()], cx).await;
 54        let buffer = project
 55            .update(cx, |project, cx| {
 56                project.open_local_buffer("/root/file", cx)
 57            })
 58            .await
 59            .unwrap();
 60        let editor = cx.add_window(|cx| {
 61            let editor =
 62                build_editor_with_project(project, MultiBuffer::build_from_buffer(buffer, cx), cx);
 63            editor.focus(cx);
 64            editor
 65        });
 66        let editor_view = editor.root_view(cx).unwrap();
 67        Self {
 68            cx: VisualTestContext::from_window(*editor.deref(), cx),
 69            window: editor.into(),
 70            editor: editor_view,
 71            assertion_cx: AssertionContextManager::new(),
 72        }
 73    }
 74
 75    pub async fn for_editor(editor: WindowHandle<Editor>, cx: &mut gpui::TestAppContext) -> Self {
 76        let editor_view = editor.root_view(cx).unwrap();
 77        Self {
 78            cx: VisualTestContext::from_window(*editor.deref(), cx),
 79            window: editor.into(),
 80            editor: editor_view,
 81            assertion_cx: AssertionContextManager::new(),
 82        }
 83    }
 84
 85    pub fn new_multibuffer<const COUNT: usize>(
 86        cx: &mut gpui::TestAppContext,
 87        excerpts: [&str; COUNT],
 88    ) -> EditorTestContext {
 89        let mut multibuffer = MultiBuffer::new(language::Capability::ReadWrite);
 90        let buffer = cx.new_model(|cx| {
 91            for excerpt in excerpts.into_iter() {
 92                let (text, ranges) = marked_text_ranges(excerpt, false);
 93                let buffer = cx.new_model(|cx| Buffer::local(text, cx));
 94                multibuffer.push_excerpts(
 95                    buffer,
 96                    ranges.into_iter().map(|range| ExcerptRange {
 97                        context: range,
 98                        primary: None,
 99                    }),
100                    cx,
101                );
102            }
103            multibuffer
104        });
105
106        let editor = cx.add_window(|cx| {
107            let editor = build_editor(buffer, cx);
108            editor.focus(cx);
109            editor
110        });
111
112        let editor_view = editor.root_view(cx).unwrap();
113        Self {
114            cx: VisualTestContext::from_window(*editor.deref(), cx),
115            window: editor.into(),
116            editor: editor_view,
117            assertion_cx: AssertionContextManager::new(),
118        }
119    }
120
121    pub fn condition(
122        &self,
123        predicate: impl FnMut(&Editor, &AppContext) -> bool,
124    ) -> impl Future<Output = ()> {
125        self.editor
126            .condition::<crate::EditorEvent>(&self.cx, predicate)
127    }
128
129    #[track_caller]
130    pub fn editor<F, T>(&mut self, read: F) -> T
131    where
132        F: FnOnce(&Editor, &ViewContext<Editor>) -> T,
133    {
134        self.editor.update(&mut self.cx, |this, cx| read(this, cx))
135    }
136
137    #[track_caller]
138    pub fn update_editor<F, T>(&mut self, update: F) -> T
139    where
140        F: FnOnce(&mut Editor, &mut ViewContext<Editor>) -> T,
141    {
142        self.editor.update(&mut self.cx, update)
143    }
144
145    pub fn multibuffer<F, T>(&mut self, read: F) -> T
146    where
147        F: FnOnce(&MultiBuffer, &AppContext) -> T,
148    {
149        self.editor(|editor, cx| read(editor.buffer().read(cx), cx))
150    }
151
152    pub fn update_multibuffer<F, T>(&mut self, update: F) -> T
153    where
154        F: FnOnce(&mut MultiBuffer, &mut ModelContext<MultiBuffer>) -> T,
155    {
156        self.update_editor(|editor, cx| editor.buffer().update(cx, update))
157    }
158
159    pub fn buffer_text(&mut self) -> String {
160        self.multibuffer(|buffer, cx| buffer.snapshot(cx).text())
161    }
162
163    pub fn display_text(&mut self) -> String {
164        self.update_editor(|editor, cx| editor.display_text(cx))
165    }
166
167    pub fn buffer<F, T>(&mut self, read: F) -> T
168    where
169        F: FnOnce(&Buffer, &AppContext) -> T,
170    {
171        self.multibuffer(|multibuffer, cx| {
172            let buffer = multibuffer.as_singleton().unwrap().read(cx);
173            read(buffer, cx)
174        })
175    }
176
177    pub fn language_registry(&mut self) -> Arc<LanguageRegistry> {
178        self.editor(|editor, cx| {
179            editor
180                .project
181                .as_ref()
182                .unwrap()
183                .read(cx)
184                .languages()
185                .clone()
186        })
187    }
188
189    pub fn update_buffer<F, T>(&mut self, update: F) -> T
190    where
191        F: FnOnce(&mut Buffer, &mut ModelContext<Buffer>) -> T,
192    {
193        self.update_multibuffer(|multibuffer, cx| {
194            let buffer = multibuffer.as_singleton().unwrap();
195            buffer.update(cx, update)
196        })
197    }
198
199    pub fn buffer_snapshot(&mut self) -> BufferSnapshot {
200        self.buffer(|buffer, _| buffer.snapshot())
201    }
202
203    pub fn add_assertion_context(&self, context: String) -> ContextHandle {
204        self.assertion_cx.add_context(context)
205    }
206
207    pub fn assertion_context(&self) -> String {
208        self.assertion_cx.context()
209    }
210
211    // unlike cx.simulate_keystrokes(), this does not run_until_parked
212    // so you can use it to test detailed timing
213    pub fn simulate_keystroke(&mut self, keystroke_text: &str) {
214        let keystroke = Keystroke::parse(keystroke_text).unwrap();
215        self.cx.dispatch_keystroke(self.window, keystroke);
216    }
217
218    pub fn run_until_parked(&mut self) {
219        self.cx.background_executor.run_until_parked();
220    }
221
222    pub fn ranges(&mut self, marked_text: &str) -> Vec<Range<usize>> {
223        let (unmarked_text, ranges) = marked_text_ranges(marked_text, false);
224        assert_eq!(self.buffer_text(), unmarked_text);
225        ranges
226    }
227
228    pub fn display_point(&mut self, marked_text: &str) -> DisplayPoint {
229        let ranges = self.ranges(marked_text);
230        let snapshot = self
231            .editor
232            .update(&mut self.cx, |editor, cx| editor.snapshot(cx));
233        ranges[0].start.to_display_point(&snapshot)
234    }
235
236    pub fn pixel_position(&mut self, marked_text: &str) -> Point<Pixels> {
237        let display_point = self.display_point(marked_text);
238        self.pixel_position_for(display_point)
239    }
240
241    pub fn pixel_position_for(&mut self, display_point: DisplayPoint) -> Point<Pixels> {
242        self.update_editor(|editor, cx| {
243            let newest_point = editor.selections.newest_display(cx).head();
244            let pixel_position = editor.pixel_position_of_newest_cursor.unwrap();
245            let line_height = editor
246                .style()
247                .unwrap()
248                .text
249                .line_height_in_pixels(cx.rem_size());
250            let snapshot = editor.snapshot(cx);
251            let details = editor.text_layout_details(cx);
252
253            let y = pixel_position.y
254                + line_height * (display_point.row().as_f32() - newest_point.row().as_f32());
255            let x = pixel_position.x + snapshot.x_for_display_point(display_point, &details)
256                - snapshot.x_for_display_point(newest_point, &details);
257            Point::new(x, y)
258        })
259    }
260
261    // Returns anchors for the current buffer using `«` and `»`
262    pub fn text_anchor_range(&mut self, marked_text: &str) -> Range<language::Anchor> {
263        let ranges = self.ranges(marked_text);
264        let snapshot = self.buffer_snapshot();
265        snapshot.anchor_before(ranges[0].start)..snapshot.anchor_after(ranges[0].end)
266    }
267
268    pub fn set_diff_base(&mut self, diff_base: Option<&str>) {
269        self.update_buffer(|buffer, cx| buffer.set_diff_base(diff_base.map(ToOwned::to_owned), cx));
270    }
271
272    /// Change the editor's text and selections using a string containing
273    /// embedded range markers that represent the ranges and directions of
274    /// each selection.
275    ///
276    /// Returns a context handle so that assertion failures can print what
277    /// editor state was needed to cause the failure.
278    ///
279    /// See the `util::test::marked_text_ranges` function for more information.
280    pub fn set_state(&mut self, marked_text: &str) -> ContextHandle {
281        let state_context = self.add_assertion_context(format!(
282            "Initial Editor State: \"{}\"",
283            marked_text.escape_debug()
284        ));
285        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
286        self.editor.update(&mut self.cx, |editor, cx| {
287            editor.set_text(unmarked_text, cx);
288            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
289                s.select_ranges(selection_ranges)
290            })
291        });
292        state_context
293    }
294
295    /// Only change the editor's selections
296    pub fn set_selections_state(&mut self, marked_text: &str) -> ContextHandle {
297        let state_context = self.add_assertion_context(format!(
298            "Initial Editor State: \"{}\"",
299            marked_text.escape_debug()
300        ));
301        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
302        self.editor.update(&mut self.cx, |editor, cx| {
303            assert_eq!(editor.text(cx), unmarked_text);
304            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
305                s.select_ranges(selection_ranges)
306            })
307        });
308        state_context
309    }
310
311    #[track_caller]
312    pub fn assert_diff_hunks(&mut self, expected_diff: String) {
313        // Normalize the expected diff. If it has no diff markers, then insert blank markers
314        // before each line. Strip any whitespace-only lines.
315        let has_diff_markers = expected_diff
316            .lines()
317            .any(|line| line.starts_with("+") || line.starts_with("-"));
318        let expected_diff_text = expected_diff
319            .split('\n')
320            .map(|line| {
321                let trimmed = line.trim();
322                if trimmed.is_empty() {
323                    String::new()
324                } else if has_diff_markers {
325                    line.to_string()
326                } else {
327                    format!("  {line}")
328                }
329            })
330            .join("\n");
331
332        // Read the actual diff from the editor's row highlights and block
333        // decorations.
334        let actual_diff = self.editor.update(&mut self.cx, |editor, cx| {
335            let snapshot = editor.snapshot(cx);
336            let text = editor.text(cx);
337            let insertions = editor
338                .highlighted_rows::<DiffRowHighlight>()
339                .map(|(range, _)| {
340                    range.start().to_point(&snapshot.buffer_snapshot).row
341                        ..range.end().to_point(&snapshot.buffer_snapshot).row + 1
342                })
343                .collect::<Vec<_>>();
344            let deletions = editor
345                .expanded_hunks
346                .hunks
347                .iter()
348                .filter_map(|hunk| {
349                    if hunk.blocks.is_empty() {
350                        return None;
351                    }
352                    let row = hunk
353                        .hunk_range
354                        .start
355                        .to_point(&snapshot.buffer_snapshot)
356                        .row;
357                    let (_, buffer, _) = editor
358                        .buffer()
359                        .read(cx)
360                        .excerpt_containing(hunk.hunk_range.start, cx)
361                        .expect("no excerpt for expanded buffer's hunk start");
362                    let deleted_text = buffer
363                        .read(cx)
364                        .diff_base()
365                        .expect("should have a diff base for expanded hunk")
366                        .slice(hunk.diff_base_byte_range.clone())
367                        .to_string();
368                    if let DiffHunkStatus::Modified | DiffHunkStatus::Removed = hunk.status {
369                        Some((row, deleted_text))
370                    } else {
371                        None
372                    }
373                })
374                .collect::<Vec<_>>();
375            format_diff(text, deletions, insertions)
376        });
377
378        pretty_assertions::assert_eq!(actual_diff, expected_diff_text, "unexpected diff state");
379    }
380
381    /// Make an assertion about the editor's text and the ranges and directions
382    /// of its selections using a string containing embedded range markers.
383    ///
384    /// See the `util::test::marked_text_ranges` function for more information.
385    #[track_caller]
386    pub fn assert_editor_state(&mut self, marked_text: &str) {
387        let (unmarked_text, expected_selections) = marked_text_ranges(marked_text, true);
388        let buffer_text = self.buffer_text();
389
390        if buffer_text != unmarked_text {
391            panic!("Unmarked text doesn't match buffer text\nBuffer text: {buffer_text:?}\nUnmarked text: {unmarked_text:?}\nRaw buffer text\n{buffer_text}\nRaw unmarked text\n{unmarked_text}");
392        }
393
394        self.assert_selections(expected_selections, marked_text.to_string())
395    }
396
397    pub fn editor_state(&mut self) -> String {
398        generate_marked_text(self.buffer_text().as_str(), &self.editor_selections(), true)
399    }
400
401    #[track_caller]
402    pub fn assert_editor_background_highlights<Tag: 'static>(&mut self, marked_text: &str) {
403        let expected_ranges = self.ranges(marked_text);
404        let actual_ranges: Vec<Range<usize>> = self.update_editor(|editor, cx| {
405            let snapshot = editor.snapshot(cx);
406            editor
407                .background_highlights
408                .get(&TypeId::of::<Tag>())
409                .map(|h| h.1.clone())
410                .unwrap_or_default()
411                .iter()
412                .map(|range| range.to_offset(&snapshot.buffer_snapshot))
413                .collect()
414        });
415        assert_set_eq!(actual_ranges, expected_ranges);
416    }
417
418    #[track_caller]
419    pub fn assert_editor_text_highlights<Tag: ?Sized + 'static>(&mut self, marked_text: &str) {
420        let expected_ranges = self.ranges(marked_text);
421        let snapshot = self.update_editor(|editor, cx| editor.snapshot(cx));
422        let actual_ranges: Vec<Range<usize>> = snapshot
423            .text_highlight_ranges::<Tag>()
424            .map(|ranges| ranges.as_ref().clone().1)
425            .unwrap_or_default()
426            .into_iter()
427            .map(|range| range.to_offset(&snapshot.buffer_snapshot))
428            .collect();
429        assert_set_eq!(actual_ranges, expected_ranges);
430    }
431
432    #[track_caller]
433    pub fn assert_editor_selections(&mut self, expected_selections: Vec<Range<usize>>) {
434        let expected_marked_text =
435            generate_marked_text(&self.buffer_text(), &expected_selections, true);
436        self.assert_selections(expected_selections, expected_marked_text)
437    }
438
439    #[track_caller]
440    fn editor_selections(&mut self) -> Vec<Range<usize>> {
441        self.editor
442            .update(&mut self.cx, |editor, cx| {
443                editor.selections.all::<usize>(cx)
444            })
445            .into_iter()
446            .map(|s| {
447                if s.reversed {
448                    s.end..s.start
449                } else {
450                    s.start..s.end
451                }
452            })
453            .collect::<Vec<_>>()
454    }
455
456    #[track_caller]
457    fn assert_selections(
458        &mut self,
459        expected_selections: Vec<Range<usize>>,
460        expected_marked_text: String,
461    ) {
462        let actual_selections = self.editor_selections();
463        let actual_marked_text =
464            generate_marked_text(&self.buffer_text(), &actual_selections, true);
465        if expected_selections != actual_selections {
466            panic!(
467                indoc! {"
468
469                {}Editor has unexpected selections.
470
471                Expected selections:
472                {}
473
474                Actual selections:
475                {}
476            "},
477                self.assertion_context(),
478                expected_marked_text,
479                actual_marked_text,
480            );
481        }
482    }
483}
484
485fn format_diff(
486    text: String,
487    actual_deletions: Vec<(u32, String)>,
488    actual_insertions: Vec<Range<u32>>,
489) -> String {
490    let mut diff = String::new();
491    for (row, line) in text.split('\n').enumerate() {
492        let row = row as u32;
493        if row > 0 {
494            diff.push('\n');
495        }
496        if let Some(text) = actual_deletions
497            .iter()
498            .find_map(|(deletion_row, deleted_text)| {
499                if *deletion_row == row {
500                    Some(deleted_text)
501                } else {
502                    None
503                }
504            })
505        {
506            for line in text.lines() {
507                diff.push('-');
508                if !line.is_empty() {
509                    diff.push(' ');
510                    diff.push_str(line);
511                }
512                diff.push('\n');
513            }
514        }
515        let marker = if actual_insertions.iter().any(|range| range.contains(&row)) {
516            "+ "
517        } else {
518            "  "
519        };
520        diff.push_str(format!("{marker}{line}").trim_end());
521    }
522    diff
523}
524
525impl Deref for EditorTestContext {
526    type Target = gpui::VisualTestContext;
527
528    fn deref(&self) -> &Self::Target {
529        &self.cx
530    }
531}
532
533impl DerefMut for EditorTestContext {
534    fn deref_mut(&mut self) -> &mut Self::Target {
535        &mut self.cx
536    }
537}
538
539/// Tracks string context to be printed when assertions fail.
540/// Often this is done by storing a context string in the manager and returning the handle.
541#[derive(Clone)]
542pub struct AssertionContextManager {
543    id: Arc<AtomicUsize>,
544    contexts: Arc<RwLock<BTreeMap<usize, String>>>,
545}
546
547impl Default for AssertionContextManager {
548    fn default() -> Self {
549        Self::new()
550    }
551}
552
553impl AssertionContextManager {
554    pub fn new() -> Self {
555        Self {
556            id: Arc::new(AtomicUsize::new(0)),
557            contexts: Arc::new(RwLock::new(BTreeMap::new())),
558        }
559    }
560
561    pub fn add_context(&self, context: String) -> ContextHandle {
562        let id = self.id.fetch_add(1, Ordering::Relaxed);
563        let mut contexts = self.contexts.write();
564        contexts.insert(id, context);
565        ContextHandle {
566            id,
567            manager: self.clone(),
568        }
569    }
570
571    pub fn context(&self) -> String {
572        let contexts = self.contexts.read();
573        format!("\n{}\n", contexts.values().join("\n"))
574    }
575}
576
577/// Used to track the lifetime of a piece of context so that it can be provided when an assertion fails.
578/// For example, in the EditorTestContext, `set_state` returns a context handle so that if an assertion fails,
579/// the state that was set initially for the failure can be printed in the error message
580pub struct ContextHandle {
581    id: usize,
582    manager: AssertionContextManager,
583}
584
585impl Drop for ContextHandle {
586    fn drop(&mut self) {
587        let mut contexts = self.manager.contexts.write();
588        contexts.remove(&self.id);
589    }
590}