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