diff --git a/zio-cache/shared/src/main/scala/zio/cache/Cache.scala b/zio-cache/shared/src/main/scala/zio/cache/Cache.scala index da44d61..3eeeb67 100644 --- a/zio-cache/shared/src/main/scala/zio/cache/Cache.scala +++ b/zio-cache/shared/src/main/scala/zio/cache/Cache.scala @@ -225,11 +225,11 @@ object Cache { promise.await case MapValue.Complete(key, exit, _, timeToLive) => trackAccess(key) - trackHit() if (hasExpired(timeToLive)) { map.remove(k, value) get(in) } else { + trackHit() ZIO.done(exit) } case MapValue.Refreshing( diff --git a/zio-cache/shared/src/test/scala/zio/cache/CacheSpec.scala b/zio-cache/shared/src/test/scala/zio/cache/CacheSpec.scala index 3d2cf46..620c02a 100644 --- a/zio-cache/shared/src/test/scala/zio/cache/CacheSpec.scala +++ b/zio-cache/shared/src/test/scala/zio/cache/CacheSpec.scala @@ -1,14 +1,17 @@ package zio.cache +import zio._ import zio.test.Assertion._ import zio.test._ -import zio.{Duration, Ref, Scope, UIO, ZIO, duration2DurationOps} object CacheSpec extends ZIOSpecDefault { def hash(x: Int): Int => UIO[Int] = y => ZIO.succeed((x ^ y).hashCode) + val identity: Int => UIO[Int] = + ZIO.succeed(_) + def spec: Spec[TestEnvironment with Scope, Any] = suite("CacheSpec")( test("cacheStats") { check(Gen.int) { salt => @@ -142,6 +145,18 @@ object CacheSpec extends ZIOSpecDefault { size <- cache.size } yield assertTrue(size == 10) } + }, + test("cache hits should not be incremented for expired entries") { + for { + cache <- Cache.make(100, 1.second, Lookup(identity)) + _ <- cache.get(42) + _ <- TestClock.adjust(2.seconds) + _ <- cache.get(42) + cacheStats <- cache.cacheStats + hits = cacheStats.hits + misses = cacheStats.misses + } yield assertTrue(hits == 0L) && + assertTrue(misses == 2L) } ) }