pekko/akka-testkit/src/main/scala/akka/testkit/TestLatch.scala

46 lines
1.5 KiB
Scala
Raw Normal View History

2011-03-31 20:32:04 +13:00
/**
2012-01-19 18:21:06 +01:00
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
2011-03-31 20:32:04 +13:00
*/
package akka.testkit
2011-03-31 20:32:04 +13:00
import akka.util.Duration
import akka.actor.ActorSystem
import akka.dispatch.Await.{ CanAwait, Awaitable }
import java.util.concurrent.{ TimeoutException, CountDownLatch, TimeUnit }
2011-03-31 20:32:04 +13:00
/**
* A count down latch wrapper for use in testing.
* It always uses a timeout when waiting and timeouts are specified as durations.
* There's a default timeout of 5 seconds and the default count is 1.
* Timeouts will always throw an exception (no need to wrap in assert in tests).
* Timeouts are multiplied by the testing time factor for Jenkins builds.
*/
object TestLatch {
val DefaultTimeout = Duration(5, TimeUnit.SECONDS)
def apply(count: Int = 1)(implicit system: ActorSystem) = new TestLatch(count)
2011-03-31 20:32:04 +13:00
}
class TestLatch(count: Int = 1)(implicit system: ActorSystem) extends Awaitable[Unit] {
2011-03-31 20:32:04 +13:00
private var latch = new CountDownLatch(count)
2011-04-12 11:35:10 +02:00
def countDown() = latch.countDown()
def isOpen: Boolean = latch.getCount == 0
def open() = while (!isOpen) countDown()
def reset() = latch = new CountDownLatch(count)
2011-03-31 20:32:04 +13:00
@throws(classOf[TimeoutException])
def ready(atMost: Duration)(implicit permit: CanAwait) = {
val opened = latch.await(atMost.dilated.toNanos, TimeUnit.NANOSECONDS)
if (!opened) throw new TimeoutException(
"Timeout of %s with time factor of %s" format (atMost.toString, TestKitExtension(system).TestTimeFactor))
this
2011-03-31 20:32:04 +13:00
}
@throws(classOf[Exception])
def result(atMost: Duration)(implicit permit: CanAwait): Unit = {
ready(atMost)
2011-03-31 20:32:04 +13:00
}
}