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