1 use anyhow::anyhow;
2 use std::error::Error as _;
3 use std::io;
4 use thiserror::Error;
5
6 #[test]
test_transparent_struct()7 fn test_transparent_struct() {
8 #[derive(Error, Debug)]
9 #[error(transparent)]
10 struct Error(ErrorKind);
11
12 #[derive(Error, Debug)]
13 enum ErrorKind {
14 #[error("E0")]
15 E0,
16 #[error("E1")]
17 E1(#[from] io::Error),
18 }
19
20 let error = Error(ErrorKind::E0);
21 assert_eq!("E0", error.to_string());
22 assert!(error.source().is_none());
23
24 let io = io::Error::new(io::ErrorKind::Other, "oh no!");
25 let error = Error(ErrorKind::from(io));
26 assert_eq!("E1", error.to_string());
27 error.source().unwrap().downcast_ref::<io::Error>().unwrap();
28 }
29
30 #[test]
test_transparent_enum()31 fn test_transparent_enum() {
32 #[derive(Error, Debug)]
33 enum Error {
34 #[error("this failed")]
35 This,
36 #[error(transparent)]
37 Other(anyhow::Error),
38 }
39
40 let error = Error::This;
41 assert_eq!("this failed", error.to_string());
42
43 let error = Error::Other(anyhow!("inner").context("outer"));
44 assert_eq!("outer", error.to_string());
45 assert_eq!("inner", error.source().unwrap().to_string());
46 }
47
48 #[test]
test_transparent_enum_with_default_message()49 fn test_transparent_enum_with_default_message() {
50 #[derive(Error, Debug)]
51 #[error("this failed: {0}_{1}")]
52 enum Error {
53 This(i32, i32),
54 #[error(transparent)]
55 Other(anyhow::Error),
56 }
57
58 let error = Error::This(-1, -1);
59 assert_eq!("this failed: -1_-1", error.to_string());
60
61 let error = Error::Other(anyhow!("inner").context("outer"));
62 assert_eq!("outer", error.to_string());
63 assert_eq!("inner", error.source().unwrap().to_string());
64 }
65
66 #[test]
test_anyhow()67 fn test_anyhow() {
68 #[derive(Error, Debug)]
69 #[error(transparent)]
70 struct Any(#[from] anyhow::Error);
71
72 let error = Any::from(anyhow!("inner").context("outer"));
73 assert_eq!("outer", error.to_string());
74 assert_eq!("inner", error.source().unwrap().to_string());
75 }
76
77 #[test]
test_non_static()78 fn test_non_static() {
79 #[derive(Error, Debug)]
80 #[error(transparent)]
81 struct Error<'a> {
82 inner: ErrorKind<'a>,
83 }
84
85 #[derive(Error, Debug)]
86 enum ErrorKind<'a> {
87 #[error("unexpected token: {:?}", token)]
88 Unexpected { token: &'a str },
89 }
90
91 let error = Error {
92 inner: ErrorKind::Unexpected { token: "error" },
93 };
94 assert_eq!("unexpected token: \"error\"", error.to_string());
95 assert!(error.source().is_none());
96 }
97