• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_anyhow()49 fn test_anyhow() {
50     #[derive(Error, Debug)]
51     #[error(transparent)]
52     struct Any(#[from] anyhow::Error);
53 
54     let error = Any::from(anyhow!("inner").context("outer"));
55     assert_eq!("outer", error.to_string());
56     assert_eq!("inner", error.source().unwrap().to_string());
57 }
58 
59 #[test]
test_non_static()60 fn test_non_static() {
61     #[derive(Error, Debug)]
62     #[error(transparent)]
63     struct Error<'a> {
64         inner: ErrorKind<'a>,
65     }
66 
67     #[derive(Error, Debug)]
68     enum ErrorKind<'a> {
69         #[error("unexpected token: {:?}", token)]
70         Unexpected { token: &'a str },
71     }
72 
73     let error = Error {
74         inner: ErrorKind::Unexpected { token: "error" },
75     };
76     assert_eq!("unexpected token: \"error\"", error.to_string());
77     assert!(error.source().is_none());
78 }
79