editor_test_context.rs

  1use crate::{
  2    display_map::ToDisplayPoint, AnchorRangeExt, Autoscroll, DisplayPoint, Editor, MultiBuffer,
  3};
  4use collections::BTreeMap;
  5use futures::Future;
  6use gpui::{
  7    AnyWindowHandle, AppContext, Keystroke, ModelContext, Pixels, Point, View, ViewContext,
  8    VisualTestContext,
  9};
 10use indoc::indoc;
 11use itertools::Itertools;
 12use language::{Buffer, BufferSnapshot, LanguageRegistry};
 13use multi_buffer::ExcerptRange;
 14use parking_lot::RwLock;
 15use project::{FakeFs, Project};
 16use std::{
 17    any::TypeId,
 18    ops::{Deref, DerefMut, Range},
 19    sync::{
 20        atomic::{AtomicUsize, Ordering},
 21        Arc,
 22    },
 23};
 24use ui::Context;
 25use util::{
 26    assert_set_eq,
 27    test::{generate_marked_text, marked_text_ranges},
 28};
 29
 30use super::{build_editor, build_editor_with_project};
 31
 32pub struct EditorTestContext {
 33    pub cx: gpui::VisualTestContext,
 34    pub window: AnyWindowHandle,
 35    pub editor: View<Editor>,
 36    pub assertion_cx: AssertionContextManager,
 37}
 38
 39impl EditorTestContext {
 40    pub async fn new(cx: &mut gpui::TestAppContext) -> EditorTestContext {
 41        let fs = FakeFs::new(cx.executor());
 42        // fs.insert_file("/file", "".to_owned()).await;
 43        fs.insert_tree(
 44            "/root",
 45            serde_json::json!({
 46                "file": "",
 47            }),
 48        )
 49        .await;
 50        let project = Project::test(fs, ["/root".as_ref()], cx).await;
 51        let buffer = project
 52            .update(cx, |project, cx| {
 53                project.open_local_buffer("/root/file", cx)
 54            })
 55            .await
 56            .unwrap();
 57        let editor = cx.add_window(|cx| {
 58            let editor =
 59                build_editor_with_project(project, MultiBuffer::build_from_buffer(buffer, cx), cx);
 60            editor.focus(cx);
 61            editor
 62        });
 63        let editor_view = editor.root_view(cx).unwrap();
 64        Self {
 65            cx: VisualTestContext::from_window(*editor.deref(), cx),
 66            window: editor.into(),
 67            editor: editor_view,
 68            assertion_cx: AssertionContextManager::new(),
 69        }
 70    }
 71
 72    pub fn new_multibuffer<const COUNT: usize>(
 73        cx: &mut gpui::TestAppContext,
 74        excerpts: [&str; COUNT],
 75    ) -> EditorTestContext {
 76        let mut multibuffer = MultiBuffer::new(0, language::Capability::ReadWrite);
 77        let buffer = cx.new_model(|cx| {
 78            for excerpt in excerpts.into_iter() {
 79                let (text, ranges) = marked_text_ranges(excerpt, false);
 80                let buffer = cx.new_model(|cx| Buffer::local(text, cx));
 81                multibuffer.push_excerpts(
 82                    buffer,
 83                    ranges.into_iter().map(|range| ExcerptRange {
 84                        context: range,
 85                        primary: None,
 86                    }),
 87                    cx,
 88                );
 89            }
 90            multibuffer
 91        });
 92
 93        let editor = cx.add_window(|cx| {
 94            let editor = build_editor(buffer, cx);
 95            editor.focus(cx);
 96            editor
 97        });
 98
 99        let editor_view = editor.root_view(cx).unwrap();
100        Self {
101            cx: VisualTestContext::from_window(*editor.deref(), cx),
102            window: editor.into(),
103            editor: editor_view,
104            assertion_cx: AssertionContextManager::new(),
105        }
106    }
107
108    pub fn condition(
109        &self,
110        predicate: impl FnMut(&Editor, &AppContext) -> bool,
111    ) -> impl Future<Output = ()> {
112        self.editor
113            .condition::<crate::EditorEvent>(&self.cx, predicate)
114    }
115
116    #[track_caller]
117    pub fn editor<F, T>(&mut self, read: F) -> T
118    where
119        F: FnOnce(&Editor, &ViewContext<Editor>) -> T,
120    {
121        self.editor
122            .update(&mut self.cx, |this, cx| read(&this, &cx))
123    }
124
125    #[track_caller]
126    pub fn update_editor<F, T>(&mut self, update: F) -> T
127    where
128        F: FnOnce(&mut Editor, &mut ViewContext<Editor>) -> T,
129    {
130        self.editor.update(&mut self.cx, update)
131    }
132
133    pub fn multibuffer<F, T>(&mut self, read: F) -> T
134    where
135        F: FnOnce(&MultiBuffer, &AppContext) -> T,
136    {
137        self.editor(|editor, cx| read(editor.buffer().read(cx), cx))
138    }
139
140    pub fn update_multibuffer<F, T>(&mut self, update: F) -> T
141    where
142        F: FnOnce(&mut MultiBuffer, &mut ModelContext<MultiBuffer>) -> T,
143    {
144        self.update_editor(|editor, cx| editor.buffer().update(cx, update))
145    }
146
147    pub fn buffer_text(&mut self) -> String {
148        self.multibuffer(|buffer, cx| buffer.snapshot(cx).text())
149    }
150
151    pub fn buffer<F, T>(&mut self, read: F) -> T
152    where
153        F: FnOnce(&Buffer, &AppContext) -> T,
154    {
155        self.multibuffer(|multibuffer, cx| {
156            let buffer = multibuffer.as_singleton().unwrap().read(cx);
157            read(buffer, cx)
158        })
159    }
160
161    pub fn language_registry(&mut self) -> Arc<LanguageRegistry> {
162        self.editor(|editor, cx| {
163            editor
164                .project
165                .as_ref()
166                .unwrap()
167                .read(cx)
168                .languages()
169                .clone()
170        })
171    }
172
173    pub fn update_buffer<F, T>(&mut self, update: F) -> T
174    where
175        F: FnOnce(&mut Buffer, &mut ModelContext<Buffer>) -> T,
176    {
177        self.update_multibuffer(|multibuffer, cx| {
178            let buffer = multibuffer.as_singleton().unwrap();
179            buffer.update(cx, update)
180        })
181    }
182
183    pub fn buffer_snapshot(&mut self) -> BufferSnapshot {
184        self.buffer(|buffer, _| buffer.snapshot())
185    }
186
187    pub fn add_assertion_context(&self, context: String) -> ContextHandle {
188        self.assertion_cx.add_context(context)
189    }
190
191    pub fn assertion_context(&self) -> String {
192        self.assertion_cx.context()
193    }
194
195    pub fn simulate_keystroke(&mut self, keystroke_text: &str) -> ContextHandle {
196        let keystroke_under_test_handle =
197            self.add_assertion_context(format!("Simulated Keystroke: {:?}", keystroke_text));
198        let keystroke = Keystroke::parse(keystroke_text).unwrap();
199
200        self.cx.dispatch_keystroke(self.window, keystroke);
201
202        keystroke_under_test_handle
203    }
204
205    pub fn simulate_keystrokes<const COUNT: usize>(
206        &mut self,
207        keystroke_texts: [&str; COUNT],
208    ) -> ContextHandle {
209        let keystrokes_under_test_handle =
210            self.add_assertion_context(format!("Simulated Keystrokes: {:?}", keystroke_texts));
211        for keystroke_text in keystroke_texts.into_iter() {
212            self.simulate_keystroke(keystroke_text);
213        }
214        // it is common for keyboard shortcuts to kick off async actions, so this ensures that they are complete
215        // before returning.
216        // NOTE: we don't do this in simulate_keystroke() because a possible cause of bugs is that typing too
217        // quickly races with async actions.
218        self.cx.background_executor.run_until_parked();
219
220        keystrokes_under_test_handle
221    }
222
223    pub fn run_until_parked(&mut self) {
224        self.cx.background_executor.run_until_parked();
225    }
226
227    pub fn ranges(&mut self, marked_text: &str) -> Vec<Range<usize>> {
228        let (unmarked_text, ranges) = marked_text_ranges(marked_text, false);
229        assert_eq!(self.buffer_text(), unmarked_text);
230        ranges
231    }
232
233    pub fn display_point(&mut self, marked_text: &str) -> DisplayPoint {
234        let ranges = self.ranges(marked_text);
235        let snapshot = self
236            .editor
237            .update(&mut self.cx, |editor, cx| editor.snapshot(cx));
238        ranges[0].start.to_display_point(&snapshot)
239    }
240
241    pub fn pixel_position(&mut self, marked_text: &str) -> Point<Pixels> {
242        let display_point = self.display_point(marked_text);
243        self.pixel_position_for(display_point)
244    }
245
246    pub fn pixel_position_for(&mut self, display_point: DisplayPoint) -> Point<Pixels> {
247        self.update_editor(|editor, cx| {
248            let newest_point = editor.selections.newest_display(cx).head();
249            let pixel_position = editor.pixel_position_of_newest_cursor.unwrap();
250            let line_height = editor
251                .style()
252                .unwrap()
253                .text
254                .line_height_in_pixels(cx.rem_size());
255            let snapshot = editor.snapshot(cx);
256            let details = editor.text_layout_details(cx);
257
258            let y = pixel_position.y
259                + line_height * (display_point.row() as f32 - newest_point.row() as f32);
260            let x = pixel_position.x + snapshot.x_for_display_point(display_point, &details)
261                - snapshot.x_for_display_point(newest_point, &details);
262            Point::new(x, y)
263        })
264    }
265
266    // Returns anchors for the current buffer using `«` and `»`
267    pub fn text_anchor_range(&mut self, marked_text: &str) -> Range<language::Anchor> {
268        let ranges = self.ranges(marked_text);
269        let snapshot = self.buffer_snapshot();
270        snapshot.anchor_before(ranges[0].start)..snapshot.anchor_after(ranges[0].end)
271    }
272
273    pub fn set_diff_base(&mut self, diff_base: Option<&str>) {
274        let diff_base = diff_base.map(String::from);
275        self.update_buffer(|buffer, cx| buffer.set_diff_base(diff_base, cx));
276    }
277
278    /// Change the editor's text and selections using a string containing
279    /// embedded range markers that represent the ranges and directions of
280    /// each selection.
281    ///
282    /// Returns a context handle so that assertion failures can print what
283    /// editor state was needed to cause the failure.
284    ///
285    /// See the `util::test::marked_text_ranges` function for more information.
286    pub fn set_state(&mut self, marked_text: &str) -> ContextHandle {
287        let state_context = self.add_assertion_context(format!(
288            "Initial Editor State: \"{}\"",
289            marked_text.escape_debug()
290        ));
291        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
292        self.editor.update(&mut self.cx, |editor, cx| {
293            editor.set_text(unmarked_text, cx);
294            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
295                s.select_ranges(selection_ranges)
296            })
297        });
298        state_context
299    }
300
301    /// Only change the editor's selections
302    pub fn set_selections_state(&mut self, marked_text: &str) -> ContextHandle {
303        let state_context = self.add_assertion_context(format!(
304            "Initial Editor State: \"{}\"",
305            marked_text.escape_debug()
306        ));
307        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
308        self.editor.update(&mut self.cx, |editor, cx| {
309            assert_eq!(editor.text(cx), unmarked_text);
310            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
311                s.select_ranges(selection_ranges)
312            })
313        });
314        state_context
315    }
316
317    /// Make an assertion about the editor's text and the ranges and directions
318    /// of its selections using a string containing embedded range markers.
319    ///
320    /// See the `util::test::marked_text_ranges` function for more information.
321    #[track_caller]
322    pub fn assert_editor_state(&mut self, marked_text: &str) {
323        let (unmarked_text, expected_selections) = marked_text_ranges(marked_text, true);
324        let buffer_text = self.buffer_text();
325
326        if buffer_text != unmarked_text {
327            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}");
328        }
329
330        self.assert_selections(expected_selections, marked_text.to_string())
331    }
332
333    pub fn editor_state(&mut self) -> String {
334        generate_marked_text(self.buffer_text().as_str(), &self.editor_selections(), true)
335    }
336
337    #[track_caller]
338    pub fn assert_editor_background_highlights<Tag: 'static>(&mut self, marked_text: &str) {
339        let expected_ranges = self.ranges(marked_text);
340        let actual_ranges: Vec<Range<usize>> = self.update_editor(|editor, cx| {
341            let snapshot = editor.snapshot(cx);
342            editor
343                .background_highlights
344                .get(&TypeId::of::<Tag>())
345                .map(|h| h.1.clone())
346                .unwrap_or_else(|| Arc::from([]))
347                .into_iter()
348                .map(|range| range.to_offset(&snapshot.buffer_snapshot))
349                .collect()
350        });
351        assert_set_eq!(actual_ranges, expected_ranges);
352    }
353
354    #[track_caller]
355    pub fn assert_editor_text_highlights<Tag: ?Sized + 'static>(&mut self, marked_text: &str) {
356        let expected_ranges = self.ranges(marked_text);
357        let snapshot = self.update_editor(|editor, cx| editor.snapshot(cx));
358        let actual_ranges: Vec<Range<usize>> = snapshot
359            .text_highlight_ranges::<Tag>()
360            .map(|ranges| ranges.as_ref().clone().1)
361            .unwrap_or_default()
362            .into_iter()
363            .map(|range| range.to_offset(&snapshot.buffer_snapshot))
364            .collect();
365        assert_set_eq!(actual_ranges, expected_ranges);
366    }
367
368    #[track_caller]
369    pub fn assert_editor_selections(&mut self, expected_selections: Vec<Range<usize>>) {
370        let expected_marked_text =
371            generate_marked_text(&self.buffer_text(), &expected_selections, true);
372        self.assert_selections(expected_selections, expected_marked_text)
373    }
374
375    #[track_caller]
376    fn editor_selections(&mut self) -> Vec<Range<usize>> {
377        self.editor
378            .update(&mut self.cx, |editor, cx| {
379                editor.selections.all::<usize>(cx)
380            })
381            .into_iter()
382            .map(|s| {
383                if s.reversed {
384                    s.end..s.start
385                } else {
386                    s.start..s.end
387                }
388            })
389            .collect::<Vec<_>>()
390    }
391
392    #[track_caller]
393    fn assert_selections(
394        &mut self,
395        expected_selections: Vec<Range<usize>>,
396        expected_marked_text: String,
397    ) {
398        let actual_selections = self.editor_selections();
399        let actual_marked_text =
400            generate_marked_text(&self.buffer_text(), &actual_selections, true);
401        if expected_selections != actual_selections {
402            panic!(
403                indoc! {"
404
405                {}Editor has unexpected selections.
406
407                Expected selections:
408                {}
409
410                Actual selections:
411                {}
412            "},
413                self.assertion_context(),
414                expected_marked_text,
415                actual_marked_text,
416            );
417        }
418    }
419}
420
421impl Deref for EditorTestContext {
422    type Target = gpui::VisualTestContext;
423
424    fn deref(&self) -> &Self::Target {
425        &self.cx
426    }
427}
428
429impl DerefMut for EditorTestContext {
430    fn deref_mut(&mut self) -> &mut Self::Target {
431        &mut self.cx
432    }
433}
434
435/// Tracks string context to be printed when assertions fail.
436/// Often this is done by storing a context string in the manager and returning the handle.
437#[derive(Clone)]
438pub struct AssertionContextManager {
439    id: Arc<AtomicUsize>,
440    contexts: Arc<RwLock<BTreeMap<usize, String>>>,
441}
442
443impl AssertionContextManager {
444    pub fn new() -> Self {
445        Self {
446            id: Arc::new(AtomicUsize::new(0)),
447            contexts: Arc::new(RwLock::new(BTreeMap::new())),
448        }
449    }
450
451    pub fn add_context(&self, context: String) -> ContextHandle {
452        let id = self.id.fetch_add(1, Ordering::Relaxed);
453        let mut contexts = self.contexts.write();
454        contexts.insert(id, context);
455        ContextHandle {
456            id,
457            manager: self.clone(),
458        }
459    }
460
461    pub fn context(&self) -> String {
462        let contexts = self.contexts.read();
463        format!("\n{}\n", contexts.values().join("\n"))
464    }
465}
466
467/// Used to track the lifetime of a piece of context so that it can be provided when an assertion fails.
468/// For example, in the EditorTestContext, `set_state` returns a context handle so that if an assertion fails,
469/// the state that was set initially for the failure can be printed in the error message
470pub struct ContextHandle {
471    id: usize,
472    manager: AssertionContextManager,
473}
474
475impl Drop for ContextHandle {
476    fn drop(&mut self) {
477        let mut contexts = self.manager.contexts.write();
478        contexts.remove(&self.id);
479    }
480}