1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
use std::cell::RefCell;
use std::thread_local;
thread_local! {
#[doc(hidden)]
pub static FAILURES: RefCell<Vec<String>> = RefCell::new(Vec::new());
}
#[macro_export]
macro_rules! expect {
($cond:expr) => {{
expect!($cond, "Expected {}", stringify!($cond));
}};
($cond:expr, $($arg:tt)+) => {{
if !($cond) {
$crate::FAILURES.with(|cell| cell.borrow_mut().push(format!($($arg)*)));
}
}};
}
#[macro_export]
macro_rules! let_fail {
() => {
use std::fmt::Write;
$crate::FAILURES.with(|cell| {
let f = cell.borrow_mut();
if f.len() > 0 {
let mut msg = format!("`expect` test failed with {} failed assertions:\n", f.len());
f.iter()
.enumerate()
.for_each(|x| writeln!(msg, "{}: {}", x.0 + 1, x.1).unwrap());
panic!(msg);
} else {
println!("`expect` test passed.");
}
});
};
}
#[test]
#[should_panic]
fn expect_failures() {
let x = 4;
let y = "is not";
let z = 5;
expect!(2 + 2 == 5, "{} surely {} {}", x, y, z);
expect!(1 + 1 == 2);
expect!(3 - 7 == -4);
expect!(3 - 7 == -3);
let_fail!();
}
#[test]
fn expect_pass() {
let x = 4;
let y = "is not";
let z = 5;
expect!(2 + 2 == 4, "{} surely {} {}", x, y, z);
expect!(1 + 1 == 2);
expect!(3 - 7 == -4);
expect!(3 - 7 == -4);
let_fail!();
}