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    #[track_caller]
234    pub fn ranges(&mut self, marked_text: &str) -> Vec<Range<usize>> {
235        let (unmarked_text, ranges) = marked_text_ranges(marked_text, false);
236        assert_eq!(self.buffer_text(), unmarked_text);
237        ranges
238    }
239
240    pub fn display_point(&mut self, marked_text: &str) -> DisplayPoint {
241        let ranges = self.ranges(marked_text);
242        let snapshot = self
243            .editor
244            .update(&mut self.cx, |editor, cx| editor.snapshot(cx));
245        ranges[0].start.to_display_point(&snapshot)
246    }
247
248    pub fn pixel_position(&mut self, marked_text: &str) -> Point<Pixels> {
249        let display_point = self.display_point(marked_text);
250        self.pixel_position_for(display_point)
251    }
252
253    pub fn pixel_position_for(&mut self, display_point: DisplayPoint) -> Point<Pixels> {
254        self.update_editor(|editor, cx| {
255            let newest_point = editor.selections.newest_display(cx).head();
256            let pixel_position = editor.pixel_position_of_newest_cursor.unwrap();
257            let line_height = editor
258                .style()
259                .unwrap()
260                .text
261                .line_height_in_pixels(cx.rem_size());
262            let snapshot = editor.snapshot(cx);
263            let details = editor.text_layout_details(cx);
264
265            let y = pixel_position.y
266                + line_height * (display_point.row().as_f32() - newest_point.row().as_f32());
267            let x = pixel_position.x + snapshot.x_for_display_point(display_point, &details)
268                - snapshot.x_for_display_point(newest_point, &details);
269            Point::new(x, y)
270        })
271    }
272
273    // Returns anchors for the current buffer using `«` and `»`
274    pub fn text_anchor_range(&mut self, marked_text: &str) -> Range<language::Anchor> {
275        let ranges = self.ranges(marked_text);
276        let snapshot = self.buffer_snapshot();
277        snapshot.anchor_before(ranges[0].start)..snapshot.anchor_after(ranges[0].end)
278    }
279
280    pub fn set_diff_base(&mut self, diff_base: &str) {
281        self.cx.run_until_parked();
282        let fs = self
283            .update_editor(|editor, cx| editor.project.as_ref().unwrap().read(cx).fs().as_fake());
284        let path = self.update_buffer(|buffer, _| buffer.file().unwrap().path().clone());
285        fs.set_index_for_repo(
286            &Self::root_path().join(".git"),
287            &[(path.as_ref(), diff_base.to_string())],
288        );
289        self.cx.run_until_parked();
290    }
291
292    /// Change the editor's text and selections using a string containing
293    /// embedded range markers that represent the ranges and directions of
294    /// each selection.
295    ///
296    /// Returns a context handle so that assertion failures can print what
297    /// editor state was needed to cause the failure.
298    ///
299    /// See the `util::test::marked_text_ranges` function for more information.
300    pub fn set_state(&mut self, marked_text: &str) -> ContextHandle {
301        let state_context = self.add_assertion_context(format!(
302            "Initial Editor State: \"{}\"",
303            marked_text.escape_debug()
304        ));
305        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
306        self.editor.update(&mut self.cx, |editor, cx| {
307            editor.set_text(unmarked_text, cx);
308            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
309                s.select_ranges(selection_ranges)
310            })
311        });
312        state_context
313    }
314
315    /// Only change the editor's selections
316    pub fn set_selections_state(&mut self, marked_text: &str) -> ContextHandle {
317        let state_context = self.add_assertion_context(format!(
318            "Initial Editor State: \"{}\"",
319            marked_text.escape_debug()
320        ));
321        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
322        self.editor.update(&mut self.cx, |editor, cx| {
323            assert_eq!(editor.text(cx), unmarked_text);
324            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
325                s.select_ranges(selection_ranges)
326            })
327        });
328        state_context
329    }
330
331    /// Assert about the text of the editor, the selections, and the expanded
332    /// diff hunks.
333    ///
334    /// Diff hunks are indicated by lines starting with `+` and `-`.
335    #[track_caller]
336    pub fn assert_state_with_diff(&mut self, expected_diff: String) {
337        let has_diff_markers = expected_diff
338            .lines()
339            .any(|line| line.starts_with("+") || line.starts_with("-"));
340        let expected_diff_text = expected_diff
341            .split('\n')
342            .map(|line| {
343                let trimmed = line.trim();
344                if trimmed.is_empty() {
345                    String::new()
346                } else if has_diff_markers {
347                    line.to_string()
348                } else {
349                    format!("  {line}")
350                }
351            })
352            .join("\n");
353
354        let actual_selections = self.editor_selections();
355        let actual_marked_text =
356            generate_marked_text(&self.buffer_text(), &actual_selections, true);
357
358        // Read the actual diff from the editor's row highlights and block
359        // decorations.
360        let actual_diff = self.editor.update(&mut self.cx, |editor, cx| {
361            let snapshot = editor.snapshot(cx);
362            let insertions = editor
363                .highlighted_rows::<DiffRowHighlight>()
364                .map(|(range, _)| {
365                    let start = range.start.to_point(&snapshot.buffer_snapshot);
366                    let end = range.end.to_point(&snapshot.buffer_snapshot);
367                    start.row..end.row
368                })
369                .collect::<Vec<_>>();
370            let deletions = editor
371                .diff_map
372                .hunks
373                .iter()
374                .filter_map(|hunk| {
375                    if hunk.blocks.is_empty() {
376                        return None;
377                    }
378                    let row = hunk
379                        .hunk_range
380                        .start
381                        .to_point(&snapshot.buffer_snapshot)
382                        .row;
383                    let (_, buffer, _) = editor
384                        .buffer()
385                        .read(cx)
386                        .excerpt_containing(hunk.hunk_range.start, cx)
387                        .expect("no excerpt for expanded buffer's hunk start");
388                    let buffer_id = buffer.read(cx).remote_id();
389                    let change_set = &editor
390                        .diff_map
391                        .diff_bases
392                        .get(&buffer_id)
393                        .expect("should have a diff base for expanded hunk")
394                        .change_set;
395                    let deleted_text = change_set
396                        .read(cx)
397                        .base_text
398                        .as_ref()
399                        .expect("no base text for expanded hunk")
400                        .read(cx)
401                        .as_rope()
402                        .slice(hunk.diff_base_byte_range.clone())
403                        .to_string();
404                    if let DiffHunkStatus::Modified | DiffHunkStatus::Removed = hunk.status {
405                        Some((row, deleted_text))
406                    } else {
407                        None
408                    }
409                })
410                .collect::<Vec<_>>();
411            format_diff(actual_marked_text, deletions, insertions)
412        });
413
414        pretty_assertions::assert_eq!(actual_diff, expected_diff_text, "unexpected diff state");
415    }
416
417    /// Make an assertion about the editor's text and the ranges and directions
418    /// of its selections using a string containing embedded range markers.
419    ///
420    /// See the `util::test::marked_text_ranges` function for more information.
421    #[track_caller]
422    pub fn assert_editor_state(&mut self, marked_text: &str) {
423        let (expected_text, expected_selections) = marked_text_ranges(marked_text, true);
424        pretty_assertions::assert_eq!(self.buffer_text(), expected_text, "unexpected buffer text");
425        self.assert_selections(expected_selections, marked_text.to_string())
426    }
427
428    pub fn editor_state(&mut self) -> String {
429        generate_marked_text(self.buffer_text().as_str(), &self.editor_selections(), true)
430    }
431
432    #[track_caller]
433    pub fn assert_editor_background_highlights<Tag: 'static>(&mut self, marked_text: &str) {
434        let expected_ranges = self.ranges(marked_text);
435        let actual_ranges: Vec<Range<usize>> = self.update_editor(|editor, cx| {
436            let snapshot = editor.snapshot(cx);
437            editor
438                .background_highlights
439                .get(&TypeId::of::<Tag>())
440                .map(|h| h.1.clone())
441                .unwrap_or_default()
442                .iter()
443                .map(|range| range.to_offset(&snapshot.buffer_snapshot))
444                .collect()
445        });
446        assert_set_eq!(actual_ranges, expected_ranges);
447    }
448
449    #[track_caller]
450    pub fn assert_editor_text_highlights<Tag: ?Sized + 'static>(&mut self, marked_text: &str) {
451        let expected_ranges = self.ranges(marked_text);
452        let snapshot = self.update_editor(|editor, cx| editor.snapshot(cx));
453        let actual_ranges: Vec<Range<usize>> = snapshot
454            .text_highlight_ranges::<Tag>()
455            .map(|ranges| ranges.as_ref().clone().1)
456            .unwrap_or_default()
457            .into_iter()
458            .map(|range| range.to_offset(&snapshot.buffer_snapshot))
459            .collect();
460        assert_set_eq!(actual_ranges, expected_ranges);
461    }
462
463    #[track_caller]
464    pub fn assert_editor_selections(&mut self, expected_selections: Vec<Range<usize>>) {
465        let expected_marked_text =
466            generate_marked_text(&self.buffer_text(), &expected_selections, true);
467        self.assert_selections(expected_selections, expected_marked_text)
468    }
469
470    #[track_caller]
471    fn editor_selections(&mut self) -> Vec<Range<usize>> {
472        self.editor
473            .update(&mut self.cx, |editor, cx| {
474                editor.selections.all::<usize>(cx)
475            })
476            .into_iter()
477            .map(|s| {
478                if s.reversed {
479                    s.end..s.start
480                } else {
481                    s.start..s.end
482                }
483            })
484            .collect::<Vec<_>>()
485    }
486
487    #[track_caller]
488    fn assert_selections(
489        &mut self,
490        expected_selections: Vec<Range<usize>>,
491        expected_marked_text: String,
492    ) {
493        let actual_selections = self.editor_selections();
494        let actual_marked_text =
495            generate_marked_text(&self.buffer_text(), &actual_selections, true);
496        if expected_selections != actual_selections {
497            pretty_assertions::assert_eq!(
498                actual_marked_text,
499                expected_marked_text,
500                "{}Editor has unexpected selections",
501                self.assertion_context(),
502            );
503        }
504    }
505}
506
507fn format_diff(
508    text: String,
509    actual_deletions: Vec<(u32, String)>,
510    actual_insertions: Vec<Range<u32>>,
511) -> String {
512    let mut diff = String::new();
513    for (row, line) in text.split('\n').enumerate() {
514        let row = row as u32;
515        if row > 0 {
516            diff.push('\n');
517        }
518        if let Some(text) = actual_deletions
519            .iter()
520            .find_map(|(deletion_row, deleted_text)| {
521                if *deletion_row == row {
522                    Some(deleted_text)
523                } else {
524                    None
525                }
526            })
527        {
528            for line in text.lines() {
529                diff.push('-');
530                if !line.is_empty() {
531                    diff.push(' ');
532                    diff.push_str(line);
533                }
534                diff.push('\n');
535            }
536        }
537        let marker = if actual_insertions.iter().any(|range| range.contains(&row)) {
538            "+ "
539        } else {
540            "  "
541        };
542        diff.push_str(format!("{marker}{line}").trim_end());
543    }
544    diff
545}
546
547impl Deref for EditorTestContext {
548    type Target = gpui::VisualTestContext;
549
550    fn deref(&self) -> &Self::Target {
551        &self.cx
552    }
553}
554
555impl DerefMut for EditorTestContext {
556    fn deref_mut(&mut self) -> &mut Self::Target {
557        &mut self.cx
558    }
559}
560
561/// Tracks string context to be printed when assertions fail.
562/// Often this is done by storing a context string in the manager and returning the handle.
563#[derive(Clone)]
564pub struct AssertionContextManager {
565    id: Arc<AtomicUsize>,
566    contexts: Arc<RwLock<BTreeMap<usize, String>>>,
567}
568
569impl Default for AssertionContextManager {
570    fn default() -> Self {
571        Self::new()
572    }
573}
574
575impl AssertionContextManager {
576    pub fn new() -> Self {
577        Self {
578            id: Arc::new(AtomicUsize::new(0)),
579            contexts: Arc::new(RwLock::new(BTreeMap::new())),
580        }
581    }
582
583    pub fn add_context(&self, context: String) -> ContextHandle {
584        let id = self.id.fetch_add(1, Ordering::Relaxed);
585        let mut contexts = self.contexts.write();
586        contexts.insert(id, context);
587        ContextHandle {
588            id,
589            manager: self.clone(),
590        }
591    }
592
593    pub fn context(&self) -> String {
594        let contexts = self.contexts.read();
595        format!("\n{}\n", contexts.values().join("\n"))
596    }
597}
598
599/// Used to track the lifetime of a piece of context so that it can be provided when an assertion fails.
600/// For example, in the EditorTestContext, `set_state` returns a context handle so that if an assertion fails,
601/// the state that was set initially for the failure can be printed in the error message
602pub struct ContextHandle {
603    id: usize,
604    manager: AssertionContextManager,
605}
606
607impl Drop for ContextHandle {
608    fn drop(&mut self) {
609        let mut contexts = self.manager.contexts.write();
610        contexts.remove(&self.id);
611    }
612}