Skip to main content

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    ///
9    /// # Examples
10    ///
11    /// ```
12    /// use fluent_assertions::*;
13    /// std::io::Error::other("boom")
14    ///     .should()
15    ///     .match_error(std::io::Error::other("boom"));
16    /// ```
17    #[track_caller]
18    pub fn match_error<T: Error + Debug>(self, error: T) -> Self {
19        assert!(
20            self.value.to_string() == error.to_string(),
21            "Expected error to be {:?}, but got {:?}",
22            error,
23            self.value
24        );
25        self
26    }
27
28    /// Asserts that the error message contains the given message
29    ///
30    /// # Examples
31    ///
32    /// ```
33    /// use fluent_assertions::*;
34    /// std::io::Error::other("boom happened").should().contain_message("boom");
35    /// ```
36    #[track_caller]
37    pub fn contain_message(self, expected_message: &str) -> Self {
38        let error_message = self.value.to_string();
39        assert!(
40            error_message.contains(expected_message),
41            "Expected error message to contain '{}', but was '{}'",
42            expected_message,
43            error_message
44        );
45        self
46    }
47}
48
49#[cfg(test)]
50mod tests {
51    use super::*;
52    use crate::assertions::*;
53
54    // Example custom error type for testing
55    #[derive(Debug)]
56    struct MyError(String);
57
58    impl std::fmt::Display for MyError {
59        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60            write!(f, "MyError: {}", self.0)
61        }
62    }
63
64    impl Error for MyError {}
65
66    #[test]
67    fn should_match_error() {
68        let error = MyError("test error".to_string());
69        error
70            .should()
71            .match_error(MyError("test error".to_string()))
72            .contain_message("test error");
73    }
74
75    #[test]
76    fn should_contain_error_message() {
77        let error = MyError("test error".to_string());
78        error.should().contain_message("test error");
79    }
80
81    #[test]
82    #[should_panic(expected = "Expected error message to contain 'wrong message'")]
83    fn should_be_wrong_message() {
84        let error = MyError("test error".to_string());
85        error.should().contain_message("wrong message");
86    }
87}