Debian Codegraph @

helix-term/tests/test/helpers.rs

raw symbols SCIP
1 use std::{
2 io::{Read, Write},
3 mem::replace,
4 path::PathBuf,
5 time::Duration,
6 };
7
8 use anyhow::bail;
9 use helix_core::{diagnostic::Severity, test, Selection, Transaction};
10 use helix_loader::workspace_trust::WorkspaceTrust;
11 use helix_term::{application::Application, args::Args, config::Config, keymap::merge_keys};
12 use helix_view::{
13 current_ref, doc,
14 editor::{ImplicitTrustLevelConfig, LspConfig, WordCompletion, WorkspaceTrustConfig},
15 input::parse_macro,
16 Editor,
17 };
18 use tempfile::NamedTempFile;
19 use tokio_stream::wrappers::UnboundedReceiverStream;
20
21 #[cfg(windows)]
22 use crossterm::event::{Event, KeyEvent};
23 #[cfg(not(windows))]
24 use termina::event::{Event, KeyEvent};
25
26 /// Specify how to set up the input text with line feeds
27 #[derive(Clone, Debug)]
28 pub enum LineFeedHandling {
29 /// Replaces all LF chars with the system's appropriate line feed character,
30 /// and if one doesn't exist already, appends the system's appropriate line
31 /// ending to the end of a string.
32 Native,
33
34 /// Do not modify the input text in any way. What you give is what you test.
35 AsIs,
36 }
37
38 impl LineFeedHandling {
39 /// Apply the line feed handling to the input string, yielding a set of
40 /// resulting texts with the appropriate line feed substitutions.
41 pub fn apply(&self, text: &str) -> String {
42 let line_end = match self {
43 LineFeedHandling::Native => helix_core::NATIVE_LINE_ENDING,
44 LineFeedHandling::AsIs => return text.into(),
45 }
46 .as_str();
47
48 // we can assume that the source files in this code base will always
49 // be LF, so indoc strings will always insert LF
50 let mut output = text.replace('\n', line_end);
51
52 if !output.ends_with(line_end) {
53 output.push_str(line_end);
54 }
55
56 output
57 }
58 }
59
60 impl Default for LineFeedHandling {
61 fn default() -> Self {
62 Self::Native
63 }
64 }
65
66 #[derive(Clone, Debug)]
67 pub struct TestCase {
68 pub in_text: String,
69 pub in_selection: Selection,
70 pub in_keys: String,
71 pub out_text: String,
72 pub out_selection: Selection,
73
74 pub line_feed_handling: LineFeedHandling,
75 }
76
77 impl<S, R, V> From<(S, R, V)> for TestCase
78 where
79 S: Into<String>,
80 R: Into<String>,
81 V: Into<String>,
82 {
83 fn from((input, keys, output): (S, R, V)) -> Self {
84 TestCase::from((input, keys, output, LineFeedHandling::default()))
85 }
86 }
87
88 impl<S, R, V> From<(S, R, V, LineFeedHandling)> for TestCase
89 where
90 S: Into<String>,
91 R: Into<String>,
92 V: Into<String>,
93 {
94 fn from((input, keys, output, line_feed_handling): (S, R, V, LineFeedHandling)) -> Self {
95 let (in_text, in_selection) = test::print(&line_feed_handling.apply(&input.into()));
96 let (out_text, out_selection) = test::print(&line_feed_handling.apply(&output.into()));
97
98 TestCase {
99 in_text,
100 in_selection,
101 in_keys: keys.into(),
102 out_text,
103 out_selection,
104 line_feed_handling,
105 }
106 }
107 }
108
109 #[inline]
110 pub async fn test_key_sequence(
111 app: &mut Application,
112 in_keys: Option<&str>,
113 test_fn: Option<&dyn Fn(&Application)>,
114 should_exit: bool,
115 ) -> anyhow::Result<()> {
116 test_key_sequences(app, vec![(in_keys, test_fn)], should_exit).await
117 }
118
119 #[allow(clippy::type_complexity)]
120 pub async fn test_key_sequences(
121 app: &mut Application,
122 inputs: Vec<(Option<&str>, Option<&dyn Fn(&Application)>)>,
123 should_exit: bool,
124 ) -> anyhow::Result<()> {
125 const TIMEOUT: Duration = Duration::from_millis(500);
126 let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
127 let mut rx_stream = UnboundedReceiverStream::new(rx);
128 let num_inputs = inputs.len();
129
130 for (i, (in_keys, test_fn)) in inputs.into_iter().enumerate() {
131 let (view, doc) = current_ref!(app.editor);
132 let state = test::plain(doc.text().slice(..), doc.selection(view.id));
133
134 log::debug!("executing test with document state:\n\n-----\n\n{}", state);
135
136 if let Some(in_keys) = in_keys {
137 for key_event in parse_macro(in_keys)?.into_iter() {
138 let key = Event::Key(KeyEvent::from(key_event));
139 log::trace!("sending key: {:?}", key);
140 tx.send(Ok(key))?;
141 }
142 }
143
144 let app_exited = !app.event_loop_until_idle(&mut rx_stream).await;
145
146 if !app_exited {
147 let (view, doc) = current_ref!(app.editor);
148 let state = test::plain(doc.text().slice(..), doc.selection(view.id));
149
150 log::debug!(
151 "finished running test with document state:\n\n-----\n\n{}",
152 state
153 );
154 }
155
156 // the app should not exit from any test until the last one
157 if i < num_inputs - 1 && app_exited {
158 bail!("application exited before test function could run");
159 }
160
161 // verify if it exited on the last iteration if it should have and
162 // the inverse
163 if i == num_inputs - 1 && app_exited != should_exit {
164 bail!("expected app to exit: {} != {}", should_exit, app_exited);
165 }
166
167 if let Some(test) = test_fn {
168 test(app);
169 };
170 }
171
172 if !should_exit {
173 for key_event in parse_macro("<esc>:q!<ret>")?.into_iter() {
174 tx.send(Ok(Event::Key(KeyEvent::from(key_event))))?;
175 }
176
177 let event_loop = app.event_loop(&mut rx_stream);
178 tokio::time::timeout(TIMEOUT, event_loop).await?;
179 }
180
181 let errs = app.close().await;
182
183 if !errs.is_empty() {
184 log::error!("Errors closing app");
185
186 for err in errs {
187 log::error!("{}", err);
188 }
189
190 bail!("Error closing app");
191 }
192
193 Ok(())
194 }
195
196 pub async fn test_key_sequence_with_input_text<T: Into<TestCase>>(
197 app: Option<Application>,
198 test_case: T,
199 test_fn: &dyn Fn(&Application),
200 should_exit: bool,
201 ) -> anyhow::Result<()> {
202 let test_case = test_case.into();
203
204 let mut app = match app {
205 Some(app) => app,
206 None => Application::new(
207 Args::default(),
208 test_config(),
209 test_syntax_loader(None),
210 WorkspaceTrust::fully_trusted(),
211 )?,
212 };
213
214 let (view, doc) = helix_view::current!(app.editor);
215 let sel = doc.selection(view.id).clone();
216
217 // replace the initial text with the input text
218 let transaction = Transaction::change_by_selection(doc.text(), &sel, |_| {
219 (0, doc.text().len_chars(), Some((&test_case.in_text).into()))
220 })
221 .with_selection(test_case.in_selection.clone());
222
223 doc.apply(&transaction, view.id);
224
225 test_key_sequence(
226 &mut app,
227 Some(&test_case.in_keys),
228 Some(test_fn),
229 should_exit,
230 )
231 .await
232 }
233
234 /// Generates language config loader that merge in overrides, like a user language
235 /// config. The argument string must be a raw TOML document.
236 pub fn test_syntax_loader(overrides: Option<String>) -> helix_core::syntax::Loader {
237 let mut lang = helix_loader::config::default_lang_config();
238
239 if let Some(overrides) = overrides {
240 let override_toml = toml::from_str(&overrides).unwrap();
241 lang = helix_loader::merge_toml_values(lang, override_toml, 3);
242 }
243
244 helix_core::syntax::Loader::new(lang.try_into().unwrap()).unwrap()
245 }
246
247 /// Use this for very simple test cases where there is one input
248 /// document, selection, and sequence of key presses, and you just
249 /// want to verify the resulting document and selection.
250 pub async fn test_with_config<T: Into<TestCase>>(
251 app_builder: AppBuilder,
252 test_case: T,
253 ) -> anyhow::Result<()> {
254 let test_case = test_case.into();
255 let app = app_builder.build()?;
256
257 test_key_sequence_with_input_text(
258 Some(app),
259 test_case.clone(),
260 &|app| {
261 let doc = doc!(app.editor);
262 assert_eq!(&test_case.out_text, doc.text());
263
264 let mut selections: Vec<_> = doc.selections().values().cloned().collect();
265 assert_eq!(1, selections.len());
266
267 let sel = selections.pop().unwrap();
268 assert_eq!(test_case.out_selection, sel);
269 },
270 false,
271 )
272 .await
273 }
274
275 pub async fn test<T: Into<TestCase>>(test_case: T) -> anyhow::Result<()> {
276 test_with_config(AppBuilder::default(), test_case).await
277 }
278
279 pub fn temp_file_with_contents<S: AsRef<str>>(
280 content: S,
281 ) -> anyhow::Result<tempfile::NamedTempFile> {
282 let mut temp_file = tempfile::NamedTempFile::new()?;
283
284 temp_file
285 .as_file_mut()
286 .write_all(content.as_ref().as_bytes())?;
287
288 temp_file.flush()?;
289 temp_file.as_file_mut().sync_all()?;
290 Ok(temp_file)
291 }
292
293 /// Generates a config with defaults more suitable for integration tests
294 pub fn test_config() -> Config {
295 Config {
296 editor: test_editor_config(),
297 keys: helix_term::keymap::default(),
298 ..Default::default()
299 }
300 }
301
302 pub fn test_editor_config() -> helix_view::editor::Config {
303 helix_view::editor::Config {
304 lsp: LspConfig {
305 enable: false,
306 ..Default::default()
307 },
308 // The word-index hook accumulates per-document pending changes across
309 // every `DocumentDidChange` and composes them on the next event for the
310 // same doc id. Each test builds a fresh `Application` that reuses
311 // `DocumentId(1)`, so the previous test's pending change tries to
312 // compose with the next test's `set_input` change (different lengths,
313 // hits the `len_after == len` assertion).
314 // Until hooks can be unregistered, keep the hook quiet by turning the
315 // feature off here.
316 word_completion: WordCompletion {
317 enable: false,
318 ..Default::default()
319 },
320 // Trust everything implicitly so tests don't hit popups.
321 workspace_trust: WorkspaceTrustConfig {
322 level: ImplicitTrustLevelConfig::Insecure,
323 ..Default::default()
324 },
325 ..Default::default()
326 }
327 }
328
329 /// Creates a new temporary file that is set to read only. Useful for
330 /// testing write failures.
331 pub fn new_readonly_tempfile() -> anyhow::Result<NamedTempFile> {
332 let mut file = tempfile::NamedTempFile::new()?;
333 let metadata = file.as_file().metadata()?;
334 let mut perms = metadata.permissions();
335 perms.set_readonly(true);
336 file.as_file_mut().set_permissions(perms)?;
337 Ok(file)
338 }
339
340 /// Creates a new temporary file in the directory that is set to read only. Useful for
341 /// testing write failures.
342 pub fn new_readonly_tempfile_in_dir(
343 dir: impl AsRef<std::path::Path>,
344 ) -> anyhow::Result<NamedTempFile> {
345 let mut file = tempfile::NamedTempFile::new_in(dir)?;
346 let metadata = file.as_file().metadata()?;
347 let mut perms = metadata.permissions();
348 perms.set_readonly(true);
349 file.as_file_mut().set_permissions(perms)?;
350 Ok(file)
351 }
352 pub struct AppBuilder {
353 args: Args,
354 config: Config,
355 syn_loader: helix_core::syntax::Loader,
356 input: Option<(String, Selection)>,
357 }
358
359 impl Default for AppBuilder {
360 fn default() -> Self {
361 Self {
362 args: Args::default(),
363 config: test_config(),
364 syn_loader: test_syntax_loader(None),
365 input: None,
366 }
367 }
368 }
369
370 impl AppBuilder {
371 pub fn new() -> Self {
372 AppBuilder::default()
373 }
374
375 pub fn with_file<P: Into<PathBuf>>(
376 mut self,
377 path: P,
378 pos: Option<helix_core::Position>,
379 ) -> Self {
380 self.args
381 .files
382 .insert(path.into(), vec![pos.unwrap_or_default()]);
383
384 self
385 }
386
387 // Remove this attribute once `with_config` is used in a test:
388 #[allow(dead_code)]
389 pub fn with_config(mut self, mut config: Config) -> Self {
390 let keys = replace(&mut config.keys, helix_term::keymap::default());
391 merge_keys(&mut config.keys, keys);
392 self.config = config;
393 self
394 }
395
396 pub fn with_input_text<S: Into<String>>(mut self, input_text: S) -> Self {
397 self.input = Some(test::print(&input_text.into()));
398 self
399 }
400
401 pub fn with_lang_loader(mut self, syn_loader: helix_core::syntax::Loader) -> Self {
402 self.syn_loader = syn_loader;
403 self
404 }
405
406 pub fn build(self) -> anyhow::Result<Application> {
407 if let Some(path) = &self.args.working_directory {
408 bail!("Changing the working directory to {path:?} is not yet supported for integration tests");
409 }
410
411 if let Some((path, _)) = self.args.files.first().filter(|p| p.0.is_dir()) {
412 bail!("Having the directory {path:?} in args.files[0] is not yet supported for integration tests");
413 }
414
415 let mut app = Application::new(
416 self.args,
417 self.config,
418 self.syn_loader,
419 WorkspaceTrust::fully_trusted(),
420 )?;
421
422 if let Some((text, selection)) = self.input {
423 let (view, doc) = helix_view::current!(app.editor);
424 let sel = doc.selection(view.id).clone();
425 let trans = Transaction::change_by_selection(doc.text(), &sel, |_| {
426 (0, doc.text().len_chars(), Some((text.clone()).into()))
427 })
428 .with_selection(selection);
429
430 // replace the initial text with the input text
431 doc.apply(&trans, view.id);
432 }
433
434 Ok(app)
435 }
436 }
437
438 pub async fn run_event_loop_until_idle(app: &mut Application) {
439 let (_, rx) = tokio::sync::mpsc::unbounded_channel();
440 let mut rx_stream = UnboundedReceiverStream::new(rx);
441 app.event_loop_until_idle(&mut rx_stream).await;
442 }
443
444 pub fn assert_file_has_content(file: &mut NamedTempFile, content: &str) -> anyhow::Result<()> {
445 reload_file(file)?;
446
447 let mut file_content = String::new();
448 file.read_to_string(&mut file_content)?;
449 assert_eq!(file_content, content);
450
451 Ok(())
452 }
453
454 pub fn assert_status_not_error(editor: &Editor) {
455 if let Some((_, sev)) = editor.get_status() {
456 assert_ne!(&Severity::Error, sev);
457 }
458 }
459
460 pub fn reload_file(file: &mut NamedTempFile) -> anyhow::Result<()> {
461 let path = file.path();
462 let f = std::fs::OpenOptions::new()
463 .write(true)
464 .read(true)
465 .open(&path)?;
466 *file.as_file_mut() = f;
467 Ok(())
468 }