editor_test_context.rs

  1use crate::{
  2    AnchorRangeExt, DisplayPoint, Editor, ExcerptId, MultiBuffer, MultiBufferSnapshot, RowExt,
  3    display_map::{HighlightKey, ToDisplayPoint},
  4};
  5use buffer_diff::DiffHunkStatusKind;
  6use collections::BTreeMap;
  7use futures::Future;
  8
  9use gpui::{
 10    AnyWindowHandle, App, Context, Entity, Focusable as _, Keystroke, Pixels, Point,
 11    VisualTestContext, Window, WindowHandle, prelude::*,
 12};
 13use itertools::Itertools;
 14use language::{Buffer, BufferSnapshot, LanguageRegistry};
 15use multi_buffer::{Anchor, ExcerptRange, MultiBufferRow};
 16use parking_lot::RwLock;
 17use project::{FakeFs, Project};
 18use std::{
 19    any::TypeId,
 20    ops::{Deref, DerefMut, Range},
 21    path::Path,
 22    sync::{
 23        Arc,
 24        atomic::{AtomicUsize, Ordering},
 25    },
 26};
 27use text::Selection;
 28use util::{
 29    assert_set_eq,
 30    test::{generate_marked_text, marked_text_ranges},
 31};
 32
 33use super::{build_editor, build_editor_with_project};
 34
 35pub struct EditorTestContext {
 36    pub cx: gpui::VisualTestContext,
 37    pub window: AnyWindowHandle,
 38    pub editor: Entity<Editor>,
 39    pub assertion_cx: AssertionContextManager,
 40}
 41
 42impl EditorTestContext {
 43    pub async fn new(cx: &mut gpui::TestAppContext) -> EditorTestContext {
 44        let fs = FakeFs::new(cx.executor());
 45        let root = Self::root_path();
 46        fs.insert_tree(
 47            root,
 48            serde_json::json!({
 49                ".git": {},
 50                "file": "",
 51            }),
 52        )
 53        .await;
 54        let project = Project::test(fs.clone(), [root], cx).await;
 55        let buffer = project
 56            .update(cx, |project, cx| {
 57                project.open_local_buffer(root.join("file"), cx)
 58            })
 59            .await
 60            .unwrap();
 61        let editor = cx.add_window(|window, cx| {
 62            let editor = build_editor_with_project(
 63                project,
 64                MultiBuffer::build_from_buffer(buffer, cx),
 65                window,
 66                cx,
 67            );
 68
 69            window.focus(&editor.focus_handle(cx));
 70            editor
 71        });
 72        let editor_view = editor.root(cx).unwrap();
 73
 74        cx.run_until_parked();
 75        Self {
 76            cx: VisualTestContext::from_window(*editor.deref(), cx),
 77            window: editor.into(),
 78            editor: editor_view,
 79            assertion_cx: AssertionContextManager::new(),
 80        }
 81    }
 82
 83    #[cfg(target_os = "windows")]
 84    fn root_path() -> &'static Path {
 85        Path::new("C:\\root")
 86    }
 87
 88    #[cfg(not(target_os = "windows"))]
 89    fn root_path() -> &'static Path {
 90        Path::new("/root")
 91    }
 92
 93    pub async fn for_editor_in(editor: Entity<Editor>, cx: &mut gpui::VisualTestContext) -> Self {
 94        cx.focus(&editor);
 95        Self {
 96            window: cx.windows()[0],
 97            cx: cx.clone(),
 98            editor,
 99            assertion_cx: AssertionContextManager::new(),
100        }
101    }
102
103    pub async fn for_editor(editor: WindowHandle<Editor>, cx: &mut gpui::TestAppContext) -> Self {
104        let editor_view = editor.root(cx).unwrap();
105        Self {
106            cx: VisualTestContext::from_window(*editor.deref(), cx),
107            window: editor.into(),
108            editor: editor_view,
109            assertion_cx: AssertionContextManager::new(),
110        }
111    }
112
113    #[track_caller]
114    pub fn new_multibuffer<const COUNT: usize>(
115        cx: &mut gpui::TestAppContext,
116        excerpts: [&str; COUNT],
117    ) -> EditorTestContext {
118        let mut multibuffer = MultiBuffer::new(language::Capability::ReadWrite);
119        let buffer = cx.new(|cx| {
120            for excerpt in excerpts.into_iter() {
121                let (text, ranges) = marked_text_ranges(excerpt, false);
122                let buffer = cx.new(|cx| Buffer::local(text, cx));
123                multibuffer.push_excerpts(buffer, ranges.into_iter().map(ExcerptRange::new), cx);
124            }
125            multibuffer
126        });
127
128        let editor = cx.add_window(|window, cx| {
129            let editor = build_editor(buffer, window, cx);
130            window.focus(&editor.focus_handle(cx));
131
132            editor
133        });
134
135        let editor_view = editor.root(cx).unwrap();
136        Self {
137            cx: VisualTestContext::from_window(*editor.deref(), cx),
138            window: editor.into(),
139            editor: editor_view,
140            assertion_cx: AssertionContextManager::new(),
141        }
142    }
143
144    pub fn condition(
145        &self,
146        predicate: impl FnMut(&Editor, &App) -> bool,
147    ) -> impl Future<Output = ()> {
148        self.editor
149            .condition::<crate::EditorEvent>(&self.cx, predicate)
150    }
151
152    #[track_caller]
153    pub fn editor<F, T>(&mut self, read: F) -> T
154    where
155        F: FnOnce(&Editor, &Window, &mut Context<Editor>) -> T,
156    {
157        self.editor
158            .update_in(&mut self.cx, |this, window, cx| read(this, window, cx))
159    }
160
161    #[track_caller]
162    pub fn update_editor<F, T>(&mut self, update: F) -> T
163    where
164        F: FnOnce(&mut Editor, &mut Window, &mut Context<Editor>) -> T,
165    {
166        self.editor.update_in(&mut self.cx, update)
167    }
168
169    pub fn multibuffer<F, T>(&mut self, read: F) -> T
170    where
171        F: FnOnce(&MultiBuffer, &App) -> T,
172    {
173        self.editor(|editor, _, cx| read(editor.buffer().read(cx), cx))
174    }
175
176    pub fn update_multibuffer<F, T>(&mut self, update: F) -> T
177    where
178        F: FnOnce(&mut MultiBuffer, &mut Context<MultiBuffer>) -> T,
179    {
180        self.update_editor(|editor, _, cx| editor.buffer().update(cx, update))
181    }
182
183    pub fn buffer_text(&mut self) -> String {
184        self.multibuffer(|buffer, cx| buffer.snapshot(cx).text())
185    }
186
187    pub fn display_text(&mut self) -> String {
188        self.update_editor(|editor, _, cx| editor.display_text(cx))
189    }
190
191    pub fn buffer<F, T>(&mut self, read: F) -> T
192    where
193        F: FnOnce(&Buffer, &App) -> T,
194    {
195        self.multibuffer(|multibuffer, cx| {
196            let buffer = multibuffer.as_singleton().unwrap().read(cx);
197            read(buffer, cx)
198        })
199    }
200
201    pub fn language_registry(&mut self) -> Arc<LanguageRegistry> {
202        self.editor(|editor, _, cx| {
203            editor
204                .project
205                .as_ref()
206                .unwrap()
207                .read(cx)
208                .languages()
209                .clone()
210        })
211    }
212
213    pub fn update_buffer<F, T>(&mut self, update: F) -> T
214    where
215        F: FnOnce(&mut Buffer, &mut Context<Buffer>) -> T,
216    {
217        self.update_multibuffer(|multibuffer, cx| {
218            let buffer = multibuffer.as_singleton().unwrap();
219            buffer.update(cx, update)
220        })
221    }
222
223    pub fn buffer_snapshot(&mut self) -> BufferSnapshot {
224        self.buffer(|buffer, _| buffer.snapshot())
225    }
226
227    pub fn add_assertion_context(&self, context: String) -> ContextHandle {
228        self.assertion_cx.add_context(context)
229    }
230
231    pub fn assertion_context(&self) -> String {
232        self.assertion_cx.context()
233    }
234
235    // unlike cx.simulate_keystrokes(), this does not run_until_parked
236    // so you can use it to test detailed timing
237    pub fn simulate_keystroke(&mut self, keystroke_text: &str) {
238        let keystroke = Keystroke::parse(keystroke_text).unwrap();
239        self.cx.dispatch_keystroke(self.window, keystroke);
240    }
241
242    pub fn run_until_parked(&mut self) {
243        self.cx.background_executor.run_until_parked();
244    }
245
246    #[track_caller]
247    pub fn ranges(&mut self, marked_text: &str) -> Vec<Range<usize>> {
248        let (unmarked_text, ranges) = marked_text_ranges(marked_text, false);
249        assert_eq!(self.buffer_text(), unmarked_text);
250        ranges
251    }
252
253    pub fn display_point(&mut self, marked_text: &str) -> DisplayPoint {
254        let ranges = self.ranges(marked_text);
255        let snapshot = self.editor.update_in(&mut self.cx, |editor, window, cx| {
256            editor.snapshot(window, cx)
257        });
258        ranges[0].start.to_display_point(&snapshot)
259    }
260
261    pub fn pixel_position(&mut self, marked_text: &str) -> Point<Pixels> {
262        let display_point = self.display_point(marked_text);
263        self.pixel_position_for(display_point)
264    }
265
266    pub fn pixel_position_for(&mut self, display_point: DisplayPoint) -> Point<Pixels> {
267        self.update_editor(|editor, window, cx| {
268            let newest_point = editor
269                .selections
270                .newest_display(&editor.display_snapshot(cx))
271                .head();
272            let pixel_position = editor.pixel_position_of_newest_cursor.unwrap();
273            let line_height = editor
274                .style()
275                .unwrap()
276                .text
277                .line_height_in_pixels(window.rem_size());
278            let snapshot = editor.snapshot(window, cx);
279            let details = editor.text_layout_details(window);
280
281            let y = pixel_position.y
282                + f32::from(line_height)
283                    * Pixels::from(display_point.row().as_f64() - newest_point.row().as_f64());
284            let x = pixel_position.x + snapshot.x_for_display_point(display_point, &details)
285                - snapshot.x_for_display_point(newest_point, &details);
286            Point::new(x, y)
287        })
288    }
289
290    // Returns anchors for the current buffer using `«` and `»`
291    pub fn text_anchor_range(&mut self, marked_text: &str) -> Range<language::Anchor> {
292        let ranges = self.ranges(marked_text);
293        let snapshot = self.buffer_snapshot();
294        snapshot.anchor_before(ranges[0].start)..snapshot.anchor_after(ranges[0].end)
295    }
296
297    pub fn set_head_text(&mut self, diff_base: &str) {
298        self.cx.run_until_parked();
299        let fs =
300            self.update_editor(|editor, _, cx| editor.project().unwrap().read(cx).fs().as_fake());
301        let path = self.update_buffer(|buffer, _| buffer.file().unwrap().path().clone());
302        fs.set_head_for_repo(
303            &Self::root_path().join(".git"),
304            &[(path.as_unix_str(), diff_base.to_string())],
305            "deadbeef",
306        );
307        self.cx.run_until_parked();
308    }
309
310    pub fn clear_index_text(&mut self) {
311        self.cx.run_until_parked();
312        let fs =
313            self.update_editor(|editor, _, cx| editor.project().unwrap().read(cx).fs().as_fake());
314        fs.set_index_for_repo(&Self::root_path().join(".git"), &[]);
315        self.cx.run_until_parked();
316    }
317
318    pub fn set_index_text(&mut self, diff_base: &str) {
319        self.cx.run_until_parked();
320        let fs =
321            self.update_editor(|editor, _, cx| editor.project().unwrap().read(cx).fs().as_fake());
322        let path = self.update_buffer(|buffer, _| buffer.file().unwrap().path().clone());
323        fs.set_index_for_repo(
324            &Self::root_path().join(".git"),
325            &[(path.as_unix_str(), diff_base.to_string())],
326        );
327        self.cx.run_until_parked();
328    }
329
330    #[track_caller]
331    pub fn assert_index_text(&mut self, expected: Option<&str>) {
332        let fs =
333            self.update_editor(|editor, _, cx| editor.project().unwrap().read(cx).fs().as_fake());
334        let path = self.update_buffer(|buffer, _| buffer.file().unwrap().path().clone());
335        let mut found = None;
336        fs.with_git_state(&Self::root_path().join(".git"), false, |git_state| {
337            found = git_state.index_contents.get(&path.into()).cloned();
338        })
339        .unwrap();
340        assert_eq!(expected, found.as_deref());
341    }
342
343    /// Change the editor's text and selections using a string containing
344    /// embedded range markers that represent the ranges and directions of
345    /// each selection.
346    ///
347    /// Returns a context handle so that assertion failures can print what
348    /// editor state was needed to cause the failure.
349    ///
350    /// See the `util::test::marked_text_ranges` function for more information.
351    #[track_caller]
352    pub fn set_state(&mut self, marked_text: &str) -> ContextHandle {
353        let state_context = self.add_assertion_context(format!(
354            "Initial Editor State: \"{}\"",
355            marked_text.escape_debug()
356        ));
357        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
358        self.editor.update_in(&mut self.cx, |editor, window, cx| {
359            editor.set_text(unmarked_text, window, cx);
360            editor.change_selections(Default::default(), window, cx, |s| {
361                s.select_ranges(selection_ranges)
362            })
363        });
364        state_context
365    }
366
367    /// Only change the editor's selections
368    #[track_caller]
369    pub fn set_selections_state(&mut self, marked_text: &str) -> ContextHandle {
370        let state_context = self.add_assertion_context(format!(
371            "Initial Editor State: \"{}\"",
372            marked_text.escape_debug()
373        ));
374        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
375        self.editor.update_in(&mut self.cx, |editor, window, cx| {
376            assert_eq!(editor.text(cx), unmarked_text);
377            editor.change_selections(Default::default(), window, cx, |s| {
378                s.select_ranges(selection_ranges)
379            })
380        });
381        state_context
382    }
383
384    /// Assert about the text of the editor, the selections, and the expanded
385    /// diff hunks.
386    ///
387    /// Diff hunks are indicated by lines starting with `+` and `-`.
388    #[track_caller]
389    pub fn assert_state_with_diff(&mut self, expected_diff_text: String) {
390        assert_state_with_diff(&self.editor, &mut self.cx, &expected_diff_text);
391    }
392
393    #[track_caller]
394    pub fn assert_excerpts_with_selections(&mut self, marked_text: &str) {
395        let actual_text = self.to_format_multibuffer_as_marked_text();
396        let fmt_additional_notes = || {
397            struct Format<'a, T: std::fmt::Display>(&'a str, &'a T);
398
399            impl<T: std::fmt::Display> std::fmt::Display for Format<'_, T> {
400                fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
401                    write!(
402                        f,
403                        "\n\n----- EXPECTED: -----\n\n{}\n\n----- ACTUAL: -----\n\n{}\n\n",
404                        self.0, self.1
405                    )
406                }
407            }
408
409            Format(marked_text, &actual_text)
410        };
411
412        let expected_excerpts = marked_text
413            .strip_prefix("[EXCERPT]\n")
414            .unwrap()
415            .split("[EXCERPT]\n")
416            .collect::<Vec<_>>();
417
418        let (multibuffer_snapshot, selections, excerpts) = self.update_editor(|editor, _, cx| {
419            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
420
421            let selections = editor.selections.disjoint_anchors_arc();
422            let excerpts = multibuffer_snapshot
423                .excerpts()
424                .map(|(e_id, snapshot, range)| (e_id, snapshot.clone(), range))
425                .collect::<Vec<_>>();
426
427            (multibuffer_snapshot, selections, excerpts)
428        });
429
430        assert!(
431            excerpts.len() == expected_excerpts.len(),
432            "should have {} excerpts, got {}{}",
433            expected_excerpts.len(),
434            excerpts.len(),
435            fmt_additional_notes(),
436        );
437
438        for (ix, (excerpt_id, snapshot, range)) in excerpts.into_iter().enumerate() {
439            let is_folded = self
440                .update_editor(|editor, _, cx| editor.is_buffer_folded(snapshot.remote_id(), cx));
441            let (expected_text, expected_selections) =
442                marked_text_ranges(expected_excerpts[ix], true);
443            if expected_text == "[FOLDED]\n" {
444                assert!(is_folded, "excerpt {} should be folded", ix);
445                let is_selected = selections.iter().any(|s| s.head().excerpt_id == excerpt_id);
446                if !expected_selections.is_empty() {
447                    assert!(
448                        is_selected,
449                        "excerpt {ix} should contain selections. got {:?}{}",
450                        self.editor_state(),
451                        fmt_additional_notes(),
452                    );
453                } else {
454                    assert!(
455                        !is_selected,
456                        "excerpt {ix} should not contain selections, got: {selections:?}{}",
457                        fmt_additional_notes(),
458                    );
459                }
460                continue;
461            }
462            assert!(
463                !is_folded,
464                "excerpt {} should not be folded{}",
465                ix,
466                fmt_additional_notes()
467            );
468            assert_eq!(
469                multibuffer_snapshot
470                    .text_for_range(Anchor::range_in_buffer(
471                        excerpt_id,
472                        snapshot.remote_id(),
473                        range.context.clone()
474                    ))
475                    .collect::<String>(),
476                expected_text,
477                "{}",
478                fmt_additional_notes(),
479            );
480
481            let selections = selections
482                .iter()
483                .filter(|s| s.head().excerpt_id == excerpt_id)
484                .map(|s| {
485                    let head = text::ToOffset::to_offset(&s.head().text_anchor, &snapshot)
486                        - text::ToOffset::to_offset(&range.context.start, &snapshot);
487                    let tail = text::ToOffset::to_offset(&s.head().text_anchor, &snapshot)
488                        - text::ToOffset::to_offset(&range.context.start, &snapshot);
489                    tail..head
490                })
491                .collect::<Vec<_>>();
492            // todo: selections that cross excerpt boundaries..
493            assert_eq!(
494                selections,
495                expected_selections,
496                "excerpt {} has incorrect selections{}",
497                ix,
498                fmt_additional_notes()
499            );
500        }
501    }
502
503    fn to_format_multibuffer_as_marked_text(&mut self) -> FormatMultiBufferAsMarkedText {
504        let (multibuffer_snapshot, selections, excerpts) = self.update_editor(|editor, _, cx| {
505            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
506
507            let selections = editor.selections.disjoint_anchors_arc().to_vec();
508            let excerpts = multibuffer_snapshot
509                .excerpts()
510                .map(|(e_id, snapshot, range)| {
511                    let is_folded = editor.is_buffer_folded(snapshot.remote_id(), cx);
512                    (e_id, snapshot.clone(), range, is_folded)
513                })
514                .collect::<Vec<_>>();
515
516            (multibuffer_snapshot, selections, excerpts)
517        });
518
519        FormatMultiBufferAsMarkedText {
520            multibuffer_snapshot,
521            selections,
522            excerpts,
523        }
524    }
525
526    /// Make an assertion about the editor's text and the ranges and directions
527    /// of its selections using a string containing embedded range markers.
528    ///
529    /// See the `util::test::marked_text_ranges` function for more information.
530    #[track_caller]
531    pub fn assert_editor_state(&mut self, marked_text: &str) {
532        let (expected_text, expected_selections) = marked_text_ranges(marked_text, true);
533        pretty_assertions::assert_eq!(self.buffer_text(), expected_text, "unexpected buffer text");
534        self.assert_selections(expected_selections, marked_text.to_string())
535    }
536
537    /// Make an assertion about the editor's text and the ranges and directions
538    /// of its selections using a string containing embedded range markers.
539    ///
540    /// See the `util::test::marked_text_ranges` function for more information.
541    #[track_caller]
542    pub fn assert_display_state(&mut self, marked_text: &str) {
543        let (expected_text, expected_selections) = marked_text_ranges(marked_text, true);
544        pretty_assertions::assert_eq!(self.display_text(), expected_text, "unexpected buffer text");
545        self.assert_selections(expected_selections, marked_text.to_string())
546    }
547
548    pub fn editor_state(&mut self) -> String {
549        generate_marked_text(self.buffer_text().as_str(), &self.editor_selections(), true)
550    }
551
552    #[track_caller]
553    pub fn assert_editor_background_highlights<Tag: 'static>(&mut self, marked_text: &str) {
554        let expected_ranges = self.ranges(marked_text);
555        let actual_ranges: Vec<Range<usize>> = self.update_editor(|editor, window, cx| {
556            let snapshot = editor.snapshot(window, cx);
557            editor
558                .background_highlights
559                .get(&HighlightKey::Type(TypeId::of::<Tag>()))
560                .map(|h| h.1.clone())
561                .unwrap_or_default()
562                .iter()
563                .map(|range| range.to_offset(&snapshot.buffer_snapshot()))
564                .collect()
565        });
566        assert_set_eq!(actual_ranges, expected_ranges);
567    }
568
569    #[track_caller]
570    pub fn assert_editor_text_highlights<Tag: ?Sized + 'static>(&mut self, marked_text: &str) {
571        let expected_ranges = self.ranges(marked_text);
572        let snapshot = self.update_editor(|editor, window, cx| editor.snapshot(window, cx));
573        let actual_ranges: Vec<Range<usize>> = snapshot
574            .text_highlight_ranges::<Tag>()
575            .map(|ranges| ranges.as_ref().clone().1)
576            .unwrap_or_default()
577            .into_iter()
578            .map(|range| range.to_offset(&snapshot.buffer_snapshot()))
579            .collect();
580        assert_set_eq!(actual_ranges, expected_ranges);
581    }
582
583    #[track_caller]
584    pub fn assert_editor_selections(&mut self, expected_selections: Vec<Range<usize>>) {
585        let expected_marked_text =
586            generate_marked_text(&self.buffer_text(), &expected_selections, true)
587                .replace(" \n", "\n");
588
589        self.assert_selections(expected_selections, expected_marked_text)
590    }
591
592    #[track_caller]
593    fn editor_selections(&mut self) -> Vec<Range<usize>> {
594        self.editor
595            .update(&mut self.cx, |editor, cx| {
596                editor.selections.all::<usize>(&editor.display_snapshot(cx))
597            })
598            .into_iter()
599            .map(|s| {
600                if s.reversed {
601                    s.end..s.start
602                } else {
603                    s.start..s.end
604                }
605            })
606            .collect::<Vec<_>>()
607    }
608
609    #[track_caller]
610    fn assert_selections(
611        &mut self,
612        expected_selections: Vec<Range<usize>>,
613        expected_marked_text: String,
614    ) {
615        let actual_selections = self.editor_selections();
616        let actual_marked_text =
617            generate_marked_text(&self.buffer_text(), &actual_selections, true)
618                .replace(" \n", "\n");
619        if expected_selections != actual_selections {
620            pretty_assertions::assert_eq!(
621                actual_marked_text,
622                expected_marked_text,
623                "{}Editor has unexpected selections",
624                self.assertion_context(),
625            );
626        }
627    }
628}
629
630struct FormatMultiBufferAsMarkedText {
631    multibuffer_snapshot: MultiBufferSnapshot,
632    selections: Vec<Selection<Anchor>>,
633    excerpts: Vec<(ExcerptId, BufferSnapshot, ExcerptRange<text::Anchor>, bool)>,
634}
635
636impl std::fmt::Display for FormatMultiBufferAsMarkedText {
637    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
638        let Self {
639            multibuffer_snapshot,
640            selections,
641            excerpts,
642        } = self;
643
644        for (excerpt_id, snapshot, range, is_folded) in excerpts.into_iter() {
645            write!(f, "[EXCERPT]\n")?;
646            if *is_folded {
647                write!(f, "[FOLDED]\n")?;
648            }
649
650            let mut text = multibuffer_snapshot
651                .text_for_range(Anchor::range_in_buffer(
652                    *excerpt_id,
653                    snapshot.remote_id(),
654                    range.context.clone(),
655                ))
656                .collect::<String>();
657
658            let selections = selections
659                .iter()
660                .filter(|&s| s.head().excerpt_id == *excerpt_id)
661                .map(|s| {
662                    let head = text::ToOffset::to_offset(&s.head().text_anchor, &snapshot)
663                        - text::ToOffset::to_offset(&range.context.start, &snapshot);
664                    let tail = text::ToOffset::to_offset(&s.head().text_anchor, &snapshot)
665                        - text::ToOffset::to_offset(&range.context.start, &snapshot);
666                    tail..head
667                })
668                .rev()
669                .collect::<Vec<_>>();
670
671            for selection in selections {
672                if selection.is_empty() {
673                    text.insert(selection.start, 'ˇ');
674                    continue;
675                }
676                text.insert(selection.end, '»');
677                text.insert(selection.start, '«');
678            }
679
680            write!(f, "{text}")?;
681        }
682
683        Ok(())
684    }
685}
686
687#[track_caller]
688pub fn assert_state_with_diff(
689    editor: &Entity<Editor>,
690    cx: &mut VisualTestContext,
691    expected_diff_text: &str,
692) {
693    let (snapshot, selections) = editor.update_in(cx, |editor, window, cx| {
694        let snapshot = editor.snapshot(window, cx);
695        (
696            snapshot.buffer_snapshot().clone(),
697            editor
698                .selections
699                .ranges::<usize>(&snapshot.display_snapshot),
700        )
701    });
702
703    let actual_marked_text = generate_marked_text(&snapshot.text(), &selections, true);
704
705    // Read the actual diff.
706    let line_infos = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
707    let has_diff = line_infos.iter().any(|info| info.diff_status.is_some());
708    let actual_diff = actual_marked_text
709        .split('\n')
710        .zip(line_infos)
711        .map(|(line, info)| {
712            let mut marker = match info.diff_status.map(|status| status.kind) {
713                Some(DiffHunkStatusKind::Added) => "+ ",
714                Some(DiffHunkStatusKind::Deleted) => "- ",
715                Some(DiffHunkStatusKind::Modified) => unreachable!(),
716                None => {
717                    if has_diff {
718                        "  "
719                    } else {
720                        ""
721                    }
722                }
723            };
724            if line.is_empty() {
725                marker = marker.trim();
726            }
727            format!("{marker}{line}")
728        })
729        .collect::<Vec<_>>()
730        .join("\n");
731
732    pretty_assertions::assert_eq!(actual_diff, expected_diff_text, "unexpected diff state");
733}
734
735impl Deref for EditorTestContext {
736    type Target = gpui::VisualTestContext;
737
738    fn deref(&self) -> &Self::Target {
739        &self.cx
740    }
741}
742
743impl DerefMut for EditorTestContext {
744    fn deref_mut(&mut self) -> &mut Self::Target {
745        &mut self.cx
746    }
747}
748
749/// Tracks string context to be printed when assertions fail.
750/// Often this is done by storing a context string in the manager and returning the handle.
751#[derive(Clone)]
752pub struct AssertionContextManager {
753    id: Arc<AtomicUsize>,
754    contexts: Arc<RwLock<BTreeMap<usize, String>>>,
755}
756
757impl Default for AssertionContextManager {
758    fn default() -> Self {
759        Self::new()
760    }
761}
762
763impl AssertionContextManager {
764    pub fn new() -> Self {
765        Self {
766            id: Arc::new(AtomicUsize::new(0)),
767            contexts: Arc::new(RwLock::new(BTreeMap::new())),
768        }
769    }
770
771    pub fn add_context(&self, context: String) -> ContextHandle {
772        let id = self.id.fetch_add(1, Ordering::Relaxed);
773        let mut contexts = self.contexts.write();
774        contexts.insert(id, context);
775        ContextHandle {
776            id,
777            manager: self.clone(),
778        }
779    }
780
781    pub fn context(&self) -> String {
782        let contexts = self.contexts.read();
783        format!("\n{}\n", contexts.values().join("\n"))
784    }
785}
786
787/// Used to track the lifetime of a piece of context so that it can be provided when an assertion fails.
788/// For example, in the EditorTestContext, `set_state` returns a context handle so that if an assertion fails,
789/// the state that was set initially for the failure can be printed in the error message
790pub struct ContextHandle {
791    id: usize,
792    manager: AssertionContextManager,
793}
794
795impl Drop for ContextHandle {
796    fn drop(&mut self) {
797        let mut contexts = self.manager.contexts.write();
798        contexts.remove(&self.id);
799    }
800}