use crate::borrow::BorrowedOrOwned;
use crate::expectation_list::ExpectationList;
use crate::{CheckResult, Expectation, ExpectationBuilder};
use std::fmt::Debug;
pub struct RootExpectations<'e, T: Debug> {
value: BorrowedOrOwned<'e, T>,
expectations: ExpectationList<'e, T>,
}
impl<'e, T: Debug> RootExpectations<'e, T> {
pub fn new(value: T) -> Self {
RootExpectations {
expectations: ExpectationList::new(),
value: BorrowedOrOwned::Owned(value),
}
}
pub fn new_ref(value: &'e T) -> Self {
RootExpectations {
expectations: ExpectationList::new(),
value: BorrowedOrOwned::Borrowed(value),
}
}
pub fn check(self) {
drop(self)
}
}
impl<'e, T: Debug + 'e> ExpectationBuilder<'e> for RootExpectations<'e, T> {
type Value = T;
fn to_pass(mut self, expectation: impl Expectation<T> + 'e) -> Self {
self.expectations.push(expectation);
self
}
}
impl<'e, T: Debug> Drop for RootExpectations<'e, T> {
fn drop(&mut self) {
let value = self.value.borrow_self();
if let CheckResult::Fail(message) = self.expectations.check(value) {
panic!("{}", message);
}
}
}
#[cfg(test)]
mod tests {
use crate::tests::TestExpectation;
use crate::{CheckResult, ExpectationBuilder, expect, expect_ref};
#[test]
pub fn that_assert_runs_an_expectation() {
let (expectation, expected) = TestExpectation::new(CheckResult::Pass);
let expectations = expect(true).to_pass(expectation);
expectations.check();
assert!(*expected.lock().unwrap());
}
#[test]
pub fn that_assert_works_on_references() {
let (expectation, _) = TestExpectation::new(CheckResult::Pass);
let value = true;
expect_ref(&value).to_pass(expectation);
}
#[test]
pub fn that_check_runs_all_expectations() {
let (expectation1, expected1) = TestExpectation::new(CheckResult::Pass);
let (expectation2, expected2) = TestExpectation::new(CheckResult::Pass);
let expectations = expect(true).to_pass(expectation1).to_pass(expectation2);
expectations.check();
assert!(*expected1.lock().unwrap());
assert!(*expected2.lock().unwrap());
}
#[test]
#[should_panic]
pub fn that_failure_panics() {
let (expectation, _) = TestExpectation::new(CheckResult::Fail("message".to_owned()));
let expectations = expect(true).to_pass(expectation);
expectations.check();
}
}