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    // unlike cx.simulate_keystrokes(), this does not run_until_parked
197    // so you can use it to test detailed timing
198    pub fn simulate_keystroke(&mut self, keystroke_text: &str) {
199        let keystroke = Keystroke::parse(keystroke_text).unwrap();
200        self.cx.dispatch_keystroke(self.window, keystroke);
201    }
202
203    pub fn run_until_parked(&mut self) {
204        self.cx.background_executor.run_until_parked();
205    }
206
207    pub fn ranges(&mut self, marked_text: &str) -> Vec<Range<usize>> {
208        let (unmarked_text, ranges) = marked_text_ranges(marked_text, false);
209        assert_eq!(self.buffer_text(), unmarked_text);
210        ranges
211    }
212
213    pub fn display_point(&mut self, marked_text: &str) -> DisplayPoint {
214        let ranges = self.ranges(marked_text);
215        let snapshot = self
216            .editor
217            .update(&mut self.cx, |editor, cx| editor.snapshot(cx));
218        ranges[0].start.to_display_point(&snapshot)
219    }
220
221    pub fn pixel_position(&mut self, marked_text: &str) -> Point<Pixels> {
222        let display_point = self.display_point(marked_text);
223        self.pixel_position_for(display_point)
224    }
225
226    pub fn pixel_position_for(&mut self, display_point: DisplayPoint) -> Point<Pixels> {
227        self.update_editor(|editor, cx| {
228            let newest_point = editor.selections.newest_display(cx).head();
229            let pixel_position = editor.pixel_position_of_newest_cursor.unwrap();
230            let line_height = editor
231                .style()
232                .unwrap()
233                .text
234                .line_height_in_pixels(cx.rem_size());
235            let snapshot = editor.snapshot(cx);
236            let details = editor.text_layout_details(cx);
237
238            let y = pixel_position.y
239                + line_height * (display_point.row().as_f32() - newest_point.row().as_f32());
240            let x = pixel_position.x + snapshot.x_for_display_point(display_point, &details)
241                - snapshot.x_for_display_point(newest_point, &details);
242            Point::new(x, y)
243        })
244    }
245
246    // Returns anchors for the current buffer using `«` and `»`
247    pub fn text_anchor_range(&mut self, marked_text: &str) -> Range<language::Anchor> {
248        let ranges = self.ranges(marked_text);
249        let snapshot = self.buffer_snapshot();
250        snapshot.anchor_before(ranges[0].start)..snapshot.anchor_after(ranges[0].end)
251    }
252
253    pub fn set_diff_base(&mut self, diff_base: Option<&str>) {
254        self.update_buffer(|buffer, cx| buffer.set_diff_base(diff_base.map(ToOwned::to_owned), cx));
255    }
256
257    /// Change the editor's text and selections using a string containing
258    /// embedded range markers that represent the ranges and directions of
259    /// each selection.
260    ///
261    /// Returns a context handle so that assertion failures can print what
262    /// editor state was needed to cause the failure.
263    ///
264    /// See the `util::test::marked_text_ranges` function for more information.
265    pub fn set_state(&mut self, marked_text: &str) -> ContextHandle {
266        let state_context = self.add_assertion_context(format!(
267            "Initial Editor State: \"{}\"",
268            marked_text.escape_debug()
269        ));
270        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
271        self.editor.update(&mut self.cx, |editor, cx| {
272            editor.set_text(unmarked_text, cx);
273            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
274                s.select_ranges(selection_ranges)
275            })
276        });
277        state_context
278    }
279
280    /// Only change the editor's selections
281    pub fn set_selections_state(&mut self, marked_text: &str) -> ContextHandle {
282        let state_context = self.add_assertion_context(format!(
283            "Initial Editor State: \"{}\"",
284            marked_text.escape_debug()
285        ));
286        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
287        self.editor.update(&mut self.cx, |editor, cx| {
288            assert_eq!(editor.text(cx), unmarked_text);
289            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
290                s.select_ranges(selection_ranges)
291            })
292        });
293        state_context
294    }
295
296    /// Make an assertion about the editor's text and the ranges and directions
297    /// of its selections using a string containing embedded range markers.
298    ///
299    /// See the `util::test::marked_text_ranges` function for more information.
300    #[track_caller]
301    pub fn assert_editor_state(&mut self, marked_text: &str) {
302        let (unmarked_text, expected_selections) = marked_text_ranges(marked_text, true);
303        let buffer_text = self.buffer_text();
304
305        if buffer_text != unmarked_text {
306            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}");
307        }
308
309        self.assert_selections(expected_selections, marked_text.to_string())
310    }
311
312    pub fn editor_state(&mut self) -> String {
313        generate_marked_text(self.buffer_text().as_str(), &self.editor_selections(), true)
314    }
315
316    #[track_caller]
317    pub fn assert_editor_background_highlights<Tag: 'static>(&mut self, marked_text: &str) {
318        let expected_ranges = self.ranges(marked_text);
319        let actual_ranges: Vec<Range<usize>> = self.update_editor(|editor, cx| {
320            let snapshot = editor.snapshot(cx);
321            editor
322                .background_highlights
323                .get(&TypeId::of::<Tag>())
324                .map(|h| h.1.clone())
325                .unwrap_or_else(|| Arc::from([]))
326                .into_iter()
327                .map(|range| range.to_offset(&snapshot.buffer_snapshot))
328                .collect()
329        });
330        assert_set_eq!(actual_ranges, expected_ranges);
331    }
332
333    #[track_caller]
334    pub fn assert_editor_text_highlights<Tag: ?Sized + 'static>(&mut self, marked_text: &str) {
335        let expected_ranges = self.ranges(marked_text);
336        let snapshot = self.update_editor(|editor, cx| editor.snapshot(cx));
337        let actual_ranges: Vec<Range<usize>> = snapshot
338            .text_highlight_ranges::<Tag>()
339            .map(|ranges| ranges.as_ref().clone().1)
340            .unwrap_or_default()
341            .into_iter()
342            .map(|range| range.to_offset(&snapshot.buffer_snapshot))
343            .collect();
344        assert_set_eq!(actual_ranges, expected_ranges);
345    }
346
347    #[track_caller]
348    pub fn assert_editor_selections(&mut self, expected_selections: Vec<Range<usize>>) {
349        let expected_marked_text =
350            generate_marked_text(&self.buffer_text(), &expected_selections, true);
351        self.assert_selections(expected_selections, expected_marked_text)
352    }
353
354    #[track_caller]
355    fn editor_selections(&mut self) -> Vec<Range<usize>> {
356        self.editor
357            .update(&mut self.cx, |editor, cx| {
358                editor.selections.all::<usize>(cx)
359            })
360            .into_iter()
361            .map(|s| {
362                if s.reversed {
363                    s.end..s.start
364                } else {
365                    s.start..s.end
366                }
367            })
368            .collect::<Vec<_>>()
369    }
370
371    #[track_caller]
372    fn assert_selections(
373        &mut self,
374        expected_selections: Vec<Range<usize>>,
375        expected_marked_text: String,
376    ) {
377        let actual_selections = self.editor_selections();
378        let actual_marked_text =
379            generate_marked_text(&self.buffer_text(), &actual_selections, true);
380        if expected_selections != actual_selections {
381            panic!(
382                indoc! {"
383
384                {}Editor has unexpected selections.
385
386                Expected selections:
387                {}
388
389                Actual selections:
390                {}
391            "},
392                self.assertion_context(),
393                expected_marked_text,
394                actual_marked_text,
395            );
396        }
397    }
398}
399
400impl Deref for EditorTestContext {
401    type Target = gpui::VisualTestContext;
402
403    fn deref(&self) -> &Self::Target {
404        &self.cx
405    }
406}
407
408impl DerefMut for EditorTestContext {
409    fn deref_mut(&mut self) -> &mut Self::Target {
410        &mut self.cx
411    }
412}
413
414/// Tracks string context to be printed when assertions fail.
415/// Often this is done by storing a context string in the manager and returning the handle.
416#[derive(Clone)]
417pub struct AssertionContextManager {
418    id: Arc<AtomicUsize>,
419    contexts: Arc<RwLock<BTreeMap<usize, String>>>,
420}
421
422impl AssertionContextManager {
423    pub fn new() -> Self {
424        Self {
425            id: Arc::new(AtomicUsize::new(0)),
426            contexts: Arc::new(RwLock::new(BTreeMap::new())),
427        }
428    }
429
430    pub fn add_context(&self, context: String) -> ContextHandle {
431        let id = self.id.fetch_add(1, Ordering::Relaxed);
432        let mut contexts = self.contexts.write();
433        contexts.insert(id, context);
434        ContextHandle {
435            id,
436            manager: self.clone(),
437        }
438    }
439
440    pub fn context(&self) -> String {
441        let contexts = self.contexts.read();
442        format!("\n{}\n", contexts.values().join("\n"))
443    }
444}
445
446/// Used to track the lifetime of a piece of context so that it can be provided when an assertion fails.
447/// For example, in the EditorTestContext, `set_state` returns a context handle so that if an assertion fails,
448/// the state that was set initially for the failure can be printed in the error message
449pub struct ContextHandle {
450    id: usize,
451    manager: AssertionContextManager,
452}
453
454impl Drop for ContextHandle {
455    fn drop(&mut self) {
456        let mut contexts = self.manager.contexts.write();
457        contexts.remove(&self.id);
458    }
459}