use crate::base::{AssertionApi, AssertionResult, AssertionStrategy, Subject};
use crate::StringAssertion;
pub trait AnyhowErrorAssertion<R> {
fn as_string(&self) -> Subject<String, (), R>;
#[track_caller]
fn has_message<E: Into<String>>(&self, expected: E) -> R;
}
impl<R> AnyhowErrorAssertion<R> for Subject<'_, anyhow::Error, (), R>
where
AssertionResult: AssertionStrategy<R>,
{
fn as_string(&self) -> Subject<String, (), R> {
let message = self.actual().to_string();
self.new_owned_subject(message, Some(format!("{}.to_string()", self.description_or_expr())), ())
}
fn has_message<E: Into<String>>(&self, expected: E) -> R {
self.as_string().is_same_string_to(expected)
}
}
#[cfg(test)]
mod tests {
use crate::testing::*;
use super::*;
#[test]
fn as_string() {
assert_that!(anyhow::Error::msg("error message")).as_string().is_same_string_to("error message");
assert_that!(anyhow::Error::msg("error message")).as_string().starts_with("error");
assert_that!(anyhow::Error::msg("error message")).as_string().contains("or");
assert_that!(check_that!(anyhow::Error::msg("error message")).as_string().is_same_string_to("wrong")).facts_are(
vec![
Fact::new("expected", "\"wrong\""),
Fact::new("actual", "\"error message\""),
]
);
}
#[test]
fn has_message() {
assert_that!(anyhow::Error::msg("error message")).has_message("error message");
assert_that!(check_that!(anyhow::Error::msg("error message")).has_message("wrong")).facts_are(
vec![
Fact::new("expected", "\"wrong\""),
Fact::new("actual", "\"error message\""),
]
);
}
}