helix-mods/helix-term/tests/test/helpers.rs

216 lines
6.4 KiB
Rust
Raw Normal View History

use std::{io::Write, path::PathBuf, time::Duration};
use anyhow::bail;
2022-04-17 04:05:45 +02:00
use crossterm::event::{Event, KeyEvent};
use helix_core::{test, Selection, Transaction};
use helix_term::{application::Application, args::Args, config::Config};
use helix_view::{doc, input::parse_macro};
use tempfile::NamedTempFile;
use tokio_stream::wrappers::UnboundedReceiverStream;
2022-04-17 04:05:45 +02:00
#[derive(Clone, Debug)]
pub struct TestCase {
pub in_text: String,
pub in_selection: Selection,
pub in_keys: String,
pub out_text: String,
pub out_selection: Selection,
}
impl<S: Into<String>> From<(S, S, S)> for TestCase {
fn from((input, keys, output): (S, S, S)) -> Self {
let (in_text, in_selection) = test::print(&input.into());
let (out_text, out_selection) = test::print(&output.into());
TestCase {
in_text,
in_selection,
in_keys: keys.into(),
out_text,
out_selection,
}
}
}
2022-05-01 02:44:54 +02:00
#[inline]
pub async fn test_key_sequence(
app: &mut Application,
2022-05-01 02:47:53 +02:00
in_keys: Option<&str>,
test_fn: Option<&dyn Fn(&Application)>,
2022-05-23 06:24:18 +02:00
should_exit: bool,
) -> anyhow::Result<()> {
2022-05-23 06:24:18 +02:00
test_key_sequences(app, vec![(in_keys, test_fn)], should_exit).await
2022-05-01 02:44:54 +02:00
}
2022-05-22 19:29:52 +02:00
#[allow(clippy::type_complexity)]
2022-05-01 02:44:54 +02:00
pub async fn test_key_sequences(
app: &mut Application,
2022-05-01 02:47:53 +02:00
inputs: Vec<(Option<&str>, Option<&dyn Fn(&Application)>)>,
2022-05-23 06:24:18 +02:00
should_exit: bool,
2022-05-01 02:44:54 +02:00
) -> anyhow::Result<()> {
const TIMEOUT: Duration = Duration::from_millis(500);
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
2022-05-01 02:44:54 +02:00
let mut rx_stream = UnboundedReceiverStream::new(rx);
2022-05-23 06:24:18 +02:00
let num_inputs = inputs.len();
2022-05-23 06:24:18 +02:00
for (i, (in_keys, test_fn)) in inputs.into_iter().enumerate() {
2022-05-01 02:47:53 +02:00
if let Some(in_keys) = in_keys {
2022-05-22 19:29:52 +02:00
for key_event in parse_macro(in_keys)?.into_iter() {
2022-05-10 05:08:12 +02:00
let key = Event::Key(KeyEvent::from(key_event));
log::trace!("sending key: {:?}", key);
tx.send(Ok(key))?;
2022-05-01 02:47:53 +02:00
}
2022-05-01 02:44:54 +02:00
}
2022-05-23 06:24:18 +02:00
let app_exited = !app.event_loop_until_idle(&mut rx_stream).await;
// the app should not exit from any test until the last one
if i < num_inputs - 1 && app_exited {
2022-05-01 02:44:54 +02:00
bail!("application exited before test function could run");
}
2022-05-23 06:24:18 +02:00
// verify if it exited on the last iteration if it should have and
// the inverse
if i == num_inputs - 1 && app_exited != should_exit {
2022-05-10 05:08:12 +02:00
bail!("expected app to exit: {} != {}", should_exit, app_exited);
2022-05-23 06:24:18 +02:00
}
2022-05-01 02:44:54 +02:00
if let Some(test) = test_fn {
test(app);
};
}
2022-05-23 06:24:18 +02:00
if !should_exit {
for key_event in parse_macro("<esc>:q!<ret>")?.into_iter() {
tx.send(Ok(Event::Key(KeyEvent::from(key_event))))?;
}
let event_loop = app.event_loop(&mut rx_stream);
tokio::time::timeout(TIMEOUT, event_loop).await?;
}
app.close().await?;
Ok(())
}
pub async fn test_key_sequence_with_input_text<T: Into<TestCase>>(
2022-04-17 04:05:45 +02:00
app: Option<Application>,
test_case: T,
test_fn: &dyn Fn(&Application),
2022-05-23 06:24:18 +02:00
should_exit: bool,
2022-04-17 04:05:45 +02:00
) -> anyhow::Result<()> {
let test_case = test_case.into();
let mut app = match app {
Some(app) => app,
None => Application::new(Args::default(), Config::default())?,
};
2022-04-17 04:05:45 +02:00
let (view, doc) = helix_view::current!(app.editor);
let sel = doc.selection(view.id).clone();
// replace the initial text with the input text
doc.apply(
2022-05-22 19:29:52 +02:00
&Transaction::change_by_selection(doc.text(), &sel, |_| {
2022-04-17 04:05:45 +02:00
(0, doc.text().len_chars(), Some((&test_case.in_text).into()))
})
.with_selection(test_case.in_selection.clone()),
view.id,
);
2022-05-23 06:24:18 +02:00
test_key_sequence(
&mut app,
Some(&test_case.in_keys),
Some(test_fn),
should_exit,
)
.await
2022-04-17 04:05:45 +02:00
}
/// Use this for very simple test cases where there is one input
/// document, selection, and sequence of key presses, and you just
/// want to verify the resulting document and selection.
2022-05-22 19:29:52 +02:00
pub async fn test_with_config<T: Into<TestCase>>(
2022-04-17 04:05:45 +02:00
args: Args,
config: Config,
test_case: T,
) -> anyhow::Result<()> {
let test_case = test_case.into();
let app = Application::new(args, config)?;
2022-04-17 04:05:45 +02:00
2022-05-23 06:24:18 +02:00
test_key_sequence_with_input_text(
Some(app),
test_case.clone(),
&|app| {
let doc = doc!(app.editor);
assert_eq!(&test_case.out_text, doc.text());
let mut selections: Vec<_> = doc.selections().values().cloned().collect();
assert_eq!(1, selections.len());
let sel = selections.pop().unwrap();
assert_eq!(test_case.out_selection, sel);
},
false,
)
.await
2022-04-17 04:05:45 +02:00
}
2022-05-22 19:29:52 +02:00
pub async fn test<T: Into<TestCase>>(test_case: T) -> anyhow::Result<()> {
test_with_config(Args::default(), Config::default(), test_case).await
}
pub fn temp_file_with_contents<S: AsRef<str>>(
content: S,
) -> anyhow::Result<tempfile::NamedTempFile> {
let mut temp_file = tempfile::NamedTempFile::new()?;
temp_file
.as_file_mut()
.write_all(content.as_ref().as_bytes())?;
temp_file.flush()?;
temp_file.as_file_mut().sync_all()?;
Ok(temp_file)
}
2022-04-29 22:27:35 +02:00
/// Replaces all LF chars with the system's appropriate line feed
/// character, and if one doesn't exist already, appends the system's
/// appropriate line ending to the end of a string.
pub fn platform_line(input: &str) -> String {
let line_end = helix_core::DEFAULT_LINE_ENDING.as_str();
// we can assume that the source files in this code base will always
// be LF, so indoc strings will always insert LF
2022-05-22 19:29:52 +02:00
let mut output = input.replace('\n', line_end);
2022-04-29 22:27:35 +02:00
if !output.ends_with(line_end) {
output.push_str(line_end);
}
output
}
/// Creates a new temporary file that is set to read only. Useful for
/// testing write failures.
pub fn new_readonly_tempfile() -> anyhow::Result<NamedTempFile> {
let mut file = tempfile::NamedTempFile::new()?;
let metadata = file.as_file().metadata()?;
let mut perms = metadata.permissions();
perms.set_readonly(true);
file.as_file_mut().set_permissions(perms)?;
Ok(file)
}
/// Creates a new Application with default config that opens the given file
/// path
pub fn app_with_file<P: Into<PathBuf>>(path: P) -> anyhow::Result<Application> {
Application::new(
Args {
files: vec![(path.into(), helix_core::Position::default())],
..Default::default()
},
Config::default(),
)
}