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