editor_test_context.rs

  1use std::{
  2    any::TypeId,
  3    ops::{Deref, DerefMut, Range},
  4};
  5
  6use futures::Future;
  7use indoc::indoc;
  8
  9use crate::{
 10    display_map::ToDisplayPoint, AnchorRangeExt, Autoscroll, DisplayPoint, Editor, MultiBuffer,
 11};
 12use gpui::{
 13    keymap_matcher::Keystroke, AppContext, ContextHandle, ModelContext, ViewContext, ViewHandle,
 14};
 15use language::{Buffer, BufferSnapshot};
 16use settings::Settings;
 17use util::{
 18    assert_set_eq,
 19    test::{generate_marked_text, marked_text_ranges},
 20};
 21
 22use super::build_editor;
 23
 24pub struct EditorTestContext<'a> {
 25    pub cx: &'a mut gpui::TestAppContext,
 26    pub window_id: usize,
 27    pub editor: ViewHandle<Editor>,
 28}
 29
 30impl<'a> EditorTestContext<'a> {
 31    pub fn new(cx: &'a mut gpui::TestAppContext) -> EditorTestContext<'a> {
 32        let (window_id, editor) = cx.update(|cx| {
 33            cx.set_global(Settings::test(cx));
 34            crate::init(cx);
 35
 36            let (window_id, editor) = cx.add_window(Default::default(), |cx| {
 37                build_editor(MultiBuffer::build_simple("", cx), cx)
 38            });
 39
 40            editor.update(cx, |_, cx| cx.focus_self());
 41
 42            (window_id, editor)
 43        });
 44
 45        Self {
 46            cx,
 47            window_id,
 48            editor,
 49        }
 50    }
 51
 52    pub fn condition(
 53        &self,
 54        predicate: impl FnMut(&Editor, &AppContext) -> bool,
 55    ) -> impl Future<Output = ()> {
 56        self.editor.condition(self.cx, predicate)
 57    }
 58
 59    pub fn editor<F, T>(&self, read: F) -> T
 60    where
 61        F: FnOnce(&Editor, &AppContext) -> T,
 62    {
 63        self.editor.read_with(self.cx, read)
 64    }
 65
 66    pub fn update_editor<F, T>(&mut self, update: F) -> T
 67    where
 68        F: FnOnce(&mut Editor, &mut ViewContext<Editor>) -> T,
 69    {
 70        self.editor.update(self.cx, update)
 71    }
 72
 73    pub fn multibuffer<F, T>(&self, read: F) -> T
 74    where
 75        F: FnOnce(&MultiBuffer, &AppContext) -> T,
 76    {
 77        self.editor(|editor, cx| read(editor.buffer().read(cx), cx))
 78    }
 79
 80    pub fn update_multibuffer<F, T>(&mut self, update: F) -> T
 81    where
 82        F: FnOnce(&mut MultiBuffer, &mut ModelContext<MultiBuffer>) -> T,
 83    {
 84        self.update_editor(|editor, cx| editor.buffer().update(cx, update))
 85    }
 86
 87    pub fn buffer_text(&self) -> String {
 88        self.multibuffer(|buffer, cx| buffer.snapshot(cx).text())
 89    }
 90
 91    pub fn buffer<F, T>(&self, read: F) -> T
 92    where
 93        F: FnOnce(&Buffer, &AppContext) -> T,
 94    {
 95        self.multibuffer(|multibuffer, cx| {
 96            let buffer = multibuffer.as_singleton().unwrap().read(cx);
 97            read(buffer, cx)
 98        })
 99    }
100
101    pub fn update_buffer<F, T>(&mut self, update: F) -> T
102    where
103        F: FnOnce(&mut Buffer, &mut ModelContext<Buffer>) -> T,
104    {
105        self.update_multibuffer(|multibuffer, cx| {
106            let buffer = multibuffer.as_singleton().unwrap();
107            buffer.update(cx, update)
108        })
109    }
110
111    pub fn buffer_snapshot(&self) -> BufferSnapshot {
112        self.buffer(|buffer, _| buffer.snapshot())
113    }
114
115    pub fn simulate_keystroke(&mut self, keystroke_text: &str) -> ContextHandle {
116        let keystroke_under_test_handle =
117            self.add_assertion_context(format!("Simulated Keystroke: {:?}", keystroke_text));
118        let keystroke = Keystroke::parse(keystroke_text).unwrap();
119        self.cx.dispatch_keystroke(self.window_id, keystroke, false);
120        keystroke_under_test_handle
121    }
122
123    pub fn simulate_keystrokes<const COUNT: usize>(
124        &mut self,
125        keystroke_texts: [&str; COUNT],
126    ) -> ContextHandle {
127        let keystrokes_under_test_handle =
128            self.add_assertion_context(format!("Simulated Keystrokes: {:?}", keystroke_texts));
129        for keystroke_text in keystroke_texts.into_iter() {
130            self.simulate_keystroke(keystroke_text);
131        }
132        keystrokes_under_test_handle
133    }
134
135    pub fn ranges(&self, marked_text: &str) -> Vec<Range<usize>> {
136        let (unmarked_text, ranges) = marked_text_ranges(marked_text, false);
137        assert_eq!(self.buffer_text(), unmarked_text);
138        ranges
139    }
140
141    pub fn display_point(&mut self, marked_text: &str) -> DisplayPoint {
142        let ranges = self.ranges(marked_text);
143        let snapshot = self
144            .editor
145            .update(self.cx, |editor, cx| editor.snapshot(cx));
146        ranges[0].start.to_display_point(&snapshot)
147    }
148
149    // Returns anchors for the current buffer using `«` and `»`
150    pub fn text_anchor_range(&self, marked_text: &str) -> Range<language::Anchor> {
151        let ranges = self.ranges(marked_text);
152        let snapshot = self.buffer_snapshot();
153        snapshot.anchor_before(ranges[0].start)..snapshot.anchor_after(ranges[0].end)
154    }
155
156    pub fn set_diff_base(&mut self, diff_base: Option<&str>) {
157        let diff_base = diff_base.map(String::from);
158        self.update_buffer(|buffer, cx| buffer.set_diff_base(diff_base, cx));
159    }
160
161    /// Change the editor's text and selections using a string containing
162    /// embedded range markers that represent the ranges and directions of
163    /// each selection.
164    ///
165    /// Returns a context handle so that assertion failures can print what
166    /// editor state was needed to cause the failure.
167    ///
168    /// See the `util::test::marked_text_ranges` function for more information.
169    pub fn set_state(&mut self, marked_text: &str) -> ContextHandle {
170        let state_context = self.add_assertion_context(format!(
171            "Initial Editor State: \"{}\"",
172            marked_text.escape_debug().to_string()
173        ));
174        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
175        self.editor.update(self.cx, |editor, cx| {
176            editor.set_text(unmarked_text, cx);
177            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
178                s.select_ranges(selection_ranges)
179            })
180        });
181        state_context
182    }
183
184    /// Only change the editor's selections
185    pub fn set_selections_state(&mut self, marked_text: &str) -> ContextHandle {
186        let state_context = self.add_assertion_context(format!(
187            "Initial Editor State: \"{}\"",
188            marked_text.escape_debug().to_string()
189        ));
190        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
191        self.editor.update(self.cx, |editor, cx| {
192            assert_eq!(editor.text(cx), unmarked_text);
193            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
194                s.select_ranges(selection_ranges)
195            })
196        });
197        state_context
198    }
199
200    /// Make an assertion about the editor's text and the ranges and directions
201    /// of its selections using a string containing embedded range markers.
202    ///
203    /// See the `util::test::marked_text_ranges` function for more information.
204    #[track_caller]
205    pub fn assert_editor_state(&mut self, marked_text: &str) {
206        let (unmarked_text, expected_selections) = marked_text_ranges(marked_text, true);
207        let buffer_text = self.buffer_text();
208
209        if buffer_text != unmarked_text {
210            panic!("Unmarked text doesn't match buffer text\nBuffer text: {buffer_text:?}\nUnmarked text: {unmarked_text:?}\nRaw buffer text\n{buffer_text}Raw unmarked text\n{unmarked_text}");
211        }
212
213        self.assert_selections(expected_selections, marked_text.to_string())
214    }
215
216    pub fn assert_editor_background_highlights<Tag: 'static>(&mut self, marked_text: &str) {
217        let expected_ranges = self.ranges(marked_text);
218        let actual_ranges: Vec<Range<usize>> = self.update_editor(|editor, cx| {
219            let snapshot = editor.snapshot(cx);
220            editor
221                .background_highlights
222                .get(&TypeId::of::<Tag>())
223                .map(|h| h.1.clone())
224                .unwrap_or_default()
225                .into_iter()
226                .map(|range| range.to_offset(&snapshot.buffer_snapshot))
227                .collect()
228        });
229        assert_set_eq!(actual_ranges, expected_ranges);
230    }
231
232    pub fn assert_editor_text_highlights<Tag: ?Sized + 'static>(&mut self, marked_text: &str) {
233        let expected_ranges = self.ranges(marked_text);
234        let snapshot = self.update_editor(|editor, cx| editor.snapshot(cx));
235        let actual_ranges: Vec<Range<usize>> = snapshot
236            .highlight_ranges::<Tag>()
237            .map(|ranges| ranges.as_ref().clone().1)
238            .unwrap_or_default()
239            .into_iter()
240            .map(|range| range.to_offset(&snapshot.buffer_snapshot))
241            .collect();
242        assert_set_eq!(actual_ranges, expected_ranges);
243    }
244
245    pub fn assert_editor_selections(&mut self, expected_selections: Vec<Range<usize>>) {
246        let expected_marked_text =
247            generate_marked_text(&self.buffer_text(), &expected_selections, true);
248        self.assert_selections(expected_selections, expected_marked_text)
249    }
250
251    fn assert_selections(
252        &mut self,
253        expected_selections: Vec<Range<usize>>,
254        expected_marked_text: String,
255    ) {
256        let actual_selections = self
257            .editor
258            .read_with(self.cx, |editor, cx| editor.selections.all::<usize>(cx))
259            .into_iter()
260            .map(|s| {
261                if s.reversed {
262                    s.end..s.start
263                } else {
264                    s.start..s.end
265                }
266            })
267            .collect::<Vec<_>>();
268        let actual_marked_text =
269            generate_marked_text(&self.buffer_text(), &actual_selections, true);
270        if expected_selections != actual_selections {
271            panic!(
272                indoc! {"
273                    {}Editor has unexpected selections.
274
275                    Expected selections:
276                    {}
277
278                    Actual selections:
279                    {}
280                "},
281                self.assertion_context(),
282                expected_marked_text,
283                actual_marked_text,
284            );
285        }
286    }
287}
288
289impl<'a> Deref for EditorTestContext<'a> {
290    type Target = gpui::TestAppContext;
291
292    fn deref(&self) -> &Self::Target {
293        self.cx
294    }
295}
296
297impl<'a> DerefMut for EditorTestContext<'a> {
298    fn deref_mut(&mut self) -> &mut Self::Target {
299        &mut self.cx
300    }
301}