fluent_assertions/assertions/
error_assertion.rs1use crate::Assertion;
2use std::error::Error;
3use std::fmt::Debug;
4
5impl<E: Error> Assertion<E> {
7 #[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 #[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 #[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}