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

77 lines
2.0 KiB
Scala
Raw Normal View History

package sbt.util
2016-06-27 15:27:42 +02:00
import sbt.io.IO
import sbt.io.syntax._
import CacheImplicits._
import sjsonnew.IsoString
2016-08-21 19:56:31 +02:00
import sjsonnew.support.scalajson.unsafe.{ CompactPrinter, Converter, Parser }
2016-06-27 15:27:42 +02:00
2017-07-14 21:56:06 +02:00
import sjsonnew.shaded.scalajson.ast.unsafe.JValue
import sbt.internal.util.UnitSpec
2016-06-27 15:27:42 +02:00
class CacheSpec extends UnitSpec {
2016-08-21 19:56:31 +02:00
implicit val isoString: IsoString[JValue] = IsoString.iso(CompactPrinter.apply, Parser.parseUnsafe)
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 {
case Hit(_) => fail
case Miss(_) => ()
}
}
}
it should "write a very simple value" in {
testCache[String, Int] {
case (cache, store) =>
cache(store)("missing") match {
case Hit(_) => fail
case Miss(update) => update(5)
}
}
}
it should "be updatable" in {
testCache[String, Int] {
case (cache, store) =>
val value = 5
cache(store)("someKey") match {
case Hit(_) => fail
case Miss(update) => update(value)
}
cache(store)("someKey") match {
case Hit(read) => assert(read === value)
case Miss(_) => fail
}
}
}
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 {
case Hit(_) => fail
case Miss(update) => update(value)
}
cache(store)(key) match {
case Hit(read) => assert(read === value)
case Miss(_) => fail
}
}
}
private def testCache[K, V](f: (Cache[K, V], CacheStore) => Unit)(implicit cache: Cache[K, V]): Unit =
IO.withTemporaryDirectory { tmp =>
val store = new FileBasedStore(tmp / "cache-store", Converter)
f(cache, store)
}
}