Debian Codegraph @

.cargo/vendor/anyhow/tests/test_macros.rs

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