From: Martin Pitt Date: Sun, 29 Aug 2021 06:49:44 +0000 (+0200) Subject: concepts: Rewrite Cacher tests using RefCell X-Git-Url: https://piware.de/gitweb/?p=learn-rust.git;a=commitdiff_plain;h=104293d702699d7338144e3fe6384a283a1e5db2;hp=b653e9fe9d8492f2d4b5419721f7e00b392055f9 concepts: Rewrite Cacher tests using RefCell Avoids an external crate. --- diff --git a/concepts/Cargo.toml b/concepts/Cargo.toml index 2ec172e..a642e49 100644 --- a/concepts/Cargo.toml +++ b/concepts/Cargo.toml @@ -6,4 +6,3 @@ 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/concepts/tests/test_lib.rs b/concepts/tests/test_lib.rs index af9bbe2..402f187 100644 --- a/concepts/tests/test_lib.rs +++ b/concepts/tests/test_lib.rs @@ -1,5 +1,4 @@ -#[macro_use] -extern crate global_counter; +use std::cell::RefCell; use learning::*; @@ -12,40 +11,40 @@ fn test_longest() { #[test] fn test_cacher_int_int() { - global_default_counter!(CALLED, u32); + let called = RefCell::new(0); let mut cacher = Cacher::new(|x| { - CALLED.inc(); + *(called.borrow_mut()) += 1; 2 * x }); assert_eq!(cacher.value(1), 2); - assert_eq!(CALLED.get_cloned(), 1); + assert_eq!(*called.borrow(), 1); // second time cached assert_eq!(cacher.value(1), 2); - assert_eq!(CALLED.get_cloned(), 1); + assert_eq!(*called.borrow(), 1); // re-evaluated for new value assert_eq!(cacher.value(-2), -4); - assert_eq!(CALLED.get_cloned(), 2); + assert_eq!(*called.borrow(), 2); // old arg still cached assert_eq!(cacher.value(1), 2); - assert_eq!(CALLED.get_cloned(), 2); + assert_eq!(*called.borrow(), 2); } #[test] fn test_cacher_str_usize() { - global_default_counter!(CALLED, u32); + let called = RefCell::new(0); let mut cacher = Cacher::new(|x: &str| { - CALLED.inc(); + *(called.borrow_mut()) += 1; x.len() }); assert_eq!(cacher.value("abc"), 3); - assert_eq!(CALLED.get_cloned(), 1); + assert_eq!(*called.borrow(), 1); // second time cached assert_eq!(cacher.value("abc"), 3); - assert_eq!(CALLED.get_cloned(), 1); + assert_eq!(*called.borrow(), 1); // re-evaluated for new value assert_eq!(cacher.value("defg"), 4); - assert_eq!(CALLED.get_cloned(), 2); + assert_eq!(*called.borrow(), 2); // old arg still cached assert_eq!(cacher.value("abc"), 3); - assert_eq!(CALLED.get_cloned(), 2); + assert_eq!(*called.borrow(), 2); }