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