use std::cell::RefCell;
use std::collections::BTreeSet;
use std::io;
use std::path::{Path, PathBuf};
use crate::port::binary::seam::{Binary, LuaTestRun};
use crate::types::name::{AIRSL, BinaryName};
use crate::types::plan::{AirslAnswer, Exit};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BinaryCall {
OnPath(BinaryName),
AirslVersion,
AirslTest(PathBuf),
}
#[derive(Debug, Clone)]
enum Airsl {
Prints(String),
ExitsWithFailure(String),
FailsToStart,
}
#[derive(Debug, Clone)]
enum TestScript {
Runs(LuaTestRun),
FailsToStart,
}
#[derive(Debug, Default)]
pub struct FakeBinary {
names: BTreeSet<BinaryName>,
airsl: Option<Airsl>,
test: Option<TestScript>,
asked: RefCell<Vec<BinaryCall>>,
}
impl FakeBinary {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with(mut self, name: BinaryName) -> Self {
self.names.insert(name);
self
}
#[must_use]
pub fn airsl(mut self, text: &str) -> Self {
self.airsl = Some(Airsl::Prints(text.to_owned()));
self
}
#[must_use]
pub fn airsl_exit_failure(mut self, text: &str) -> Self {
self.airsl = Some(Airsl::ExitsWithFailure(text.to_owned()));
self
}
#[must_use]
pub fn airsl_spawn_failure(mut self) -> Self {
self.airsl = Some(Airsl::FailsToStart);
self
}
#[must_use]
pub fn airsl_test_run(mut self, run: LuaTestRun) -> Self {
self.test = Some(TestScript::Runs(run));
self
}
#[must_use]
pub fn airsl_test_spawn_failure(mut self) -> Self {
self.test = Some(TestScript::FailsToStart);
self
}
#[must_use]
pub fn denied() -> io::Error {
io::Error::new(io::ErrorKind::PermissionDenied, "permission denied")
}
#[must_use]
pub fn asked(&self) -> Vec<BinaryCall> {
self.asked.borrow().clone()
}
}
impl Binary for FakeBinary {
fn on_path(&self, name: &BinaryName) -> bool {
self.asked
.borrow_mut()
.push(BinaryCall::OnPath(name.clone()));
self.names.contains(name) || (name.as_str() == AIRSL && self.airsl.is_some())
}
fn airsl_version(&self) -> AirslAnswer {
self.asked.borrow_mut().push(BinaryCall::AirslVersion);
match &self.airsl {
None => AirslAnswer::NotFound,
Some(Airsl::Prints(text)) => AirslAnswer::from_output(text.as_bytes(), Exit::Success),
Some(Airsl::ExitsWithFailure(text)) => {
AirslAnswer::from_output(text.as_bytes(), Exit::Failure)
}
Some(Airsl::FailsToStart) => AirslAnswer::SpawnFailed(Self::denied()),
}
}
fn airsl_test(&self, dir: &Path) -> io::Result<LuaTestRun> {
self.asked
.borrow_mut()
.push(BinaryCall::AirslTest(dir.to_path_buf()));
match &self.test {
None => Ok(LuaTestRun {
success: true,
stdout: String::new(),
stderr: String::new(),
}),
Some(TestScript::Runs(run)) => Ok(run.clone()),
Some(TestScript::FailsToStart) => Err(Self::denied()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::plan::AirslAnswer;
type TestResult = Result<(), Box<dyn std::error::Error>>;
fn name(text: &str) -> Result<BinaryName, Box<dyn std::error::Error>> {
Ok(BinaryName::new(text)?)
}
#[test]
fn on_path_answers_configured_names() -> TestResult {
let binary = FakeBinary::new().with(name("rg")?);
assert!(binary.on_path(&name("rg")?));
assert!(!binary.on_path(&name("node")?));
Ok(())
}
#[test]
fn airsl_version_is_not_found_by_default() {
assert!(matches!(
FakeBinary::new().airsl_version(),
AirslAnswer::NotFound
));
}
#[test]
fn airsl_version_prints_the_configured_text() -> TestResult {
let binary = FakeBinary::new().airsl("airsl 0.1.4");
assert!(matches!(
binary.airsl_version(),
AirslAnswer::Printed(text) if text == "airsl 0.1.4"
));
assert!(binary.on_path(&name("airsl")?));
Ok(())
}
#[test]
fn airsl_exit_failure_is_the_unparseable_answer() -> TestResult {
let binary = FakeBinary::new().airsl_exit_failure("airsl 0.1.4");
assert!(matches!(
binary.airsl_version(),
AirslAnswer::Failed(text) if text == "airsl 0.1.4"
));
assert!(binary.on_path(&name("airsl")?));
Ok(())
}
#[test]
fn airsl_spawn_failure_carries_the_io_error() -> TestResult {
let binary = FakeBinary::new().airsl_spawn_failure();
let AirslAnswer::SpawnFailed(error) = binary.airsl_version() else {
return Err("a spawn failure".into());
};
assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
assert_eq!(error.to_string(), FakeBinary::denied().to_string());
assert!(binary.on_path(&name("airsl")?));
Ok(())
}
#[test]
fn questions_are_logged() -> TestResult {
let binary = FakeBinary::new();
binary.on_path(&name("rg")?);
binary.on_path(&name("node")?);
let _ = binary.airsl_version();
assert_eq!(
binary.asked(),
[
BinaryCall::OnPath(name("rg")?),
BinaryCall::OnPath(name("node")?),
BinaryCall::AirslVersion,
]
);
Ok(())
}
#[test]
fn fake_binary_test_returns_script() -> TestResult {
let run = LuaTestRun {
success: false,
stdout: "1 passed\n".to_owned(),
stderr: "boom\n".to_owned(),
};
let binary = FakeBinary::new().airsl_test_run(run.clone());
assert_eq!(binary.airsl_test(Path::new("/work/ext"))?, run);
assert_eq!(
binary.asked(),
[BinaryCall::AirslTest(PathBuf::from("/work/ext"))]
);
let failing = FakeBinary::new().airsl_test_spawn_failure();
let Err(error) = failing.airsl_test(Path::new("/work/ext")) else {
return Err("a spawn failure".into());
};
assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
assert_eq!(error.to_string(), FakeBinary::denied().to_string());
Ok(())
}
}