pekko/akka-actor-tests/src/test/scala/akka/pattern/PatternSpec.scala

70 lines
2.3 KiB
Scala
Raw Normal View History

/*
* Copyright (C) 2009-2020 Lightbend Inc. <https://www.lightbend.com>
*/
package akka.pattern
import language.postfixOps
2019-03-11 10:38:24 +01:00
import akka.testkit.{ AkkaSpec, TestLatch }
import akka.actor.{ Actor, Props }
import scala.concurrent.{ Await, Future, Promise }
import scala.concurrent.duration._
import scala.concurrent.ExecutionContextExecutor
object PatternSpec {
2014-03-07 13:20:01 +01:00
final case class Work(duration: Duration)
class TargetActor extends Actor {
def receive = {
case (testLatch: TestLatch, duration: FiniteDuration) =>
2012-12-18 14:31:18 +01:00
Await.ready(testLatch, duration)
}
}
}
class PatternSpec extends AkkaSpec {
implicit val ec: ExecutionContextExecutor = system.dispatcher
import PatternSpec._
"pattern.gracefulStop" must {
"provide Future for stopping an actor" in {
val target = system.actorOf(Props[TargetActor])
val result = gracefulStop(target, 5 seconds)
2015-01-16 11:09:59 +01:00
Await.result(result, 6 seconds) should ===(true)
}
"complete Future when actor already terminated" in {
val target = system.actorOf(Props[TargetActor])
Await.ready(gracefulStop(target, 5 seconds), 6 seconds)
Await.ready(gracefulStop(target, 1 millis), 1 second)
}
2012-12-18 14:31:18 +01:00
"complete Future with AskTimeoutException when actor not terminated within timeout" in {
val target = system.actorOf(Props[TargetActor])
2012-12-18 14:31:18 +01:00
val latch = TestLatch()
target ! ((latch, remainingOrDefault))
intercept[AskTimeoutException] { Await.result(gracefulStop(target, 500 millis), remainingOrDefault) }
2012-12-18 14:31:18 +01:00
latch.open()
}
}
"pattern.after" must {
"be completed successfully eventually" in {
// TODO after is unfortunately shadowed by ScalaTest, fix as part of #3759
val f = akka.pattern.after(1 second, using = system.scheduler)(Future.successful(5))
2012-07-04 15:25:30 +02:00
val r = Future.firstCompletedOf(Seq(Promise[Int]().future, f))
2015-01-16 11:09:59 +01:00
Await.result(r, remainingOrDefault) should ===(5)
}
"be completed abnormally eventually" in {
// TODO after is unfortunately shadowed by ScalaTest, fix as part of #3759
val f = akka.pattern.after(1 second, using = system.scheduler)(Future.failed(new IllegalStateException("Mexico")))
2012-07-04 15:25:30 +02:00
val r = Future.firstCompletedOf(Seq(Promise[Int]().future, f))
2015-01-16 11:09:59 +01:00
intercept[IllegalStateException] { Await.result(r, remainingOrDefault) }.getMessage should ===("Mexico")
}
}
}