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

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

94 lines
2.5 KiB
Scala
Raw Normal View History

/*
* sbt
2023-06-20 13:42:07 +02:00
* Copyright 2023, Scala center
* Copyright 2011 - 2022, 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._
import sjsonnew.{ Builder, deserializationError, JsonFormat, Unbuilder }
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 SingletonCacheSpec extends AnyFlatSpec {
2016-06-27 15:27:42 +02:00
case class ComplexType(val x: Int, y: String, z: List[Int])
object ComplexType {
2024-11-17 00:28:38 +01:00
given format: JsonFormat[ComplexType] =
2016-06-27 15:27:42 +02:00
new JsonFormat[ComplexType] {
override def read[J](jsOpt: Option[J], unbuilder: Unbuilder[J]): ComplexType = {
jsOpt match {
case Some(js) =>
unbuilder.beginObject(js)
val x = unbuilder.readField[Int]("x")
val y = unbuilder.readField[String]("y")
val z = unbuilder.readField[List[Int]]("z")
unbuilder.endObject()
ComplexType(x, y, z)
case None =>
deserializationError("Exception JObject but found None")
}
}
override def write[J](obj: ComplexType, builder: Builder[J]): Unit = {
builder.beginObject()
builder.addField("x", obj.x)
builder.addField("y", obj.y)
builder.addField("z", obj.z)
builder.endObject()
}
}
}
"A singleton cache" should "throw an exception if read without being written previously" in {
2021-12-20 08:00:30 +01:00
testCache[Int] { case (cache, store) =>
intercept[Exception] {
cache.read(store)
}
()
2016-06-27 15:27:42 +02:00
}
}
it should "write a very simple value" in {
2021-12-20 08:00:30 +01:00
testCache[Int] { case (cache, store) =>
cache.write(store, 5)
2016-06-27 15:27:42 +02:00
}
}
it should "return the simple value that has been previously written" in {
2021-12-20 08:00:30 +01:00
testCache[Int] { case (cache, store) =>
val value = 5
cache.write(store, value)
val read = cache.read(store)
2016-06-27 15:27:42 +02:00
2021-12-20 08:00:30 +01:00
assert(read === value); ()
2016-06-27 15:27:42 +02:00
}
}
it should "write a complex value" in {
2021-12-20 08:00:30 +01:00
testCache[ComplexType] { case (cache, store) =>
val value = ComplexType(1, "hello, world!", (1 to 10 by 3).toList)
cache.write(store, value)
val read = cache.read(store)
2016-06-27 15:27:42 +02:00
2021-12-20 08:00:30 +01:00
assert(read === value); ()
2016-06-27 15:27:42 +02:00
}
}
private def testCache[T](f: (SingletonCache[T], CacheStore) => Unit)(using
2021-12-20 08:00:30 +01:00
cache: SingletonCache[T]
2017-08-10 12:24:29 +02:00
): 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
}