pi_result 0.2.0

Thin, typed, and observable Result aliases and error interoperability utilities
Documentation
//! 测试断言辅助。
//!
//! 本模块提供面向 `pi_result` 使用场景的简洁断言函数,避免在单元测试和
//! 集成测试中反复书写样板代码。

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}"
    );
}

/// 断言公共错误中包含指定 typed context。
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)
    );
}

/// 断言公共错误中包含指定 attachment。
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);
    }
}