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