pub fn err<InnerMatcherT>(inner: InnerMatcherT) -> __internal::ErrMatcher<InnerMatcherT> {
__internal::ErrMatcher { inner }
}
pub mod __internal {
use crate::{
description::Description,
matcher::{Describable, Matcher, MatcherResult},
};
use core::fmt::Debug;
#[doc(hidden)]
pub struct ErrMatcher<InnerMatcherT> {
pub(super) inner: InnerMatcherT,
}
impl<T: Debug, E: Debug, InnerMatcherT: Matcher<E>> Matcher<core::result::Result<T, E>>
for ErrMatcher<InnerMatcherT>
{
fn matches(&self, actual: &core::result::Result<T, E>) -> MatcherResult {
actual.as_ref().err().map(|v| self.inner.matches(v)).unwrap_or(MatcherResult::NoMatch)
}
fn explain_match(&self, actual: &core::result::Result<T, E>) -> Description {
match actual {
Err(e) => {
Description::new().text("which is an error").nested(self.inner.explain_match(e))
}
Ok(_) => "which is a success".into(),
}
}
}
impl<InnerMatcherT: Describable> Describable for ErrMatcher<InnerMatcherT> {
fn describe(&self, matcher_result: MatcherResult) -> Description {
match matcher_result {
MatcherResult::Match => {
format!("is an error which {}", self.inner.describe(MatcherResult::Match))
.into()
}
MatcherResult::NoMatch => format!(
"is a success or is an error containing a value which {}",
self.inner.describe(MatcherResult::NoMatch)
)
.into(),
}
}
}
}
#[cfg(test)]
mod tests {
use super::err;
use crate::matcher::{Matcher, MatcherResult};
use crate::prelude::*;
use indoc::indoc;
#[test]
fn err_matches_result_with_err_value() -> TestResult<()> {
let matcher = err(eq(1));
let value: core::result::Result<i32, i32> = Err(1);
let result = matcher.matches(&value);
verify_that!(result, eq(MatcherResult::Match))
}
#[test]
fn err_does_not_match_result_with_wrong_err_value() -> TestResult<()> {
let matcher = err(eq(1));
let value: core::result::Result<i32, i32> = Err(0);
let result = matcher.matches(&value);
verify_that!(result, eq(MatcherResult::NoMatch))
}
#[test]
fn err_does_not_match_result_with_ok() -> TestResult<()> {
let matcher = err(eq(1));
let value: core::result::Result<i32, i32> = Ok(1);
let result = matcher.matches(&value);
verify_that!(result, eq(MatcherResult::NoMatch))
}
#[test]
fn err_full_error_message() -> TestResult<()> {
let result = verify_that!(Err::<i32, i32>(1), err(eq(2)));
verify_that!(
result,
err(displays_as(contains_substring(indoc!(
"
Value of: Err::<i32, i32>(1)
Expected: is an error which is equal to 2
Actual: Err(1),
which is an error
which isn't equal to 2
"
))))
)
}
#[test]
fn err_describe_matches() -> TestResult<()> {
let result = verify_that!(Err::<i32, i32>(2), err(eq(1)));
verify_that!(
result,
err(displays_as(contains_substring("is an error which is equal to 1")))
)
}
}