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
|
|
|
*/
|
|
|
|
|
|
2011-06-17 22:19:17 +02:00
|
|
|
package akka.testkit
|
2011-03-31 20:32:04 +13:00
|
|
|
|
|
|
|
|
import akka.util.Duration
|
2011-11-10 20:08:00 +01:00
|
|
|
import akka.actor.ActorSystem
|
2011-12-19 15:05:33 +01:00
|
|
|
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)
|
|
|
|
|
|
2011-11-17 12:36:35 +01:00
|
|
|
def apply(count: Int = 1)(implicit system: ActorSystem) = new TestLatch(count)
|
2011-03-31 20:32:04 +13:00
|
|
|
}
|
|
|
|
|
|
2011-12-19 15:05:33 +01: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()
|
2011-12-14 12:39:27 +01:00
|
|
|
def isOpen: Boolean = latch.getCount == 0
|
|
|
|
|
def open() = while (!isOpen) countDown()
|
2011-12-19 15:05:33 +01:00
|
|
|
def reset() = latch = new CountDownLatch(count)
|
2011-03-31 20:32:04 +13:00
|
|
|
|
2012-02-16 12:31:49 +01:00
|
|
|
@throws(classOf[TimeoutException])
|
2011-12-19 15:05:33 +01:00
|
|
|
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
|
|
|
}
|
2012-02-16 12:31:49 +01:00
|
|
|
@throws(classOf[Exception])
|
2011-12-19 15:05:33 +01:00
|
|
|
def result(atMost: Duration)(implicit permit: CanAwait): Unit = {
|
|
|
|
|
ready(atMost)
|
2011-03-31 20:32:04 +13:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|