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 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};
 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        let root = Self::root_path();
 47        fs.insert_tree(
 48            root,
 49            serde_json::json!({
 50                "file": "",
 51            }),
 52        )
 53        .await;
 54        let project = Project::test(fs, [root], cx).await;
 55        let buffer = project
 56            .update(cx, |project, cx| {
 57                project.open_local_buffer(root.join("file"), cx)
 58            })
 59            .await
 60            .unwrap();
 61        let editor = cx.add_window(|cx| {
 62            let editor =
 63                build_editor_with_project(project, MultiBuffer::build_from_buffer(buffer, cx), cx);
 64            editor.focus(cx);
 65            editor
 66        });
 67        let editor_view = editor.root_view(cx).unwrap();
 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: Option<&str>) {
280        self.update_buffer(|buffer, cx| buffer.set_diff_base(diff_base.map(ToOwned::to_owned), cx));
281    }
282
283    /// Change the editor's text and selections using a string containing
284    /// embedded range markers that represent the ranges and directions of
285    /// each selection.
286    ///
287    /// Returns a context handle so that assertion failures can print what
288    /// editor state was needed to cause the failure.
289    ///
290    /// See the `util::test::marked_text_ranges` function for more information.
291    pub fn set_state(&mut self, marked_text: &str) -> ContextHandle {
292        let state_context = self.add_assertion_context(format!(
293            "Initial Editor State: \"{}\"",
294            marked_text.escape_debug()
295        ));
296        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
297        self.editor.update(&mut self.cx, |editor, cx| {
298            editor.set_text(unmarked_text, cx);
299            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
300                s.select_ranges(selection_ranges)
301            })
302        });
303        state_context
304    }
305
306    /// Only change the editor's selections
307    pub fn set_selections_state(&mut self, marked_text: &str) -> ContextHandle {
308        let state_context = self.add_assertion_context(format!(
309            "Initial Editor State: \"{}\"",
310            marked_text.escape_debug()
311        ));
312        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
313        self.editor.update(&mut self.cx, |editor, cx| {
314            assert_eq!(editor.text(cx), unmarked_text);
315            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
316                s.select_ranges(selection_ranges)
317            })
318        });
319        state_context
320    }
321
322    #[track_caller]
323    pub fn assert_diff_hunks(&mut self, expected_diff: String) {
324        // Normalize the expected diff. If it has no diff markers, then insert blank markers
325        // before each line. Strip any whitespace-only lines.
326        let has_diff_markers = expected_diff
327            .lines()
328            .any(|line| line.starts_with("+") || line.starts_with("-"));
329        let expected_diff_text = expected_diff
330            .split('\n')
331            .map(|line| {
332                let trimmed = line.trim();
333                if trimmed.is_empty() {
334                    String::new()
335                } else if has_diff_markers {
336                    line.to_string()
337                } else {
338                    format!("  {line}")
339                }
340            })
341            .join("\n");
342
343        // Read the actual diff from the editor's row highlights and block
344        // decorations.
345        let actual_diff = self.editor.update(&mut self.cx, |editor, cx| {
346            let snapshot = editor.snapshot(cx);
347            let text = editor.text(cx);
348            let insertions = editor
349                .highlighted_rows::<DiffRowHighlight>()
350                .map(|(range, _)| {
351                    let start = range.start.to_point(&snapshot.buffer_snapshot);
352                    let end = range.end.to_point(&snapshot.buffer_snapshot);
353                    start.row..end.row
354                })
355                .collect::<Vec<_>>();
356            let deletions = editor
357                .expanded_hunks
358                .hunks
359                .iter()
360                .filter_map(|hunk| {
361                    if hunk.blocks.is_empty() {
362                        return None;
363                    }
364                    let row = hunk
365                        .hunk_range
366                        .start
367                        .to_point(&snapshot.buffer_snapshot)
368                        .row;
369                    let (_, buffer, _) = editor
370                        .buffer()
371                        .read(cx)
372                        .excerpt_containing(hunk.hunk_range.start, cx)
373                        .expect("no excerpt for expanded buffer's hunk start");
374                    let deleted_text = buffer
375                        .read(cx)
376                        .diff_base()
377                        .expect("should have a diff base for expanded hunk")
378                        .slice(hunk.diff_base_byte_range.clone())
379                        .to_string();
380                    if let DiffHunkStatus::Modified | DiffHunkStatus::Removed = hunk.status {
381                        Some((row, deleted_text))
382                    } else {
383                        None
384                    }
385                })
386                .collect::<Vec<_>>();
387            format_diff(text, deletions, insertions)
388        });
389
390        pretty_assertions::assert_eq!(actual_diff, expected_diff_text, "unexpected diff state");
391    }
392
393    /// Make an assertion about the editor's text and the ranges and directions
394    /// of its selections using a string containing embedded range markers.
395    ///
396    /// See the `util::test::marked_text_ranges` function for more information.
397    #[track_caller]
398    pub fn assert_editor_state(&mut self, marked_text: &str) {
399        let (expected_text, expected_selections) = marked_text_ranges(marked_text, true);
400        pretty_assertions::assert_eq!(self.buffer_text(), expected_text, "unexpected buffer text");
401        self.assert_selections(expected_selections, marked_text.to_string())
402    }
403
404    pub fn editor_state(&mut self) -> String {
405        generate_marked_text(self.buffer_text().as_str(), &self.editor_selections(), true)
406    }
407
408    #[track_caller]
409    pub fn assert_editor_background_highlights<Tag: 'static>(&mut self, marked_text: &str) {
410        let expected_ranges = self.ranges(marked_text);
411        let actual_ranges: Vec<Range<usize>> = self.update_editor(|editor, cx| {
412            let snapshot = editor.snapshot(cx);
413            editor
414                .background_highlights
415                .get(&TypeId::of::<Tag>())
416                .map(|h| h.1.clone())
417                .unwrap_or_default()
418                .iter()
419                .map(|range| range.to_offset(&snapshot.buffer_snapshot))
420                .collect()
421        });
422        assert_set_eq!(actual_ranges, expected_ranges);
423    }
424
425    #[track_caller]
426    pub fn assert_editor_text_highlights<Tag: ?Sized + 'static>(&mut self, marked_text: &str) {
427        let expected_ranges = self.ranges(marked_text);
428        let snapshot = self.update_editor(|editor, cx| editor.snapshot(cx));
429        let actual_ranges: Vec<Range<usize>> = snapshot
430            .text_highlight_ranges::<Tag>()
431            .map(|ranges| ranges.as_ref().clone().1)
432            .unwrap_or_default()
433            .into_iter()
434            .map(|range| range.to_offset(&snapshot.buffer_snapshot))
435            .collect();
436        assert_set_eq!(actual_ranges, expected_ranges);
437    }
438
439    #[track_caller]
440    pub fn assert_editor_selections(&mut self, expected_selections: Vec<Range<usize>>) {
441        let expected_marked_text =
442            generate_marked_text(&self.buffer_text(), &expected_selections, true);
443        self.assert_selections(expected_selections, expected_marked_text)
444    }
445
446    #[track_caller]
447    fn editor_selections(&mut self) -> Vec<Range<usize>> {
448        self.editor
449            .update(&mut self.cx, |editor, cx| {
450                editor.selections.all::<usize>(cx)
451            })
452            .into_iter()
453            .map(|s| {
454                if s.reversed {
455                    s.end..s.start
456                } else {
457                    s.start..s.end
458                }
459            })
460            .collect::<Vec<_>>()
461    }
462
463    #[track_caller]
464    fn assert_selections(
465        &mut self,
466        expected_selections: Vec<Range<usize>>,
467        expected_marked_text: String,
468    ) {
469        let actual_selections = self.editor_selections();
470        let actual_marked_text =
471            generate_marked_text(&self.buffer_text(), &actual_selections, true);
472        if expected_selections != actual_selections {
473            pretty_assertions::assert_eq!(
474                actual_marked_text,
475                expected_marked_text,
476                "{}Editor has unexpected selections",
477                self.assertion_context(),
478            );
479        }
480    }
481}
482
483fn format_diff(
484    text: String,
485    actual_deletions: Vec<(u32, String)>,
486    actual_insertions: Vec<Range<u32>>,
487) -> String {
488    let mut diff = String::new();
489    for (row, line) in text.split('\n').enumerate() {
490        let row = row as u32;
491        if row > 0 {
492            diff.push('\n');
493        }
494        if let Some(text) = actual_deletions
495            .iter()
496            .find_map(|(deletion_row, deleted_text)| {
497                if *deletion_row == row {
498                    Some(deleted_text)
499                } else {
500                    None
501                }
502            })
503        {
504            for line in text.lines() {
505                diff.push('-');
506                if !line.is_empty() {
507                    diff.push(' ');
508                    diff.push_str(line);
509                }
510                diff.push('\n');
511            }
512        }
513        let marker = if actual_insertions.iter().any(|range| range.contains(&row)) {
514            "+ "
515        } else {
516            "  "
517        };
518        diff.push_str(format!("{marker}{line}").trim_end());
519    }
520    diff
521}
522
523impl Deref for EditorTestContext {
524    type Target = gpui::VisualTestContext;
525
526    fn deref(&self) -> &Self::Target {
527        &self.cx
528    }
529}
530
531impl DerefMut for EditorTestContext {
532    fn deref_mut(&mut self) -> &mut Self::Target {
533        &mut self.cx
534    }
535}
536
537/// Tracks string context to be printed when assertions fail.
538/// Often this is done by storing a context string in the manager and returning the handle.
539#[derive(Clone)]
540pub struct AssertionContextManager {
541    id: Arc<AtomicUsize>,
542    contexts: Arc<RwLock<BTreeMap<usize, String>>>,
543}
544
545impl Default for AssertionContextManager {
546    fn default() -> Self {
547        Self::new()
548    }
549}
550
551impl AssertionContextManager {
552    pub fn new() -> Self {
553        Self {
554            id: Arc::new(AtomicUsize::new(0)),
555            contexts: Arc::new(RwLock::new(BTreeMap::new())),
556        }
557    }
558
559    pub fn add_context(&self, context: String) -> ContextHandle {
560        let id = self.id.fetch_add(1, Ordering::Relaxed);
561        let mut contexts = self.contexts.write();
562        contexts.insert(id, context);
563        ContextHandle {
564            id,
565            manager: self.clone(),
566        }
567    }
568
569    pub fn context(&self) -> String {
570        let contexts = self.contexts.read();
571        format!("\n{}\n", contexts.values().join("\n"))
572    }
573}
574
575/// Used to track the lifetime of a piece of context so that it can be provided when an assertion fails.
576/// For example, in the EditorTestContext, `set_state` returns a context handle so that if an assertion fails,
577/// the state that was set initially for the failure can be printed in the error message
578pub struct ContextHandle {
579    id: usize,
580    manager: AssertionContextManager,
581}
582
583impl Drop for ContextHandle {
584    fn drop(&mut self) {
585        let mut contexts = self.manager.contexts.write();
586        contexts.remove(&self.id);
587    }
588}