use std::fmt::Debug;
use std::panic::Location;
use proptest::collection::{SizeRange, vec};
use proptest::prelude::{BoxedStrategy, Strategy};
use proptest::test_runner::{Config, TestCaseError, TestError, TestRunner};
use super::prop_check_on;
use crate::Effect;
use crate::testing::TestExecutor;
pub trait StateMachine {
type State: Clone + Debug;
type Sut: Send + 'static;
type Command: Clone + Debug + 'static;
fn initial_state(&self) -> Self::State;
fn commands(&self) -> BoxedStrategy<Self::Command>;
fn precondition(&self, state: &Self::State, command: &Self::Command) -> bool {
let _ = (state, command);
true
}
fn next_state(&self, state: &Self::State, command: &Self::Command) -> Self::State;
fn init_sut(&self) -> Effect<Self::Sut, TestCaseError>;
fn apply(
&self,
sut: &Self::Sut,
command: &Self::Command,
before: &Self::State,
after: &Self::State,
) -> Effect<(), TestCaseError>;
}
pub fn commands<M: StateMachine>(
machine: &M,
size: impl Into<SizeRange>,
) -> impl Strategy<Value = Vec<M::Command>> {
vec(machine.commands(), size)
}
pub fn check_commands<M: StateMachine>(
machine: &M,
commands: &[M::Command],
) -> Result<(), TestCaseError> {
let exec = TestExecutor::new();
let sut = prop_check_on(&exec, machine.init_sut())?;
let mut state = machine.initial_state();
for (step, command) in commands.iter().enumerate() {
if !machine.precondition(&state, command) {
continue;
}
let next = machine.next_state(&state, command);
prop_check_on(&exec, machine.apply(&sut, command, &state, &next)).map_err(|e| match e {
TestCaseError::Fail(why) => {
TestCaseError::fail(format!("step {step} {command:?} (model {state:?}): {why}"))
}
reject => reject,
})?;
state = next;
}
Ok(())
}
#[track_caller]
pub fn run_state_machine<M: StateMachine>(machine: &M, config: Config, size: impl Into<SizeRange>) {
let mut config = config;
if config.source_file.is_none() {
config.source_file = Some(Location::caller().file());
}
let mut runner = TestRunner::new(config);
let result = runner.run(&commands(machine, size), |cmds| {
check_commands(machine, &cmds)
});
match result {
Ok(()) => {}
Err(TestError::Fail(why, cmds)) => {
panic!("state machine failed: {why}\nminimal failing commands: {cmds:#?}")
}
Err(TestError::Abort(why)) => panic!("state machine aborted: {why}"),
}
}
#[cfg(test)]
mod tests {
use std::collections::VecDeque;
use std::time::Duration;
use proptest::prelude::*;
use super::super::prop_sync;
use super::*;
use crate::{Queue, QueueError, sleep, succeed};
#[derive(Clone, Debug)]
enum Cmd {
Offer(u8),
Poll,
Wait(u64),
}
struct BoundedQueue {
cap: usize,
}
impl StateMachine for BoundedQueue {
type State = VecDeque<u8>;
type Sut = Queue<u8>;
type Command = Cmd;
fn initial_state(&self) -> VecDeque<u8> {
VecDeque::new()
}
fn commands(&self) -> BoxedStrategy<Cmd> {
prop_oneof![
any::<u8>().prop_map(Cmd::Offer),
Just(Cmd::Poll),
(1u64..100).prop_map(Cmd::Wait),
]
.boxed()
}
fn precondition(&self, state: &VecDeque<u8>, cmd: &Cmd) -> bool {
!matches!(cmd, Cmd::Offer(_)) || state.len() < self.cap
}
fn next_state(&self, state: &VecDeque<u8>, cmd: &Cmd) -> VecDeque<u8> {
let mut s = state.clone();
match cmd {
Cmd::Offer(n) => s.push_back(*n),
Cmd::Poll => {
s.pop_front();
}
Cmd::Wait(_) => {}
}
s
}
fn init_sut(&self) -> Effect<Queue<u8>, TestCaseError> {
succeed(Queue::bounded(self.cap))
}
fn apply(
&self,
q: &Queue<u8>,
cmd: &Cmd,
before: &VecDeque<u8>,
after: &VecDeque<u8>,
) -> Effect<(), TestCaseError> {
let expected_front = before.front().copied();
let expected_len = after.len();
let q2 = q.clone();
let step: Effect<(), TestCaseError> = match cmd {
Cmd::Offer(n) => q.offer(*n).map(|_| ()),
Cmd::Poll => q
.poll()
.map_err(|e: QueueError| TestCaseError::fail(format!("{e:?}")))
.flat_map(move |got| {
prop_sync(move || {
prop_assert_eq!(got, expected_front);
Ok(())
})
}),
Cmd::Wait(ms) => sleep(Duration::from_millis(*ms)),
};
step.then(q2.size()).flat_map(move |len| {
prop_sync(move || {
prop_assert_eq!(len, expected_len);
Ok(())
})
})
}
}
#[test]
fn bounded_queue_matches_its_model() {
run_state_machine(&BoundedQueue { cap: 3 }, Config::with_cases(64), 0..40);
}
proptest! {
#[test]
fn check_commands_inside_proptest(cmds in commands(&BoundedQueue { cap: 2 }, 0..20)) {
check_commands(&BoundedQueue { cap: 2 }, &cmds)?;
}
}
struct WrongModel;
impl StateMachine for WrongModel {
type State = usize;
type Sut = Queue<u8>;
type Command = u8;
fn initial_state(&self) -> usize {
0
}
fn commands(&self) -> BoxedStrategy<u8> {
any::<u8>().boxed()
}
fn next_state(&self, state: &usize, _cmd: &u8) -> usize {
(state + 1).min(1)
}
fn init_sut(&self) -> Effect<Queue<u8>, TestCaseError> {
succeed(Queue::unbounded())
}
fn apply(
&self,
q: &Queue<u8>,
cmd: &u8,
_: &usize,
after: &usize,
) -> Effect<(), TestCaseError> {
let expected = *after;
q.offer(*cmd).then(q.size()).flat_map(move |len| {
prop_sync(move || {
prop_assert_eq!(len, expected);
Ok(())
})
})
}
}
#[test]
fn a_failing_machine_shrinks_to_two_commands() {
let config = Config {
failure_persistence: None,
..Config::with_cases(64)
};
let run = std::panic::AssertUnwindSafe(|| run_state_machine(&WrongModel, config, 0..20));
let panic = std::panic::catch_unwind(run).expect_err("the wrong model must fail");
let msg = panic.downcast_ref::<String>().cloned().unwrap_or_default();
assert!(msg.contains("step 1"), "{msg}");
assert!(
msg.contains("minimal failing commands: [\n 0,\n 0,\n]"),
"{msg}"
);
}
#[test]
fn check_commands_skips_commands_whose_precondition_fails() {
let machine = BoundedQueue { cap: 1 };
let cmds = [Cmd::Offer(1), Cmd::Offer(2), Cmd::Poll, Cmd::Poll];
assert!(check_commands(&machine, &cmds).is_ok());
}
}