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