tests for serialized writes

imgbot
Skyler Hawthorne 2 years ago
parent ee705dcb33
commit 07fc80aece

@ -17,6 +17,7 @@ mod integration {
Args::default(), Args::default(),
Config::default(), Config::default(),
("#[\n|]#", "ihello world<esc>", "hello world#[|\n]#"), ("#[\n|]#", "ihello world<esc>", "hello world#[|\n]#"),
None,
) )
.await?; .await?;
@ -25,6 +26,7 @@ mod integration {
mod auto_indent; mod auto_indent;
mod auto_pairs; mod auto_pairs;
mod commands;
mod movement; mod movement;
mod write; mod write;
} }

@ -18,6 +18,7 @@ async fn auto_indent_c() -> anyhow::Result<()> {
} }
"}, "},
), ),
None,
) )
.await?; .await?;

@ -6,6 +6,7 @@ async fn auto_pairs_basic() -> anyhow::Result<()> {
Args::default(), Args::default(),
Config::default(), Config::default(),
("#[\n|]#", "i(<esc>", "(#[|)]#\n"), ("#[\n|]#", "i(<esc>", "(#[|)]#\n"),
None,
) )
.await?; .await?;
@ -19,6 +20,7 @@ async fn auto_pairs_basic() -> anyhow::Result<()> {
..Default::default() ..Default::default()
}, },
("#[\n|]#", "i(<esc>", "(#[|\n]#"), ("#[\n|]#", "i(<esc>", "(#[|\n]#"),
None,
) )
.await?; .await?;

@ -0,0 +1,25 @@
use helix_core::diagnostic::Severity;
use helix_term::application::Application;
use super::*;
#[tokio::test]
async fn test_write_quit_fail() -> anyhow::Result<()> {
test_key_sequence(
&mut Application::new(
Args {
files: vec![(PathBuf::from("/foo"), Position::default())],
..Default::default()
},
Config::default(),
)?,
"ihello<esc>:wq<ret>",
Some(&|app| {
assert_eq!(&Severity::Error, app.editor.get_status().unwrap().1);
}),
None,
)
.await?;
Ok(())
}

