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 text::Rope;
 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        let diff_base = diff_base.map(Rope::from);
276        self.update_buffer(|buffer, cx| buffer.set_diff_base(diff_base, cx));
277    }
278
279    /// Change the editor's text and selections using a string containing
280    /// embedded range markers that represent the ranges and directions of
281    /// each selection.
282    ///
283    /// Returns a context handle so that assertion failures can print what
284    /// editor state was needed to cause the failure.
285    ///
286    /// See the `util::test::marked_text_ranges` function for more information.
287    pub fn set_state(&mut self, marked_text: &str) -> ContextHandle {
288        let state_context = self.add_assertion_context(format!(
289            "Initial Editor State: \"{}\"",
290            marked_text.escape_debug()
291        ));
292        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
293        self.editor.update(&mut self.cx, |editor, cx| {
294            editor.set_text(unmarked_text, cx);
295            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
296                s.select_ranges(selection_ranges)
297            })
298        });
299        state_context
300    }
301
302    /// Only change the editor's selections
303    pub fn set_selections_state(&mut self, marked_text: &str) -> ContextHandle {
304        let state_context = self.add_assertion_context(format!(
305            "Initial Editor State: \"{}\"",
306            marked_text.escape_debug()
307        ));
308        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
309        self.editor.update(&mut self.cx, |editor, cx| {
310            assert_eq!(editor.text(cx), unmarked_text);
311            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
312                s.select_ranges(selection_ranges)
313            })
314        });
315        state_context
316    }
317
318    /// Make an assertion about the editor's text and the ranges and directions
319    /// of its selections using a string containing embedded range markers.
320    ///
321    /// See the `util::test::marked_text_ranges` function for more information.
322    #[track_caller]
323    pub fn assert_editor_state(&mut self, marked_text: &str) {
324        let (unmarked_text, expected_selections) = marked_text_ranges(marked_text, true);
325        let buffer_text = self.buffer_text();
326
327        if buffer_text != unmarked_text {
328            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}");
329        }
330
331        self.assert_selections(expected_selections, marked_text.to_string())
332    }
333
334    pub fn editor_state(&mut self) -> String {
335        generate_marked_text(self.buffer_text().as_str(), &self.editor_selections(), true)
336    }
337
338    #[track_caller]
339    pub fn assert_editor_background_highlights<Tag: 'static>(&mut self, marked_text: &str) {
340        let expected_ranges = self.ranges(marked_text);
341        let actual_ranges: Vec<Range<usize>> = self.update_editor(|editor, cx| {
342            let snapshot = editor.snapshot(cx);
343            editor
344                .background_highlights
345                .get(&TypeId::of::<Tag>())
346                .map(|h| h.1.clone())
347                .unwrap_or_else(|| Arc::from([]))
348                .into_iter()
349                .map(|range| range.to_offset(&snapshot.buffer_snapshot))
350                .collect()
351        });
352        assert_set_eq!(actual_ranges, expected_ranges);
353    }
354
355    #[track_caller]
356    pub fn assert_editor_text_highlights<Tag: ?Sized + 'static>(&mut self, marked_text: &str) {
357        let expected_ranges = self.ranges(marked_text);
358        let snapshot = self.update_editor(|editor, cx| editor.snapshot(cx));
359        let actual_ranges: Vec<Range<usize>> = snapshot
360            .text_highlight_ranges::<Tag>()
361            .map(|ranges| ranges.as_ref().clone().1)
362            .unwrap_or_default()
363            .into_iter()
364            .map(|range| range.to_offset(&snapshot.buffer_snapshot))
365            .collect();
366        assert_set_eq!(actual_ranges, expected_ranges);
367    }
368
369    #[track_caller]
370    pub fn assert_editor_selections(&mut self, expected_selections: Vec<Range<usize>>) {
371        let expected_marked_text =
372            generate_marked_text(&self.buffer_text(), &expected_selections, true);
373        self.assert_selections(expected_selections, expected_marked_text)
374    }
375
376    #[track_caller]
377    fn editor_selections(&mut self) -> Vec<Range<usize>> {
378        self.editor
379            .update(&mut self.cx, |editor, cx| {
380                editor.selections.all::<usize>(cx)
381            })
382            .into_iter()
383            .map(|s| {
384                if s.reversed {
385                    s.end..s.start
386                } else {
387                    s.start..s.end
388                }
389            })
390            .collect::<Vec<_>>()
391    }
392
393    #[track_caller]
394    fn assert_selections(
395        &mut self,
396        expected_selections: Vec<Range<usize>>,
397        expected_marked_text: String,
398    ) {
399        let actual_selections = self.editor_selections();
400        let actual_marked_text =
401            generate_marked_text(&self.buffer_text(), &actual_selections, true);
402        if expected_selections != actual_selections {
403            panic!(
404                indoc! {"
405
406                {}Editor has unexpected selections.
407
408                Expected selections:
409                {}
410
411                Actual selections:
412                {}
413            "},
414                self.assertion_context(),
415                expected_marked_text,
416                actual_marked_text,
417            );
418        }
419    }
420}
421
422impl Deref for EditorTestContext {
423    type Target = gpui::VisualTestContext;
424
425    fn deref(&self) -> &Self::Target {
426        &self.cx
427    }
428}
429
430impl DerefMut for EditorTestContext {
431    fn deref_mut(&mut self) -> &mut Self::Target {
432        &mut self.cx
433    }
434}
435
436/// Tracks string context to be printed when assertions fail.
437/// Often this is done by storing a context string in the manager and returning the handle.
438#[derive(Clone)]
439pub struct AssertionContextManager {
440    id: Arc<AtomicUsize>,
441    contexts: Arc<RwLock<BTreeMap<usize, String>>>,
442}
443
444impl AssertionContextManager {
445    pub fn new() -> Self {
446        Self {
447            id: Arc::new(AtomicUsize::new(0)),
448            contexts: Arc::new(RwLock::new(BTreeMap::new())),
449        }
450    }
451
452    pub fn add_context(&self, context: String) -> ContextHandle {
453        let id = self.id.fetch_add(1, Ordering::Relaxed);
454        let mut contexts = self.contexts.write();
455        contexts.insert(id, context);
456        ContextHandle {
457            id,
458            manager: self.clone(),
459        }
460    }
461
462    pub fn context(&self) -> String {
463        let contexts = self.contexts.read();
464        format!("\n{}\n", contexts.values().join("\n"))
465    }
466}
467
468/// Used to track the lifetime of a piece of context so that it can be provided when an assertion fails.
469/// For example, in the EditorTestContext, `set_state` returns a context handle so that if an assertion fails,
470/// the state that was set initially for the failure can be printed in the error message
471pub struct ContextHandle {
472    id: usize,
473    manager: AssertionContextManager,
474}
475
476impl Drop for ContextHandle {
477    fn drop(&mut self) {
478        let mut contexts = self.manager.contexts.write();
479        contexts.remove(&self.id);
480    }
481}