|
1 |
| -use super::{const_io_error, Custom, Error, ErrorData, ErrorKind, Repr}; |
| 1 | +use super::{const_io_error, Custom, Error, ErrorData, ErrorKind, Repr, SimpleMessage}; |
2 | 2 | use crate::assert_matches::assert_matches;
|
3 | 3 | use crate::error;
|
4 | 4 | use crate::fmt;
|
@@ -141,3 +141,54 @@ fn test_custom_error_packing() {
|
141 | 141 | }) if error.downcast_ref::<Bojji>().as_deref() == Some(&Bojji(true)),
|
142 | 142 | );
|
143 | 143 | }
|
| 144 | + |
| 145 | +#[derive(Debug)] |
| 146 | +struct E; |
| 147 | + |
| 148 | +impl fmt::Display for E { |
| 149 | + fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 150 | + Ok(()) |
| 151 | + } |
| 152 | +} |
| 153 | + |
| 154 | +impl error::Error for E {} |
| 155 | + |
| 156 | +#[test] |
| 157 | +fn test_try_downcast_inner() { |
| 158 | + // Case 1: custom error, downcast succeeds |
| 159 | + let io_error = Error::new(ErrorKind::Other, Bojji(true)); |
| 160 | + let e: Box<Bojji> = io_error.try_downcast_inner().unwrap(); |
| 161 | + assert!(e.0); |
| 162 | + |
| 163 | + // Case 2: custom error, downcast fails |
| 164 | + let io_error = Error::new(ErrorKind::Other, Bojji(true)); |
| 165 | + let io_error = io_error.try_downcast_inner::<E>().unwrap_err(); |
| 166 | + |
| 167 | + // ensures that the custom error is intact |
| 168 | + assert_eq!(ErrorKind::Other, io_error.kind()); |
| 169 | + let e: Box<Bojji> = io_error.try_downcast_inner().unwrap(); |
| 170 | + assert!(e.0); |
| 171 | + |
| 172 | + // Case 3: os error |
| 173 | + let errno = 20; |
| 174 | + let io_error = Error::from_raw_os_error(errno); |
| 175 | + let io_error = io_error.try_downcast_inner::<E>().unwrap_err(); |
| 176 | + |
| 177 | + assert_eq!(errno, io_error.raw_os_error().unwrap()); |
| 178 | + |
| 179 | + // Case 4: simple |
| 180 | + let kind = ErrorKind::OutOfMemory; |
| 181 | + let io_error: Error = kind.into(); |
| 182 | + let io_error = io_error.try_downcast_inner::<E>().unwrap_err(); |
| 183 | + |
| 184 | + assert_eq!(kind, io_error.kind()); |
| 185 | + |
| 186 | + // Case 5: simple message |
| 187 | + const SIMPLE_MESSAGE: SimpleMessage = |
| 188 | + SimpleMessage { kind: ErrorKind::Other, message: "simple message error test" }; |
| 189 | + let io_error = Error::from_static_message(&SIMPLE_MESSAGE); |
| 190 | + let io_error = io_error.try_downcast_inner::<E>().unwrap_err(); |
| 191 | + |
| 192 | + assert_eq!(SIMPLE_MESSAGE.kind, io_error.kind()); |
| 193 | + assert_eq!(SIMPLE_MESSAGE.message, &*format!("{io_error}")); |
| 194 | +} |
0 commit comments