@ -5,7 +5,6 @@ use crossterm::event::{Event, KeyEvent};
use helix_core::{test, Selection, Transaction}; use helix_core::{test, Selection, Transaction};
use helix_term::{application::Application, args::Args, config::Config}; use helix_term::{application::Application, args::Args, config::Config};
use helix_view::{doc, input::parse_macro}; use helix_view::{doc, input::parse_macro};
use tokio::time::timeout;
use tokio_stream::wrappers::UnboundedReceiverStream; use tokio_stream::wrappers::UnboundedReceiverStream;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
@ -32,20 +31,32 @@ impl<S: Into<String>> From<(S, S, S)> for TestCase {
} }
} }
#[inline]
pub async fn test_key_sequence( pub async fn test_key_sequence(
app: &mut Application, app: &mut Application,
in_keys: &str, in_keys: &str,
test_fn: Option<&dyn Fn(&Application)>, test_fn: Option<&dyn Fn(&Application)>,
timeout: Option<Duration>,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
test_key_sequences(app, vec![(in_keys, test_fn)], timeout).await
}
pub async fn test_key_sequences(
app: &mut Application,
inputs: Vec<(&str, Option<&dyn Fn(&Application)>)>,
timeout: Option<Duration>,
) -> anyhow::Result<()> {
let timeout = timeout.unwrap_or(Duration::from_millis(500));
let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
let mut rx_stream = UnboundedReceiverStream::new(rx);
for (in_keys, test_fn) in inputs {
for key_event in parse_macro(&in_keys)?.into_iter() { for key_event in parse_macro(&in_keys)?.into_iter() {
tx.send(Ok(Event::Key(KeyEvent::from(key_event))))?; tx.send(Ok(Event::Key(KeyEvent::from(key_event))))?;
} }
let mut rx_stream = UnboundedReceiverStream::new(rx);
let event_loop = app.event_loop(&mut rx_stream); let event_loop = app.event_loop(&mut rx_stream);
let result = timeout(Duration::from_millis(500), event_loop).await; let result = tokio::time::timeout(timeout, event_loop).await;
if result.is_ok() { if result.is_ok() {
bail!("application exited before test function could run"); bail!("application exited before test function could run");
@ -54,13 +65,14 @@ pub async fn test_key_sequence(
if let Some(test) = test_fn { if let Some(test) = test_fn {
test(app); test(app);
}; };
}
for key_event in parse_macro("<esc>:q!<ret>")?.into_iter() { for key_event in parse_macro("<esc>:q!<ret>")?.into_iter() {
tx.send(Ok(Event::Key(KeyEvent::from(key_event))))?; tx.send(Ok(Event::Key(KeyEvent::from(key_event))))?;
} }
let event_loop = app.event_loop(&mut rx_stream); let event_loop = app.event_loop(&mut rx_stream);
timeout(Duration::from_millis(5000), event_loop).await?; tokio::time::timeout(timeout, event_loop).await?;
app.close().await?; app.close().await?;
Ok(()) Ok(())
@ -70,6 +82,7 @@ pub async fn test_key_sequence_with_input_text<T: Into<TestCase>>(
app: Option<Application>, app: Option<Application>,
test_case: T, test_case: T,
test_fn: &dyn Fn(&Application), test_fn: &dyn Fn(&Application),
timeout: Option<Duration>,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
let test_case = test_case.into(); let test_case = test_case.into();
let mut app = let mut app =
@ -87,7 +100,7 @@ pub async fn test_key_sequence_with_input_text<T: Into<TestCase>>(
view.id, view.id,
); );
test_key_sequence(&mut app, &test_case.in_keys, Some(test_fn)).await test_key_sequence(&mut app, &test_case.in_keys, Some(test_fn), timeout).await
} }
/// Use this for very simple test cases where there is one input /// Use this for very simple test cases where there is one input
@ -97,11 +110,15 @@ pub async fn test_key_sequence_text_result<T: Into<TestCase>>(
args: Args, args: Args,
config: Config, config: Config,
test_case: T, test_case: T,
timeout: Option<Duration>,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
let test_case = test_case.into(); let test_case = test_case.into();
let app = Application::new(args, config).unwrap(); let app = Application::new(args, config).unwrap();
test_key_sequence_with_input_text(Some(app), test_case.clone(), &|app| { test_key_sequence_with_input_text(
Some(app),
test_case.clone(),
&|app| {
let doc = doc!(app.editor); let doc = doc!(app.editor);
assert_eq!(&test_case.out_text, doc.text()); assert_eq!(&test_case.out_text, doc.text());
@ -110,7 +127,9 @@ pub async fn test_key_sequence_text_result<T: Into<TestCase>>(
let sel = selections.pop().unwrap(); let sel = selections.pop().unwrap();
assert_eq!(test_case.out_selection, sel); assert_eq!(test_case.out_selection, sel);
}) },
timeout,
)
.await .await
} }

@ -14,6 +14,7 @@ async fn insert_mode_cursor_position() -> anyhow::Result<()> {
out_text: String::new(), out_text: String::new(),
out_selection: Selection::single(0, 0), out_selection: Selection::single(0, 0),
}, },
None,
) )
.await?; .await?;
@ -21,6 +22,7 @@ async fn insert_mode_cursor_position() -> anyhow::Result<()> {
Args::default(), Args::default(),
Config::default(), Config::default(),
("#[\n|]#", "i", "#[|\n]#"), ("#[\n|]#", "i", "#[|\n]#"),
None,
) )
.await?; .await?;
@ -28,6 +30,7 @@ async fn insert_mode_cursor_position() -> anyhow::Result<()> {
Args::default(), Args::default(),
Config::default(), Config::default(),
("#[\n|]#", "i<esc>", "#[|\n]#"), ("#[\n|]#", "i<esc>", "#[|\n]#"),
None,
) )
.await?; .await?;
@ -35,6 +38,7 @@ async fn insert_mode_cursor_position() -> anyhow::Result<()> {
Args::default(), Args::default(),
Config::default(), Config::default(),
("#[\n|]#", "i<esc>i", "#[|\n]#"), ("#[\n|]#", "i<esc>i", "#[|\n]#"),
None,
) )
.await?; .await?;
@ -48,6 +52,7 @@ async fn insert_to_normal_mode_cursor_position() -> anyhow::Result<()> {
Args::default(), Args::default(),
Config::default(), Config::default(),
("#[f|]#oo\n", "vll<A-;><esc>", "#[|foo]#\n"), ("#[f|]#oo\n", "vll<A-;><esc>", "#[|foo]#\n"),
None,
) )
.await?; .await?;
@ -65,6 +70,7 @@ async fn insert_to_normal_mode_cursor_position() -> anyhow::Result<()> {
#(|bar)#" #(|bar)#"
}, },
), ),
None,
) )
.await?; .await?;
@ -82,6 +88,7 @@ async fn insert_to_normal_mode_cursor_position() -> anyhow::Result<()> {
#(ba|)#r" #(ba|)#r"
}, },
), ),
None,
) )
.await?; .await?;
@ -99,6 +106,7 @@ async fn insert_to_normal_mode_cursor_position() -> anyhow::Result<()> {
#(b|)#ar" #(b|)#ar"
}, },
), ),
None,
) )
.await?; .await?;

