process: Fix testing setup

This commit is contained in:
Vicki Pfau 2024-04-04 20:01:59 -07:00
parent cf962b26c5
commit 7e16f2978f
2 changed files with 49 additions and 5 deletions

View file

@ -22,7 +22,7 @@ pub async fn script_exit_code(executable: &str, args: &[impl AsRef<OsStr>]) -> R
pub async fn script_exit_code(executable: &str, args: &[impl AsRef<OsStr>]) -> Result<i32> {
let test = crate::testing::current();
let args: Vec<&OsStr> = args.iter().map(|arg| arg.as_ref()).collect();
let cb = &test.process_cb;
let cb = test.process_cb.get();
cb(executable, args.as_ref()).map(|(res, _)| res)
}
@ -51,6 +51,50 @@ pub async fn script_output(executable: &str, args: &[impl AsRef<OsStr>]) -> Resu
pub async fn script_output(executable: &str, args: &[impl AsRef<OsStr>]) -> Result<String> {
let test = crate::testing::current();
let args: Vec<&OsStr> = args.iter().map(|arg| arg.as_ref()).collect();
let cb = &test.process_cb;
let cb = test.process_cb.get();
cb(executable, args.as_ref()).map(|(_, res)| res)
}
#[cfg(test)]
mod test {
use super::*;
use crate::testing;
fn ok(_: &str, args: &[&OsStr]) -> Result<(i32, String)> {
Ok((0, String::from("ok")))
}
fn code(_: &str, args: &[&OsStr]) -> Result<(i32, String)> {
Ok((1, String::from("code")))
}
fn exit(_: &str, args: &[&OsStr]) -> Result<(i32, String)> {
Err(anyhow!("oops!"))
}
#[tokio::test]
async fn test_run_script() {
let h = testing::start();
h.test.process_cb.set(ok);
assert!(run_script("", &[] as &[&OsStr]).await.is_ok());
h.test.process_cb.set(code);
assert_eq!(
run_script("", &[] as &[&OsStr])
.await
.unwrap_err()
.to_string(),
"Exited 1"
);
h.test.process_cb.set(exit);
assert_eq!(
run_script("", &[] as &[&OsStr])
.await
.unwrap_err()
.to_string(),
"oops!"
);
}
}

View file

@ -1,5 +1,5 @@
use anyhow::{anyhow, Result};
use std::cell::RefCell;
use std::cell::{Cell, RefCell};
use std::ffi::OsStr;
use std::path::Path;
use std::rc::Rc;
@ -14,7 +14,7 @@ pub fn start() -> TestHandle {
assert!(lock.borrow().as_ref().is_none());
let test: Rc<Test> = Rc::new(Test {
base: tempdir().expect("Couldn't create test directory"),
process_cb: |_, _| Err(anyhow!("No current process_cb")),
process_cb: Cell::new(|_, _| Err(anyhow!("No current process_cb"))),
});
*lock.borrow_mut() = Some(test.clone());
TestHandle { test }
@ -31,7 +31,7 @@ pub fn current() -> Rc<Test> {
pub struct Test {
base: TempDir,
pub process_cb: fn(&str, &[&OsStr]) -> Result<(i32, String)>,
pub process_cb: Cell<fn(&str, &[&OsStr]) -> Result<(i32, String)>>,
}
pub struct TestHandle {