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, MultiBufferOffset, 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 MultiBufferOffset(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(
377 selection_ranges
378 .into_iter()
379 .map(|range| MultiBufferOffset(range.start)..MultiBufferOffset(range.end)),
380 )
381 })
382 });
383 state_context
384 }
385
386 /// Only change the editor's selections
387 #[track_caller]
388 pub fn set_selections_state(&mut self, marked_text: &str) -> ContextHandle {
389 let state_context = self.add_assertion_context(format!(
390 "Initial Editor State: \"{}\"",
391 marked_text.escape_debug()
392 ));
393 let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
394 self.editor.update_in(&mut self.cx, |editor, window, cx| {
395 assert_eq!(editor.text(cx), unmarked_text);
396 editor.change_selections(Default::default(), window, cx, |s| {
397 s.select_ranges(
398 selection_ranges
399 .into_iter()
400 .map(|range| MultiBufferOffset(range.start)..MultiBufferOffset(range.end)),
401 )
402 })
403 });
404 state_context
405 }
406
407 /// Assert about the text of the editor, the selections, and the expanded
408 /// diff hunks.
409 ///
410 /// Diff hunks are indicated by lines starting with `+` and `-`.
411 #[track_caller]
412 pub fn assert_state_with_diff(&mut self, expected_diff_text: String) {
413 assert_state_with_diff(&self.editor, &mut self.cx, &expected_diff_text);
414 }
415
416 #[track_caller]
417 pub fn assert_excerpts_with_selections(&mut self, marked_text: &str) {
418 let actual_text = self.to_format_multibuffer_as_marked_text();
419 let fmt_additional_notes = || {
420 struct Format<'a, T: std::fmt::Display>(&'a str, &'a T);
421
422 impl<T: std::fmt::Display> std::fmt::Display for Format<'_, T> {
423 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
424 write!(
425 f,
426 "\n\n----- EXPECTED: -----\n\n{}\n\n----- ACTUAL: -----\n\n{}\n\n",
427 self.0, self.1
428 )
429 }
430 }
431
432 Format(marked_text, &actual_text)
433 };
434
435 let expected_excerpts = marked_text
436 .strip_prefix("[EXCERPT]\n")
437 .unwrap()
438 .split("[EXCERPT]\n")
439 .collect::<Vec<_>>();
440
441 let (multibuffer_snapshot, selections, excerpts) = self.update_editor(|editor, _, cx| {
442 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
443
444 let selections = editor.selections.disjoint_anchors_arc();
445 let excerpts = multibuffer_snapshot
446 .excerpts()
447 .map(|(e_id, snapshot, range)| (e_id, snapshot.clone(), range))
448 .collect::<Vec<_>>();
449
450 (multibuffer_snapshot, selections, excerpts)
451 });
452
453 assert!(
454 excerpts.len() == expected_excerpts.len(),
455 "should have {} excerpts, got {}{}",
456 expected_excerpts.len(),
457 excerpts.len(),
458 fmt_additional_notes(),
459 );
460
461 for (ix, (excerpt_id, snapshot, range)) in excerpts.into_iter().enumerate() {
462 let is_folded = self
463 .update_editor(|editor, _, cx| editor.is_buffer_folded(snapshot.remote_id(), cx));
464 let (expected_text, expected_selections) =
465 marked_text_ranges(expected_excerpts[ix], true);
466 if expected_text == "[FOLDED]\n" {
467 assert!(is_folded, "excerpt {} should be folded", ix);
468 let is_selected = selections.iter().any(|s| s.head().excerpt_id == excerpt_id);
469 if !expected_selections.is_empty() {
470 assert!(
471 is_selected,
472 "excerpt {ix} should contain selections. got {:?}{}",
473 self.editor_state(),
474 fmt_additional_notes(),
475 );
476 } else {
477 assert!(
478 !is_selected,
479 "excerpt {ix} should not contain selections, got: {selections:?}{}",
480 fmt_additional_notes(),
481 );
482 }
483 continue;
484 }
485 assert!(
486 !is_folded,
487 "excerpt {} should not be folded{}",
488 ix,
489 fmt_additional_notes()
490 );
491 assert_eq!(
492 multibuffer_snapshot
493 .text_for_range(Anchor::range_in_buffer(excerpt_id, range.context.clone()))
494 .collect::<String>(),
495 expected_text,
496 "{}",
497 fmt_additional_notes(),
498 );
499
500 let selections = selections
501 .iter()
502 .filter(|s| s.head().excerpt_id == excerpt_id)
503 .map(|s| {
504 let head = text::ToOffset::to_offset(&s.head().text_anchor, &snapshot)
505 - text::ToOffset::to_offset(&range.context.start, &snapshot);
506 let tail = text::ToOffset::to_offset(&s.head().text_anchor, &snapshot)
507 - text::ToOffset::to_offset(&range.context.start, &snapshot);
508 tail..head
509 })
510 .collect::<Vec<_>>();
511 // todo: selections that cross excerpt boundaries..
512 assert_eq!(
513 selections,
514 expected_selections,
515 "excerpt {} has incorrect selections{}",
516 ix,
517 fmt_additional_notes()
518 );
519 }
520 }
521
522 fn to_format_multibuffer_as_marked_text(&mut self) -> FormatMultiBufferAsMarkedText {
523 let (multibuffer_snapshot, selections, excerpts) = self.update_editor(|editor, _, cx| {
524 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
525
526 let selections = editor.selections.disjoint_anchors_arc().to_vec();
527 let excerpts = multibuffer_snapshot
528 .excerpts()
529 .map(|(e_id, snapshot, range)| {
530 let is_folded = editor.is_buffer_folded(snapshot.remote_id(), cx);
531 (e_id, snapshot.clone(), range, is_folded)
532 })
533 .collect::<Vec<_>>();
534
535 (multibuffer_snapshot, selections, excerpts)
536 });
537
538 FormatMultiBufferAsMarkedText {
539 multibuffer_snapshot,
540 selections,
541 excerpts,
542 }
543 }
544
545 /// Make an assertion about the editor's text and the ranges and directions
546 /// of its selections using a string containing embedded range markers.
547 ///
548 /// See the `util::test::marked_text_ranges` function for more information.
549 #[track_caller]
550 pub fn assert_editor_state(&mut self, marked_text: &str) {
551 let (expected_text, expected_selections) = marked_text_ranges(marked_text, true);
552 pretty_assertions::assert_eq!(self.buffer_text(), expected_text, "unexpected buffer text");
553 self.assert_selections(expected_selections, marked_text.to_string())
554 }
555
556 /// Make an assertion about the editor's text and the ranges and directions
557 /// of its selections using a string containing embedded range markers.
558 ///
559 /// See the `util::test::marked_text_ranges` function for more information.
560 #[track_caller]
561 pub fn assert_display_state(&mut self, marked_text: &str) {
562 let (expected_text, expected_selections) = marked_text_ranges(marked_text, true);
563 pretty_assertions::assert_eq!(self.display_text(), expected_text, "unexpected buffer text");
564 self.assert_selections(expected_selections, marked_text.to_string())
565 }
566
567 pub fn editor_state(&mut self) -> String {
568 generate_marked_text(self.buffer_text().as_str(), &self.editor_selections(), true)
569 }
570
571 #[track_caller]
572 pub fn assert_editor_background_highlights<Tag: 'static>(&mut self, marked_text: &str) {
573 let expected_ranges = self.ranges(marked_text);
574 let actual_ranges: Vec<Range<usize>> = self.update_editor(|editor, window, cx| {
575 let snapshot = editor.snapshot(window, cx);
576 editor
577 .background_highlights
578 .get(&HighlightKey::Type(TypeId::of::<Tag>()))
579 .map(|h| h.1.clone())
580 .unwrap_or_default()
581 .iter()
582 .map(|range| range.to_offset(&snapshot.buffer_snapshot()))
583 .map(|range| range.start.0..range.end.0)
584 .collect()
585 });
586 assert_set_eq!(actual_ranges, expected_ranges);
587 }
588
589 #[track_caller]
590 pub fn assert_editor_text_highlights<Tag: ?Sized + 'static>(&mut self, marked_text: &str) {
591 let expected_ranges = self.ranges(marked_text);
592 let snapshot = self.update_editor(|editor, window, cx| editor.snapshot(window, cx));
593 let actual_ranges: Vec<Range<usize>> = snapshot
594 .text_highlight_ranges::<Tag>()
595 .map(|ranges| ranges.as_ref().clone().1)
596 .unwrap_or_default()
597 .into_iter()
598 .map(|range| range.to_offset(&snapshot.buffer_snapshot()))
599 .map(|range| range.start.0..range.end.0)
600 .collect();
601 assert_set_eq!(actual_ranges, expected_ranges);
602 }
603
604 #[track_caller]
605 pub fn assert_editor_selections(&mut self, expected_selections: Vec<Range<usize>>) {
606 let expected_marked_text =
607 generate_marked_text(&self.buffer_text(), &expected_selections, true)
608 .replace(" \n", "•\n");
609
610 self.assert_selections(expected_selections, expected_marked_text)
611 }
612
613 #[track_caller]
614 fn editor_selections(&mut self) -> Vec<Range<usize>> {
615 self.editor
616 .update(&mut self.cx, |editor, cx| {
617 editor
618 .selections
619 .all::<MultiBufferOffset>(&editor.display_snapshot(cx))
620 })
621 .into_iter()
622 .map(|s| {
623 if s.reversed {
624 s.end.0..s.start.0
625 } else {
626 s.start.0..s.end.0
627 }
628 })
629 .collect::<Vec<_>>()
630 }
631
632 #[track_caller]
633 fn assert_selections(
634 &mut self,
635 expected_selections: Vec<Range<usize>>,
636 expected_marked_text: String,
637 ) {
638 let actual_selections = self.editor_selections();
639 let actual_marked_text =
640 generate_marked_text(&self.buffer_text(), &actual_selections, true)
641 .replace(" \n", "•\n");
642 if expected_selections != actual_selections {
643 pretty_assertions::assert_eq!(
644 actual_marked_text,
645 expected_marked_text,
646 "{}Editor has unexpected selections",
647 self.assertion_context(),
648 );
649 }
650 }
651}
652
653struct FormatMultiBufferAsMarkedText {
654 multibuffer_snapshot: MultiBufferSnapshot,
655 selections: Vec<Selection<Anchor>>,
656 excerpts: Vec<(ExcerptId, BufferSnapshot, ExcerptRange<text::Anchor>, bool)>,
657}
658
659impl std::fmt::Display for FormatMultiBufferAsMarkedText {
660 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
661 let Self {
662 multibuffer_snapshot,
663 selections,
664 excerpts,
665 } = self;
666
667 for (excerpt_id, snapshot, range, is_folded) in excerpts.into_iter() {
668 write!(f, "[EXCERPT]\n")?;
669 if *is_folded {
670 write!(f, "[FOLDED]\n")?;
671 }
672
673 let mut text = multibuffer_snapshot
674 .text_for_range(Anchor::range_in_buffer(*excerpt_id, range.context.clone()))
675 .collect::<String>();
676
677 let selections = selections
678 .iter()
679 .filter(|&s| s.head().excerpt_id == *excerpt_id)
680 .map(|s| {
681 let head = text::ToOffset::to_offset(&s.head().text_anchor, &snapshot)
682 - text::ToOffset::to_offset(&range.context.start, &snapshot);
683 let tail = text::ToOffset::to_offset(&s.head().text_anchor, &snapshot)
684 - text::ToOffset::to_offset(&range.context.start, &snapshot);
685 tail..head
686 })
687 .rev()
688 .collect::<Vec<_>>();
689
690 for selection in selections {
691 if selection.is_empty() {
692 text.insert(selection.start, 'ˇ');
693 continue;
694 }
695 text.insert(selection.end, '»');
696 text.insert(selection.start, '«');
697 }
698
699 write!(f, "{text}")?;
700 }
701
702 Ok(())
703 }
704}
705
706#[track_caller]
707pub fn assert_state_with_diff(
708 editor: &Entity<Editor>,
709 cx: &mut VisualTestContext,
710 expected_diff_text: &str,
711) {
712 let (snapshot, selections) = editor.update_in(cx, |editor, window, cx| {
713 let snapshot = editor.snapshot(window, cx);
714 (
715 snapshot.buffer_snapshot().clone(),
716 editor
717 .selections
718 .ranges::<MultiBufferOffset>(&snapshot.display_snapshot)
719 .into_iter()
720 .map(|range| range.start.0..range.end.0)
721 .collect::<Vec<_>>(),
722 )
723 });
724
725 let actual_marked_text = generate_marked_text(&snapshot.text(), &selections, true);
726
727 // Read the actual diff.
728 let line_infos = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
729 let has_diff = line_infos.iter().any(|info| info.diff_status.is_some());
730 let actual_diff = actual_marked_text
731 .split('\n')
732 .zip(line_infos)
733 .map(|(line, info)| {
734 let mut marker = match info.diff_status.map(|status| status.kind) {
735 Some(DiffHunkStatusKind::Added) => "+ ",
736 Some(DiffHunkStatusKind::Deleted) => "- ",
737 Some(DiffHunkStatusKind::Modified) => unreachable!(),
738 None => {
739 if has_diff {
740 " "
741 } else {
742 ""
743 }
744 }
745 };
746 if line.is_empty() {
747 marker = marker.trim();
748 }
749 format!("{marker}{line}")
750 })
751 .collect::<Vec<_>>()
752 .join("\n");
753
754 pretty_assertions::assert_eq!(actual_diff, expected_diff_text, "unexpected diff state");
755}
756
757impl Deref for EditorTestContext {
758 type Target = gpui::VisualTestContext;
759
760 fn deref(&self) -> &Self::Target {
761 &self.cx
762 }
763}
764
765impl DerefMut for EditorTestContext {
766 fn deref_mut(&mut self) -> &mut Self::Target {
767 &mut self.cx
768 }
769}
770
771/// Tracks string context to be printed when assertions fail.
772/// Often this is done by storing a context string in the manager and returning the handle.
773#[derive(Clone)]
774pub struct AssertionContextManager {
775 id: Arc<AtomicUsize>,
776 contexts: Arc<RwLock<BTreeMap<usize, String>>>,
777}
778
779impl Default for AssertionContextManager {
780 fn default() -> Self {
781 Self::new()
782 }
783}
784
785impl AssertionContextManager {
786 pub fn new() -> Self {
787 Self {
788 id: Arc::new(AtomicUsize::new(0)),
789 contexts: Arc::new(RwLock::new(BTreeMap::new())),
790 }
791 }
792
793 pub fn add_context(&self, context: String) -> ContextHandle {
794 let id = self.id.fetch_add(1, Ordering::Relaxed);
795 let mut contexts = self.contexts.write();
796 contexts.insert(id, context);
797 ContextHandle {
798 id,
799 manager: self.clone(),
800 }
801 }
802
803 pub fn context(&self) -> String {
804 let contexts = self.contexts.read();
805 format!("\n{}\n", contexts.values().join("\n"))
806 }
807}
808
809/// Used to track the lifetime of a piece of context so that it can be provided when an assertion fails.
810/// For example, in the EditorTestContext, `set_state` returns a context handle so that if an assertion fails,
811/// the state that was set initially for the failure can be printed in the error message
812pub struct ContextHandle {
813 id: usize,
814 manager: AssertionContextManager,
815}
816
817impl Drop for ContextHandle {
818 fn drop(&mut self) {
819 let mut contexts = self.manager.contexts.write();
820 contexts.remove(&self.id);
821 }
822}