From b756cb948f64416c2f5fd280a971bc7daa3bddea Mon Sep 17 00:00:00 2001 From: Martin Pitt Date: Wed, 25 Aug 2021 08:36:47 +0200 Subject: [PATCH] Replace unsafe test code with global_counter https://docs.rs/crate/global_counter --- Cargo.toml | 1 + tests/test_lib.rs | 30 +++++++++++++++--------------- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index a642e49..2ec172e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,3 +6,4 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +global_counter = { version = "0.2.2", default-features = false } diff --git a/tests/test_lib.rs b/tests/test_lib.rs index 186ffd7..af9bbe2 100644 --- a/tests/test_lib.rs +++ b/tests/test_lib.rs @@ -1,3 +1,6 @@ +#[macro_use] +extern crate global_counter; + use learning::*; #[test] @@ -7,45 +10,42 @@ fn test_longest() { assert_eq!(longest("abc", "defg"), "defg"); } -// FIXME: How to make this not unsafe? -static mut CALLED: u32 = 0; - #[test] fn test_cacher_int_int() { - unsafe { CALLED = 0; } + global_default_counter!(CALLED, u32); let mut cacher = Cacher::new(|x| { - unsafe { CALLED += 1; } + CALLED.inc(); 2 * x }); assert_eq!(cacher.value(1), 2); - unsafe { assert_eq!(CALLED, 1); } + assert_eq!(CALLED.get_cloned(), 1); // second time cached assert_eq!(cacher.value(1), 2); - unsafe { assert_eq!(CALLED, 1); } + assert_eq!(CALLED.get_cloned(), 1); // re-evaluated for new value assert_eq!(cacher.value(-2), -4); - unsafe { assert_eq!(CALLED, 2); } + assert_eq!(CALLED.get_cloned(), 2); // old arg still cached assert_eq!(cacher.value(1), 2); - unsafe { assert_eq!(CALLED, 2); } + assert_eq!(CALLED.get_cloned(), 2); } #[test] fn test_cacher_str_usize() { - unsafe { CALLED = 0; } + global_default_counter!(CALLED, u32); let mut cacher = Cacher::new(|x: &str| { - unsafe { CALLED += 1; } + CALLED.inc(); x.len() }); assert_eq!(cacher.value("abc"), 3); - unsafe { assert_eq!(CALLED, 1); } + assert_eq!(CALLED.get_cloned(), 1); // second time cached assert_eq!(cacher.value("abc"), 3); - unsafe { assert_eq!(CALLED, 1); } + assert_eq!(CALLED.get_cloned(), 1); // re-evaluated for new value assert_eq!(cacher.value("defg"), 4); - unsafe { assert_eq!(CALLED, 2); } + assert_eq!(CALLED.get_cloned(), 2); // old arg still cached assert_eq!(cacher.value("abc"), 3); - unsafe { assert_eq!(CALLED, 2); } + assert_eq!(CALLED.get_cloned(), 2); } -- 2.39.5