fluent_assertions/assertions/
error_assertion.rs

1use crate::Assertion;
2use std::error::Error;
3use std::fmt::Debug;
4
5// Specific assertions for Error types
6impl<E: Error> Assertion<E> {
7    /// Asserts that the error is equal to the given error
8    pub fn match_error<T: Error + Debug>(self, error: T) -> Self {
9        assert!(
10            self.value.to_string() == error.to_string(),
11            "Expected error to be {:?}, but got {:?}",
12            error,
13            self.value
14        );
15        self
16    }
17
18    /// Asserts that the error message contains the given message
19    pub fn contain_message(self, expected_message: &str) -> Self {
20        let error_message = self.value.to_string();
21        assert!(
22            error_message.contains(expected_message),
23            "Expected error message to contain '{}', but was '{}'",
24            expected_message,
25            error_message
26        );
27        self
28    }
29}
30
31#[cfg(test)]
32mod tests {
33    use super::*;
34    use crate::assertions::*;
35
36    // Example custom error type for testing
37    #[derive(Debug)]
38    struct MyError(String);
39
40    impl std::fmt::Display for MyError {
41        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42            write!(f, "MyError: {}", self.0)
43        }
44    }
45
46    impl Error for MyError {}
47
48    #[test]
49    fn should_match_error() {
50        let error = MyError("test error".to_string());
51        error
52            .should()
53            .match_error(MyError("test error".to_string()))
54            .contain_message("test error");
55    }
56
57    #[test]
58    fn should_contain_error_message() {
59        let error = MyError("test error".to_string());
60        error.should().contain_message("test error");
61    }
62
63    #[test]
64    #[should_panic(expected = "Expected error message to contain 'wrong message'")]
65    fn should_be_wrong_message() {
66        let error = MyError("test error".to_string());
67        error.should().contain_message("wrong message");
68    }
69}