use crate::{
Error, ErrorKind, ErrorReport,
fmt::debug_message,
inspect::{ErrorInspectExt, contains_type},
};
pub fn assert_kind(report: &Error, expected: ErrorKind) {
assert_eq!(
*report.current_kind(),
expected,
"unexpected error kind\nexpected: {expected:?}\nactual: {:?}\nreport:\n{}",
report.current_kind(),
debug_message(report)
);
}
pub fn assert_contains_text<C>(report: &ErrorReport<C>, needle: &str)
where
C: Send + Sync + 'static,
{
let text = format!("{report:?}");
assert!(
text.contains(needle),
"report did not contain expected text: {needle}\nreport:\n{text}"
);
}
pub fn assert_has_context<C>(report: &Error)
where
C: Send + Sync + 'static,
{
assert!(
report.contains_context::<C>(),
"report did not contain expected context `{}`\nreport:\n{}",
core::any::type_name::<C>(),
debug_message(report)
);
}
pub fn assert_has_attachment<A>(report: &Error)
where
A: Send + Sync + 'static,
{
assert!(
contains_type::<ErrorKind, A>(report),
"report did not contain expected attachment `{}`\nreport:\n{}",
core::any::type_name::<A>(),
debug_message(report)
);
}
#[cfg(test)]
mod tests {
use super::{assert_contains_text, assert_has_attachment, assert_has_context, assert_kind};
use crate::{Error, ErrorKind, attachment::Operation};
use error_stack::Report;
use thiserror::Error;
#[derive(Debug, Error)]
#[error("decode failed")]
struct DecodeContext;
#[test]
fn test_assert_kind_accepts_matching_kind() {
let report: Error = Report::new(ErrorKind::Timeout);
assert_kind(&report, ErrorKind::Timeout);
}
#[test]
fn test_assert_contains_text_accepts_matching_text() {
let report: Error = Report::new(ErrorKind::Internal).attach(Operation("decode"));
assert_contains_text(&report, "decode");
}
#[test]
fn test_assert_has_context_accepts_matching_context() {
let report: Error = Report::new(DecodeContext).change_context(ErrorKind::Internal);
assert_has_context::<DecodeContext>(&report);
}
#[test]
fn test_assert_has_attachment_accepts_matching_attachment() {
let report: Error = Report::new(ErrorKind::Dependency).attach(Operation("load"));
assert_has_attachment::<Operation>(&report);
}
}