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

56 lines
1.9 KiB
Scala
Raw Normal View History

2011-03-31 20:32:04 +13:00
/**
* Copyright (C) 2009-2011 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 java.util.concurrent.{ CountDownLatch, TimeUnit }
import akka.actor.ActorSystem
2011-03-31 20:32:04 +13:00
class TestLatchTimeoutException(message: String) extends RuntimeException(message)
class TestLatchNoTimeoutException(message: String) extends RuntimeException(message)
/**
* 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 app: ActorSystem) = new TestLatch(count)
2011-03-31 20:32:04 +13:00
}
class TestLatch(count: Int = 1)(implicit app: ActorSystem) {
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()
2011-03-31 20:32:04 +13:00
2011-04-12 11:35:10 +02:00
def open() = countDown()
2011-03-31 20:32:04 +13:00
def await(): Boolean = await(TestLatch.DefaultTimeout)
def await(timeout: Duration): Boolean = {
val opened = latch.await(timeout.dilated.toNanos, TimeUnit.NANOSECONDS)
2011-03-31 20:32:04 +13:00
if (!opened) throw new TestLatchTimeoutException(
2011-11-17 11:51:14 +01:00
"Timeout of %s with time factor of %s" format (timeout.toString, app.settings.TestTimeFactor))
2011-03-31 20:32:04 +13:00
opened
}
/**
* Timeout is expected. Throws exception if latch is opened before timeout.
*/
def awaitTimeout(timeout: Duration = TestLatch.DefaultTimeout) = {
val opened = latch.await(timeout.dilated.toNanos, TimeUnit.NANOSECONDS)
2011-03-31 20:32:04 +13:00
if (opened) throw new TestLatchNoTimeoutException(
2011-11-17 11:51:14 +01:00
"Latch opened before timeout of %s with time factor of %s" format (timeout.toString, app.settings.TestTimeFactor))
2011-03-31 20:32:04 +13:00
opened
}
2011-04-12 11:35:10 +02:00
def reset() = latch = new CountDownLatch(count)
2011-03-31 20:32:04 +13:00
}