1 mod common;
2 mod drop;
3
4 use self::common::*;
5 use self::drop::{DetectDrop, Flag};
6 use anyhow::Error;
7 use std::error::Error as StdError;
8 use std::fmt::{self, Display};
9 use std::io;
10
11 #[test]
test_downcast()12 fn test_downcast() {
13 assert_eq!(
14 "oh no!",
15 bail_literal().unwrap_err().downcast::<&str>().unwrap(),
16 );
17 assert_eq!(
18 "oh no!",
19 bail_fmt().unwrap_err().downcast::<String>().unwrap(),
20 );
21 assert_eq!(
22 "oh no!",
23 bail_error()
24 .unwrap_err()
25 .downcast::<io::Error>()
26 .unwrap()
27 .to_string(),
28 );
29 }
30
31 #[test]
test_downcast_ref()32 fn test_downcast_ref() {
33 assert_eq!(
34 "oh no!",
35 *bail_literal().unwrap_err().downcast_ref::<&str>().unwrap(),
36 );
37 assert_eq!(
38 "oh no!",
39 bail_fmt().unwrap_err().downcast_ref::<String>().unwrap(),
40 );
41 assert_eq!(
42 "oh no!",
43 bail_error()
44 .unwrap_err()
45 .downcast_ref::<io::Error>()
46 .unwrap()
47 .to_string(),
48 );
49 }
50
51 #[test]
test_downcast_mut()52 fn test_downcast_mut() {
53 assert_eq!(
54 "oh no!",
55 *bail_literal().unwrap_err().downcast_mut::<&str>().unwrap(),
56 );
57 assert_eq!(
58 "oh no!",
59 bail_fmt().unwrap_err().downcast_mut::<String>().unwrap(),
60 );
61 assert_eq!(
62 "oh no!",
63 bail_error()
64 .unwrap_err()
65 .downcast_mut::<io::Error>()
66 .unwrap()
67 .to_string(),
68 );
69 }
70
71 #[test]
test_drop()72 fn test_drop() {
73 let has_dropped = Flag::new();
74 let error = Error::new(DetectDrop::new(&has_dropped));
75 drop(error.downcast::<DetectDrop>().unwrap());
76 assert!(has_dropped.get());
77 }
78
79 #[test]
test_large_alignment()80 fn test_large_alignment() {
81 #[repr(align(64))]
82 #[derive(Debug)]
83 struct LargeAlignedError(&'static str);
84
85 impl Display for LargeAlignedError {
86 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
87 f.write_str(self.0)
88 }
89 }
90
91 impl StdError for LargeAlignedError {}
92
93 let error = Error::new(LargeAlignedError("oh no!"));
94 assert_eq!(
95 "oh no!",
96 error.downcast_ref::<LargeAlignedError>().unwrap().0
97 );
98 }
99
100 #[test]
test_unsuccessful_downcast()101 fn test_unsuccessful_downcast() {
102 let mut error = bail_error().unwrap_err();
103 assert!(error.downcast_ref::<&str>().is_none());
104 assert!(error.downcast_mut::<&str>().is_none());
105 assert!(error.downcast::<&str>().is_err());
106 }
107