From 501257684ec2e3ee8336ad12d27e1e5f1b9ac812 Mon Sep 17 00:00:00 2001 From: Valentin Brandl Date: Wed, 7 Aug 2019 22:19:41 +0200 Subject: [PATCH] Implement tests --- time-cache/src/lib.rs | 77 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 75 insertions(+), 2 deletions(-) diff --git a/time-cache/src/lib.rs b/time-cache/src/lib.rs index a325285..884c6d8 100644 --- a/time-cache/src/lib.rs +++ b/time-cache/src/lib.rs @@ -148,10 +148,83 @@ impl CacheEntry { CacheEntry(Instant::now() + duration, value) } } + #[cfg(test)] mod tests { + use super::{Cache, CacheResult}; + use std::time::Duration; + #[test] - fn it_works() { - assert_eq!(2 + 2, 4); + fn always_invalid() { + let key = 0; + let value = 1; + let mut cache = Cache::new(Duration::from_secs(0)); + assert_eq!(CacheResult::Empty, cache.get(&key)); + cache.store(key, value); + assert_eq!(CacheResult::Invalid, cache.get(&key)); + } + + #[test] + fn valid() { + let key = 0; + let value = 1; + let mut cache = Cache::new(Duration::from_secs(100)); + assert_eq!(CacheResult::Empty, cache.get(&key)); + cache.store(key, value); + assert_eq!(CacheResult::Cached(&value), cache.get(&key)); + } + + #[test] + fn wait_for_invalidation() { + let key = 0; + let value = 1; + let dur = Duration::from_millis(500); + let mut cache = Cache::new(dur); + assert_eq!(CacheResult::Empty, cache.get(&key)); + cache.store(key, value); + assert_eq!(CacheResult::Cached(&value), cache.get(&key)); + std::thread::sleep(dur); + assert_eq!(CacheResult::Invalid, cache.get(&key)); + } + + #[test] + fn invalidate() { + let key = 0; + let value = 1; + let dur = Duration::from_secs(100); + let mut cache = Cache::new(dur); + assert_eq!(CacheResult::Empty, cache.get(&key)); + cache.store(key, value); + assert_eq!(CacheResult::Cached(&value), cache.get(&key)); + assert!(cache.invalidate(&key)); + assert_eq!(CacheResult::Empty, cache.get(&key)); + } + + #[test] + fn invalidate_wait() { + let key = 0; + let value = 1; + let dur = Duration::from_millis(500); + let mut cache = Cache::new(dur); + assert_eq!(CacheResult::Empty, cache.get(&key)); + cache.store(key, value); + assert_eq!(CacheResult::Cached(&value), cache.get(&key)); + std::thread::sleep(dur); + assert_eq!(CacheResult::Invalid, cache.get(&key)); + assert!(cache.invalidate(&key)); + assert_eq!(CacheResult::Empty, cache.get(&key)); + } + + #[test] + fn clear() { + let key = 0; + let value = 1; + let dur = Duration::from_secs(0); + let mut cache = Cache::new(dur); + assert_eq!(CacheResult::Empty, cache.get(&key)); + cache.store(key, value); + assert_eq!(CacheResult::Invalid, cache.get(&key)); + cache.clear(); + assert_eq!(CacheResult::Empty, cache.get(&key)); } }