assert_not_modified/lib.rs
1//! Macro which, given a variable and a block of code, executes the block of code and checks that the
2//! variable has not changed.
3//!
4//! For instance, this can check that a function does not have side-effects.
5
6/// Given a variable and a block of code, executes the block of code and checks that the variable has not
7/// changed.
8///
9/// The given variable must implement Clone and Debug.
10///
11/// # Panics
12///
13/// Panics if data is modified with message "Data was modified where it should not have been".
14///
15/// # Example
16///
17///```
18/// #[macro_use] extern crate assert_not_modified;
19///
20/// // This function returns Err but modifies x anyway. This is misleading.
21/// fn modify_x_or_err(x: &mut i32) -> Result<(), String> {
22/// *x = *x + 1;
23/// Err("Something wrong happened !".to_owned())
24/// }
25///
26/// // This test will expose the lying function :
27/// assert!(std::panic::catch_unwind(|| {
28/// let mut x = 3;
29/// assert_not_modified!(x, modify_x_or_err(&mut x)); // Panics
30/// })
31/// .is_err());
32/// ```
33#[macro_export]
34macro_rules! assert_not_modified {
35 ($data: ident, $block_which_should_not_modify_data: expr) => {
36 let old_data = $data.clone();
37 let _ = $block_which_should_not_modify_data;
38 assert_eq!(
39 old_data, $data,
40 "Data was modified where it should not have been"
41 );
42 };
43}
44
45#[cfg(test)]
46mod tests {
47 #[test]
48 #[should_panic(expected = "Data was modified where it should not have been")]
49 fn test_should_not_modify_data_panics() {
50 let mut x = 4;
51 assert_not_modified!(x, x += 1);
52 }
53
54 #[test]
55 fn test_should_not_modify_data_does_not_panic() {
56 let mut x = 4;
57 assert_not_modified!(x, {
58 x += 1;
59 x -= 1;
60 });
61 }
62}