| 1 |
use anyhow::anyhow; |
| 2 |
use std::error::Error as StdError; |
| 3 |
use std::fmt::{self, Display}; |
| 4 |
use std::io; |
| 5 |
|
| 6 |
#[derive(Debug)] |
| 7 |
enum TestError { |
| 8 |
Io(io::Error), |
| 9 |
} |
| 10 |
|
| 11 |
impl Display for TestError { |
| 12 |
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { |
| 13 |
match self { |
| 14 |
TestError::Io(e) => Display::fmt(e, formatter), |
| 15 |
} |
| 16 |
} |
| 17 |
} |
| 18 |
|
| 19 |
impl StdError for TestError { |
| 20 |
fn source(&self) -> Option<&(dyn StdError + 'static)> { |
| 21 |
match self { |
| 22 |
TestError::Io(io) => Some(io), |
| 23 |
} |
| 24 |
} |
| 25 |
} |
| 26 |
|
| 27 |
#[test] |
| 28 |
fn test_literal_source() { |
| 29 |
let error = anyhow!("oh no!"); |
| 30 |
assert!(error.source().is_none()); |
| 31 |
} |
| 32 |
|
| 33 |
#[test] |
| 34 |
fn test_variable_source() { |
| 35 |
let msg = "oh no!"; |
| 36 |
let error = anyhow!(msg); |
| 37 |
assert!(error.source().is_none()); |
| 38 |
|
| 39 |
let msg = msg.to_owned(); |
| 40 |
let error = anyhow!(msg); |
| 41 |
assert!(error.source().is_none()); |
| 42 |
} |
| 43 |
|
| 44 |
#[test] |
| 45 |
fn test_fmt_source() { |
| 46 |
let error = anyhow!("{} {}!", "oh", "no"); |
| 47 |
assert!(error.source().is_none()); |
| 48 |
} |
| 49 |
|
| 50 |
#[test] |
| 51 |
fn test_io_source() { |
| 52 |
let io = io::Error::new(io::ErrorKind::Other, "oh no!"); |
| 53 |
let error = anyhow!(TestError::Io(io)); |
| 54 |
assert_eq!("oh no!", error.source().unwrap().to_string()); |
| 55 |
} |
| 56 |
|
| 57 |
#[test] |
| 58 |
fn test_anyhow_from_anyhow() { |
| 59 |
let error = anyhow!("oh no!").context("context"); |
| 60 |
let error = anyhow!(error); |
| 61 |
assert_eq!("oh no!", error.source().unwrap().to_string()); |
| 62 |
} |