Skip to content

Commit 7cf4af0

Browse files
committed
util: unit tests for retry_loop()
Signed-off-by: james-parky <[email protected]>
1 parent a53a13a commit 7cf4af0

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

src/util.rs

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,52 @@ where
3939

4040
func()
4141
}
42+
43+
#[cfg(test)]
44+
mod tests {
45+
use std::cell::Cell;
46+
use super::*;
47+
48+
#[test]
49+
fn test_success_first_try() {
50+
let res: Result<(), ()> = retry_loop(|| Ok(()), 3);
51+
assert_eq!(res, Ok(()));
52+
}
53+
54+
#[test]
55+
fn test_fail_first_try() {
56+
let res: Result<i32, ()> = retry_loop(|| Err(()), 3);
57+
assert_eq!(res, Err(()));
58+
}
59+
60+
#[test]
61+
fn test_success_after_some_retries() {
62+
let attempts = Cell::new(0);
63+
64+
let mut func = || {
65+
let current: u8 = attempts.get();
66+
attempts.set(current.wrapping_add(1));
67+
if current < 2 {
68+
Err(())
69+
} else {
70+
Ok(())
71+
}
72+
};
73+
74+
let res = retry_loop(&mut func, 5);
75+
assert_eq!(res, Ok(()));
76+
assert_eq!(attempts.get(), 3);
77+
}
78+
79+
#[test]
80+
fn test_fail_after_max_tries() {
81+
let attempts = Cell::new(0);
82+
let mut func = || {
83+
attempts.set(attempts.get() + 1);
84+
Err(())
85+
};
86+
let res: Result<(), ()> = retry_loop(&mut func, 5);
87+
assert_eq!(res, Err(()));
88+
assert_eq!(attempts.get(), 5);
89+
}
90+
}

0 commit comments

Comments
 (0)