1 use anyhow::{bail, Context, Result};
2 use std::io;
3
f() -> Result<()>4 fn f() -> Result<()> {
5 bail!(io::Error::new(io::ErrorKind::PermissionDenied, "oh no!"));
6 }
7
g() -> Result<()>8 fn g() -> Result<()> {
9 f().context("f failed")
10 }
11
h() -> Result<()>12 fn h() -> Result<()> {
13 g().context("g failed")
14 }
15
16 const EXPECTED_ALTDISPLAY_F: &str = "oh no!";
17
18 const EXPECTED_ALTDISPLAY_G: &str = "f failed: oh no!";
19
20 const EXPECTED_ALTDISPLAY_H: &str = "g failed: f failed: oh no!";
21
22 const EXPECTED_DEBUG_F: &str = "oh no!";
23
24 const EXPECTED_DEBUG_G: &str = "\
25 f failed
26
27 Caused by:
28 oh no!\
29 ";
30
31 const EXPECTED_DEBUG_H: &str = "\
32 g failed
33
34 Caused by:
35 0: f failed
36 1: oh no!\
37 ";
38
39 const EXPECTED_ALTDEBUG_F: &str = "\
40 Custom {
41 kind: PermissionDenied,
42 error: \"oh no!\",
43 }\
44 ";
45
46 const EXPECTED_ALTDEBUG_G: &str = "\
47 Error {
48 context: \"f failed\",
49 source: Custom {
50 kind: PermissionDenied,
51 error: \"oh no!\",
52 },
53 }\
54 ";
55
56 const EXPECTED_ALTDEBUG_H: &str = "\
57 Error {
58 context: \"g failed\",
59 source: Error {
60 context: \"f failed\",
61 source: Custom {
62 kind: PermissionDenied,
63 error: \"oh no!\",
64 },
65 },
66 }\
67 ";
68
69 #[test]
test_display()70 fn test_display() {
71 assert!(h().unwrap_err().to_string().starts_with("g failed"));
72 }
73
74 #[test]
test_altdisplay()75 fn test_altdisplay() {
76 assert!(format!("{:#}", f().unwrap_err()).starts_with(EXPECTED_ALTDISPLAY_F));
77 assert!(format!("{:#}", g().unwrap_err()).starts_with(EXPECTED_ALTDISPLAY_G));
78 assert!(format!("{:#}", h().unwrap_err()).starts_with(EXPECTED_ALTDISPLAY_H));
79 }
80
81 #[test]
82 #[cfg_attr(not(std_backtrace), ignore)]
test_debug()83 fn test_debug() {
84 assert!(format!("{:?}", f().unwrap_err()).starts_with(EXPECTED_DEBUG_F));
85 assert!(format!("{:?}", g().unwrap_err()).starts_with(EXPECTED_DEBUG_G));
86 assert!(format!("{:?}", h().unwrap_err()).starts_with(EXPECTED_DEBUG_H));
87 }
88
89 #[test]
test_altdebug()90 fn test_altdebug() {
91 assert!(format!("{:#?}", f().unwrap_err()).starts_with(EXPECTED_ALTDEBUG_F));
92 assert!(format!("{:#?}", g().unwrap_err()).starts_with(EXPECTED_ALTDEBUG_G));
93 assert!(format!("{:#?}", h().unwrap_err()).starts_with(EXPECTED_ALTDEBUG_H));
94 }
95