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.selections.newest_display(cx).head();
269 let pixel_position = editor.pixel_position_of_newest_cursor.unwrap();
270 let line_height = editor
271 .style()
272 .unwrap()
273 .text
274 .line_height_in_pixels(window.rem_size());
275 let snapshot = editor.snapshot(window, cx);
276 let details = editor.text_layout_details(window);
277
278 let y = pixel_position.y
279 + f32::from(line_height)
280 * Pixels::from(display_point.row().as_f64() - newest_point.row().as_f64());
281 let x = pixel_position.x + snapshot.x_for_display_point(display_point, &details)
282 - snapshot.x_for_display_point(newest_point, &details);
283 Point::new(x, y)
284 })
285 }
286
287 // Returns anchors for the current buffer using `«` and `»`
288 pub fn text_anchor_range(&mut self, marked_text: &str) -> Range<language::Anchor> {
289 let ranges = self.ranges(marked_text);
290 let snapshot = self.buffer_snapshot();
291 snapshot.anchor_before(ranges[0].start)..snapshot.anchor_after(ranges[0].end)
292 }
293
294 pub fn set_head_text(&mut self, diff_base: &str) {
295 self.cx.run_until_parked();
296 let fs =
297 self.update_editor(|editor, _, cx| editor.project().unwrap().read(cx).fs().as_fake());
298 let path = self.update_buffer(|buffer, _| buffer.file().unwrap().path().clone());
299 fs.set_head_for_repo(
300 &Self::root_path().join(".git"),
301 &[(path.as_unix_str(), diff_base.to_string())],
302 "deadbeef",
303 );
304 self.cx.run_until_parked();
305 }
306
307 pub fn clear_index_text(&mut self) {
308 self.cx.run_until_parked();
309 let fs =
310 self.update_editor(|editor, _, cx| editor.project().unwrap().read(cx).fs().as_fake());
311 fs.set_index_for_repo(&Self::root_path().join(".git"), &[]);
312 self.cx.run_until_parked();
313 }
314
315 pub fn set_index_text(&mut self, diff_base: &str) {
316 self.cx.run_until_parked();
317 let fs =
318 self.update_editor(|editor, _, cx| editor.project().unwrap().read(cx).fs().as_fake());
319 let path = self.update_buffer(|buffer, _| buffer.file().unwrap().path().clone());
320 fs.set_index_for_repo(
321 &Self::root_path().join(".git"),
322 &[(path.as_unix_str(), diff_base.to_string())],
323 );
324 self.cx.run_until_parked();
325 }
326
327 #[track_caller]
328 pub fn assert_index_text(&mut self, expected: Option<&str>) {
329 let fs =
330 self.update_editor(|editor, _, cx| editor.project().unwrap().read(cx).fs().as_fake());
331 let path = self.update_buffer(|buffer, _| buffer.file().unwrap().path().clone());
332 let mut found = None;
333 fs.with_git_state(&Self::root_path().join(".git"), false, |git_state| {
334 found = git_state.index_contents.get(&path.into()).cloned();
335 })
336 .unwrap();
337 assert_eq!(expected, found.as_deref());
338 }
339
340 /// Change the editor's text and selections using a string containing
341 /// embedded range markers that represent the ranges and directions of
342 /// each selection.
343 ///
344 /// Returns a context handle so that assertion failures can print what
345 /// editor state was needed to cause the failure.
346 ///
347 /// See the `util::test::marked_text_ranges` function for more information.
348 #[track_caller]
349 pub fn set_state(&mut self, marked_text: &str) -> ContextHandle {
350 let state_context = self.add_assertion_context(format!(
351 "Initial Editor State: \"{}\"",
352 marked_text.escape_debug()
353 ));
354 let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
355 self.editor.update_in(&mut self.cx, |editor, window, cx| {
356 editor.set_text(unmarked_text, window, cx);
357 editor.change_selections(Default::default(), window, cx, |s| {
358 s.select_ranges(selection_ranges)
359 })
360 });
361 state_context
362 }
363
364 /// Only change the editor's selections
365 #[track_caller]
366 pub fn set_selections_state(&mut self, marked_text: &str) -> ContextHandle {
367 let state_context = self.add_assertion_context(format!(
368 "Initial Editor State: \"{}\"",
369 marked_text.escape_debug()
370 ));
371 let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
372 self.editor.update_in(&mut self.cx, |editor, window, cx| {
373 assert_eq!(editor.text(cx), unmarked_text);
374 editor.change_selections(Default::default(), window, cx, |s| {
375 s.select_ranges(selection_ranges)
376 })
377 });
378 state_context
379 }
380
381 /// Assert about the text of the editor, the selections, and the expanded
382 /// diff hunks.
383 ///
384 /// Diff hunks are indicated by lines starting with `+` and `-`.
385 #[track_caller]
386 pub fn assert_state_with_diff(&mut self, expected_diff_text: String) {
387 assert_state_with_diff(&self.editor, &mut self.cx, &expected_diff_text);
388 }
389
390 #[track_caller]
391 pub fn assert_excerpts_with_selections(&mut self, marked_text: &str) {
392 let actual_text = self.to_format_multibuffer_as_marked_text();
393 let fmt_additional_notes = || {
394 struct Format<'a, T: std::fmt::Display>(&'a str, &'a T);
395
396 impl<T: std::fmt::Display> std::fmt::Display for Format<'_, T> {
397 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
398 write!(
399 f,
400 "\n\n----- EXPECTED: -----\n\n{}\n\n----- ACTUAL: -----\n\n{}\n\n",
401 self.0, self.1
402 )
403 }
404 }
405
406 Format(marked_text, &actual_text)
407 };
408
409 let expected_excerpts = marked_text
410 .strip_prefix("[EXCERPT]\n")
411 .unwrap()
412 .split("[EXCERPT]\n")
413 .collect::<Vec<_>>();
414
415 let (multibuffer_snapshot, selections, excerpts) = self.update_editor(|editor, _, cx| {
416 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
417
418 let selections = editor.selections.disjoint_anchors_arc();
419 let excerpts = multibuffer_snapshot
420 .excerpts()
421 .map(|(e_id, snapshot, range)| (e_id, snapshot.clone(), range))
422 .collect::<Vec<_>>();
423
424 (multibuffer_snapshot, selections, excerpts)
425 });
426
427 assert!(
428 excerpts.len() == expected_excerpts.len(),
429 "should have {} excerpts, got {}{}",
430 expected_excerpts.len(),
431 excerpts.len(),
432 fmt_additional_notes(),
433 );
434
435 for (ix, (excerpt_id, snapshot, range)) in excerpts.into_iter().enumerate() {
436 let is_folded = self
437 .update_editor(|editor, _, cx| editor.is_buffer_folded(snapshot.remote_id(), cx));
438 let (expected_text, expected_selections) =
439 marked_text_ranges(expected_excerpts[ix], true);
440 if expected_text == "[FOLDED]\n" {
441 assert!(is_folded, "excerpt {} should be folded", ix);
442 let is_selected = selections.iter().any(|s| s.head().excerpt_id == excerpt_id);
443 if !expected_selections.is_empty() {
444 assert!(
445 is_selected,
446 "excerpt {ix} should contain selections. got {:?}{}",
447 self.editor_state(),
448 fmt_additional_notes(),
449 );
450 } else {
451 assert!(
452 !is_selected,
453 "excerpt {ix} should not contain selections, got: {selections:?}{}",
454 fmt_additional_notes(),
455 );
456 }
457 continue;
458 }
459 assert!(
460 !is_folded,
461 "excerpt {} should not be folded{}",
462 ix,
463 fmt_additional_notes()
464 );
465 assert_eq!(
466 multibuffer_snapshot
467 .text_for_range(Anchor::range_in_buffer(
468 excerpt_id,
469 snapshot.remote_id(),
470 range.context.clone()
471 ))
472 .collect::<String>(),
473 expected_text,
474 "{}",
475 fmt_additional_notes(),
476 );
477
478 let selections = selections
479 .iter()
480 .filter(|s| s.head().excerpt_id == excerpt_id)
481 .map(|s| {
482 let head = text::ToOffset::to_offset(&s.head().text_anchor, &snapshot)
483 - text::ToOffset::to_offset(&range.context.start, &snapshot);
484 let tail = text::ToOffset::to_offset(&s.head().text_anchor, &snapshot)
485 - text::ToOffset::to_offset(&range.context.start, &snapshot);
486 tail..head
487 })
488 .collect::<Vec<_>>();
489 // todo: selections that cross excerpt boundaries..
490 assert_eq!(
491 selections,
492 expected_selections,
493 "excerpt {} has incorrect selections{}",
494 ix,
495 fmt_additional_notes()
496 );
497 }
498 }
499
500 fn to_format_multibuffer_as_marked_text(&mut self) -> FormatMultiBufferAsMarkedText {
501 let (multibuffer_snapshot, selections, excerpts) = self.update_editor(|editor, _, cx| {
502 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
503
504 let selections = editor.selections.disjoint_anchors_arc().to_vec();
505 let excerpts = multibuffer_snapshot
506 .excerpts()
507 .map(|(e_id, snapshot, range)| {
508 let is_folded = editor.is_buffer_folded(snapshot.remote_id(), cx);
509 (e_id, snapshot.clone(), range, is_folded)
510 })
511 .collect::<Vec<_>>();
512
513 (multibuffer_snapshot, selections, excerpts)
514 });
515
516 FormatMultiBufferAsMarkedText {
517 multibuffer_snapshot,
518 selections,
519 excerpts,
520 }
521 }
522
523 /// Make an assertion about the editor's text and the ranges and directions
524 /// of its selections using a string containing embedded range markers.
525 ///
526 /// See the `util::test::marked_text_ranges` function for more information.
527 #[track_caller]
528 pub fn assert_editor_state(&mut self, marked_text: &str) {
529 let (expected_text, expected_selections) = marked_text_ranges(marked_text, true);
530 pretty_assertions::assert_eq!(self.buffer_text(), expected_text, "unexpected buffer text");
531 self.assert_selections(expected_selections, marked_text.to_string())
532 }
533
534 /// Make an assertion about the editor's text and the ranges and directions
535 /// of its selections using a string containing embedded range markers.
536 ///
537 /// See the `util::test::marked_text_ranges` function for more information.
538 #[track_caller]
539 pub fn assert_display_state(&mut self, marked_text: &str) {
540 let (expected_text, expected_selections) = marked_text_ranges(marked_text, true);
541 pretty_assertions::assert_eq!(self.display_text(), expected_text, "unexpected buffer text");
542 self.assert_selections(expected_selections, marked_text.to_string())
543 }
544
545 pub fn editor_state(&mut self) -> String {
546 generate_marked_text(self.buffer_text().as_str(), &self.editor_selections(), true)
547 }
548
549 #[track_caller]
550 pub fn assert_editor_background_highlights<Tag: 'static>(&mut self, marked_text: &str) {
551 let expected_ranges = self.ranges(marked_text);
552 let actual_ranges: Vec<Range<usize>> = self.update_editor(|editor, window, cx| {
553 let snapshot = editor.snapshot(window, cx);
554 editor
555 .background_highlights
556 .get(&HighlightKey::Type(TypeId::of::<Tag>()))
557 .map(|h| h.1.clone())
558 .unwrap_or_default()
559 .iter()
560 .map(|range| range.to_offset(&snapshot.buffer_snapshot()))
561 .collect()
562 });
563 assert_set_eq!(actual_ranges, expected_ranges);
564 }
565
566 #[track_caller]
567 pub fn assert_editor_text_highlights<Tag: ?Sized + 'static>(&mut self, marked_text: &str) {
568 let expected_ranges = self.ranges(marked_text);
569 let snapshot = self.update_editor(|editor, window, cx| editor.snapshot(window, cx));
570 let actual_ranges: Vec<Range<usize>> = snapshot
571 .text_highlight_ranges::<Tag>()
572 .map(|ranges| ranges.as_ref().clone().1)
573 .unwrap_or_default()
574 .into_iter()
575 .map(|range| range.to_offset(&snapshot.buffer_snapshot()))
576 .collect();
577 assert_set_eq!(actual_ranges, expected_ranges);
578 }
579
580 #[track_caller]
581 pub fn assert_editor_selections(&mut self, expected_selections: Vec<Range<usize>>) {
582 let expected_marked_text =
583 generate_marked_text(&self.buffer_text(), &expected_selections, true)
584 .replace(" \n", "•\n");
585
586 self.assert_selections(expected_selections, expected_marked_text)
587 }
588
589 #[track_caller]
590 fn editor_selections(&mut self) -> Vec<Range<usize>> {
591 self.editor
592 .update(&mut self.cx, |editor, cx| {
593 editor.selections.all::<usize>(cx)
594 })
595 .into_iter()
596 .map(|s| {
597 if s.reversed {
598 s.end..s.start
599 } else {
600 s.start..s.end
601 }
602 })
603 .collect::<Vec<_>>()
604 }
605
606 #[track_caller]
607 fn assert_selections(
608 &mut self,
609 expected_selections: Vec<Range<usize>>,
610 expected_marked_text: String,
611 ) {
612 let actual_selections = self.editor_selections();
613 let actual_marked_text =
614 generate_marked_text(&self.buffer_text(), &actual_selections, true)
615 .replace(" \n", "•\n");
616 if expected_selections != actual_selections {
617 pretty_assertions::assert_eq!(
618 actual_marked_text,
619 expected_marked_text,
620 "{}Editor has unexpected selections",
621 self.assertion_context(),
622 );
623 }
624 }
625}
626
627struct FormatMultiBufferAsMarkedText {
628 multibuffer_snapshot: MultiBufferSnapshot,
629 selections: Vec<Selection<Anchor>>,
630 excerpts: Vec<(ExcerptId, BufferSnapshot, ExcerptRange<text::Anchor>, bool)>,
631}
632
633impl std::fmt::Display for FormatMultiBufferAsMarkedText {
634 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
635 let Self {
636 multibuffer_snapshot,
637 selections,
638 excerpts,
639 } = self;
640
641 for (excerpt_id, snapshot, range, is_folded) in excerpts.into_iter() {
642 write!(f, "[EXCERPT]\n")?;
643 if *is_folded {
644 write!(f, "[FOLDED]\n")?;
645 }
646
647 let mut text = multibuffer_snapshot
648 .text_for_range(Anchor::range_in_buffer(
649 *excerpt_id,
650 snapshot.remote_id(),
651 range.context.clone(),
652 ))
653 .collect::<String>();
654
655 let selections = selections
656 .iter()
657 .filter(|&s| s.head().excerpt_id == *excerpt_id)
658 .map(|s| {
659 let head = text::ToOffset::to_offset(&s.head().text_anchor, &snapshot)
660 - text::ToOffset::to_offset(&range.context.start, &snapshot);
661 let tail = text::ToOffset::to_offset(&s.head().text_anchor, &snapshot)
662 - text::ToOffset::to_offset(&range.context.start, &snapshot);
663 tail..head
664 })
665 .rev()
666 .collect::<Vec<_>>();
667
668 for selection in selections {
669 if selection.is_empty() {
670 text.insert(selection.start, 'ˇ');
671 continue;
672 }
673 text.insert(selection.end, '»');
674 text.insert(selection.start, '«');
675 }
676
677 write!(f, "{text}")?;
678 }
679
680 Ok(())
681 }
682}
683
684#[track_caller]
685pub fn assert_state_with_diff(
686 editor: &Entity<Editor>,
687 cx: &mut VisualTestContext,
688 expected_diff_text: &str,
689) {
690 let (snapshot, selections) = editor.update_in(cx, |editor, window, cx| {
691 (
692 editor.snapshot(window, cx).buffer_snapshot().clone(),
693 editor.selections.ranges::<usize>(cx),
694 )
695 });
696
697 let actual_marked_text = generate_marked_text(&snapshot.text(), &selections, true);
698
699 // Read the actual diff.
700 let line_infos = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
701 let has_diff = line_infos.iter().any(|info| info.diff_status.is_some());
702 let actual_diff = actual_marked_text
703 .split('\n')
704 .zip(line_infos)
705 .map(|(line, info)| {
706 let mut marker = match info.diff_status.map(|status| status.kind) {
707 Some(DiffHunkStatusKind::Added) => "+ ",
708 Some(DiffHunkStatusKind::Deleted) => "- ",
709 Some(DiffHunkStatusKind::Modified) => unreachable!(),
710 None => {
711 if has_diff {
712 " "
713 } else {
714 ""
715 }
716 }
717 };
718 if line.is_empty() {
719 marker = marker.trim();
720 }
721 format!("{marker}{line}")
722 })
723 .collect::<Vec<_>>()
724 .join("\n");
725
726 pretty_assertions::assert_eq!(actual_diff, expected_diff_text, "unexpected diff state");
727}
728
729impl Deref for EditorTestContext {
730 type Target = gpui::VisualTestContext;
731
732 fn deref(&self) -> &Self::Target {
733 &self.cx
734 }
735}
736
737impl DerefMut for EditorTestContext {
738 fn deref_mut(&mut self) -> &mut Self::Target {
739 &mut self.cx
740 }
741}
742
743/// Tracks string context to be printed when assertions fail.
744/// Often this is done by storing a context string in the manager and returning the handle.
745#[derive(Clone)]
746pub struct AssertionContextManager {
747 id: Arc<AtomicUsize>,
748 contexts: Arc<RwLock<BTreeMap<usize, String>>>,
749}
750
751impl Default for AssertionContextManager {
752 fn default() -> Self {
753 Self::new()
754 }
755}
756
757impl AssertionContextManager {
758 pub fn new() -> Self {
759 Self {
760 id: Arc::new(AtomicUsize::new(0)),
761 contexts: Arc::new(RwLock::new(BTreeMap::new())),
762 }
763 }
764
765 pub fn add_context(&self, context: String) -> ContextHandle {
766 let id = self.id.fetch_add(1, Ordering::Relaxed);
767 let mut contexts = self.contexts.write();
768 contexts.insert(id, context);
769 ContextHandle {
770 id,
771 manager: self.clone(),
772 }
773 }
774
775 pub fn context(&self) -> String {
776 let contexts = self.contexts.read();
777 format!("\n{}\n", contexts.values().join("\n"))
778 }
779}
780
781/// Used to track the lifetime of a piece of context so that it can be provided when an assertion fails.
782/// For example, in the EditorTestContext, `set_state` returns a context handle so that if an assertion fails,
783/// the state that was set initially for the failure can be printed in the error message
784pub struct ContextHandle {
785 id: usize,
786 manager: AssertionContextManager,
787}
788
789impl Drop for ContextHandle {
790 fn drop(&mut self) {
791 let mut contexts = self.manager.contexts.write();
792 contexts.remove(&self.id);
793 }
794}