@ -1,9 +1,11 @@
use std::{ use std::{
io::{Read, Write}, io::{Read, Write},
ops::RangeInclusive, time::Duration,
}; };
use helix_core::diagnostic::Severity;
use helix_term::application::Application; use helix_term::application::Application;
use helix_view::doc;
use super::*; use super::*;
@ -21,6 +23,7 @@ async fn test_write() -> anyhow::Result<()> {
)?, )?,
"ii can eat glass, it will not hurt me<ret><esc>:w<ret>", "ii can eat glass, it will not hurt me<ret><esc>:w<ret>",
None, None,
Some(Duration::from_millis(1000)),
) )
.await?; .await?;
@ -35,35 +38,73 @@ async fn test_write() -> anyhow::Result<()> {
} }
#[tokio::test] #[tokio::test]
async fn test_write_concurrent() -> anyhow::Result<()> { async fn test_write_fail_mod_flag() -> anyhow::Result<()> {
let mut file = tempfile::NamedTempFile::new().unwrap(); test_key_sequences(
let mut command = String::new();
const RANGE: RangeInclusive<i32> = 1..=1000;
for i in RANGE {
let cmd = format!("%c{}<esc>:w<ret>", i);
command.push_str(&cmd);
}
test_key_sequence(
&mut Application::new( &mut Application::new(
Args { Args {
files: vec![(file.path().to_path_buf(), Position::default())], files: vec![(PathBuf::from("/foo"), Position::default())],
..Default::default() ..Default::default()
}, },
Config::default(), Config::default(),
)?, )?,
&command, vec![
(
"",
Some(&|app| {
let doc = doc!(app.editor);
assert!(!doc.is_modified());
}),
),
(
"ihello<esc>",
Some(&|app| {
let doc = doc!(app.editor);
assert!(doc.is_modified());
}),
),
(
":w<ret>",
Some(&|app| {
assert_eq!(&Severity::Error, app.editor.get_status().unwrap().1);
let doc = doc!(app.editor);
assert!(doc.is_modified());
}),
),
],
None, None,
) )
.await?; .await?;
file.as_file_mut().flush()?; Ok(())
file.as_file_mut().sync_all()?; }
let mut file_content = String::new(); #[tokio::test]
file.as_file_mut().read_to_string(&mut file_content)?; #[ignore]
assert_eq!(RANGE.end().to_string(), file_content); async fn test_write_fail_new_path() -> anyhow::Result<()> {
test_key_sequences(
&mut Application::new(Args::default(), Config::default())?,
vec![
(
"",
Some(&|app| {
let doc = doc!(app.editor);
assert_eq!(None, app.editor.get_status());
assert_eq!(None, doc.path());
}),
),
(
":w /foo<ret>",
Some(&|app| {
let doc = doc!(app.editor);
assert_eq!(&Severity::Error, app.editor.get_status().unwrap().1);
assert_eq!(None, doc.path());
}),
),
],
Some(Duration::from_millis(1000)),
)
.await?;
Ok(()) Ok(())
} }

@ -571,6 +571,11 @@ impl Editor {
self.status_msg = Some((error.into(), Severity::Error)); self.status_msg = Some((error.into(), Severity::Error));
} }
#[inline]
pub fn get_status(&self) -> Option<(&Cow<'static, str>, &Severity)> {
self.status_msg.as_ref().map(|(status, sev)| (status, sev))
}
pub fn set_theme(&mut self, theme: Theme) { pub fn set_theme(&mut self, theme: Theme) {
// `ui.selection` is the only scope required to be able to render a theme. // `ui.selection` is the only scope required to be able to render a theme.
if theme.find_scope_index("ui.selection").is_none() { if theme.find_scope_index("ui.selection").is_none() {

Loading…
Cancel
Save