From 7e16f2978f84c853e2add3488a266eccca755d14 Mon Sep 17 00:00:00 2001 From: Vicki Pfau Date: Thu, 4 Apr 2024 20:01:59 -0700 Subject: [PATCH] process: Fix testing setup --- src/process.rs | 48 ++++++++++++++++++++++++++++++++++++++++++++++-- src/testing.rs | 6 +++--- 2 files changed, 49 insertions(+), 5 deletions(-) diff --git a/src/process.rs b/src/process.rs index 18f7eb4..ad0da0f 100644 --- a/src/process.rs +++ b/src/process.rs @@ -22,7 +22,7 @@ pub async fn script_exit_code(executable: &str, args: &[impl AsRef]) -> R pub async fn script_exit_code(executable: &str, args: &[impl AsRef]) -> Result { 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]) -> Resu pub async fn script_output(executable: &str, args: &[impl AsRef]) -> Result { 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!" + ); + } +} diff --git a/src/testing.rs b/src/testing.rs index 042434d..ae19cd2 100644 --- a/src/testing.rs +++ b/src/testing.rs @@ -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 = 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 { pub struct Test { base: TempDir, - pub process_cb: fn(&str, &[&OsStr]) -> Result<(i32, String)>, + pub process_cb: Cell Result<(i32, String)>>, } pub struct TestHandle {