1use crate::{
2 display_map::ToDisplayPoint, AnchorRangeExt, Autoscroll, DisplayPoint, Editor, MultiBuffer,
3};
4use futures::Future;
5use gpui::{
6 keymap_matcher::Keystroke, AppContext, ContextHandle, ModelContext, ViewContext, ViewHandle,
7};
8use indoc::indoc;
9use language::{Buffer, BufferSnapshot};
10use project::{FakeFs, Project};
11use std::{
12 any::TypeId,
13 ops::{Deref, DerefMut, Range},
14};
15use util::{
16 assert_set_eq,
17 test::{generate_marked_text, marked_text_ranges},
18};
19
20use super::build_editor;
21
22pub struct EditorTestContext<'a> {
23 pub cx: &'a mut gpui::TestAppContext,
24 pub window_id: usize,
25 pub editor: ViewHandle<Editor>,
26}
27
28impl<'a> EditorTestContext<'a> {
29 pub async fn new(cx: &'a mut gpui::TestAppContext) -> EditorTestContext<'a> {
30 let fs = FakeFs::new(cx.background());
31 let project = Project::test(fs, [], cx).await;
32 let buffer = project
33 .update(cx, |project, cx| project.create_buffer("", None, cx))
34 .unwrap();
35 let (window_id, editor) = cx.update(|cx| {
36 cx.add_window(Default::default(), |cx| {
37 cx.focus_self();
38 build_editor(MultiBuffer::build_from_buffer(buffer, cx), cx)
39 })
40 });
41
42 Self {
43 cx,
44 window_id,
45 editor,
46 }
47 }
48
49 pub fn condition(
50 &self,
51 predicate: impl FnMut(&Editor, &AppContext) -> bool,
52 ) -> impl Future<Output = ()> {
53 self.editor.condition(self.cx, predicate)
54 }
55
56 pub fn editor<F, T>(&self, read: F) -> T
57 where
58 F: FnOnce(&Editor, &ViewContext<Editor>) -> T,
59 {
60 self.editor.read_with(self.cx, read)
61 }
62
63 pub fn update_editor<F, T>(&mut self, update: F) -> T
64 where
65 F: FnOnce(&mut Editor, &mut ViewContext<Editor>) -> T,
66 {
67 self.editor.update(self.cx, update)
68 }
69
70 pub fn multibuffer<F, T>(&self, read: F) -> T
71 where
72 F: FnOnce(&MultiBuffer, &AppContext) -> T,
73 {
74 self.editor(|editor, cx| read(editor.buffer().read(cx), cx))
75 }
76
77 pub fn update_multibuffer<F, T>(&mut self, update: F) -> T
78 where
79 F: FnOnce(&mut MultiBuffer, &mut ModelContext<MultiBuffer>) -> T,
80 {
81 self.update_editor(|editor, cx| editor.buffer().update(cx, update))
82 }
83
84 pub fn buffer_text(&self) -> String {
85 self.multibuffer(|buffer, cx| buffer.snapshot(cx).text())
86 }
87
88 pub fn buffer<F, T>(&self, read: F) -> T
89 where
90 F: FnOnce(&Buffer, &AppContext) -> T,
91 {
92 self.multibuffer(|multibuffer, cx| {
93 let buffer = multibuffer.as_singleton().unwrap().read(cx);
94 read(buffer, cx)
95 })
96 }
97
98 pub fn update_buffer<F, T>(&mut self, update: F) -> T
99 where
100 F: FnOnce(&mut Buffer, &mut ModelContext<Buffer>) -> T,
101 {
102 self.update_multibuffer(|multibuffer, cx| {
103 let buffer = multibuffer.as_singleton().unwrap();
104 buffer.update(cx, update)
105 })
106 }
107
108 pub fn buffer_snapshot(&self) -> BufferSnapshot {
109 self.buffer(|buffer, _| buffer.snapshot())
110 }
111
112 pub fn simulate_keystroke(&mut self, keystroke_text: &str) -> ContextHandle {
113 let keystroke_under_test_handle =
114 self.add_assertion_context(format!("Simulated Keystroke: {:?}", keystroke_text));
115 let keystroke = Keystroke::parse(keystroke_text).unwrap();
116 self.cx.dispatch_keystroke(self.window_id, keystroke, false);
117 keystroke_under_test_handle
118 }
119
120 pub fn simulate_keystrokes<const COUNT: usize>(
121 &mut self,
122 keystroke_texts: [&str; COUNT],
123 ) -> ContextHandle {
124 let keystrokes_under_test_handle =
125 self.add_assertion_context(format!("Simulated Keystrokes: {:?}", keystroke_texts));
126 for keystroke_text in keystroke_texts.into_iter() {
127 self.simulate_keystroke(keystroke_text);
128 }
129 keystrokes_under_test_handle
130 }
131
132 pub fn ranges(&self, marked_text: &str) -> Vec<Range<usize>> {
133 let (unmarked_text, ranges) = marked_text_ranges(marked_text, false);
134 assert_eq!(self.buffer_text(), unmarked_text);
135 ranges
136 }
137
138 pub fn display_point(&mut self, marked_text: &str) -> DisplayPoint {
139 let ranges = self.ranges(marked_text);
140 let snapshot = self
141 .editor
142 .update(self.cx, |editor, cx| editor.snapshot(cx));
143 ranges[0].start.to_display_point(&snapshot)
144 }
145
146 // Returns anchors for the current buffer using `«` and `»`
147 pub fn text_anchor_range(&self, marked_text: &str) -> Range<language::Anchor> {
148 let ranges = self.ranges(marked_text);
149 let snapshot = self.buffer_snapshot();
150 snapshot.anchor_before(ranges[0].start)..snapshot.anchor_after(ranges[0].end)
151 }
152
153 pub fn set_diff_base(&mut self, diff_base: Option<&str>) {
154 let diff_base = diff_base.map(String::from);
155 self.update_buffer(|buffer, cx| buffer.set_diff_base(diff_base, cx));
156 }
157
158 /// Change the editor's text and selections using a string containing
159 /// embedded range markers that represent the ranges and directions of
160 /// each selection.
161 ///
162 /// Returns a context handle so that assertion failures can print what
163 /// editor state was needed to cause the failure.
164 ///
165 /// See the `util::test::marked_text_ranges` function for more information.
166 pub fn set_state(&mut self, marked_text: &str) -> ContextHandle {
167 let state_context = self.add_assertion_context(format!(
168 "Initial Editor State: \"{}\"",
169 marked_text.escape_debug().to_string()
170 ));
171 let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
172 self.editor.update(self.cx, |editor, cx| {
173 editor.set_text(unmarked_text, cx);
174 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
175 s.select_ranges(selection_ranges)
176 })
177 });
178 state_context
179 }
180
181 /// Only change the editor's selections
182 pub fn set_selections_state(&mut self, marked_text: &str) -> ContextHandle {
183 let state_context = self.add_assertion_context(format!(
184 "Initial Editor State: \"{}\"",
185 marked_text.escape_debug().to_string()
186 ));
187 let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
188 self.editor.update(self.cx, |editor, cx| {
189 assert_eq!(editor.text(cx), unmarked_text);
190 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
191 s.select_ranges(selection_ranges)
192 })
193 });
194 state_context
195 }
196
197 /// Make an assertion about the editor's text and the ranges and directions
198 /// of its selections using a string containing embedded range markers.
199 ///
200 /// See the `util::test::marked_text_ranges` function for more information.
201 #[track_caller]
202 pub fn assert_editor_state(&mut self, marked_text: &str) {
203 let (unmarked_text, expected_selections) = marked_text_ranges(marked_text, true);
204 let buffer_text = self.buffer_text();
205
206 if buffer_text != unmarked_text {
207 panic!("Unmarked text doesn't match buffer text\nBuffer text: {buffer_text:?}\nUnmarked text: {unmarked_text:?}\nRaw buffer text\n{buffer_text}Raw unmarked text\n{unmarked_text}");
208 }
209
210 self.assert_selections(expected_selections, marked_text.to_string())
211 }
212
213 #[track_caller]
214 pub fn assert_editor_background_highlights<Tag: 'static>(&mut self, marked_text: &str) {
215 let expected_ranges = self.ranges(marked_text);
216 let actual_ranges: Vec<Range<usize>> = self.update_editor(|editor, cx| {
217 let snapshot = editor.snapshot(cx);
218 editor
219 .background_highlights
220 .get(&TypeId::of::<Tag>())
221 .map(|h| h.1.clone())
222 .unwrap_or_default()
223 .into_iter()
224 .map(|range| range.to_offset(&snapshot.buffer_snapshot))
225 .collect()
226 });
227 assert_set_eq!(actual_ranges, expected_ranges);
228 }
229
230 #[track_caller]
231 pub fn assert_editor_text_highlights<Tag: ?Sized + 'static>(&mut self, marked_text: &str) {
232 let expected_ranges = self.ranges(marked_text);
233 let snapshot = self.update_editor(|editor, cx| editor.snapshot(cx));
234 let actual_ranges: Vec<Range<usize>> = snapshot
235 .highlight_ranges::<Tag>()
236 .map(|ranges| ranges.as_ref().clone().1)
237 .unwrap_or_default()
238 .into_iter()
239 .map(|range| range.to_offset(&snapshot.buffer_snapshot))
240 .collect();
241 assert_set_eq!(actual_ranges, expected_ranges);
242 }
243
244 #[track_caller]
245 pub fn assert_editor_selections(&mut self, expected_selections: Vec<Range<usize>>) {
246 let expected_marked_text =
247 generate_marked_text(&self.buffer_text(), &expected_selections, true);
248 self.assert_selections(expected_selections, expected_marked_text)
249 }
250
251 #[track_caller]
252 fn assert_selections(
253 &mut self,
254 expected_selections: Vec<Range<usize>>,
255 expected_marked_text: String,
256 ) {
257 let actual_selections = self
258 .editor
259 .read_with(self.cx, |editor, cx| editor.selections.all::<usize>(cx))
260 .into_iter()
261 .map(|s| {
262 if s.reversed {
263 s.end..s.start
264 } else {
265 s.start..s.end
266 }
267 })
268 .collect::<Vec<_>>();
269 let actual_marked_text =
270 generate_marked_text(&self.buffer_text(), &actual_selections, true);
271 if expected_selections != actual_selections {
272 panic!(
273 indoc! {"
274 {}Editor has unexpected selections.
275
276 Expected selections:
277 {}
278
279 Actual selections:
280 {}
281 "},
282 self.assertion_context(),
283 expected_marked_text,
284 actual_marked_text,
285 );
286 }
287 }
288}
289
290impl<'a> Deref for EditorTestContext<'a> {
291 type Target = gpui::TestAppContext;
292
293 fn deref(&self) -> &Self::Target {
294 self.cx
295 }
296}
297
298impl<'a> DerefMut for EditorTestContext<'a> {
299 fn deref_mut(&mut self) -> &mut Self::Target {
300 &mut self.cx
301 }
302}