sbt/util-cache/src/test/scala/CacheSpec.scala

81 lines
1.9 KiB
Scala
Raw Normal View History

/*
* sbt
* Copyright 2011 - 2018, Lightbend, Inc.
* Copyright 2008 - 2010, Mark Harrah
* Licensed under Apache License 2.0 (see LICENSE)
*/
package sbt.util
2016-06-27 15:27:42 +02:00
import sbt.io.IO
import sbt.io.syntax._
import CacheImplicits._
2021-11-14 14:00:10 +01:00
import org.scalatest.flatspec.AnyFlatSpec
2016-06-27 15:27:42 +02:00
2021-11-14 14:00:10 +01:00
class CacheSpec extends AnyFlatSpec {
2016-06-27 15:27:42 +02:00
"A cache" should "NOT throw an exception if read without being written previously" in {
testCache[String, Int] {
case (cache, store) =>
cache(store)("missing") match {
2021-11-14 14:59:34 +01:00
case Hit(_) => fail()
2016-06-27 15:27:42 +02:00
case Miss(_) => ()
}
}
}
it should "write a very simple value" in {
testCache[String, Int] {
case (cache, store) =>
cache(store)("missing") match {
2021-11-14 14:59:34 +01:00
case Hit(_) => fail()
2016-06-27 15:27:42 +02:00
case Miss(update) => update(5)
}
}
}
it should "be updatable" in {
testCache[String, Int] {
case (cache, store) =>
val value = 5
cache(store)("someKey") match {
2021-11-14 14:59:34 +01:00
case Hit(_) => fail()
2016-06-27 15:27:42 +02:00
case Miss(update) => update(value)
}
cache(store)("someKey") match {
2018-09-20 04:46:38 +02:00
case Hit(read) => assert(read === value); ()
2021-11-14 14:59:34 +01:00
case Miss(_) => fail()
2016-06-27 15:27:42 +02:00
}
}
}
it should "return the value that has been previously written" in {
testCache[String, Int] {
case (cache, store) =>
val key = "someKey"
val value = 5
cache(store)(key) match {
2021-11-14 14:59:34 +01:00
case Hit(_) => fail()
2016-06-27 15:27:42 +02:00
case Miss(update) => update(value)
}
cache(store)(key) match {
2018-09-20 04:46:38 +02:00
case Hit(read) => assert(read === value); ()
2021-11-14 14:59:34 +01:00
case Miss(_) => fail()
2016-06-27 15:27:42 +02:00
}
}
}
2017-08-10 12:24:29 +02:00
private def testCache[K, V](f: (Cache[K, V], CacheStore) => Unit)(
implicit cache: Cache[K, V]
): Unit =
2016-06-27 15:27:42 +02:00
IO.withTemporaryDirectory { tmp =>
val store = new FileBasedStore(tmp / "cache-store")
2016-06-27 15:27:42 +02:00
f(cache, store)
}
2017-08-10 12:24:29 +02:00
}