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