Skip to content

Commit d2211c9

Browse files
committed
Add new unit test test_try_downcast_inner
Signed-off-by: Jiahao XU <[email protected]>
1 parent e0ea0c2 commit d2211c9

File tree

1 file changed

+52
-1
lines changed

1 file changed

+52
-1
lines changed

library/std/src/io/error/tests.rs

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use super::{const_io_error, Custom, Error, ErrorData, ErrorKind, Repr};
1+
use super::{const_io_error, Custom, Error, ErrorData, ErrorKind, Repr, SimpleMessage};
22
use crate::assert_matches::assert_matches;
33
use crate::error;
44
use crate::fmt;
@@ -141,3 +141,54 @@ fn test_custom_error_packing() {
141141
}) if error.downcast_ref::<Bojji>().as_deref() == Some(&Bojji(true)),
142142
);
143143
}
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

Comments
 (0)