editor_test_context.rs

  1use crate::{
  2    display_map::ToDisplayPoint, AnchorRangeExt, Autoscroll, DisplayPoint, Editor, MultiBuffer,
  3    RowExt,
  4};
  5use collections::BTreeMap;
  6use futures::Future;
  7use gpui::{
  8    AnyWindowHandle, AppContext, Keystroke, ModelContext, Pixels, Point, View, ViewContext,
  9    VisualTestContext,
 10};
 11use indoc::indoc;
 12use itertools::Itertools;
 13use language::{Buffer, BufferSnapshot, LanguageRegistry};
 14use multi_buffer::ExcerptRange;
 15use parking_lot::RwLock;
 16use project::{FakeFs, Project};
 17use std::{
 18    any::TypeId,
 19    ops::{Deref, DerefMut, Range},
 20    sync::{
 21        atomic::{AtomicUsize, Ordering},
 22        Arc,
 23    },
 24};
 25use ui::Context;
 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        // fs.insert_file("/file", "".to_owned()).await;
 44        fs.insert_tree(
 45            "/root",
 46            serde_json::json!({
 47                "file": "",
 48            }),
 49        )
 50        .await;
 51        let project = Project::test(fs, ["/root".as_ref()], cx).await;
 52        let buffer = project
 53            .update(cx, |project, cx| {
 54                project.open_local_buffer("/root/file", cx)
 55            })
 56            .await
 57            .unwrap();
 58        let editor = cx.add_window(|cx| {
 59            let editor =
 60                build_editor_with_project(project, MultiBuffer::build_from_buffer(buffer, cx), cx);
 61            editor.focus(cx);
 62            editor
 63        });
 64        let editor_view = editor.root_view(cx).unwrap();
 65        Self {
 66            cx: VisualTestContext::from_window(*editor.deref(), cx),
 67            window: editor.into(),
 68            editor: editor_view,
 69            assertion_cx: AssertionContextManager::new(),
 70        }
 71    }
 72
 73    pub fn new_multibuffer<const COUNT: usize>(
 74        cx: &mut gpui::TestAppContext,
 75        excerpts: [&str; COUNT],
 76    ) -> EditorTestContext {
 77        let mut multibuffer = MultiBuffer::new(0, language::Capability::ReadWrite);
 78        let buffer = cx.new_model(|cx| {
 79            for excerpt in excerpts.into_iter() {
 80                let (text, ranges) = marked_text_ranges(excerpt, false);
 81                let buffer = cx.new_model(|cx| Buffer::local(text, cx));
 82                multibuffer.push_excerpts(
 83                    buffer,
 84                    ranges.into_iter().map(|range| ExcerptRange {
 85                        context: range,
 86                        primary: None,
 87                    }),
 88                    cx,
 89                );
 90            }
 91            multibuffer
 92        });
 93
 94        let editor = cx.add_window(|cx| {
 95            let editor = build_editor(buffer, cx);
 96            editor.focus(cx);
 97            editor
 98        });
 99
100        let editor_view = editor.root_view(cx).unwrap();
101        Self {
102            cx: VisualTestContext::from_window(*editor.deref(), cx),
103            window: editor.into(),
104            editor: editor_view,
105            assertion_cx: AssertionContextManager::new(),
106        }
107    }
108
109    pub fn condition(
110        &self,
111        predicate: impl FnMut(&Editor, &AppContext) -> bool,
112    ) -> impl Future<Output = ()> {
113        self.editor
114            .condition::<crate::EditorEvent>(&self.cx, predicate)
115    }
116
117    #[track_caller]
118    pub fn editor<F, T>(&mut self, read: F) -> T
119    where
120        F: FnOnce(&Editor, &ViewContext<Editor>) -> T,
121    {
122        self.editor
123            .update(&mut self.cx, |this, cx| read(&this, &cx))
124    }
125
126    #[track_caller]
127    pub fn update_editor<F, T>(&mut self, update: F) -> T
128    where
129        F: FnOnce(&mut Editor, &mut ViewContext<Editor>) -> T,
130    {
131        self.editor.update(&mut self.cx, update)
132    }
133
134    pub fn multibuffer<F, T>(&mut self, read: F) -> T
135    where
136        F: FnOnce(&MultiBuffer, &AppContext) -> T,
137    {
138        self.editor(|editor, cx| read(editor.buffer().read(cx), cx))
139    }
140
141    pub fn update_multibuffer<F, T>(&mut self, update: F) -> T
142    where
143        F: FnOnce(&mut MultiBuffer, &mut ModelContext<MultiBuffer>) -> T,
144    {
145        self.update_editor(|editor, cx| editor.buffer().update(cx, update))
146    }
147
148    pub fn buffer_text(&mut self) -> String {
149        self.multibuffer(|buffer, cx| buffer.snapshot(cx).text())
150    }
151
152    pub fn buffer<F, T>(&mut self, read: F) -> T
153    where
154        F: FnOnce(&Buffer, &AppContext) -> T,
155    {
156        self.multibuffer(|multibuffer, cx| {
157            let buffer = multibuffer.as_singleton().unwrap().read(cx);
158            read(buffer, cx)
159        })
160    }
161
162    pub fn language_registry(&mut self) -> Arc<LanguageRegistry> {
163        self.editor(|editor, cx| {
164            editor
165                .project
166                .as_ref()
167                .unwrap()
168                .read(cx)
169                .languages()
170                .clone()
171        })
172    }
173
174    pub fn update_buffer<F, T>(&mut self, update: F) -> T
175    where
176        F: FnOnce(&mut Buffer, &mut ModelContext<Buffer>) -> T,
177    {
178        self.update_multibuffer(|multibuffer, cx| {
179            let buffer = multibuffer.as_singleton().unwrap();
180            buffer.update(cx, update)
181        })
182    }
183
184    pub fn buffer_snapshot(&mut self) -> BufferSnapshot {
185        self.buffer(|buffer, _| buffer.snapshot())
186    }
187
188    pub fn add_assertion_context(&self, context: String) -> ContextHandle {
189        self.assertion_cx.add_context(context)
190    }
191
192    pub fn assertion_context(&self) -> String {
193        self.assertion_cx.context()
194    }
195
196    pub fn simulate_keystroke(&mut self, keystroke_text: &str) -> ContextHandle {
197        let keystroke_under_test_handle =
198            self.add_assertion_context(format!("Simulated Keystroke: {:?}", keystroke_text));
199        let keystroke = Keystroke::parse(keystroke_text).unwrap();
200
201        self.cx.dispatch_keystroke(self.window, keystroke);
202
203        keystroke_under_test_handle
204    }
205
206    pub fn simulate_keystrokes<const COUNT: usize>(
207        &mut self,
208        keystroke_texts: [&str; COUNT],
209    ) -> ContextHandle {
210        let keystrokes_under_test_handle =
211            self.add_assertion_context(format!("Simulated Keystrokes: {:?}", keystroke_texts));
212        for keystroke_text in keystroke_texts.into_iter() {
213            self.simulate_keystroke(keystroke_text);
214        }
215        // it is common for keyboard shortcuts to kick off async actions, so this ensures that they are complete
216        // before returning.
217        // NOTE: we don't do this in simulate_keystroke() because a possible cause of bugs is that typing too
218        // quickly races with async actions.
219        self.cx.background_executor.run_until_parked();
220
221        keystrokes_under_test_handle
222    }
223
224    pub fn run_until_parked(&mut self) {
225        self.cx.background_executor.run_until_parked();
226    }
227
228    pub fn ranges(&mut self, marked_text: &str) -> Vec<Range<usize>> {
229        let (unmarked_text, ranges) = marked_text_ranges(marked_text, false);
230        assert_eq!(self.buffer_text(), unmarked_text);
231        ranges
232    }
233
234    pub fn display_point(&mut self, marked_text: &str) -> DisplayPoint {
235        let ranges = self.ranges(marked_text);
236        let snapshot = self
237            .editor
238            .update(&mut self.cx, |editor, cx| editor.snapshot(cx));
239        ranges[0].start.to_display_point(&snapshot)
240    }
241
242    pub fn pixel_position(&mut self, marked_text: &str) -> Point<Pixels> {
243        let display_point = self.display_point(marked_text);
244        self.pixel_position_for(display_point)
245    }
246
247    pub fn pixel_position_for(&mut self, display_point: DisplayPoint) -> Point<Pixels> {
248        self.update_editor(|editor, cx| {
249            let newest_point = editor.selections.newest_display(cx).head();
250            let pixel_position = editor.pixel_position_of_newest_cursor.unwrap();
251            let line_height = editor
252                .style()
253                .unwrap()
254                .text
255                .line_height_in_pixels(cx.rem_size());
256            let snapshot = editor.snapshot(cx);
257            let details = editor.text_layout_details(cx);
258
259            let y = pixel_position.y
260                + line_height * (display_point.row().as_f32() - newest_point.row().as_f32());
261            let x = pixel_position.x + snapshot.x_for_display_point(display_point, &details)
262                - snapshot.x_for_display_point(newest_point, &details);
263            Point::new(x, y)
264        })
265    }
266
267    // Returns anchors for the current buffer using `«` and `»`
268    pub fn text_anchor_range(&mut self, marked_text: &str) -> Range<language::Anchor> {
269        let ranges = self.ranges(marked_text);
270        let snapshot = self.buffer_snapshot();
271        snapshot.anchor_before(ranges[0].start)..snapshot.anchor_after(ranges[0].end)
272    }
273
274    pub fn set_diff_base(&mut self, diff_base: Option<&str>) {
275        self.update_buffer(|buffer, cx| buffer.set_diff_base(diff_base.map(ToOwned::to_owned), 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}