| 1 |
#![allow( |
| 2 |
clippy::assertions_on_result_states, |
| 3 |
clippy::eq_op, |
| 4 |
clippy::items_after_statements, |
| 5 |
clippy::needless_pass_by_value, |
| 6 |
clippy::shadow_unrelated, |
| 7 |
clippy::wildcard_imports |
| 8 |
)] |
| 9 |
|
| 10 |
mod common; |
| 11 |
|
| 12 |
use self::common::*; |
| 13 |
use anyhow::{anyhow, ensure}; |
| 14 |
use std::cell::Cell; |
| 15 |
use std::future; |
| 16 |
|
| 17 |
#[test] |
| 18 |
fn test_messages() { |
| 19 |
assert_eq!("oh no!", bail_literal().unwrap_err().to_string()); |
| 20 |
assert_eq!("oh no!", bail_fmt().unwrap_err().to_string()); |
| 21 |
assert_eq!("oh no!", bail_error().unwrap_err().to_string()); |
| 22 |
} |
| 23 |
|
| 24 |
#[test] |
| 25 |
fn test_ensure() { |
| 26 |
let f = || { |
| 27 |
ensure!(1 + 1 == 2, "This is correct"); |
| 28 |
Ok(()) |
| 29 |
}; |
| 30 |
assert!(f().is_ok()); |
| 31 |
|
| 32 |
let v = 1; |
| 33 |
let f = || { |
| 34 |
ensure!(v + v == 2, "This is correct, v: {}", v); |
| 35 |
Ok(()) |
| 36 |
}; |
| 37 |
assert!(f().is_ok()); |
| 38 |
|
| 39 |
let f = || { |
| 40 |
ensure!(v + v == 1, "This is not correct, v: {}", v); |
| 41 |
Ok(()) |
| 42 |
}; |
| 43 |
assert!(f().is_err()); |
| 44 |
|
| 45 |
let f = || { |
| 46 |
ensure!(v + v == 1); |
| 47 |
Ok(()) |
| 48 |
}; |
| 49 |
assert_eq!( |
| 50 |
f().unwrap_err().to_string(), |
| 51 |
"Condition failed: `v + v == 1` (2 vs 1)", |
| 52 |
); |
| 53 |
} |
| 54 |
|
| 55 |
#[test] |
| 56 |
fn test_temporaries() { |
| 57 |
fn require_send_sync(_: impl Send + Sync) {} |
| 58 |
|
| 59 |
require_send_sync(async { |
| 60 |
// If anyhow hasn't dropped any temporary format_args it creates by the |
| 61 |
// time it's done evaluating, those will stick around until the |
| 62 |
// semicolon, which is on the other side of the await point, making the |
| 63 |
// enclosing future non-Send. |
| 64 |
future::ready(anyhow!("...")).await; |
| 65 |
}); |
| 66 |
|
| 67 |
fn message(cell: Cell<&str>) -> &str { |
| 68 |
cell.get() |
| 69 |
} |
| 70 |
|
| 71 |
require_send_sync(async { |
| 72 |
future::ready(anyhow!(message(Cell::new("...")))).await; |
| 73 |
}); |
| 74 |
} |
| 75 |
|
| 76 |
#[test] |
| 77 |
fn test_brace_escape() { |
| 78 |
let err = anyhow!("unterminated ${{..}} expression"); |
| 79 |
assert_eq!("unterminated ${..} expression", err.to_string()); |
| 80 |
} |