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 itertools::Itertools;
 13use language::{Buffer, BufferSnapshot, LanguageRegistry};
 14use multi_buffer::{ExcerptRange, ToPoint};
 15use parking_lot::RwLock;
 16use pretty_assertions::assert_eq;
 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                    let start = range.start.to_point(&snapshot.buffer_snapshot);
341                    let end = range.end.to_point(&snapshot.buffer_snapshot);
342                    start.row..end.row
343                })
344                .collect::<Vec<_>>();
345            let deletions = editor
346                .expanded_hunks
347                .hunks
348                .iter()
349                .filter_map(|hunk| {
350                    if hunk.blocks.is_empty() {
351                        return None;
352                    }
353                    let row = hunk
354                        .hunk_range
355                        .start
356                        .to_point(&snapshot.buffer_snapshot)
357                        .row;
358                    let (_, buffer, _) = editor
359                        .buffer()
360                        .read(cx)
361                        .excerpt_containing(hunk.hunk_range.start, cx)
362                        .expect("no excerpt for expanded buffer's hunk start");
363                    let deleted_text = buffer
364                        .read(cx)
365                        .diff_base()
366                        .expect("should have a diff base for expanded hunk")
367                        .slice(hunk.diff_base_byte_range.clone())
368                        .to_string();
369                    if let DiffHunkStatus::Modified | DiffHunkStatus::Removed = hunk.status {
370                        Some((row, deleted_text))
371                    } else {
372                        None
373                    }
374                })
375                .collect::<Vec<_>>();
376            format_diff(text, deletions, insertions)
377        });
378
379        pretty_assertions::assert_eq!(actual_diff, expected_diff_text, "unexpected diff state");
380    }
381
382    /// Make an assertion about the editor's text and the ranges and directions
383    /// of its selections using a string containing embedded range markers.
384    ///
385    /// See the `util::test::marked_text_ranges` function for more information.
386    #[track_caller]
387    pub fn assert_editor_state(&mut self, marked_text: &str) {
388        let (expected_text, expected_selections) = marked_text_ranges(marked_text, true);
389        pretty_assertions::assert_eq!(self.buffer_text(), expected_text, "unexpected buffer text");
390        self.assert_selections(expected_selections, marked_text.to_string())
391    }
392
393    pub fn editor_state(&mut self) -> String {
394        generate_marked_text(self.buffer_text().as_str(), &self.editor_selections(), true)
395    }
396
397    #[track_caller]
398    pub fn assert_editor_background_highlights<Tag: 'static>(&mut self, marked_text: &str) {
399        let expected_ranges = self.ranges(marked_text);
400        let actual_ranges: Vec<Range<usize>> = self.update_editor(|editor, cx| {
401            let snapshot = editor.snapshot(cx);
402            editor
403                .background_highlights
404                .get(&TypeId::of::<Tag>())
405                .map(|h| h.1.clone())
406                .unwrap_or_default()
407                .iter()
408                .map(|range| range.to_offset(&snapshot.buffer_snapshot))
409                .collect()
410        });
411        assert_set_eq!(actual_ranges, expected_ranges);
412    }
413
414    #[track_caller]
415    pub fn assert_editor_text_highlights<Tag: ?Sized + 'static>(&mut self, marked_text: &str) {
416        let expected_ranges = self.ranges(marked_text);
417        let snapshot = self.update_editor(|editor, cx| editor.snapshot(cx));
418        let actual_ranges: Vec<Range<usize>> = snapshot
419            .text_highlight_ranges::<Tag>()
420            .map(|ranges| ranges.as_ref().clone().1)
421            .unwrap_or_default()
422            .into_iter()
423            .map(|range| range.to_offset(&snapshot.buffer_snapshot))
424            .collect();
425        assert_set_eq!(actual_ranges, expected_ranges);
426    }
427
428    #[track_caller]
429    pub fn assert_editor_selections(&mut self, expected_selections: Vec<Range<usize>>) {
430        let expected_marked_text =
431            generate_marked_text(&self.buffer_text(), &expected_selections, true);
432        self.assert_selections(expected_selections, expected_marked_text)
433    }
434
435    #[track_caller]
436    fn editor_selections(&mut self) -> Vec<Range<usize>> {
437        self.editor
438            .update(&mut self.cx, |editor, cx| {
439                editor.selections.all::<usize>(cx)
440            })
441            .into_iter()
442            .map(|s| {
443                if s.reversed {
444                    s.end..s.start
445                } else {
446                    s.start..s.end
447                }
448            })
449            .collect::<Vec<_>>()
450    }
451
452    #[track_caller]
453    fn assert_selections(
454        &mut self,
455        expected_selections: Vec<Range<usize>>,
456        expected_marked_text: String,
457    ) {
458        let actual_selections = self.editor_selections();
459        let actual_marked_text =
460            generate_marked_text(&self.buffer_text(), &actual_selections, true);
461        if expected_selections != actual_selections {
462            pretty_assertions::assert_eq!(
463                actual_marked_text,
464                expected_marked_text,
465                "{}Editor has unexpected selections",
466                self.assertion_context(),
467            );
468        }
469    }
470}
471
472fn format_diff(
473    text: String,
474    actual_deletions: Vec<(u32, String)>,
475    actual_insertions: Vec<Range<u32>>,
476) -> String {
477    let mut diff = String::new();
478    for (row, line) in text.split('\n').enumerate() {
479        let row = row as u32;
480        if row > 0 {
481            diff.push('\n');
482        }
483        if let Some(text) = actual_deletions
484            .iter()
485            .find_map(|(deletion_row, deleted_text)| {
486                if *deletion_row == row {
487                    Some(deleted_text)
488                } else {
489                    None
490                }
491            })
492        {
493            for line in text.lines() {
494                diff.push('-');
495                if !line.is_empty() {
496                    diff.push(' ');
497                    diff.push_str(line);
498                }
499                diff.push('\n');
500            }
501        }
502        let marker = if actual_insertions.iter().any(|range| range.contains(&row)) {
503            "+ "
504        } else {
505            "  "
506        };
507        diff.push_str(format!("{marker}{line}").trim_end());
508    }
509    diff
510}
511
512impl Deref for EditorTestContext {
513    type Target = gpui::VisualTestContext;
514
515    fn deref(&self) -> &Self::Target {
516        &self.cx
517    }
518}
519
520impl DerefMut for EditorTestContext {
521    fn deref_mut(&mut self) -> &mut Self::Target {
522        &mut self.cx
523    }
524}
525
526/// Tracks string context to be printed when assertions fail.
527/// Often this is done by storing a context string in the manager and returning the handle.
528#[derive(Clone)]
529pub struct AssertionContextManager {
530    id: Arc<AtomicUsize>,
531    contexts: Arc<RwLock<BTreeMap<usize, String>>>,
532}
533
534impl Default for AssertionContextManager {
535    fn default() -> Self {
536        Self::new()
537    }
538}
539
540impl AssertionContextManager {
541    pub fn new() -> Self {
542        Self {
543            id: Arc::new(AtomicUsize::new(0)),
544            contexts: Arc::new(RwLock::new(BTreeMap::new())),
545        }
546    }
547
548    pub fn add_context(&self, context: String) -> ContextHandle {
549        let id = self.id.fetch_add(1, Ordering::Relaxed);
550        let mut contexts = self.contexts.write();
551        contexts.insert(id, context);
552        ContextHandle {
553            id,
554            manager: self.clone(),
555        }
556    }
557
558    pub fn context(&self) -> String {
559        let contexts = self.contexts.read();
560        format!("\n{}\n", contexts.values().join("\n"))
561    }
562}
563
564/// Used to track the lifetime of a piece of context so that it can be provided when an assertion fails.
565/// For example, in the EditorTestContext, `set_state` returns a context handle so that if an assertion fails,
566/// the state that was set initially for the failure can be printed in the error message
567pub struct ContextHandle {
568    id: usize,
569    manager: AssertionContextManager,
570}
571
572impl Drop for ContextHandle {
573    fn drop(&mut self) {
574        let mut contexts = self.manager.contexts.write();
575        contexts.remove(&self.id);
576    }
577}