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 git::diff::DiffHunkStatus;
  8use gpui::{
  9    prelude::*, AnyWindowHandle, AppContext, Keystroke, ModelContext, Pixels, Point, View,
 10    ViewContext, VisualTestContext, WindowHandle,
 11};
 12use itertools::Itertools;
 13use language::{Buffer, BufferSnapshot, LanguageRegistry};
 14use multi_buffer::{ExcerptRange, MultiBufferRow};
 15use parking_lot::RwLock;
 16use project::{FakeFs, Project};
 17use std::{
 18    any::TypeId,
 19    ops::{Deref, DerefMut, Range},
 20    path::Path,
 21    sync::{
 22        atomic::{AtomicUsize, Ordering},
 23        Arc,
 24    },
 25};
 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        let root = Self::root_path();
 44        fs.insert_tree(
 45            root,
 46            serde_json::json!({
 47                ".git": {},
 48                "file": "",
 49            }),
 50        )
 51        .await;
 52        let project = Project::test(fs.clone(), [root], cx).await;
 53        let buffer = project
 54            .update(cx, |project, cx| {
 55                project.open_local_buffer(root.join("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
 67        cx.run_until_parked();
 68        Self {
 69            cx: VisualTestContext::from_window(*editor.deref(), cx),
 70            window: editor.into(),
 71            editor: editor_view,
 72            assertion_cx: AssertionContextManager::new(),
 73        }
 74    }
 75
 76    #[cfg(target_os = "windows")]
 77    fn root_path() -> &'static Path {
 78        Path::new("C:\\root")
 79    }
 80
 81    #[cfg(not(target_os = "windows"))]
 82    fn root_path() -> &'static Path {
 83        Path::new("/root")
 84    }
 85
 86    pub async fn for_editor(editor: WindowHandle<Editor>, cx: &mut gpui::TestAppContext) -> Self {
 87        let editor_view = editor.root_view(cx).unwrap();
 88        Self {
 89            cx: VisualTestContext::from_window(*editor.deref(), cx),
 90            window: editor.into(),
 91            editor: editor_view,
 92            assertion_cx: AssertionContextManager::new(),
 93        }
 94    }
 95
 96    pub fn new_multibuffer<const COUNT: usize>(
 97        cx: &mut gpui::TestAppContext,
 98        excerpts: [&str; COUNT],
 99    ) -> EditorTestContext {
100        let mut multibuffer = MultiBuffer::new(language::Capability::ReadWrite);
101        let buffer = cx.new_model(|cx| {
102            for excerpt in excerpts.into_iter() {
103                let (text, ranges) = marked_text_ranges(excerpt, false);
104                let buffer = cx.new_model(|cx| Buffer::local(text, cx));
105                multibuffer.push_excerpts(
106                    buffer,
107                    ranges.into_iter().map(|range| ExcerptRange {
108                        context: range,
109                        primary: None,
110                    }),
111                    cx,
112                );
113            }
114            multibuffer
115        });
116
117        let editor = cx.add_window(|cx| {
118            let editor = build_editor(buffer, cx);
119            editor.focus(cx);
120            editor
121        });
122
123        let editor_view = editor.root_view(cx).unwrap();
124        Self {
125            cx: VisualTestContext::from_window(*editor.deref(), cx),
126            window: editor.into(),
127            editor: editor_view,
128            assertion_cx: AssertionContextManager::new(),
129        }
130    }
131
132    pub fn condition(
133        &self,
134        predicate: impl FnMut(&Editor, &AppContext) -> bool,
135    ) -> impl Future<Output = ()> {
136        self.editor
137            .condition::<crate::EditorEvent>(&self.cx, predicate)
138    }
139
140    #[track_caller]
141    pub fn editor<F, T>(&mut self, read: F) -> T
142    where
143        F: FnOnce(&Editor, &ViewContext<Editor>) -> T,
144    {
145        self.editor.update(&mut self.cx, |this, cx| read(this, cx))
146    }
147
148    #[track_caller]
149    pub fn update_editor<F, T>(&mut self, update: F) -> T
150    where
151        F: FnOnce(&mut Editor, &mut ViewContext<Editor>) -> T,
152    {
153        self.editor.update(&mut self.cx, update)
154    }
155
156    pub fn multibuffer<F, T>(&mut self, read: F) -> T
157    where
158        F: FnOnce(&MultiBuffer, &AppContext) -> T,
159    {
160        self.editor(|editor, cx| read(editor.buffer().read(cx), cx))
161    }
162
163    pub fn update_multibuffer<F, T>(&mut self, update: F) -> T
164    where
165        F: FnOnce(&mut MultiBuffer, &mut ModelContext<MultiBuffer>) -> T,
166    {
167        self.update_editor(|editor, cx| editor.buffer().update(cx, update))
168    }
169
170    pub fn buffer_text(&mut self) -> String {
171        self.multibuffer(|buffer, cx| buffer.snapshot(cx).text())
172    }
173
174    pub fn display_text(&mut self) -> String {
175        self.update_editor(|editor, cx| editor.display_text(cx))
176    }
177
178    pub fn buffer<F, T>(&mut self, read: F) -> T
179    where
180        F: FnOnce(&Buffer, &AppContext) -> T,
181    {
182        self.multibuffer(|multibuffer, cx| {
183            let buffer = multibuffer.as_singleton().unwrap().read(cx);
184            read(buffer, cx)
185        })
186    }
187
188    pub fn language_registry(&mut self) -> Arc<LanguageRegistry> {
189        self.editor(|editor, cx| {
190            editor
191                .project
192                .as_ref()
193                .unwrap()
194                .read(cx)
195                .languages()
196                .clone()
197        })
198    }
199
200    pub fn update_buffer<F, T>(&mut self, update: F) -> T
201    where
202        F: FnOnce(&mut Buffer, &mut ModelContext<Buffer>) -> T,
203    {
204        self.update_multibuffer(|multibuffer, cx| {
205            let buffer = multibuffer.as_singleton().unwrap();
206            buffer.update(cx, update)
207        })
208    }
209
210    pub fn buffer_snapshot(&mut self) -> BufferSnapshot {
211        self.buffer(|buffer, _| buffer.snapshot())
212    }
213
214    pub fn add_assertion_context(&self, context: String) -> ContextHandle {
215        self.assertion_cx.add_context(context)
216    }
217
218    pub fn assertion_context(&self) -> String {
219        self.assertion_cx.context()
220    }
221
222    // unlike cx.simulate_keystrokes(), this does not run_until_parked
223    // so you can use it to test detailed timing
224    pub fn simulate_keystroke(&mut self, keystroke_text: &str) {
225        let keystroke = Keystroke::parse(keystroke_text).unwrap();
226        self.cx.dispatch_keystroke(self.window, keystroke);
227    }
228
229    pub fn run_until_parked(&mut self) {
230        self.cx.background_executor.run_until_parked();
231    }
232
233    #[track_caller]
234    pub fn ranges(&mut self, marked_text: &str) -> Vec<Range<usize>> {
235        let (unmarked_text, ranges) = marked_text_ranges(marked_text, false);
236        assert_eq!(self.buffer_text(), unmarked_text);
237        ranges
238    }
239
240    pub fn display_point(&mut self, marked_text: &str) -> DisplayPoint {
241        let ranges = self.ranges(marked_text);
242        let snapshot = self
243            .editor
244            .update(&mut self.cx, |editor, cx| editor.snapshot(cx));
245        ranges[0].start.to_display_point(&snapshot)
246    }
247
248    pub fn pixel_position(&mut self, marked_text: &str) -> Point<Pixels> {
249        let display_point = self.display_point(marked_text);
250        self.pixel_position_for(display_point)
251    }
252
253    pub fn pixel_position_for(&mut self, display_point: DisplayPoint) -> Point<Pixels> {
254        self.update_editor(|editor, cx| {
255            let newest_point = editor.selections.newest_display(cx).head();
256            let pixel_position = editor.pixel_position_of_newest_cursor.unwrap();
257            let line_height = editor
258                .style()
259                .unwrap()
260                .text
261                .line_height_in_pixels(cx.rem_size());
262            let snapshot = editor.snapshot(cx);
263            let details = editor.text_layout_details(cx);
264
265            let y = pixel_position.y
266                + line_height * (display_point.row().as_f32() - newest_point.row().as_f32());
267            let x = pixel_position.x + snapshot.x_for_display_point(display_point, &details)
268                - snapshot.x_for_display_point(newest_point, &details);
269            Point::new(x, y)
270        })
271    }
272
273    // Returns anchors for the current buffer using `«` and `»`
274    pub fn text_anchor_range(&mut self, marked_text: &str) -> Range<language::Anchor> {
275        let ranges = self.ranges(marked_text);
276        let snapshot = self.buffer_snapshot();
277        snapshot.anchor_before(ranges[0].start)..snapshot.anchor_after(ranges[0].end)
278    }
279
280    pub fn set_diff_base(&mut self, diff_base: &str) {
281        self.cx.run_until_parked();
282        let fs = self
283            .update_editor(|editor, cx| editor.project.as_ref().unwrap().read(cx).fs().as_fake());
284        let path = self.update_buffer(|buffer, _| buffer.file().unwrap().path().clone());
285        fs.set_index_for_repo(
286            &Self::root_path().join(".git"),
287            &[(path.as_ref(), diff_base.to_string())],
288        );
289        self.cx.run_until_parked();
290    }
291
292    /// Change the editor's text and selections using a string containing
293    /// embedded range markers that represent the ranges and directions of
294    /// each selection.
295    ///
296    /// Returns a context handle so that assertion failures can print what
297    /// editor state was needed to cause the failure.
298    ///
299    /// See the `util::test::marked_text_ranges` function for more information.
300    pub fn set_state(&mut self, marked_text: &str) -> ContextHandle {
301        let state_context = self.add_assertion_context(format!(
302            "Initial Editor State: \"{}\"",
303            marked_text.escape_debug()
304        ));
305        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
306        self.editor.update(&mut self.cx, |editor, cx| {
307            editor.set_text(unmarked_text, cx);
308            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
309                s.select_ranges(selection_ranges)
310            })
311        });
312        state_context
313    }
314
315    /// Only change the editor's selections
316    pub fn set_selections_state(&mut self, marked_text: &str) -> ContextHandle {
317        let state_context = self.add_assertion_context(format!(
318            "Initial Editor State: \"{}\"",
319            marked_text.escape_debug()
320        ));
321        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
322        self.editor.update(&mut self.cx, |editor, cx| {
323            assert_eq!(editor.text(cx), unmarked_text);
324            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
325                s.select_ranges(selection_ranges)
326            })
327        });
328        state_context
329    }
330
331    /// Assert about the text of the editor, the selections, and the expanded
332    /// diff hunks.
333    ///
334    /// Diff hunks are indicated by lines starting with `+` and `-`.
335    #[track_caller]
336    pub fn assert_state_with_diff(&mut self, expected_diff_text: String) {
337        assert_state_with_diff(&self.editor, &mut self.cx, &expected_diff_text);
338    }
339
340    /// Make an assertion about the editor's text and the ranges and directions
341    /// of its selections using a string containing embedded range markers.
342    ///
343    /// See the `util::test::marked_text_ranges` function for more information.
344    #[track_caller]
345    pub fn assert_editor_state(&mut self, marked_text: &str) {
346        let (expected_text, expected_selections) = marked_text_ranges(marked_text, true);
347        pretty_assertions::assert_eq!(self.buffer_text(), expected_text, "unexpected buffer text");
348        self.assert_selections(expected_selections, marked_text.to_string())
349    }
350
351    pub fn editor_state(&mut self) -> String {
352        generate_marked_text(self.buffer_text().as_str(), &self.editor_selections(), true)
353    }
354
355    #[track_caller]
356    pub fn assert_editor_background_highlights<Tag: 'static>(&mut self, marked_text: &str) {
357        let expected_ranges = self.ranges(marked_text);
358        let actual_ranges: Vec<Range<usize>> = self.update_editor(|editor, cx| {
359            let snapshot = editor.snapshot(cx);
360            editor
361                .background_highlights
362                .get(&TypeId::of::<Tag>())
363                .map(|h| h.1.clone())
364                .unwrap_or_default()
365                .iter()
366                .map(|range| range.to_offset(&snapshot.buffer_snapshot))
367                .collect()
368        });
369        assert_set_eq!(actual_ranges, expected_ranges);
370    }
371
372    #[track_caller]
373    pub fn assert_editor_text_highlights<Tag: ?Sized + 'static>(&mut self, marked_text: &str) {
374        let expected_ranges = self.ranges(marked_text);
375        let snapshot = self.update_editor(|editor, cx| editor.snapshot(cx));
376        let actual_ranges: Vec<Range<usize>> = snapshot
377            .text_highlight_ranges::<Tag>()
378            .map(|ranges| ranges.as_ref().clone().1)
379            .unwrap_or_default()
380            .into_iter()
381            .map(|range| range.to_offset(&snapshot.buffer_snapshot))
382            .collect();
383        assert_set_eq!(actual_ranges, expected_ranges);
384    }
385
386    #[track_caller]
387    pub fn assert_editor_selections(&mut self, expected_selections: Vec<Range<usize>>) {
388        let expected_marked_text =
389            generate_marked_text(&self.buffer_text(), &expected_selections, true);
390        self.assert_selections(expected_selections, expected_marked_text)
391    }
392
393    #[track_caller]
394    fn editor_selections(&mut self) -> Vec<Range<usize>> {
395        self.editor
396            .update(&mut self.cx, |editor, cx| {
397                editor.selections.all::<usize>(cx)
398            })
399            .into_iter()
400            .map(|s| {
401                if s.reversed {
402                    s.end..s.start
403                } else {
404                    s.start..s.end
405                }
406            })
407            .collect::<Vec<_>>()
408    }
409
410    #[track_caller]
411    fn assert_selections(
412        &mut self,
413        expected_selections: Vec<Range<usize>>,
414        expected_marked_text: String,
415    ) {
416        let actual_selections = self.editor_selections();
417        let actual_marked_text =
418            generate_marked_text(&self.buffer_text(), &actual_selections, true);
419        if expected_selections != actual_selections {
420            pretty_assertions::assert_eq!(
421                actual_marked_text,
422                expected_marked_text,
423                "{}Editor has unexpected selections",
424                self.assertion_context(),
425            );
426        }
427    }
428}
429
430#[track_caller]
431pub fn assert_state_with_diff(
432    editor: &View<Editor>,
433    cx: &mut VisualTestContext,
434    expected_diff_text: &str,
435) {
436    let (snapshot, selections) = editor.update(cx, |editor, cx| {
437        (
438            editor.snapshot(cx).buffer_snapshot.clone(),
439            editor.selections.ranges::<usize>(cx),
440        )
441    });
442
443    let actual_marked_text = generate_marked_text(&snapshot.text(), &selections, true);
444
445    // Read the actual diff.
446    let line_infos = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
447    let has_diff = line_infos.iter().any(|info| info.diff_status.is_some());
448    let actual_diff = actual_marked_text
449        .split('\n')
450        .zip(line_infos)
451        .map(|(line, info)| {
452            let mut marker = match info.diff_status {
453                Some(DiffHunkStatus::Added) => "+ ",
454                Some(DiffHunkStatus::Removed) => "- ",
455                Some(DiffHunkStatus::Modified) => unreachable!(),
456                None => {
457                    if has_diff {
458                        "  "
459                    } else {
460                        ""
461                    }
462                }
463            };
464            if line.is_empty() {
465                marker = marker.trim();
466            }
467            format!("{marker}{line}")
468        })
469        .collect::<Vec<_>>()
470        .join("\n");
471
472    pretty_assertions::assert_eq!(actual_diff, expected_diff_text, "unexpected diff state");
473}
474
475impl Deref for EditorTestContext {
476    type Target = gpui::VisualTestContext;
477
478    fn deref(&self) -> &Self::Target {
479        &self.cx
480    }
481}
482
483impl DerefMut for EditorTestContext {
484    fn deref_mut(&mut self) -> &mut Self::Target {
485        &mut self.cx
486    }
487}
488
489/// Tracks string context to be printed when assertions fail.
490/// Often this is done by storing a context string in the manager and returning the handle.
491#[derive(Clone)]
492pub struct AssertionContextManager {
493    id: Arc<AtomicUsize>,
494    contexts: Arc<RwLock<BTreeMap<usize, String>>>,
495}
496
497impl Default for AssertionContextManager {
498    fn default() -> Self {
499        Self::new()
500    }
501}
502
503impl AssertionContextManager {
504    pub fn new() -> Self {
505        Self {
506            id: Arc::new(AtomicUsize::new(0)),
507            contexts: Arc::new(RwLock::new(BTreeMap::new())),
508        }
509    }
510
511    pub fn add_context(&self, context: String) -> ContextHandle {
512        let id = self.id.fetch_add(1, Ordering::Relaxed);
513        let mut contexts = self.contexts.write();
514        contexts.insert(id, context);
515        ContextHandle {
516            id,
517            manager: self.clone(),
518        }
519    }
520
521    pub fn context(&self) -> String {
522        let contexts = self.contexts.read();
523        format!("\n{}\n", contexts.values().join("\n"))
524    }
525}
526
527/// Used to track the lifetime of a piece of context so that it can be provided when an assertion fails.
528/// For example, in the EditorTestContext, `set_state` returns a context handle so that if an assertion fails,
529/// the state that was set initially for the failure can be printed in the error message
530pub struct ContextHandle {
531    id: usize,
532    manager: AssertionContextManager,
533}
534
535impl Drop for ContextHandle {
536    fn drop(&mut self) {
537        let mut contexts = self.manager.contexts.write();
538        contexts.remove(&self.id);
539    }
540}