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