Update scalafmt-core to 3.8.4 (#1717)

* Update scalafmt-core to 3.8.4

* Reformat with scalafmt 3.8.4

Executed command: scalafmt --non-interactive

* Add 'Reformat with scalafmt 3.8.4' to .git-blame-ignore-revs

* remove postfixOps imports

Assuming we want to keep the default
`rewrite.avoidInfix.excludePostfix = false` - otherwise
we can drop this commit

---------

Co-authored-by: scala-steward-asf[bot] <147768647+scala-steward-asf[bot]@users.noreply.github.com>
Co-authored-by: Arnout Engelen <arnout@bzzt.net>
This commit is contained in:
scala-steward-asf[bot] 2025-01-18 10:36:38 +08:00 committed by GitHub
parent a75bc7a772
commit 5b2aab6f7a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
126 changed files with 728 additions and 860 deletions

View file

@ -76,3 +76,6 @@ c44c0b7cbdab11d85176cfe062288fdcba16c56a
# Scala Steward: Reformat with scalafmt 3.8.2 # Scala Steward: Reformat with scalafmt 3.8.2
38b03829b4e38e983521f3efd7e589d315658f18 38b03829b4e38e983521f3efd7e589d315658f18
# Scala Steward: Reformat with scalafmt 3.8.4
f48453e60a8d11f74acc7a10d3a9da90b8acd4af

View file

@ -1,4 +1,4 @@
version = 3.8.3 version = 3.8.4
runner.dialect = scala213 runner.dialect = scala213
project.git = true project.git = true
style = defaultWithAlign style = defaultWithAlign

View file

@ -15,7 +15,6 @@ package org.apache.pekko.actor
import scala.concurrent.duration._ import scala.concurrent.duration._
import language.postfixOps
import org.scalatest.BeforeAndAfterEach import org.scalatest.BeforeAndAfterEach
import org.apache.pekko import org.apache.pekko
@ -79,7 +78,7 @@ class ActorConfigurationVerificationSpec
"fail verification with a ConfigurationException if also configured with a ScatterGatherFirstCompletedPool" in { "fail verification with a ConfigurationException if also configured with a ScatterGatherFirstCompletedPool" in {
intercept[ConfigurationException] { intercept[ConfigurationException] {
system.actorOf( system.actorOf(
ScatterGatherFirstCompletedPool(nrOfInstances = 2, within = 2 seconds) ScatterGatherFirstCompletedPool(nrOfInstances = 2, within = 2.seconds)
.withDispatcher("balancing-dispatcher") .withDispatcher("balancing-dispatcher")
.props(Props[TestActor]())) .props(Props[TestActor]()))
} }

View file

@ -14,7 +14,6 @@
package org.apache.pekko.actor package org.apache.pekko.actor
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.language.postfixOps
import com.codahale.metrics.Histogram import com.codahale.metrics.Histogram
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
@ -153,10 +152,10 @@ class ActorCreationPerfSpec
expectMsg(Alive) expectMsg(Alive)
driver ! Create(number, propsCreator) driver ! Create(number, propsCreator)
expectMsgPF(15 seconds, s"$scenarioName waiting for Created") { case Created => } expectMsgPF(15.seconds, s"$scenarioName waiting for Created") { case Created => }
driver ! WaitForChildren driver ! WaitForChildren
expectMsgPF(15 seconds, s"$scenarioName waiting for Waited") { case Waited => } expectMsgPF(15.seconds, s"$scenarioName waiting for Waited") { case Waited => }
driver ! PoisonPill driver ! PoisonPill
watch(driver) watch(driver)
@ -175,10 +174,10 @@ class ActorCreationPerfSpec
val before = mem.getHeapSnapshot val before = mem.getHeapSnapshot
driver ! Create(number, propsCreator) driver ! Create(number, propsCreator)
expectMsgPF(15 seconds, s"$scenarioName waiting for Created") { case Created => } expectMsgPF(15.seconds, s"$scenarioName waiting for Created") { case Created => }
driver ! WaitForChildren driver ! WaitForChildren
expectMsgPF(15 seconds, s"$scenarioName waiting for Waited") { case Waited => } expectMsgPF(15.seconds, s"$scenarioName waiting for Waited") { case Waited => }
gc() gc()
val after = mem.getHeapSnapshot val after = mem.getHeapSnapshot
@ -252,5 +251,5 @@ class ActorCreationPerfSpec
override def afterTermination() = shutdownMetrics() override def afterTermination() = shutdownMetrics()
override def expectedTestDuration = 5 minutes override def expectedTestDuration = 5.minutes
} }

View file

@ -19,8 +19,6 @@ import scala.concurrent.Await
import scala.concurrent.Promise import scala.concurrent.Promise
import scala.concurrent.duration._ import scala.concurrent.duration._
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.pattern.ask import pekko.pattern.ask
import pekko.serialization.JavaSerializer import pekko.serialization.JavaSerializer
@ -141,7 +139,7 @@ class ActorRefSpec extends PekkoSpec("""
def wrap[T](f: Promise[Actor] => T): T = { def wrap[T](f: Promise[Actor] => T): T = {
val result = Promise[Actor]() val result = Promise[Actor]()
val r = f(result) val r = f(result)
Await.result(result.future, 1 minute) Await.result(result.future, 1.minute)
r r
} }
@ -448,7 +446,7 @@ class ActorRefSpec extends PekkoSpec("""
val boss = system.actorOf(Props(new Actor { val boss = system.actorOf(Props(new Actor {
override val supervisorStrategy = override val supervisorStrategy =
OneForOneStrategy(maxNrOfRetries = 2, withinTimeRange = 1 second)(List(classOf[Throwable])) OneForOneStrategy(maxNrOfRetries = 2, withinTimeRange = 1.second)(List(classOf[Throwable]))
val ref = context.actorOf(Props(new Actor { val ref = context.actorOf(Props(new Actor {
def receive = { case _ => } def receive = { case _ => }
@ -460,7 +458,7 @@ class ActorRefSpec extends PekkoSpec("""
})) }))
boss ! "sendKill" boss ! "sendKill"
Await.ready(latch, 5 seconds) Await.ready(latch, 5.seconds)
} }
} }

View file

@ -18,7 +18,6 @@ import java.util.concurrent.atomic.AtomicInteger
import scala.concurrent.{ Await, Future } import scala.concurrent.{ Await, Future }
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.language.postfixOps
import scala.annotation.nowarn import scala.annotation.nowarn
import com.typesafe.config.{ Config, ConfigFactory } import com.typesafe.config.{ Config, ConfigFactory }
@ -224,7 +223,7 @@ class ActorSystemSpec extends PekkoSpec(ActorSystemSpec.config) with ImplicitSen
} }
system2.terminate() system2.terminate()
Await.ready(latch, 5 seconds) Await.ready(latch, 5.seconds)
val expected = (for (i <- 1 to count) yield i).reverse val expected = (for (i <- 1 to count) yield i).reverse
@ -243,7 +242,7 @@ class ActorSystemSpec extends PekkoSpec(ActorSystemSpec.config) with ImplicitSen
import system.dispatcher import system.dispatcher
system2.scheduler.scheduleOnce(200.millis.dilated) { system2.terminate() } system2.scheduler.scheduleOnce(200.millis.dilated) { system2.terminate() }
Await.ready(system2.whenTerminated, 5 seconds) Await.ready(system2.whenTerminated, 5.seconds)
callbackWasRun should ===(true) callbackWasRun should ===(true)
} }
@ -252,17 +251,17 @@ class ActorSystemSpec extends PekkoSpec(ActorSystemSpec.config) with ImplicitSen
val wt = system.whenTerminated val wt = system.whenTerminated
wt.isCompleted should ===(false) wt.isCompleted should ===(false)
val f = system.terminate() val f = system.terminate()
val terminated = Await.result(wt, 10 seconds) val terminated = Await.result(wt, 10.seconds)
system.whenTerminated.isCompleted should ===(true) system.whenTerminated.isCompleted should ===(true)
terminated.actor should ===(system.provider.rootGuardian) terminated.actor should ===(system.provider.rootGuardian)
terminated.addressTerminated should ===(true) terminated.addressTerminated should ===(true)
terminated.existenceConfirmed should ===(true) terminated.existenceConfirmed should ===(true)
(terminated should be).theSameInstanceAs(Await.result(f, 10 seconds)) (terminated should be).theSameInstanceAs(Await.result(f, 10.seconds))
} }
"throw RejectedExecutionException when shutdown" in { "throw RejectedExecutionException when shutdown" in {
val system2 = ActorSystem("RejectedExecution-1", PekkoSpec.testConf) val system2 = ActorSystem("RejectedExecution-1", PekkoSpec.testConf)
Await.ready(system2.terminate(), 10 seconds) Await.ready(system2.terminate(), 10.seconds)
intercept[RejectedExecutionException] { intercept[RejectedExecutionException] {
system2.registerOnTermination { println("IF YOU SEE THIS THEN THERE'S A BUG HERE") } system2.registerOnTermination { println("IF YOU SEE THIS THEN THERE'S A BUG HERE") }
@ -287,7 +286,7 @@ class ActorSystemSpec extends PekkoSpec(ActorSystemSpec.config) with ImplicitSen
"reliably create waves of actors" in { "reliably create waves of actors" in {
import system.dispatcher import system.dispatcher
implicit val timeout: Timeout = Timeout((20 seconds).dilated) implicit val timeout: Timeout = Timeout(20.seconds.dilated)
val waves = for (_ <- 1 to 3) yield system.actorOf(Props[ActorSystemSpec.Waves]()) ? 50000 val waves = for (_ <- 1 to 3) yield system.actorOf(Props[ActorSystemSpec.Waves]()) ? 50000
Await.result(Future.sequence(waves), timeout.duration + 5.seconds) should ===(Vector("done", "done", "done")) Await.result(Future.sequence(waves), timeout.duration + 5.seconds) should ===(Vector("done", "done", "done"))
} }
@ -300,7 +299,7 @@ class ActorSystemSpec extends PekkoSpec(ActorSystemSpec.config) with ImplicitSen
"reliable deny creation of actors while shutting down" in { "reliable deny creation of actors while shutting down" in {
val system = ActorSystem() val system = ActorSystem()
import system.dispatcher import system.dispatcher
system.scheduler.scheduleOnce(100 millis) { system.terminate() } system.scheduler.scheduleOnce(100.millis) { system.terminate() }
var failing = false var failing = false
var created = Vector.empty[ActorRef] var created = Vector.empty[ActorRef]
while (!system.whenTerminated.isCompleted) { while (!system.whenTerminated.isCompleted) {

View file

@ -16,7 +16,6 @@ package org.apache.pekko.actor
import scala.concurrent.duration._ import scala.concurrent.duration._
import com.typesafe.config.{ Config, ConfigFactory } import com.typesafe.config.{ Config, ConfigFactory }
import language.postfixOps
import org.scalatest.BeforeAndAfterEach import org.scalatest.BeforeAndAfterEach
import org.apache.pekko import org.apache.pekko
@ -67,9 +66,9 @@ object ActorWithBoundedStashSpec {
} }
// bounded deque-based mailbox with capacity 10 // bounded deque-based mailbox with capacity 10
class Bounded10(@unused settings: Settings, @unused config: Config) extends BoundedDequeBasedMailbox(10, 500 millis) class Bounded10(@unused settings: Settings, @unused config: Config) extends BoundedDequeBasedMailbox(10, 500.millis)
class Bounded100(@unused settings: Settings, @unused config: Config) extends BoundedDequeBasedMailbox(100, 500 millis) class Bounded100(@unused settings: Settings, @unused config: Config) extends BoundedDequeBasedMailbox(100, 500.millis)
val dispatcherId1 = "my-dispatcher-1" val dispatcherId1 = "my-dispatcher-1"
val dispatcherId2 = "my-dispatcher-2" val dispatcherId2 = "my-dispatcher-2"

View file

@ -17,7 +17,6 @@ import scala.concurrent.Await
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.annotation.nowarn import scala.annotation.nowarn
import language.postfixOps
import org.scalatest.BeforeAndAfterEach import org.scalatest.BeforeAndAfterEach
import org.apache.pekko import org.apache.pekko
@ -144,13 +143,13 @@ class ActorWithStashSpec extends PekkoSpec with DefaultTimeout with BeforeAndAft
val stasher = system.actorOf(Props[StashingTwiceActor]()) val stasher = system.actorOf(Props[StashingTwiceActor]())
stasher ! "hello" stasher ! "hello"
stasher ! "hello" stasher ! "hello"
Await.ready(state.expectedException, 10 seconds) Await.ready(state.expectedException, 10.seconds)
} }
"process stashed messages after restart" in { "process stashed messages after restart" in {
val boss = system.actorOf( val boss = system.actorOf(
Props( Props(
new Supervisor(OneForOneStrategy(maxNrOfRetries = 2, withinTimeRange = 1 second)(List(classOf[Throwable]))))) new Supervisor(OneForOneStrategy(maxNrOfRetries = 2, withinTimeRange = 1.second)(List(classOf[Throwable])))))
val restartLatch = new TestLatch val restartLatch = new TestLatch
val hasMsgLatch = new TestLatch val hasMsgLatch = new TestLatch
@ -180,8 +179,8 @@ class ActorWithStashSpec extends PekkoSpec with DefaultTimeout with BeforeAndAft
employee ! "hello" employee ! "hello"
employee ! "crash" employee ! "crash"
Await.ready(restartLatch, 10 seconds) Await.ready(restartLatch, 10.seconds)
Await.ready(hasMsgLatch, 10 seconds) Await.ready(hasMsgLatch, 10.seconds)
} }
"re-receive unstashed Terminated messages" in { "re-receive unstashed Terminated messages" in {

View file

@ -15,8 +15,6 @@ package org.apache.pekko.actor
import scala.concurrent.duration._ import scala.concurrent.duration._
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.dispatch.ThreadPoolConfig import pekko.dispatch.ThreadPoolConfig
import pekko.testkit.PekkoSpec import pekko.testkit.PekkoSpec
@ -80,7 +78,7 @@ class ConsistencySpec extends PekkoSpec(ConsistencySpec.config) {
for (a <- actors) { a.tell("done", testActor) } for (a <- actors) { a.tell("done", testActor) }
for (_ <- actors) expectMsg(5 minutes, "done") for (_ <- actors) expectMsg(5.minutes, "done")
} }
} }
} }

View file

@ -17,7 +17,6 @@ import scala.concurrent.Await
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.annotation.nowarn import scala.annotation.nowarn
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.actor.Props.EmptyActor import pekko.actor.Props.EmptyActor
@ -125,11 +124,11 @@ trait DeathWatchSpec { this: PekkoSpec with ImplicitSender with DefaultTimeout =
lazy val supervisor = system.actorOf(Props(classOf[Supervisor], SupervisorStrategy.defaultStrategy), "watchers") lazy val supervisor = system.actorOf(Props(classOf[Supervisor], SupervisorStrategy.defaultStrategy), "watchers")
def startWatching(target: ActorRef) = def startWatching(target: ActorRef) =
Await.result((supervisor ? Watcher.props(target, testActor)).mapTo[ActorRef], 3 seconds) Await.result((supervisor ? Watcher.props(target, testActor)).mapTo[ActorRef], 3.seconds)
"The Death Watch" must { "The Death Watch" must {
def expectTerminationOf(actorRef: ActorRef) = def expectTerminationOf(actorRef: ActorRef) =
expectMsgPF(5 seconds, "" + actorRef + ": Stopped or Already terminated when linking") { expectMsgPF(5.seconds, "" + actorRef + ": Stopped or Already terminated when linking") {
case WrappedTerminated(Terminated(`actorRef`)) => true case WrappedTerminated(Terminated(`actorRef`)) => true
} }
@ -236,7 +235,7 @@ trait DeathWatchSpec { this: PekkoSpec with ImplicitSender with DefaultTimeout =
startWatching(brother) startWatching(brother)
failed ! Kill failed ! Kill
val result = receiveWhile(3 seconds, messages = 3) { val result = receiveWhile(3.seconds, messages = 3) {
case FF(Failed(_, _: ActorKilledException, _)) if lastSender eq failed => 1 case FF(Failed(_, _: ActorKilledException, _)) if lastSender eq failed => 1
case FF(Failed(_, DeathPactException(`failed`), _)) if lastSender eq brother => 2 case FF(Failed(_, DeathPactException(`failed`), _)) if lastSender eq brother => 2
case WrappedTerminated(Terminated(`brother`)) => 3 case WrappedTerminated(Terminated(`brother`)) => 3

View file

@ -17,7 +17,6 @@ import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
import com.typesafe.config.ConfigParseOptions import com.typesafe.config.ConfigParseOptions
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.routing._ import pekko.routing._
@ -201,7 +200,7 @@ class DeployerSpec extends PekkoSpec(DeployerSpec.deployerConf) {
"be able to parse 'pekko.actor.deployment._' with scatter-gather router" in { "be able to parse 'pekko.actor.deployment._' with scatter-gather router" in {
assertRouting( assertRouting(
"/service-scatter-gather", "/service-scatter-gather",
ScatterGatherFirstCompletedPool(nrOfInstances = 1, within = 2 seconds), ScatterGatherFirstCompletedPool(nrOfInstances = 1, within = 2.seconds),
"/service-scatter-gather") "/service-scatter-gather")
} }
@ -218,7 +217,7 @@ class DeployerSpec extends PekkoSpec(DeployerSpec.deployerConf) {
assertRouting("/some/wildcardmatch", RandomPool(1), "/some/*") assertRouting("/some/wildcardmatch", RandomPool(1), "/some/*")
assertRouting( assertRouting(
"/somewildcardmatch/some", "/somewildcardmatch/some",
ScatterGatherFirstCompletedPool(nrOfInstances = 1, within = 2 seconds), ScatterGatherFirstCompletedPool(nrOfInstances = 1, within = 2.seconds),
"/*/some") "/*/some")
} }

View file

@ -17,7 +17,6 @@ import scala.concurrent.Await
import scala.concurrent.duration._ import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.event._ import pekko.event._
@ -113,7 +112,7 @@ object FSMActorSpec {
class FSMActorSpec extends PekkoSpec(Map("pekko.actor.debug.fsm" -> true)) with ImplicitSender { class FSMActorSpec extends PekkoSpec(Map("pekko.actor.debug.fsm" -> true)) with ImplicitSender {
import FSMActorSpec._ import FSMActorSpec._
val timeout = Timeout(2 seconds) val timeout = Timeout(2.seconds)
"An FSM Actor" must { "An FSM Actor" must {
@ -125,7 +124,7 @@ class FSMActorSpec extends PekkoSpec(Map("pekko.actor.debug.fsm" -> true)) with
import latches._ import latches._
// lock that locked after being open for 1 sec // lock that locked after being open for 1 sec
val lock = system.actorOf(Props(new Lock("33221", 1 second, latches))) val lock = system.actorOf(Props(new Lock("33221", 1.second, latches)))
val transitionTester = system.actorOf(Props(new Actor { val transitionTester = system.actorOf(Props(new Actor {
def receive = { def receive = {
@ -179,7 +178,7 @@ class FSMActorSpec extends PekkoSpec(Map("pekko.actor.debug.fsm" -> true)) with
EventFilter.error("Next state 2 does not exist", occurrences = 1).intercept { EventFilter.error("Next state 2 does not exist", occurrences = 1).intercept {
system.eventStream.subscribe(testActor, classOf[Logging.Error]) system.eventStream.subscribe(testActor, classOf[Logging.Error])
fsm ! "go" fsm ! "go"
expectMsgPF(1 second, hint = "Next state 2 does not exist") { expectMsgPF(1.second, hint = "Next state 2 does not exist") {
case Logging.Error(_, `name`, _, "Next state 2 does not exist") => true case Logging.Error(_, `name`, _, "Next state 2 does not exist") => true
} }
system.eventStream.unsubscribe(testActor) system.eventStream.unsubscribe(testActor)
@ -203,7 +202,7 @@ class FSMActorSpec extends PekkoSpec(Map("pekko.actor.debug.fsm" -> true)) with
val ref = system.actorOf(Props(fsm)) val ref = system.actorOf(Props(fsm))
Await.ready(started, timeout.duration) Await.ready(started, timeout.duration)
system.stop(ref) system.stop(ref)
expectMsg(1 second, fsm.StopEvent(FSM.Shutdown, 1, null)) expectMsg(1.second, fsm.StopEvent(FSM.Shutdown, 1, null))
} }
"run onTermination with updated state upon stop(reason, stateData)" in { "run onTermination with updated state upon stop(reason, stateData)" in {
@ -230,12 +229,12 @@ class FSMActorSpec extends PekkoSpec(Map("pekko.actor.debug.fsm" -> true)) with
when("not-started") { when("not-started") {
case Event("start", _) => goto("started").replying("starting") case Event("start", _) => goto("started").replying("starting")
} }
when("started", stateTimeout = 10 seconds) { when("started", stateTimeout = 10.seconds) {
case Event("stop", _) => stop() case Event("stop", _) => stop()
} }
onTransition { onTransition {
case "not-started" -> "started" => case "not-started" -> "started" =>
for (timerName <- timerNames) startSingleTimer(timerName, (), 10 seconds) for (timerName <- timerNames) startSingleTimer(timerName, (), 10.seconds)
} }
onTermination { onTermination {
case _ => { case _ => {
@ -253,11 +252,11 @@ class FSMActorSpec extends PekkoSpec(Map("pekko.actor.debug.fsm" -> true)) with
checkTimersActive(false) checkTimersActive(false)
fsmref ! "start" fsmref ! "start"
expectMsg(1 second, "starting") expectMsg(1.second, "starting")
checkTimersActive(true) checkTimersActive(true)
fsmref ! "stop" fsmref ! "stop"
expectMsg(1 second, "stopped") expectMsg(1.second, "stopped")
} }
"log events and transitions if asked to do so" in { "log events and transitions if asked to do so" in {
@ -273,7 +272,7 @@ class FSMActorSpec extends PekkoSpec(Map("pekko.actor.debug.fsm" -> true)) with
startWith(1, null) startWith(1, null)
when(1) { when(1) {
case Event("go", _) => case Event("go", _) =>
startSingleTimer("t", FSM.Shutdown, 1.5 seconds) startSingleTimer("t", FSM.Shutdown, 1.5.seconds)
goto(2) goto(2)
} }
when(2) { when(2) {
@ -289,21 +288,21 @@ class FSMActorSpec extends PekkoSpec(Map("pekko.actor.debug.fsm" -> true)) with
val fsmClass = fsm.underlyingActor.getClass val fsmClass = fsm.underlyingActor.getClass
system.eventStream.subscribe(testActor, classOf[Logging.Debug]) system.eventStream.subscribe(testActor, classOf[Logging.Debug])
fsm ! "go" fsm ! "go"
expectMsgPF(1 second, hint = "processing Event(go,null)") { expectMsgPF(1.second, hint = "processing Event(go,null)") {
case Logging.Debug(`name`, `fsmClass`, s: String) case Logging.Debug(`name`, `fsmClass`, s: String)
if s.startsWith("processing Event(go,null) from Actor[") => if s.startsWith("processing Event(go,null) from Actor[") =>
true true
} }
expectMsg(1 second, Logging.Debug(name, fsmClass, "setting timer 't'/1500 milliseconds: Shutdown")) expectMsg(1.second, Logging.Debug(name, fsmClass, "setting timer 't'/1500 milliseconds: Shutdown"))
expectMsg(1 second, Logging.Debug(name, fsmClass, "transition 1 -> 2")) expectMsg(1.second, Logging.Debug(name, fsmClass, "transition 1 -> 2"))
fsm ! "stop" fsm ! "stop"
expectMsgPF(1 second, hint = "processing Event(stop,null)") { expectMsgPF(1.second, hint = "processing Event(stop,null)") {
case Logging.Debug(`name`, `fsmClass`, s: String) case Logging.Debug(`name`, `fsmClass`, s: String)
if s.startsWith("processing Event(stop,null) from Actor[") => if s.startsWith("processing Event(stop,null) from Actor[") =>
true true
} }
expectMsgAllOf(1 second, Logging.Debug(name, fsmClass, "canceling timer 't'"), FSM.Normal) expectMsgAllOf(1.second, Logging.Debug(name, fsmClass, "canceling timer 't'"), FSM.Normal)
expectNoMessage(1 second) expectNoMessage(1.second)
system.eventStream.unsubscribe(testActor) system.eventStream.unsubscribe(testActor)
} }
} }
@ -323,13 +322,13 @@ class FSMActorSpec extends PekkoSpec(Map("pekko.actor.debug.fsm" -> true)) with
}) })
fsmref ! "log" fsmref ! "log"
import FSM.LogEntry import FSM.LogEntry
expectMsg(1 second, IndexedSeq(LogEntry(1, 0, "log"))) expectMsg(1.second, IndexedSeq(LogEntry(1, 0, "log")))
fsmref ! "count" fsmref ! "count"
fsmref ! "log" fsmref ! "log"
expectMsg(1 second, IndexedSeq(LogEntry(1, 0, "log"), LogEntry(1, 0, "count"), LogEntry(1, 1, "log"))) expectMsg(1.second, IndexedSeq(LogEntry(1, 0, "log"), LogEntry(1, 0, "count"), LogEntry(1, 1, "log")))
fsmref ! "count" fsmref ! "count"
fsmref ! "log" fsmref ! "log"
expectMsg(1 second, IndexedSeq(LogEntry(1, 1, "log"), LogEntry(1, 1, "count"), LogEntry(1, 2, "log"))) expectMsg(1.second, IndexedSeq(LogEntry(1, 1, "log"), LogEntry(1, 1, "count"), LogEntry(1, 2, "log")))
} }
"allow transforming of state results" in { "allow transforming of state results" in {

View file

@ -13,8 +13,6 @@
package org.apache.pekko.actor package org.apache.pekko.actor
import language.postfixOps
import org.apache.pekko.testkit._ import org.apache.pekko.testkit._
import scala.concurrent.duration._ import scala.concurrent.duration._
@ -24,7 +22,7 @@ class FSMTimingSpec extends PekkoSpec with ImplicitSender {
val fsm = system.actorOf(Props(new StateMachine(testActor))) val fsm = system.actorOf(Props(new StateMachine(testActor)))
fsm ! SubscribeTransitionCallBack(testActor) fsm ! SubscribeTransitionCallBack(testActor)
expectMsg(1 second, CurrentState(fsm, Initial)) expectMsg(1.second, CurrentState(fsm, Initial))
ignoreMsg { ignoreMsg {
case Transition(_, bs: FSMTimingSpec.State, _) if bs eq Initial => true // SI-5900 workaround case Transition(_, bs: FSMTimingSpec.State, _) if bs eq Initial => true // SI-5900 workaround
@ -33,8 +31,8 @@ class FSMTimingSpec extends PekkoSpec with ImplicitSender {
"A Finite State Machine" must { "A Finite State Machine" must {
"receive StateTimeout" taggedAs TimingTest in { "receive StateTimeout" taggedAs TimingTest in {
within(2 seconds) { within(2.seconds) {
within(500 millis, 2 seconds) { within(500.millis, 2.seconds) {
fsm ! TestStateTimeout fsm ! TestStateTimeout
expectMsg(Transition(fsm, TestStateTimeout, Initial)) expectMsg(Transition(fsm, TestStateTimeout, Initial))
} }
@ -43,7 +41,7 @@ class FSMTimingSpec extends PekkoSpec with ImplicitSender {
} }
"cancel a StateTimeout" taggedAs TimingTest in { "cancel a StateTimeout" taggedAs TimingTest in {
within(1 second) { within(1.second) {
fsm ! TestStateTimeout fsm ! TestStateTimeout
fsm ! Cancel fsm ! Cancel
expectMsg(Cancel) expectMsg(Cancel)
@ -56,18 +54,18 @@ class FSMTimingSpec extends PekkoSpec with ImplicitSender {
val stoppingActor = system.actorOf(Props[StoppingActor]()) val stoppingActor = system.actorOf(Props[StoppingActor]())
system.eventStream.subscribe(testActor, classOf[DeadLetter]) system.eventStream.subscribe(testActor, classOf[DeadLetter])
stoppingActor ! TestStoppingActorStateTimeout stoppingActor ! TestStoppingActorStateTimeout
within(400 millis) { within(400.millis) {
expectNoMessage(remainingOrDefault) expectNoMessage(remainingOrDefault)
} }
} }
"allow StateTimeout override" taggedAs TimingTest in { "allow StateTimeout override" taggedAs TimingTest in {
// the timeout in state TestStateTimeout is 800 ms, then it will change to Initial // the timeout in state TestStateTimeout is 800 ms, then it will change to Initial
within(400 millis) { within(400.millis) {
fsm ! TestStateTimeoutOverride fsm ! TestStateTimeoutOverride
expectNoMessage() expectNoMessage()
} }
within(1 second) { within(1.second) {
fsm ! Cancel fsm ! Cancel
expectMsg(Cancel) expectMsg(Cancel)
expectMsg(Transition(fsm, TestStateTimeout, Initial)) expectMsg(Transition(fsm, TestStateTimeout, Initial))
@ -75,8 +73,8 @@ class FSMTimingSpec extends PekkoSpec with ImplicitSender {
} }
"receive single-shot timer" taggedAs TimingTest in { "receive single-shot timer" taggedAs TimingTest in {
within(2 seconds) { within(2.seconds) {
within(500 millis, 1 second) { within(500.millis, 1.second) {
fsm ! TestSingleTimer fsm ! TestSingleTimer
expectMsg(Tick) expectMsg(Tick)
expectMsg(Transition(fsm, TestSingleTimer, Initial)) expectMsg(Transition(fsm, TestSingleTimer, Initial))
@ -86,12 +84,12 @@ class FSMTimingSpec extends PekkoSpec with ImplicitSender {
} }
"resubmit single-shot timer" taggedAs TimingTest in { "resubmit single-shot timer" taggedAs TimingTest in {
within(2.5 seconds) { within(2.5.seconds) {
within(500 millis, 1 second) { within(500.millis, 1.second) {
fsm ! TestSingleTimerResubmit fsm ! TestSingleTimerResubmit
expectMsg(Tick) expectMsg(Tick)
} }
within(1 second) { within(1.second) {
expectMsg(Tock) expectMsg(Tock)
expectMsg(Transition(fsm, TestSingleTimerResubmit, Initial)) expectMsg(Transition(fsm, TestSingleTimerResubmit, Initial))
} }
@ -101,28 +99,28 @@ class FSMTimingSpec extends PekkoSpec with ImplicitSender {
"correctly cancel a named timer" taggedAs TimingTest in { "correctly cancel a named timer" taggedAs TimingTest in {
fsm ! TestCancelTimer fsm ! TestCancelTimer
within(500 millis) { within(500.millis) {
fsm ! Tick fsm ! Tick
expectMsg(Tick) expectMsg(Tick)
} }
within(300 millis, 1 second) { within(300.millis, 1.second) {
expectMsg(Tock) expectMsg(Tock)
} }
fsm ! Cancel fsm ! Cancel
expectMsg(1 second, Transition(fsm, TestCancelTimer, Initial)) expectMsg(1.second, Transition(fsm, TestCancelTimer, Initial))
} }
"not get confused between named and state timers" taggedAs TimingTest in { "not get confused between named and state timers" taggedAs TimingTest in {
fsm ! TestCancelStateTimerInNamedTimerMessage fsm ! TestCancelStateTimerInNamedTimerMessage
fsm ! Tick fsm ! Tick
expectMsg(500 millis, Tick) expectMsg(500.millis, Tick)
Thread.sleep(200) // this is ugly: need to wait for StateTimeout to be queued Thread.sleep(200) // this is ugly: need to wait for StateTimeout to be queued
resume(fsm) resume(fsm)
expectMsg( expectMsg(
500 millis, 500.millis,
Transition(fsm, TestCancelStateTimerInNamedTimerMessage, TestCancelStateTimerInNamedTimerMessage2)) Transition(fsm, TestCancelStateTimerInNamedTimerMessage, TestCancelStateTimerInNamedTimerMessage2))
fsm ! Cancel fsm ! Cancel
within(500 millis) { within(500.millis) {
expectMsg(Cancel) // if this is not received, that means StateTimeout was not properly discarded expectMsg(Cancel) // if this is not received, that means StateTimeout was not properly discarded
expectMsg(Transition(fsm, TestCancelStateTimerInNamedTimerMessage2, Initial)) expectMsg(Transition(fsm, TestCancelStateTimerInNamedTimerMessage2, Initial))
} }
@ -130,11 +128,11 @@ class FSMTimingSpec extends PekkoSpec with ImplicitSender {
"receive and cancel a repeated timer" taggedAs TimingTest in { "receive and cancel a repeated timer" taggedAs TimingTest in {
fsm ! TestRepeatedTimer fsm ! TestRepeatedTimer
val seq = receiveWhile(2 seconds) { val seq = receiveWhile(2.seconds) {
case Tick => Tick case Tick => Tick
} }
(seq should have).length(5) (seq should have).length(5)
within(500 millis) { within(500.millis) {
expectMsg(Transition(fsm, TestRepeatedTimer, Initial)) expectMsg(Transition(fsm, TestRepeatedTimer, Initial))
} }
} }
@ -147,7 +145,7 @@ class FSMTimingSpec extends PekkoSpec with ImplicitSender {
source = fsm.path.toString, source = fsm.path.toString,
occurrences = 1)) { occurrences = 1)) {
fsm ! TestUnhandled fsm ! TestUnhandled
within(3 second) { within(3.second) {
fsm ! Tick fsm ! Tick
fsm ! SetHandler fsm ! SetHandler
fsm ! Tick fsm ! Tick
@ -292,7 +290,7 @@ object FSMTimingSpec {
class StoppingActor extends Actor with FSM[State, Int] { class StoppingActor extends Actor with FSM[State, Int] {
startWith(Initial, 0) startWith(Initial, 0)
when(Initial, 200 millis) { when(Initial, 200.millis) {
case Event(TestStoppingActorStateTimeout, _) => case Event(TestStoppingActorStateTimeout, _) =>
context.stop(self) context.stop(self)
stay() stay()

View file

@ -14,7 +14,6 @@
package org.apache.pekko.actor package org.apache.pekko.actor
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.testkit._ import pekko.testkit._
@ -91,7 +90,7 @@ class FSMTransitionSpec extends PekkoSpec with ImplicitSender {
import FSM.{ CurrentState, SubscribeTransitionCallBack, Transition } import FSM.{ CurrentState, SubscribeTransitionCallBack, Transition }
val fsm = system.actorOf(Props(new MyFSM(testActor))) val fsm = system.actorOf(Props(new MyFSM(testActor)))
within(1 second) { within(1.second) {
fsm ! SubscribeTransitionCallBack(testActor) fsm ! SubscribeTransitionCallBack(testActor)
expectMsg(CurrentState(fsm, 0)) expectMsg(CurrentState(fsm, 0))
fsm ! "tick" fsm ! "tick"
@ -105,10 +104,10 @@ class FSMTransitionSpec extends PekkoSpec with ImplicitSender {
val forward = system.actorOf(Props(new Forwarder(testActor))) val forward = system.actorOf(Props(new Forwarder(testActor)))
val fsm = system.actorOf(Props(new MyFSM(testActor))) val fsm = system.actorOf(Props(new MyFSM(testActor)))
within(1 second) { within(1.second) {
fsm ! FSM.SubscribeTransitionCallBack(forward) fsm ! FSM.SubscribeTransitionCallBack(forward)
expectMsg(FSM.CurrentState(fsm, 0)) expectMsg(FSM.CurrentState(fsm, 0))
pekko.pattern.gracefulStop(forward, 5 seconds) pekko.pattern.gracefulStop(forward, 5.seconds)
fsm ! "tick" fsm ! "tick"
expectNoMessage() expectNoMessage()
} }
@ -119,7 +118,7 @@ class FSMTransitionSpec extends PekkoSpec with ImplicitSender {
"make previous and next state data available in onTransition" in { "make previous and next state data available in onTransition" in {
val fsm = system.actorOf(Props(new OtherFSM(testActor))) val fsm = system.actorOf(Props(new OtherFSM(testActor)))
within(1 second) { within(1.second) {
fsm ! "tick" fsm ! "tick"
expectMsg((0, 1)) expectMsg((0, 1))
} }
@ -130,7 +129,7 @@ class FSMTransitionSpec extends PekkoSpec with ImplicitSender {
val forward = system.actorOf(Props(new Forwarder(testActor))) val forward = system.actorOf(Props(new Forwarder(testActor)))
val fsm = system.actorOf(Props(new OtherFSM(testActor))) val fsm = system.actorOf(Props(new OtherFSM(testActor)))
within(1 second) { within(1.second) {
fsm ! FSM.SubscribeTransitionCallBack(forward) fsm ! FSM.SubscribeTransitionCallBack(forward)
expectMsg(FSM.CurrentState(fsm, 0)) expectMsg(FSM.CurrentState(fsm, 0))
fsm ! "tick" fsm ! "tick"
@ -146,7 +145,7 @@ class FSMTransitionSpec extends PekkoSpec with ImplicitSender {
val forward = system.actorOf(Props(new Forwarder(testActor))) val forward = system.actorOf(Props(new Forwarder(testActor)))
val fsm = system.actorOf(Props(new OtherFSM(testActor))) val fsm = system.actorOf(Props(new OtherFSM(testActor)))
within(1 second) { within(1.second) {
fsm ! FSM.SubscribeTransitionCallBack(forward) fsm ! FSM.SubscribeTransitionCallBack(forward)
expectMsg(FSM.CurrentState(fsm, 0)) expectMsg(FSM.CurrentState(fsm, 0))
fsm ! "stay" fsm ! "stay"

View file

@ -16,8 +16,6 @@ package org.apache.pekko.actor
import scala.concurrent.ExecutionContextExecutor import scala.concurrent.ExecutionContextExecutor
import scala.concurrent.duration._ import scala.concurrent.duration._
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.pattern.{ ask, pipe } import pekko.pattern.{ ask, pipe }
import pekko.testkit._ import pekko.testkit._
@ -52,13 +50,13 @@ class ForwardActorSpec extends PekkoSpec {
val chain = createForwardingChain(system) val chain = createForwardingChain(system)
chain.tell(ExpectedMessage, replyTo) chain.tell(ExpectedMessage, replyTo)
expectMsg(5 seconds, ExpectedMessage) expectMsg(5.seconds, ExpectedMessage)
} }
"forward actor reference when invoking forward on ask" in { "forward actor reference when invoking forward on ask" in {
val chain = createForwardingChain(system) val chain = createForwardingChain(system)
chain.ask(ExpectedMessage)(5 seconds).pipeTo(testActor) chain.ask(ExpectedMessage)(5.seconds).pipeTo(testActor)
expectMsg(5 seconds, ExpectedMessage) expectMsg(5.seconds, ExpectedMessage)
} }
} }
} }

View file

@ -20,7 +20,6 @@ import scala.util.Failure
import scala.util.Success import scala.util.Success
import scala.annotation.nowarn import scala.annotation.nowarn
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.testkit._ import pekko.testkit._
@ -126,7 +125,7 @@ class LocalActorRefProviderSpec extends PekkoSpec(LocalActorRefProviderSpec.conf
val childProps2 = child.asInstanceOf[LocalActorRef].underlying.props val childProps2 = child.asInstanceOf[LocalActorRef].underlying.props
childProps2 should not be theSameInstanceAs(childProps1) childProps2 should not be theSameInstanceAs(childProps1)
(childProps2 should be).theSameInstanceAs(ActorCell.terminatedProps) (childProps2 should be).theSameInstanceAs(ActorCell.terminatedProps)
}, 1 second) }, 1.second)
} }
} }
@ -140,7 +139,7 @@ class LocalActorRefProviderSpec extends PekkoSpec(LocalActorRefProviderSpec.conf
for (i <- 0 until 100) { for (i <- 0 until 100) {
val address = "new-actor" + i val address = "new-actor" + i
implicit val timeout: Timeout = Timeout(5 seconds) implicit val timeout: Timeout = Timeout(5.seconds)
val actors = val actors =
for (_ <- 1 to 4) for (_ <- 1 to 4)
yield Future(system.actorOf(Props(new Actor { def receive = { case _ => } }), address)) yield Future(system.actorOf(Props(new Actor { def receive = { case _ => } }), address))

View file

@ -20,8 +20,6 @@ import java.util.concurrent.atomic.AtomicInteger
import scala.concurrent.Await import scala.concurrent.Await
import scala.concurrent.duration._ import scala.concurrent.duration._
import language.postfixOps
import org.apache.pekko.testkit._ import org.apache.pekko.testkit._
object ReceiveTimeoutSpec { object ReceiveTimeoutSpec {
@ -85,7 +83,7 @@ class ReceiveTimeoutSpec extends PekkoSpec() {
val timeoutLatch = TestLatch() val timeoutLatch = TestLatch()
val timeoutActor = system.actorOf(Props(new Actor { val timeoutActor = system.actorOf(Props(new Actor {
context.setReceiveTimeout(500 milliseconds) context.setReceiveTimeout(500.milliseconds)
def receive = { def receive = {
case ReceiveTimeout => timeoutLatch.open() case ReceiveTimeout => timeoutLatch.open()
@ -100,7 +98,7 @@ class ReceiveTimeoutSpec extends PekkoSpec() {
val timeoutLatch = TestLatch() val timeoutLatch = TestLatch()
val timeoutActor = system.actorOf(Props(new Actor { val timeoutActor = system.actorOf(Props(new Actor {
context.setReceiveTimeout(500 milliseconds) context.setReceiveTimeout(500.milliseconds)
def receive = { def receive = {
case Tick => () case Tick => ()
@ -119,7 +117,7 @@ class ReceiveTimeoutSpec extends PekkoSpec() {
val timeoutLatch = TestLatch() val timeoutLatch = TestLatch()
val timeoutActor = system.actorOf(Props(new Actor { val timeoutActor = system.actorOf(Props(new Actor {
context.setReceiveTimeout(500 milliseconds) context.setReceiveTimeout(500.milliseconds)
def receive = { def receive = {
case Tick => () case Tick => ()
@ -146,7 +144,7 @@ class ReceiveTimeoutSpec extends PekkoSpec() {
} }
})) }))
intercept[TimeoutException] { Await.ready(timeoutLatch, 1 second) } intercept[TimeoutException] { Await.ready(timeoutLatch, 1.second) }
system.stop(timeoutActor) system.stop(timeoutActor)
} }
@ -154,7 +152,7 @@ class ReceiveTimeoutSpec extends PekkoSpec() {
val timeoutLatch = TestLatch() val timeoutLatch = TestLatch()
val timeoutActor = system.actorOf(Props(new Actor { val timeoutActor = system.actorOf(Props(new Actor {
context.setReceiveTimeout(1 second) context.setReceiveTimeout(1.second)
def receive = { def receive = {
case ReceiveTimeout => timeoutLatch.open() case ReceiveTimeout => timeoutLatch.open()
@ -176,7 +174,7 @@ class ReceiveTimeoutSpec extends PekkoSpec() {
val timeoutLatch = TestLatch(2) val timeoutLatch = TestLatch(2)
val timeoutActor = system.actorOf(Props(new Actor { val timeoutActor = system.actorOf(Props(new Actor {
context.setReceiveTimeout(1 second) context.setReceiveTimeout(1.second)
def receive = { def receive = {
case ReceiveTimeout => case ReceiveTimeout =>
@ -198,7 +196,7 @@ class ReceiveTimeoutSpec extends PekkoSpec() {
timers.startTimerWithFixedDelay("transparentTick", TransparentTick, 100.millis) timers.startTimerWithFixedDelay("transparentTick", TransparentTick, 100.millis)
timers.startTimerWithFixedDelay("identifyTick", Identify(None), 100.millis) timers.startTimerWithFixedDelay("identifyTick", Identify(None), 100.millis)
context.setReceiveTimeout(1 second) context.setReceiveTimeout(1.second)
def receive: Receive = { def receive: Receive = {
case ReceiveTimeout => case ReceiveTimeout =>
timeoutLatch.open() timeoutLatch.open()
@ -219,7 +217,7 @@ class ReceiveTimeoutSpec extends PekkoSpec() {
val timeoutActor = system.actorOf(Props(new Actor { val timeoutActor = system.actorOf(Props(new Actor {
def receive = { def receive = {
case TransparentTick => context.setReceiveTimeout(500 milliseconds) case TransparentTick => context.setReceiveTimeout(500.milliseconds)
case ReceiveTimeout => timeoutLatch.open() case ReceiveTimeout => timeoutLatch.open()
} }
})) }))
@ -234,7 +232,7 @@ class ReceiveTimeoutSpec extends PekkoSpec() {
val timeoutLatch = TestLatch() val timeoutLatch = TestLatch()
val timeoutActor = system.actorOf(Props(new Actor { val timeoutActor = system.actorOf(Props(new Actor {
context.setReceiveTimeout(500 milliseconds) context.setReceiveTimeout(500.milliseconds)
def receive = { def receive = {
case TransparentTick => context.setReceiveTimeout(Duration.Inf) case TransparentTick => context.setReceiveTimeout(Duration.Inf)
@ -244,7 +242,7 @@ class ReceiveTimeoutSpec extends PekkoSpec() {
timeoutActor ! TransparentTick timeoutActor ! TransparentTick
intercept[TimeoutException] { Await.ready(timeoutLatch, 1 second) } intercept[TimeoutException] { Await.ready(timeoutLatch, 1.second) }
system.stop(timeoutActor) system.stop(timeoutActor)
} }

View file

@ -19,7 +19,6 @@ import scala.concurrent.Await
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.annotation.nowarn import scala.annotation.nowarn
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.pattern.ask import pekko.pattern.ask
@ -44,7 +43,7 @@ class RestartStrategySpec extends PekkoSpec with DefaultTimeout {
"ensure that employee stays dead after max restarts within time range" in { "ensure that employee stays dead after max restarts within time range" in {
val boss = system.actorOf( val boss = system.actorOf(
Props( Props(
new Supervisor(OneForOneStrategy(maxNrOfRetries = 2, withinTimeRange = 1 second)(List(classOf[Throwable]))))) new Supervisor(OneForOneStrategy(maxNrOfRetries = 2, withinTimeRange = 1.second)(List(classOf[Throwable])))))
val restartLatch = new TestLatch val restartLatch = new TestLatch
val secondRestartLatch = new TestLatch val secondRestartLatch = new TestLatch
@ -76,17 +75,17 @@ class RestartStrategySpec extends PekkoSpec with DefaultTimeout {
employee ! Ping employee ! Ping
// test restart and post restart ping // test restart and post restart ping
Await.ready(restartLatch, 10 seconds) Await.ready(restartLatch, 10.seconds)
// now crash again... should not restart // now crash again... should not restart
employee ! Crash employee ! Crash
employee ! Ping employee ! Ping
Await.ready(secondRestartLatch, 10 seconds) Await.ready(secondRestartLatch, 10.seconds)
Await.ready(countDownLatch, 10 seconds) Await.ready(countDownLatch, 10.seconds)
employee ! Crash employee ! Crash
Await.ready(stopLatch, 10 seconds) Await.ready(stopLatch, 10.seconds)
} }
"ensure that employee is immortal without max restarts and time range" in { "ensure that employee is immortal without max restarts and time range" in {
@ -109,13 +108,13 @@ class RestartStrategySpec extends PekkoSpec with DefaultTimeout {
(1 to 100).foreach { _ => (1 to 100).foreach { _ =>
employee ! Crash employee ! Crash
} }
Await.ready(countDownLatch, 2 minutes) Await.ready(countDownLatch, 2.minutes)
assert(!employee.isTerminated) assert(!employee.isTerminated)
} }
"ensure that employee restarts after number of crashes not within time range" in { "ensure that employee restarts after number of crashes not within time range" in {
val boss = system.actorOf(Props( val boss = system.actorOf(Props(
new Supervisor(OneForOneStrategy(maxNrOfRetries = 2, withinTimeRange = 500 millis)(List(classOf[Throwable]))))) new Supervisor(OneForOneStrategy(maxNrOfRetries = 2, withinTimeRange = 500.millis)(List(classOf[Throwable])))))
val restartLatch = new TestLatch val restartLatch = new TestLatch
val secondRestartLatch = new TestLatch val secondRestartLatch = new TestLatch
@ -150,14 +149,14 @@ class RestartStrategySpec extends PekkoSpec with DefaultTimeout {
employee ! Ping employee ! Ping
employee ! Crash employee ! Crash
Await.ready(restartLatch, 10 seconds) Await.ready(restartLatch, 10.seconds)
Await.ready(pingLatch, 10 seconds) Await.ready(pingLatch, 10.seconds)
employee ! Ping employee ! Ping
employee ! Crash employee ! Crash
Await.ready(secondRestartLatch, 10 seconds) Await.ready(secondRestartLatch, 10.seconds)
Await.ready(secondPingLatch, 10 seconds) Await.ready(secondPingLatch, 10.seconds)
// sleep to go out of the restart strategy's time range // sleep to go out of the restart strategy's time range
sleep(700L) sleep(700L)
@ -166,7 +165,7 @@ class RestartStrategySpec extends PekkoSpec with DefaultTimeout {
employee ! Crash employee ! Crash
employee ! Ping employee ! Ping
Await.ready(thirdRestartLatch, 1 second) Await.ready(thirdRestartLatch, 1.second)
assert(!employee.isTerminated) assert(!employee.isTerminated)
} }
@ -203,7 +202,7 @@ class RestartStrategySpec extends PekkoSpec with DefaultTimeout {
employee ! Ping employee ! Ping
// test restart and post restart ping // test restart and post restart ping
Await.ready(restartLatch, 10 seconds) Await.ready(restartLatch, 10.seconds)
assert(!employee.isTerminated) assert(!employee.isTerminated)
@ -211,13 +210,13 @@ class RestartStrategySpec extends PekkoSpec with DefaultTimeout {
employee ! Crash employee ! Crash
employee ! Ping employee ! Ping
Await.ready(secondRestartLatch, 10 seconds) Await.ready(secondRestartLatch, 10.seconds)
Await.ready(countDownLatch, 10 seconds) Await.ready(countDownLatch, 10.seconds)
sleep(700L) sleep(700L)
employee ! Crash employee ! Crash
Await.ready(stopLatch, 10 seconds) Await.ready(stopLatch, 10.seconds)
sleep(500L) sleep(500L)
assert(employee.isTerminated) assert(employee.isTerminated)
} }
@ -227,7 +226,7 @@ class RestartStrategySpec extends PekkoSpec with DefaultTimeout {
val countDownLatch = new TestLatch(2) val countDownLatch = new TestLatch(2)
val boss = system.actorOf(Props(new Actor { val boss = system.actorOf(Props(new Actor {
override val supervisorStrategy = OneForOneStrategy(withinTimeRange = 1 second)(List(classOf[Throwable])) override val supervisorStrategy = OneForOneStrategy(withinTimeRange = 1.second)(List(classOf[Throwable]))
def receive = { def receive = {
case p: Props => sender() ! context.watch(context.actorOf(p)) case p: Props => sender() ! context.watch(context.actorOf(p))
case _: Terminated => maxNoOfRestartsLatch.open() case _: Terminated => maxNoOfRestartsLatch.open()
@ -256,7 +255,7 @@ class RestartStrategySpec extends PekkoSpec with DefaultTimeout {
employee ! Ping employee ! Ping
// test restart and post restart ping // test restart and post restart ping
Await.ready(restartLatch, 10 seconds) Await.ready(restartLatch, 10.seconds)
assert(!employee.isTerminated) assert(!employee.isTerminated)
@ -265,14 +264,14 @@ class RestartStrategySpec extends PekkoSpec with DefaultTimeout {
// may not be running // may not be running
employee ! Ping employee ! Ping
Await.ready(countDownLatch, 10 seconds) Await.ready(countDownLatch, 10.seconds)
// may not be running // may not be running
employee ! Crash employee ! Crash
Await.ready(stopLatch, 10 seconds) Await.ready(stopLatch, 10.seconds)
Await.ready(maxNoOfRestartsLatch, 10 seconds) Await.ready(maxNoOfRestartsLatch, 10.seconds)
sleep(500L) sleep(500L)
assert(employee.isTerminated) assert(employee.isTerminated)
} }

View file

@ -27,7 +27,6 @@ import atomic.{ AtomicInteger, AtomicReference }
import scala.annotation.nowarn import scala.annotation.nowarn
import com.typesafe.config.{ Config, ConfigFactory } import com.typesafe.config.{ Config, ConfigFactory }
import language.postfixOps
import org.scalatest.BeforeAndAfterEach import org.scalatest.BeforeAndAfterEach
import org.apache.pekko import org.apache.pekko
import pekko.pattern.ask import pekko.pattern.ask
@ -118,13 +117,13 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
* ticket #372 * ticket #372
*/ */
"be cancellable" taggedAs TimingTest in { "be cancellable" taggedAs TimingTest in {
for (_ <- 1 to 10) system.scheduler.scheduleOnce(1 second, testActor, "fail").cancel() for (_ <- 1 to 10) system.scheduler.scheduleOnce(1.second, testActor, "fail").cancel()
expectNoMessage(2 seconds) expectNoMessage(2.seconds)
} }
"be canceled if cancel is performed before execution" taggedAs TimingTest in { "be canceled if cancel is performed before execution" taggedAs TimingTest in {
val task = collectCancellable(system.scheduler.scheduleOnce(10 seconds)(())) val task = collectCancellable(system.scheduler.scheduleOnce(10.seconds)(()))
task.cancel() should ===(true) task.cancel() should ===(true)
task.isCancelled should ===(true) task.isCancelled should ===(true)
task.cancel() should ===(false) task.cancel() should ===(false)
@ -133,7 +132,7 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
"notify callback if cancel is performed before execution" taggedAs TimingTest in { "notify callback if cancel is performed before execution" taggedAs TimingTest in {
val latch = new CountDownLatch(1) val latch = new CountDownLatch(1)
val task = system.scheduler.scheduleOnce(100 millis, val task = system.scheduler.scheduleOnce(100.millis,
new SchedulerTask { new SchedulerTask {
override def run(): Unit = () override def run(): Unit = ()
override def cancelled(): Unit = latch.countDown() override def cancelled(): Unit = latch.countDown()
@ -172,7 +171,7 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
Thread.sleep(5) Thread.sleep(5)
} }
Await.ready(ticks, 3 seconds) Await.ready(ticks, 3.seconds)
} }
"handle timeouts equal to multiple of wheel period" taggedAs TimingTest in { "handle timeouts equal to multiple of wheel period" taggedAs TimingTest in {
@ -374,7 +373,7 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
val pingLatch = new TestLatch(6) val pingLatch = new TestLatch(6)
val supervisor = val supervisor =
system.actorOf(Props(new Supervisor(AllForOneStrategy(3, 1 second)(List(classOf[Exception]))))) system.actorOf(Props(new Supervisor(AllForOneStrategy(3, 1.second)(List(classOf[Exception])))))
val props = Props(new Actor { val props = Props(new Actor {
def receive = { def receive = {
case Ping => pingLatch.countDown() case Ping => pingLatch.countDown()
@ -391,9 +390,9 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
collectCancellable(system.scheduler.scheduleOnce(1000.millis, actor, Crash)) collectCancellable(system.scheduler.scheduleOnce(1000.millis, actor, Crash))
} }
Await.ready(restartLatch, 2 seconds) Await.ready(restartLatch, 2.seconds)
// should be enough time for the ping countdown to recover and reach 6 pings // should be enough time for the ping countdown to recover and reach 6 pings
Await.ready(pingLatch, 5 seconds) Await.ready(pingLatch, 5.seconds)
} }
"schedule with different initial delay and frequency" taggedAs TimingTest in { "schedule with different initial delay and frequency" taggedAs TimingTest in {
@ -406,8 +405,8 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
})) }))
val startTime = System.nanoTime() val startTime = System.nanoTime()
collectCancellable(scheduleAdapter.schedule(1 second, 300.millis, actor, Msg)) collectCancellable(scheduleAdapter.schedule(1.second, 300.millis, actor, Msg))
Await.ready(ticks, 3 seconds) Await.ready(ticks, 3.seconds)
// LARS is a bit more aggressive in scheduling recurring tasks at the right // LARS is a bit more aggressive in scheduling recurring tasks at the right
// frequency and may execute them a little earlier; the actual expected timing // frequency and may execute them a little earlier; the actual expected timing
@ -810,7 +809,7 @@ class LightArrayRevolverSchedulerSpec extends PekkoSpec(SchedulerSpec.testConfRe
time time
} }
override protected def getShutdownTimeout: FiniteDuration = (10 seconds).dilated override protected def getShutdownTimeout: FiniteDuration = 10.seconds.dilated
override protected def waitNanos(ns: Long): Unit = { override protected def waitNanos(ns: Long): Unit = {
// println(s"waiting $ns") // println(s"waiting $ns")

View file

@ -27,7 +27,6 @@ import scala.util.control.NoStackTrace
import SupervisorStrategy.{ Directive, Restart, Resume, Stop } import SupervisorStrategy.{ Directive, Restart, Resume, Stop }
import scala.annotation.nowarn import scala.annotation.nowarn
import com.typesafe.config.{ Config, ConfigFactory } import com.typesafe.config.{ Config, ConfigFactory }
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.actor.SupervisorStrategy.seqThrowable2Decider import pekko.actor.SupervisorStrategy.seqThrowable2Decider
@ -240,7 +239,7 @@ object SupervisorHierarchySpec {
case (_, x) => case (_, x) =>
log :+= Event("unhandled exception from " + sender() + Logging.stackTraceFor(x), identityHashCode(this)) log :+= Event("unhandled exception from " + sender() + Logging.stackTraceFor(x), identityHashCode(this))
sender() ! Dump(0) sender() ! Dump(0)
context.system.scheduler.scheduleOnce(1 second, self, Dump(0))(context.dispatcher) context.system.scheduler.scheduleOnce(1.second, self, Dump(0))(context.dispatcher)
Resume Resume
}) })
@ -477,7 +476,7 @@ object SupervisorHierarchySpec {
case this.Event(Init, _) => case this.Event(Init, _) =>
hierarchy = context.watch( hierarchy = context.watch(
context.actorOf(Props(new Hierarchy(size, breadth, self, 0, random)).withDispatcher("hierarchy"), "head")) context.actorOf(Props(new Hierarchy(size, breadth, self, 0, random)).withDispatcher("hierarchy"), "head"))
startSingleTimer("phase", StateTimeout, 5 seconds) startSingleTimer("phase", StateTimeout, 5.seconds)
goto(Init) goto(Init)
} }
@ -646,7 +645,7 @@ object SupervisorHierarchySpec {
goto(Failed) goto(Failed)
} }
when(GC, stateTimeout = 10 seconds) { when(GC, stateTimeout = 10.seconds) {
case this.Event(GCcheck(weak), _) => case this.Event(GCcheck(weak), _) =>
val next = weak.filter(_.get ne null) val next = weak.filter(_.get ne null)
if (next.nonEmpty) { if (next.nonEmpty) {
@ -793,7 +792,7 @@ class SupervisorHierarchySpec extends PekkoSpec(SupervisorHierarchySpec.config)
val countDownMax = new CountDownLatch(1) val countDownMax = new CountDownLatch(1)
val boss = system.actorOf(Props(new Actor { val boss = system.actorOf(Props(new Actor {
override val supervisorStrategy = override val supervisorStrategy =
OneForOneStrategy(maxNrOfRetries = 1, withinTimeRange = 5 seconds)(List(classOf[Throwable])) OneForOneStrategy(maxNrOfRetries = 1, withinTimeRange = 5.seconds)(List(classOf[Throwable]))
val crasher = context.watch( val crasher = context.watch(
context.actorOf(Props(new CountDownActor(countDownMessages, SupervisorStrategy.defaultStrategy)))) context.actorOf(Props(new CountDownActor(countDownMessages, SupervisorStrategy.defaultStrategy))))
@ -853,7 +852,7 @@ class SupervisorHierarchySpec extends PekkoSpec(SupervisorHierarchySpec.config)
boss ! "fail" boss ! "fail"
awaitCond(worker.asInstanceOf[LocalActorRef].underlying.mailbox.isSuspended) awaitCond(worker.asInstanceOf[LocalActorRef].underlying.mailbox.isSuspended)
worker ! "ping" worker ! "ping"
expectNoMessage(2 seconds) expectNoMessage(2.seconds)
latch.countDown() latch.countDown()
} }
expectMsg("pong") expectMsg("pong")
@ -935,7 +934,7 @@ class SupervisorHierarchySpec extends PekkoSpec(SupervisorHierarchySpec.config)
fsm ! Init fsm ! Init
expectMsg(110 seconds, "stressTestSuccessful") expectMsg(110.seconds, "stressTestSuccessful")
expectMsg("stressTestStopped") expectMsg("stressTestStopped")
} }
} }

View file

@ -20,7 +20,6 @@ import scala.concurrent.duration._
import scala.util.control.NonFatal import scala.util.control.NonFatal
import scala.annotation.nowarn import scala.annotation.nowarn
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.pattern.ask import pekko.pattern.ask
@ -49,7 +48,7 @@ class SupervisorMiscSpec extends PekkoSpec(SupervisorMiscSpec.config) with Defau
val countDownLatch = new CountDownLatch(4) val countDownLatch = new CountDownLatch(4)
val supervisor = system.actorOf(Props( val supervisor = system.actorOf(Props(
new Supervisor(OneForOneStrategy(maxNrOfRetries = 3, withinTimeRange = 5 seconds)(List(classOf[Exception]))))) new Supervisor(OneForOneStrategy(maxNrOfRetries = 3, withinTimeRange = 5.seconds)(List(classOf[Exception])))))
val workerProps = Props(new Actor { val workerProps = Props(new Actor {
override def postRestart(cause: Throwable): Unit = { countDownLatch.countDown() } override def postRestart(cause: Throwable): Unit = { countDownLatch.countDown() }

View file

@ -20,7 +20,6 @@ import scala.concurrent.duration._
import com.typesafe.config.Config import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
import language.postfixOps
import org.scalatest.BeforeAndAfterEach import org.scalatest.BeforeAndAfterEach
import org.apache.pekko import org.apache.pekko
@ -224,7 +223,7 @@ class SupervisorSpec
def killExpectNoRestart(pingPongActor: ActorRef) = { def killExpectNoRestart(pingPongActor: ActorRef) = {
val result = pingPongActor.?(DieReply)(DilatedTimeout) val result = pingPongActor.?(DieReply)(DilatedTimeout)
expectNoMessage(500 milliseconds) expectNoMessage(500.milliseconds)
intercept[RuntimeException] { Await.result(result, DilatedTimeout) } intercept[RuntimeException] { Await.result(result, DilatedTimeout) }
} }
@ -234,8 +233,8 @@ class SupervisorSpec
val master = system.actorOf(Props(new Master(testActor))) val master = system.actorOf(Props(new Master(testActor)))
master ! Die master ! Die
expectMsg(3 seconds, "terminated") expectMsg(3.seconds, "terminated")
expectNoMessage(1 second) expectNoMessage(1.second)
} }
"restart properly when same instance is returned" in { "restart properly when same instance is returned" in {
@ -287,7 +286,7 @@ class SupervisorSpec
expectMsg("postStop1") expectMsg("postStop1")
} }
expectNoMessage(1 second) expectNoMessage(1.second)
} }
"not restart temporary actor" in { "not restart temporary actor" in {
@ -295,13 +294,13 @@ class SupervisorSpec
intercept[RuntimeException] { Await.result(temporaryActor.?(DieReply)(DilatedTimeout), DilatedTimeout) } intercept[RuntimeException] { Await.result(temporaryActor.?(DieReply)(DilatedTimeout), DilatedTimeout) }
expectNoMessage(1 second) expectNoMessage(1.second)
} }
"start server for nested supervisor hierarchy" in { "start server for nested supervisor hierarchy" in {
val (actor1, _, _, _) = nestedSupervisorsAllForOne val (actor1, _, _, _) = nestedSupervisorsAllForOne
ping(actor1) ping(actor1)
expectNoMessage(1 second) expectNoMessage(1.second)
} }
"kill single actor OneForOne" in { "kill single actor OneForOne" in {
@ -420,7 +419,7 @@ class SupervisorSpec
"attempt restart when exception during restart" in { "attempt restart when exception during restart" in {
val inits = new AtomicInteger(0) val inits = new AtomicInteger(0)
val supervisor = system.actorOf(Props( val supervisor = system.actorOf(Props(
new Supervisor(OneForOneStrategy(maxNrOfRetries = 3, withinTimeRange = 10 seconds)(classOf[Exception] :: Nil)))) new Supervisor(OneForOneStrategy(maxNrOfRetries = 3, withinTimeRange = 10.seconds)(classOf[Exception] :: Nil))))
val dyingProps = Props(new Actor { val dyingProps = Props(new Actor {
val init = inits.getAndIncrement() val init = inits.getAndIncrement()
@ -467,7 +466,7 @@ class SupervisorSpec
val child = context.watch(context.actorOf(Props(new Actor { val child = context.watch(context.actorOf(Props(new Actor {
override def postRestart(reason: Throwable): Unit = testActor ! "child restarted" override def postRestart(reason: Throwable): Unit = testActor ! "child restarted"
def receive = { def receive = {
case l: TestLatch => { Await.ready(l, 5 seconds); throw new IllegalStateException("OHNOES") } case l: TestLatch => { Await.ready(l, 5.seconds); throw new IllegalStateException("OHNOES") }
case "test" => sender() ! "child green" case "test" => sender() ! "child green"
} }
}), "child")) }), "child"))
@ -589,7 +588,7 @@ class SupervisorSpec
"treats maxNrOfRetries = -1 as maxNrOfRetries = 1 if withinTimeRange is non-infinite Duration" in { "treats maxNrOfRetries = -1 as maxNrOfRetries = 1 if withinTimeRange is non-infinite Duration" in {
val supervisor = system.actorOf(Props( val supervisor = system.actorOf(Props(
new Supervisor(OneForOneStrategy(maxNrOfRetries = -1, withinTimeRange = 10 seconds)(classOf[Exception] :: Nil)))) new Supervisor(OneForOneStrategy(maxNrOfRetries = -1, withinTimeRange = 10.seconds)(classOf[Exception] :: Nil))))
val pingpong = child(supervisor, Props(new PingPongActor(testActor))) val pingpong = child(supervisor, Props(new PingPongActor(testActor)))

View file

@ -16,8 +16,6 @@ package org.apache.pekko.actor
import scala.concurrent.Await import scala.concurrent.Await
import scala.concurrent.duration._ import scala.concurrent.duration._
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.pattern.ask import pekko.pattern.ask
import pekko.testkit.{ DefaultTimeout, EventFilter, ImplicitSender, PekkoSpec } import pekko.testkit.{ DefaultTimeout, EventFilter, ImplicitSender, PekkoSpec }
@ -28,10 +26,10 @@ class SupervisorTreeSpec extends PekkoSpec with ImplicitSender with DefaultTimeo
"be able to kill the middle actor and see itself and its child restarted" in { "be able to kill the middle actor and see itself and its child restarted" in {
EventFilter[ActorKilledException](occurrences = 1).intercept { EventFilter[ActorKilledException](occurrences = 1).intercept {
within(5 seconds) { within(5.seconds) {
val p = Props(new Actor { val p = Props(new Actor {
override val supervisorStrategy = override val supervisorStrategy =
OneForOneStrategy(maxNrOfRetries = 3, withinTimeRange = 1 second)(List(classOf[Exception])) OneForOneStrategy(maxNrOfRetries = 3, withinTimeRange = 1.second)(List(classOf[Exception]))
def receive = { def receive = {
case p: Props => sender() ! context.actorOf(p) case p: Props => sender() ! context.actorOf(p)
} }
@ -44,7 +42,7 @@ class SupervisorTreeSpec extends PekkoSpec with ImplicitSender with DefaultTimeo
middleActor ! Kill middleActor ! Kill
expectMsg(middleActor.path) expectMsg(middleActor.path)
expectMsg(lastActor.path) expectMsg(lastActor.path)
expectNoMessage(2 seconds) expectNoMessage(2.seconds)
system.stop(headActor) system.stop(headActor)
} }
} }

View file

@ -16,7 +16,6 @@ package org.apache.pekko.actor
import scala.concurrent.Await import scala.concurrent.Await
import scala.concurrent.duration._ import scala.concurrent.duration._
import language.postfixOps
import org.scalatest.BeforeAndAfterAll import org.scalatest.BeforeAndAfterAll
import org.apache.pekko import org.apache.pekko
@ -38,7 +37,7 @@ class Ticket669Spec extends PekkoSpec with BeforeAndAfterAll with ImplicitSender
"be able to reply on failure during preRestart" in { "be able to reply on failure during preRestart" in {
filterEvents(EventFilter[Exception]("test", occurrences = 1)) { filterEvents(EventFilter[Exception]("test", occurrences = 1)) {
val supervisor = val supervisor =
system.actorOf(Props(new Supervisor(AllForOneStrategy(5, 10 seconds)(List(classOf[Exception]))))) system.actorOf(Props(new Supervisor(AllForOneStrategy(5, 10.seconds)(List(classOf[Exception])))))
val supervised = Await.result((supervisor ? Props[Supervised]()).mapTo[ActorRef], timeout.duration) val supervised = Await.result((supervisor ? Props[Supervised]()).mapTo[ActorRef], timeout.duration)
supervised.!("test")(testActor) supervised.!("test")(testActor)

View file

@ -20,7 +20,6 @@ import scala.annotation.tailrec
import scala.collection.immutable import scala.collection.immutable
import scala.concurrent.{ Await, Future } import scala.concurrent.{ Await, Future }
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.language.postfixOps
import scala.annotation.nowarn import scala.annotation.nowarn
import org.scalatest.{ BeforeAndAfterAll, BeforeAndAfterEach } import org.scalatest.{ BeforeAndAfterAll, BeforeAndAfterEach }
@ -148,7 +147,7 @@ object TypedActorSpec {
@nowarn @nowarn
def futureComposePigdogFrom(foo: Foo): Future[String] = { def futureComposePigdogFrom(foo: Foo): Future[String] = {
foo.futurePigdog(500 millis).map(_.toUpperCase) foo.futurePigdog(500.millis).map(_.toUpperCase)
} }
def optionPigdog(): Option[String] = Some(pigdog()) def optionPigdog(): Option[String] = Some(pigdog())
@ -360,7 +359,7 @@ class TypedActorSpec
"be able to call Future-returning methods non-blockingly" in { "be able to call Future-returning methods non-blockingly" in {
val t = newFooBar val t = newFooBar
val f = t.futurePigdog(200 millis) val f = t.futurePigdog(200.millis)
f.isCompleted should ===(false) f.isCompleted should ===(false)
Await.result(f, timeout.duration) should ===("Pigdog") Await.result(f, timeout.duration) should ===("Pigdog")
mustStop(t) mustStop(t)
@ -368,7 +367,7 @@ class TypedActorSpec
"be able to call multiple Future-returning methods non-blockingly" in within(timeout.duration) { "be able to call multiple Future-returning methods non-blockingly" in within(timeout.duration) {
val t = newFooBar val t = newFooBar
val futures = for (i <- 1 to 20) yield (i, t.futurePigdog(20 millis, i)) val futures = for (i <- 1 to 20) yield (i, t.futurePigdog(20.millis, i))
for ((i, f) <- futures) { for ((i, f) <- futures) {
Await.result(f, remaining) should ===("Pigdog" + i) Await.result(f, remaining) should ===("Pigdog" + i)
} }
@ -376,22 +375,22 @@ class TypedActorSpec
} }
"be able to call methods returning Java Options" taggedAs TimingTest in { "be able to call methods returning Java Options" taggedAs TimingTest in {
val t = newFooBar(1 second) val t = newFooBar(1.second)
t.joptionPigdog(100 millis).get should ===("Pigdog") t.joptionPigdog(100.millis).get should ===("Pigdog")
t.joptionPigdog(2 seconds) should ===(JOption.none[String]) t.joptionPigdog(2.seconds) should ===(JOption.none[String])
mustStop(t) mustStop(t)
} }
"be able to handle AskTimeoutException as None" taggedAs TimingTest in { "be able to handle AskTimeoutException as None" taggedAs TimingTest in {
val t = newFooBar(200 millis) val t = newFooBar(200.millis)
t.joptionPigdog(600 millis) should ===(JOption.none[String]) t.joptionPigdog(600.millis) should ===(JOption.none[String])
mustStop(t) mustStop(t)
} }
"be able to call methods returning Scala Options" taggedAs TimingTest in { "be able to call methods returning Scala Options" taggedAs TimingTest in {
val t = newFooBar(1 second) val t = newFooBar(1.second)
t.optionPigdog(100 millis).get should ===("Pigdog") t.optionPigdog(100.millis).get should ===("Pigdog")
t.optionPigdog(2 seconds) should ===(None) t.optionPigdog(2.seconds) should ===(None)
mustStop(t) mustStop(t)
} }
@ -415,14 +414,14 @@ class TypedActorSpec
} }
})) }))
val t = Await.result( val t = Await.result(
(boss ? TypedProps[Bar](classOf[Foo], classOf[Bar]).withTimeout(2 seconds)).mapTo[Foo], (boss ? TypedProps[Bar](classOf[Foo], classOf[Bar]).withTimeout(2.seconds)).mapTo[Foo],
timeout.duration) timeout.duration)
t.incr() t.incr()
t.failingPigdog() t.failingPigdog()
t.read() should ===(1) // Make sure state is not reset after failure t.read() should ===(1) // Make sure state is not reset after failure
intercept[IllegalStateException] { Await.result(t.failingFuturePigdog(), 2 seconds) }.getMessage should ===( intercept[IllegalStateException] { Await.result(t.failingFuturePigdog(), 2.seconds) }.getMessage should ===(
"expected") "expected")
t.read() should ===(1) // Make sure state is not reset after failure t.read() should ===(1) // Make sure state is not reset after failure
@ -461,7 +460,7 @@ class TypedActorSpec
"be able to support implementation only typed actors" in within(timeout.duration) { "be able to support implementation only typed actors" in within(timeout.duration) {
val t: Foo = pekko.actor.TypedActor(system).typedActorOf(TypedProps[Bar]()) val t: Foo = pekko.actor.TypedActor(system).typedActorOf(TypedProps[Bar]())
val f = t.futurePigdog(200 millis) val f = t.futurePigdog(200.millis)
val f2 = t.futurePigdog(Duration.Zero) val f2 = t.futurePigdog(Duration.Zero)
f2.isCompleted should ===(false) f2.isCompleted should ===(false)
f.isCompleted should ===(false) f.isCompleted should ===(false)
@ -477,10 +476,10 @@ class TypedActorSpec
} }
"be able to use balancing dispatcher" in within(timeout.duration) { "be able to use balancing dispatcher" in within(timeout.duration) {
val thais = for (_ <- 1 to 60) yield newFooBar("pooled-dispatcher", 6 seconds) val thais = for (_ <- 1 to 60) yield newFooBar("pooled-dispatcher", 6.seconds)
val iterator = new CyclicIterator(thais) val iterator = new CyclicIterator(thais)
val results = for (i <- 1 to 120) yield (i, iterator.next().futurePigdog(200 millis, i)) val results = for (i <- 1 to 120) yield (i, iterator.next().futurePigdog(200.millis, i))
for ((i, r) <- results) Await.result(r, remaining) should ===("Pigdog" + i) for ((i, r) <- results) Await.result(r, remaining) should ===("Pigdog" + i)

View file

@ -23,7 +23,6 @@ import scala.concurrent.duration._
import scala.annotation.nowarn import scala.annotation.nowarn
import com.typesafe.config.Config import com.typesafe.config.Config
import language.postfixOps
import org.scalatest.Assertions._ import org.scalatest.Assertions._
import org.apache.pekko import org.apache.pekko
@ -273,7 +272,7 @@ abstract class ActorModelSpec(config: String) extends PekkoSpec(config) with Def
awaitCond(ref match { awaitCond(ref match {
case r: RepointableRef => r.isStarted case r: RepointableRef => r.isStarted
case _ => true case _ => true
}, 1 second, 10 millis) }, 1.second, 10.millis)
} }
protected def interceptedDispatcher(): MessageDispatcherInterceptor protected def interceptedDispatcher(): MessageDispatcherInterceptor
@ -322,7 +321,7 @@ abstract class ActorModelSpec(config: String) extends PekkoSpec(config) with Def
a ! Wait(1000) a ! Wait(1000)
a ! CountDown(oneAtATime) a ! CountDown(oneAtATime)
// in case of serialization violation, restart would happen instead of count down // in case of serialization violation, restart would happen instead of count down
assertCountDown(oneAtATime, (1.5 seconds).dilated.toMillis, "Processed message when allowed") assertCountDown(oneAtATime, 1.5.seconds.dilated.toMillis, "Processed message when allowed")
assertRefDefaultZero(a)(registers = 1, msgsReceived = 3, msgsProcessed = 3) assertRefDefaultZero(a)(registers = 1, msgsReceived = 3, msgsProcessed = 3)
system.stop(a) system.stop(a)
@ -389,7 +388,7 @@ abstract class ActorModelSpec(config: String) extends PekkoSpec(config) with Def
val cachedMessage = CountDownNStop(new CountDownLatch(num)) val cachedMessage = CountDownNStop(new CountDownLatch(num))
val stopLatch = new CountDownLatch(num) val stopLatch = new CountDownLatch(num)
val keepAliveLatch = new CountDownLatch(1) val keepAliveLatch = new CountDownLatch(1)
val waitTime = (20 seconds).dilated.toMillis val waitTime = 20.seconds.dilated.toMillis
val boss = system.actorOf(Props(new Actor { val boss = system.actorOf(Props(new Actor {
def receive = { def receive = {
case "run" => for (_ <- 1 to num) context.watch(context.actorOf(props)) ! cachedMessage case "run" => for (_ <- 1 to num) context.watch(context.actorOf(props)) ! cachedMessage

View file

@ -19,8 +19,6 @@ import java.util.concurrent.atomic.AtomicBoolean
import scala.concurrent.Await import scala.concurrent.Await
import scala.concurrent.duration._ import scala.concurrent.duration._
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.actor.{ Actor, Props } import pekko.actor.{ Actor, Props }
import pekko.pattern.ask import pekko.pattern.ask
@ -112,7 +110,7 @@ class DispatcherActorSpec extends PekkoSpec(DispatcherActorSpec.config) with Def
} }
"respect throughput deadline" in { "respect throughput deadline" in {
val deadline = 100 millis val deadline = 100.millis
val throughputDispatcher = "test-throughput-deadline-dispatcher" val throughputDispatcher = "test-throughput-deadline-dispatcher"
val works = new AtomicBoolean(true) val works = new AtomicBoolean(true)

View file

@ -19,8 +19,6 @@ import scala.concurrent.ExecutionException
import scala.concurrent.Future import scala.concurrent.Future
import scala.concurrent.duration._ import scala.concurrent.duration._
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.actor.{ Actor, Props } import pekko.actor.{ Actor, Props }
import pekko.actor.ActorRef import pekko.actor.ActorRef
@ -33,20 +31,20 @@ class Future2ActorSpec extends PekkoSpec with DefaultTimeout {
"support convenient sending to multiple destinations" in { "support convenient sending to multiple destinations" in {
Future(42).pipeTo(testActor).pipeTo(testActor) Future(42).pipeTo(testActor).pipeTo(testActor)
expectMsgAllOf(1 second, 42, 42) expectMsgAllOf(1.second, 42, 42)
} }
"support convenient sending to multiple destinations with implicit sender" in { "support convenient sending to multiple destinations with implicit sender" in {
implicit val someActor: ActorRef = system.actorOf(Props(new Actor { def receive = Actor.emptyBehavior })) implicit val someActor: ActorRef = system.actorOf(Props(new Actor { def receive = Actor.emptyBehavior }))
Future(42).pipeTo(testActor).pipeTo(testActor) Future(42).pipeTo(testActor).pipeTo(testActor)
expectMsgAllOf(1 second, 42, 42) expectMsgAllOf(1.second, 42, 42)
lastSender should ===(someActor) lastSender should ===(someActor)
} }
"support convenient sending with explicit sender" in { "support convenient sending with explicit sender" in {
val someActor = system.actorOf(Props(new Actor { def receive = Actor.emptyBehavior })) val someActor = system.actorOf(Props(new Actor { def receive = Actor.emptyBehavior }))
Future(42).to(testActor, someActor) Future(42).to(testActor, someActor)
expectMsgAllOf(1 second, 42) expectMsgAllOf(1.second, 42)
lastSender should ===(someActor) lastSender should ===(someActor)
} }

View file

@ -19,7 +19,6 @@ import scala.concurrent.{ Await, ExecutionContext, Future }
import scala.concurrent.duration._ import scala.concurrent.duration._
import com.typesafe.config.{ Config, ConfigFactory } import com.typesafe.config.{ Config, ConfigFactory }
import language.postfixOps
import org.scalatest.{ BeforeAndAfterAll, BeforeAndAfterEach } import org.scalatest.{ BeforeAndAfterAll, BeforeAndAfterEach }
import org.apache.pekko import org.apache.pekko
@ -51,11 +50,11 @@ abstract class MailboxSpec extends PekkoSpec with BeforeAndAfterAll with BeforeA
} }
"BoundedMailbox.numberOfMessages should be consistent with queue size" in { "BoundedMailbox.numberOfMessages should be consistent with queue size" in {
ensureSingleConsumerEnqueueDequeue(BoundedMailbox(1000, 10 milliseconds)) ensureSingleConsumerEnqueueDequeue(BoundedMailbox(1000, 10.milliseconds))
} }
"create a bounded mailbox with 10 capacity and with push timeout" in { "create a bounded mailbox with 10 capacity and with push timeout" in {
val config = BoundedMailbox(10, 10 milliseconds) val config = BoundedMailbox(10, 10.milliseconds)
config.capacity should ===(10) config.capacity should ===(10)
val q = factory(config) val q = factory(config)
ensureInitialMailboxState(config, q) ensureInitialMailboxState(config, q)
@ -80,15 +79,15 @@ abstract class MailboxSpec extends PekkoSpec with BeforeAndAfterAll with BeforeA
} }
"dequeue what was enqueued properly for bounded mailboxes" in { "dequeue what was enqueued properly for bounded mailboxes" in {
testEnqueueDequeue(BoundedMailbox(10000, -1 millisecond)) testEnqueueDequeue(BoundedMailbox(10000, -1.millisecond))
} }
"dequeue what was enqueued properly for bounded mailboxes with 0 pushTimeout" in { "dequeue what was enqueued properly for bounded mailboxes with 0 pushTimeout" in {
testEnqueueDequeue(BoundedMailbox(10, 0 millisecond), 20, 10, false) testEnqueueDequeue(BoundedMailbox(10, 0.millisecond), 20, 10, false)
} }
"dequeue what was enqueued properly for bounded mailboxes with pushTimeout" in { "dequeue what was enqueued properly for bounded mailboxes with pushTimeout" in {
testEnqueueDequeue(BoundedMailbox(10000, 100 milliseconds)) testEnqueueDequeue(BoundedMailbox(10000, 100.milliseconds))
} }
} }
@ -144,7 +143,7 @@ abstract class MailboxSpec extends PekkoSpec with BeforeAndAfterAll with BeforeA
config: MailboxType, config: MailboxType,
enqueueN: Int = 10000, enqueueN: Int = 10000,
dequeueN: Int = 10000, dequeueN: Int = 10000,
parallel: Boolean = true): Unit = within(10 seconds) { parallel: Boolean = true): Unit = within(10.seconds) {
val q = factory(config) val q = factory(config)
ensureInitialMailboxState(config, q) ensureInitialMailboxState(config, q)
@ -260,7 +259,7 @@ class CustomMailboxSpec extends PekkoSpec(CustomMailboxSpec.config) {
awaitCond(actor match { awaitCond(actor match {
case r: RepointableRef => r.isStarted case r: RepointableRef => r.isStarted
case _ => true case _ => true
}, 1 second, 10 millis) }, 1.second, 10.millis)
val queue = actor.asInstanceOf[ActorRefWithCell].underlying.asInstanceOf[ActorCell].mailbox.messageQueue val queue = actor.asInstanceOf[ActorRefWithCell].underlying.asInstanceOf[ActorCell].mailbox.messageQueue
queue.getClass should ===(classOf[CustomMailboxSpec.MyMailbox]) queue.getClass should ===(classOf[CustomMailboxSpec.MyMailbox])
} }

View file

@ -16,7 +16,6 @@ package org.apache.pekko.dispatch
import scala.concurrent.duration._ import scala.concurrent.duration._
import com.typesafe.config.Config import com.typesafe.config.Config
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.actor.{ Actor, ActorSystem, Props } import pekko.actor.{ Actor, ActorSystem, Props }
@ -48,7 +47,7 @@ object PriorityDispatcherSpec {
case i: Int => i // Reverse order case i: Int => i // Reverse order
case Result => Int.MaxValue case Result => Int.MaxValue
case _ => throw new RuntimeException() // compiler exhaustiveness check pleaser case _ => throw new RuntimeException() // compiler exhaustiveness check pleaser
}: Any => Int), 1000, 10 seconds) }: Any => Int), 1000, 10.seconds)
} }
@ -68,7 +67,7 @@ class PriorityDispatcherSpec extends PekkoSpec(PriorityDispatcherSpec.config) wi
} }
def testOrdering(dispatcherKey: String): Unit = { def testOrdering(dispatcherKey: String): Unit = {
val msgs = (1 to 100) toList val msgs = (1 to 100).toList
// It's important that the actor under test is not a top level actor // It's important that the actor under test is not a top level actor
// with RepointableActorRef, since messages might be queued in // with RepointableActorRef, since messages might be queued in

View file

@ -16,7 +16,6 @@ package org.apache.pekko.dispatch
import scala.concurrent.duration._ import scala.concurrent.duration._
import com.typesafe.config.Config import com.typesafe.config.Config
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.actor.{ Actor, ActorSystem, Props } import pekko.actor.{ Actor, ActorSystem, Props }
@ -49,7 +48,7 @@ object StablePriorityDispatcherSpec {
case _: Int => 101 // Don't care for other integers case _: Int => 101 // Don't care for other integers
case Result => Int.MaxValue case Result => Int.MaxValue
case _ => throw new RuntimeException() // compiler exhaustiveness check pleaser case _ => throw new RuntimeException() // compiler exhaustiveness check pleaser
}: Any => Int), 1000, 10 seconds) }: Any => Int), 1000, 10.seconds)
} }
@ -70,7 +69,7 @@ class StablePriorityDispatcherSpec extends PekkoSpec(StablePriorityDispatcherSpe
} }
def testOrdering(dispatcherKey: String): Unit = { def testOrdering(dispatcherKey: String): Unit = {
val msgs = (1 to 200) toList val msgs = (1 to 200).toList
val shuffled = scala.util.Random.shuffle(msgs) val shuffled = scala.util.Random.shuffle(msgs)
// It's important that the actor under test is not a top level actor // It's important that the actor under test is not a top level actor
@ -100,7 +99,7 @@ class StablePriorityDispatcherSpec extends PekkoSpec(StablePriorityDispatcherSpe
// Low messages should come out first, and in priority order. High messages follow - they are equal priority and // Low messages should come out first, and in priority order. High messages follow - they are equal priority and
// should come out in the same order in which they were sent. // should come out in the same order in which they were sent.
val lo = (1 to 100) toList val lo = (1 to 100).toList
val hi = shuffled.filter { _ > 100 } val hi = shuffled.filter { _ > 100 }
(expectMsgType[List[Int]]: List[Int]) should ===(lo ++ hi) (expectMsgType[List[Int]]: List[Int]) should ===(lo ++ hi)
} }

View file

@ -17,7 +17,6 @@ import scala.annotation.tailrec
import scala.concurrent.duration._ import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
import language.postfixOps
import org.scalatest.BeforeAndAfterAll import org.scalatest.BeforeAndAfterAll
import org.scalatest.wordspec.AnyWordSpec import org.scalatest.wordspec.AnyWordSpec
@ -29,7 +28,7 @@ import pekko.util.ccompat.JavaConverters._
object LoggingReceiveSpec { object LoggingReceiveSpec {
class TestLogActor extends Actor { class TestLogActor extends Actor {
override val supervisorStrategy = override val supervisorStrategy =
OneForOneStrategy(maxNrOfRetries = 5, withinTimeRange = 5 seconds)(List(classOf[Throwable])) OneForOneStrategy(maxNrOfRetries = 5, withinTimeRange = 5.seconds)(List(classOf[Throwable]))
def receive = { case _ => } def receive = { case _ => }
} }
} }
@ -85,12 +84,12 @@ class LoggingReceiveSpec extends AnyWordSpec with BeforeAndAfterAll {
})) }))
a ! "hallo" a ! "hallo"
expectMsg( expectMsg(
1 second, 1.second,
Logging.Debug( Logging.Debug(
"funky", "funky",
classOf[DummyClassForStringSources], classOf[DummyClassForStringSources],
"received unhandled message hallo from " + system.deadLetters)) "received unhandled message hallo from " + system.deadLetters))
expectMsgType[UnhandledMessage](1 second) expectMsgType[UnhandledMessage](1.second)
} }
} }
@ -206,7 +205,7 @@ class LoggingReceiveSpec extends AnyWordSpec with BeforeAndAfterAll {
"log Supervision events if requested" in { "log Supervision events if requested" in {
new TestKit(appLifecycle) { new TestKit(appLifecycle) {
system.eventStream.subscribe(testActor, classOf[Logging.Debug]) system.eventStream.subscribe(testActor, classOf[Logging.Debug])
within(3 seconds) { within(3.seconds) {
val lifecycleGuardian = appLifecycle.asInstanceOf[ActorSystemImpl].guardian val lifecycleGuardian = appLifecycle.asInstanceOf[ActorSystemImpl].guardian
val lname = lifecycleGuardian.path.toString val lname = lifecycleGuardian.path.toString
val supervisor = TestActorRef[TestLogActor](Props[TestLogActor]()) val supervisor = TestActorRef[TestLogActor](Props[TestLogActor]())
@ -230,7 +229,7 @@ class LoggingReceiveSpec extends AnyWordSpec with BeforeAndAfterAll {
"log DeathWatch events if requested" in { "log DeathWatch events if requested" in {
new TestKit(appLifecycle) { new TestKit(appLifecycle) {
system.eventStream.subscribe(testActor, classOf[Logging.Debug]) system.eventStream.subscribe(testActor, classOf[Logging.Debug])
within(3 seconds) { within(3.seconds) {
val supervisor = TestActorRef[TestLogActor](Props[TestLogActor]()) val supervisor = TestActorRef[TestLogActor](Props[TestLogActor]())
val sclass = classOf[TestLogActor] val sclass = classOf[TestLogActor]
val actor = TestActorRef[TestLogActor](Props[TestLogActor](), supervisor, "none") val actor = TestActorRef[TestLogActor](Props[TestLogActor](), supervisor, "none")
@ -255,7 +254,7 @@ class LoggingReceiveSpec extends AnyWordSpec with BeforeAndAfterAll {
new TestKit(appLifecycle) { new TestKit(appLifecycle) {
system.eventStream.subscribe(testActor, classOf[Logging.Debug]) system.eventStream.subscribe(testActor, classOf[Logging.Debug])
system.eventStream.subscribe(testActor, classOf[Logging.Error]) system.eventStream.subscribe(testActor, classOf[Logging.Error])
within(3 seconds) { within(3.seconds) {
val supervisor = TestActorRef[TestLogActor](Props[TestLogActor]()) val supervisor = TestActorRef[TestLogActor](Props[TestLogActor]())
val sname = supervisor.path.toString val sname = supervisor.path.toString
val sclass = classOf[TestLogActor] val sclass = classOf[TestLogActor]

View file

@ -17,7 +17,6 @@ import java.io.IOException
import java.net.{ InetSocketAddress, ServerSocket } import java.net.{ InetSocketAddress, ServerSocket }
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.language.postfixOps
import org.scalatest.concurrent.TimeLimits import org.scalatest.concurrent.TimeLimits
@ -194,7 +193,7 @@ class TcpIntegrationSpec extends PekkoSpec("""
connectCommander.expectMsgType[Connected].remoteAddress should ===(endpoint) connectCommander.expectMsgType[Connected].remoteAddress should ===(endpoint)
val connectionActor = connectCommander.lastSender val connectionActor = connectCommander.lastSender
connectCommander.send(connectionActor, PoisonPill) connectCommander.send(connectionActor, PoisonPill)
failAfter(3 seconds) { failAfter(3.seconds) {
try { try {
accept.getInputStream.read() should ===(-1) accept.getInputStream.read() should ===(-1)
} catch { } catch {

View file

@ -18,8 +18,6 @@ import scala.concurrent.duration._
import scala.util.Failure import scala.util.Failure
import scala.annotation.nowarn import scala.annotation.nowarn
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.actor._ import pekko.actor._
import pekko.testkit.{ PekkoSpec, TestProbe } import pekko.testkit.{ PekkoSpec, TestProbe }
@ -41,7 +39,7 @@ class AskSpec extends PekkoSpec("""
} }
"return broken promises on DeadLetters" in { "return broken promises on DeadLetters" in {
val f = system.deadLetters.ask(42)(1 second) val f = system.deadLetters.ask(42)(1.second)
f.isCompleted should ===(true) f.isCompleted should ===(true)
f.value.get match { f.value.get match {
case Failure(_: AskTimeoutException) => case Failure(_: AskTimeoutException) =>
@ -50,7 +48,7 @@ class AskSpec extends PekkoSpec("""
} }
"return broken promises on EmptyLocalActorRefs" in { "return broken promises on EmptyLocalActorRefs" in {
implicit val timeout: Timeout = Timeout(5 seconds) implicit val timeout: Timeout = Timeout(5.seconds)
val empty = system.asInstanceOf[ExtendedActorSystem].provider.resolveActorRef("/user/unknown") val empty = system.asInstanceOf[ExtendedActorSystem].provider.resolveActorRef("/user/unknown")
val f = empty ? 3.14 val f = empty ? 3.14
f.isCompleted should ===(true) f.isCompleted should ===(true)
@ -61,7 +59,7 @@ class AskSpec extends PekkoSpec("""
} }
"return broken promises on unsupported ActorRefs" in { "return broken promises on unsupported ActorRefs" in {
implicit val timeout: Timeout = Timeout(5 seconds) implicit val timeout: Timeout = Timeout(5.seconds)
val f = ask(null: ActorRef, 3.14) val f = ask(null: ActorRef, 3.14)
f.isCompleted should ===(true) f.isCompleted should ===(true)
@ -72,7 +70,7 @@ class AskSpec extends PekkoSpec("""
} }
"return broken promises on 0 timeout" in { "return broken promises on 0 timeout" in {
implicit val timeout: Timeout = Timeout(0 seconds) implicit val timeout: Timeout = Timeout(0.seconds)
val echo = system.actorOf(Props(new Actor { def receive = { case x => sender() ! x } })) val echo = system.actorOf(Props(new Actor { def receive = { case x => sender() ! x } }))
val f = echo ? "foo" val f = echo ? "foo"
val expectedMsg = val expectedMsg =
@ -83,7 +81,7 @@ class AskSpec extends PekkoSpec("""
} }
"return broken promises on < 0 timeout" in { "return broken promises on < 0 timeout" in {
implicit val timeout: Timeout = Timeout(-1000 seconds) implicit val timeout: Timeout = Timeout(-1000.seconds)
val echo = system.actorOf(Props(new Actor { def receive = { case x => sender() ! x } })) val echo = system.actorOf(Props(new Actor { def receive = { case x => sender() ! x } }))
val f = echo ? "foo" val f = echo ? "foo"
val expectedMsg = val expectedMsg =
@ -94,51 +92,51 @@ class AskSpec extends PekkoSpec("""
} }
"include target information in AskTimeout" in { "include target information in AskTimeout" in {
implicit val timeout: Timeout = Timeout(0.5 seconds) implicit val timeout: Timeout = Timeout(0.5.seconds)
val silentOne = system.actorOf(Props.empty, "silent") val silentOne = system.actorOf(Props.empty, "silent")
val f = silentOne ? "noreply" val f = silentOne ? "noreply"
intercept[AskTimeoutException] { intercept[AskTimeoutException] {
Await.result(f, 1 second) Await.result(f, 1.second)
}.getMessage.contains("/user/silent") should ===(true) }.getMessage.contains("/user/silent") should ===(true)
} }
"include timeout information in AskTimeout" in { "include timeout information in AskTimeout" in {
implicit val timeout: Timeout = Timeout(0.5 seconds) implicit val timeout: Timeout = Timeout(0.5.seconds)
val f = system.actorOf(Props.empty) ? "noreply" val f = system.actorOf(Props.empty) ? "noreply"
intercept[AskTimeoutException] { intercept[AskTimeoutException] {
Await.result(f, 1 second) Await.result(f, 1.second)
}.getMessage should include(timeout.duration.toMillis.toString) }.getMessage should include(timeout.duration.toMillis.toString)
} }
"include sender information in AskTimeout" in { "include sender information in AskTimeout" in {
implicit val timeout: Timeout = Timeout(0.5 seconds) implicit val timeout: Timeout = Timeout(0.5.seconds)
implicit val sender: ActorRef = system.actorOf(Props.empty) implicit val sender: ActorRef = system.actorOf(Props.empty)
val f = system.actorOf(Props.empty) ? "noreply" val f = system.actorOf(Props.empty) ? "noreply"
intercept[AskTimeoutException] { intercept[AskTimeoutException] {
Await.result(f, 1 second) Await.result(f, 1.second)
}.getMessage.contains(sender.toString) should ===(true) }.getMessage.contains(sender.toString) should ===(true)
} }
"include message class information in AskTimeout" in { "include message class information in AskTimeout" in {
implicit val timeout: Timeout = Timeout(0.5 seconds) implicit val timeout: Timeout = Timeout(0.5.seconds)
val f = system.actorOf(Props.empty) ? Integer.valueOf(17) val f = system.actorOf(Props.empty) ? Integer.valueOf(17)
intercept[AskTimeoutException] { intercept[AskTimeoutException] {
Await.result(f, 1 second) Await.result(f, 1.second)
}.getMessage should include("[java.lang.Integer") }.getMessage should include("[java.lang.Integer")
} }
"work for ActorSelection" in { "work for ActorSelection" in {
implicit val timeout: Timeout = Timeout(5 seconds) implicit val timeout: Timeout = Timeout(5.seconds)
import system.dispatcher import system.dispatcher
val echo = system.actorOf(Props(new Actor { def receive = { case x => sender() ! x } }), "select-echo") val echo = system.actorOf(Props(new Actor { def receive = { case x => sender() ! x } }), "select-echo")
val identityFuture = val identityFuture =
(system.actorSelection("/user/select-echo") ? Identify(None)).mapTo[ActorIdentity].map(_.ref.get) (system.actorSelection("/user/select-echo") ? Identify(None)).mapTo[ActorIdentity].map(_.ref.get)
Await.result(identityFuture, 5 seconds) should ===(echo) Await.result(identityFuture, 5.seconds) should ===(echo)
} }
"work when reply uses actor selection" in { "work when reply uses actor selection" in {
implicit val timeout: Timeout = Timeout(5 seconds) implicit val timeout: Timeout = Timeout(5.seconds)
val deadListener = TestProbe() val deadListener = TestProbe()
system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter]) system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter])
@ -147,13 +145,13 @@ class AskSpec extends PekkoSpec("""
}), "select-echo2") }), "select-echo2")
val f = echo ? "hi" val f = echo ? "hi"
Await.result(f, 1 seconds) should ===("hi") Await.result(f, 1.seconds) should ===("hi")
deadListener.expectNoMessage(200 milliseconds) deadListener.expectNoMessage(200.milliseconds)
} }
"throw AskTimeoutException on using *" in { "throw AskTimeoutException on using *" in {
implicit val timeout: Timeout = Timeout(0.5 seconds) implicit val timeout: Timeout = Timeout(0.5.seconds)
val deadListener = TestProbe() val deadListener = TestProbe()
system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter]) system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter])
@ -162,14 +160,14 @@ class AskSpec extends PekkoSpec("""
"select-echo3") "select-echo3")
val f = echo ? "hi" val f = echo ? "hi"
intercept[AskTimeoutException] { intercept[AskTimeoutException] {
Await.result(f, 1 seconds) Await.result(f, 1.seconds)
} }
deadListener.expectMsgClass(200 milliseconds, classOf[DeadLetter]) deadListener.expectMsgClass(200.milliseconds, classOf[DeadLetter])
} }
"throw AskTimeoutException on using .." in { "throw AskTimeoutException on using .." in {
implicit val timeout: Timeout = Timeout(0.5 seconds) implicit val timeout: Timeout = Timeout(0.5.seconds)
val deadListener = TestProbe() val deadListener = TestProbe()
system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter]) system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter])
@ -183,14 +181,14 @@ class AskSpec extends PekkoSpec("""
}), "select-echo4") }), "select-echo4")
val f = echo ? "hi" val f = echo ? "hi"
intercept[AskTimeoutException] { intercept[AskTimeoutException] {
Await.result(f, 1 seconds) should ===("hi") Await.result(f, 1.seconds) should ===("hi")
} }
deadListener.expectMsgClass(200 milliseconds, classOf[DeadLetter]) deadListener.expectMsgClass(200.milliseconds, classOf[DeadLetter])
} }
"send to DeadLetter when child does not exist" in { "send to DeadLetter when child does not exist" in {
implicit val timeout: Timeout = Timeout(0.5 seconds) implicit val timeout: Timeout = Timeout(0.5.seconds)
val deadListener = TestProbe() val deadListener = TestProbe()
system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter]) system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter])
@ -203,13 +201,13 @@ class AskSpec extends PekkoSpec("""
}), "select-echo5") }), "select-echo5")
val f = echo ? "hi" val f = echo ? "hi"
intercept[AskTimeoutException] { intercept[AskTimeoutException] {
Await.result(f, 1 seconds) should ===("hi") Await.result(f, 1.seconds) should ===("hi")
} }
deadListener.expectMsgClass(200 milliseconds, classOf[DeadLetter]) deadListener.expectMsgClass(200.milliseconds, classOf[DeadLetter])
} }
"send DeadLetter when answering to grandchild" in { "send DeadLetter when answering to grandchild" in {
implicit val timeout: Timeout = Timeout(0.5 seconds) implicit val timeout: Timeout = Timeout(0.5.seconds)
val deadListener = TestProbe() val deadListener = TestProbe()
system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter]) system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter])
@ -221,13 +219,13 @@ class AskSpec extends PekkoSpec("""
}), "select-echo6") }), "select-echo6")
val f = echo ? "hi" val f = echo ? "hi"
intercept[AskTimeoutException] { intercept[AskTimeoutException] {
Await.result(f, 1 seconds) should ===(ActorSelectionMessage("hi", Vector(SelectChildName("missing")), false)) Await.result(f, 1.seconds) should ===(ActorSelectionMessage("hi", Vector(SelectChildName("missing")), false))
} }
deadListener.expectMsgClass(200 milliseconds, classOf[DeadLetter]) deadListener.expectMsgClass(200.milliseconds, classOf[DeadLetter])
} }
"allow watching the promiseActor and send Terminated() when completes" in { "allow watching the promiseActor and send Terminated() when completes" in {
implicit val timeout: Timeout = Timeout(300 millis) implicit val timeout: Timeout = Timeout(300.millis)
val p = TestProbe() val p = TestProbe()
val act = system.actorOf(Props(new Actor { val act = system.actorOf(Props(new Actor {
@ -248,7 +246,7 @@ class AskSpec extends PekkoSpec("""
} }
"encode target name in temporary actor name" in { "encode target name in temporary actor name" in {
implicit val timeout: Timeout = Timeout(300 millis) implicit val timeout: Timeout = Timeout(300.millis)
val p = TestProbe() val p = TestProbe()
val act = system.actorOf(Props(new Actor { val act = system.actorOf(Props(new Actor {
@ -268,7 +266,7 @@ class AskSpec extends PekkoSpec("""
} }
"proper path when promise actor terminated" in { "proper path when promise actor terminated" in {
implicit val timeout: Timeout = Timeout(300 millis) implicit val timeout: Timeout = Timeout(300.millis)
val p = TestProbe() val p = TestProbe()
val act = system.actorOf(Props(new Actor { val act = system.actorOf(Props(new Actor {

View file

@ -16,7 +16,6 @@ package org.apache.pekko.pattern
import java.util.concurrent.{ CountDownLatch, TimeUnit } import java.util.concurrent.{ CountDownLatch, TimeUnit }
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.language.postfixOps
import scala.annotation.nowarn import scala.annotation.nowarn
@ -70,9 +69,9 @@ class BackoffOnRestartSupervisorSpec extends PekkoSpec("""
def supervisorProps(probeRef: ActorRef) = { def supervisorProps(probeRef: ActorRef) = {
val options = BackoffOpts val options = BackoffOpts
.onFailure(TestActor.props(probeRef), "someChildName", 200 millis, 10 seconds, 0.0) .onFailure(TestActor.props(probeRef), "someChildName", 200.millis, 10.seconds, 0.0)
.withMaxNrOfRetries(-1) .withMaxNrOfRetries(-1)
.withSupervisorStrategy(OneForOneStrategy(maxNrOfRetries = 5, withinTimeRange = 30 seconds) { .withSupervisorStrategy(OneForOneStrategy(maxNrOfRetries = 5, withinTimeRange = 30.seconds) {
case _: TestActor.StoppingException => SupervisorStrategy.Stop case _: TestActor.StoppingException => SupervisorStrategy.Stop
}) })
BackoffSupervisor.props(options) BackoffSupervisor.props(options)
@ -105,23 +104,23 @@ class BackoffOnRestartSupervisorSpec extends PekkoSpec("""
// Exponential back off restart test // Exponential back off restart test
supervisor ! "THROW" supervisor ! "THROW"
// numRestart = 0: expected delay ~200 millis // numRestart = 0: expected delay ~200 millis
probe.expectNoMessage(200 millis) probe.expectNoMessage(200.millis)
probe.expectMsg(250 millis, "STARTED") probe.expectMsg(250.millis, "STARTED")
supervisor ! "THROW" supervisor ! "THROW"
// numRestart = 1: expected delay ~400 millis // numRestart = 1: expected delay ~400 millis
probe.expectNoMessage(400 millis) probe.expectNoMessage(400.millis)
probe.expectMsg(250 millis, "STARTED") probe.expectMsg(250.millis, "STARTED")
supervisor ! "THROW" supervisor ! "THROW"
// numRestart = 2: expected delay ~800 millis // numRestart = 2: expected delay ~800 millis
probe.expectNoMessage(800 millis) probe.expectNoMessage(800.millis)
probe.expectMsg(250 millis, "STARTED") probe.expectMsg(250.millis, "STARTED")
supervisor ! "THROW" supervisor ! "THROW"
// numRestart = 3: expected delay ~1600 millis // numRestart = 3: expected delay ~1600 millis
probe.expectNoMessage(1600 millis) probe.expectNoMessage(1600.millis)
probe.expectMsg(250 millis, "STARTED") probe.expectMsg(250.millis, "STARTED")
// Verify that we only have one child at this point by selecting all the children // Verify that we only have one child at this point by selecting all the children
// under the supervisor and broadcasting to them. // under the supervisor and broadcasting to them.
@ -166,7 +165,7 @@ class BackoffOnRestartSupervisorSpec extends PekkoSpec("""
val postStopLatch = new CountDownLatch(1) val postStopLatch = new CountDownLatch(1)
@nowarn @nowarn
val options = BackoffOpts val options = BackoffOpts
.onFailure(Props(new SlowlyFailingActor(postStopLatch)), "someChildName", 1 nanos, 1 nanos, 0.0) .onFailure(Props(new SlowlyFailingActor(postStopLatch)), "someChildName", 1.nanos, 1.nanos, 0.0)
.withMaxNrOfRetries(-1) .withMaxNrOfRetries(-1)
.withSupervisorStrategy(OneForOneStrategy(loggingEnabled = false) { .withSupervisorStrategy(OneForOneStrategy(loggingEnabled = false) {
case _: TestActor.StoppingException => SupervisorStrategy.Stop case _: TestActor.StoppingException => SupervisorStrategy.Stop
@ -212,7 +211,7 @@ class BackoffOnRestartSupervisorSpec extends PekkoSpec("""
if (i < 6) { if (i < 6) {
// Since we should've died on this throw, don't expect to be started. // Since we should've died on this throw, don't expect to be started.
// We're not testing timing, so set a reasonably high timeout. // We're not testing timing, so set a reasonably high timeout.
probe.expectMsg(4 seconds, "STARTED") probe.expectMsg(4.seconds, "STARTED")
} }
} }
// Supervisor should've terminated. // Supervisor should've terminated.
@ -228,7 +227,7 @@ class BackoffOnRestartSupervisorSpec extends PekkoSpec("""
val options = BackoffOpts val options = BackoffOpts
.onFailure(TestActor.props(probe.ref), "someChildName", 300.millis, 10.seconds, 0.0) .onFailure(TestActor.props(probe.ref), "someChildName", 300.millis, 10.seconds, 0.0)
.withMaxNrOfRetries(-1) .withMaxNrOfRetries(-1)
.withSupervisorStrategy(OneForOneStrategy(withinTimeRange = 1 seconds, maxNrOfRetries = 3) { .withSupervisorStrategy(OneForOneStrategy(withinTimeRange = 1.seconds, maxNrOfRetries = 3) {
case _: TestActor.StoppingException => SupervisorStrategy.Stop case _: TestActor.StoppingException => SupervisorStrategy.Stop
}) })
val supervisor = system.actorOf(BackoffSupervisor.props(options)) val supervisor = system.actorOf(BackoffSupervisor.props(options))

View file

@ -19,7 +19,6 @@ import scala.concurrent.ExecutionContextExecutor
import scala.concurrent.Future import scala.concurrent.Future
import scala.concurrent.TimeoutException import scala.concurrent.TimeoutException
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.language.postfixOps
import scala.util.Failure import scala.util.Failure
import scala.util.Success import scala.util.Success
import scala.util.Try import scala.util.Try
@ -119,7 +118,7 @@ class CircuitBreakerSpec extends PekkoSpec("""
new Breaker(new CircuitBreaker(system.scheduler, 1, 1000.millis.dilated, shortResetTimeout)) new Breaker(new CircuitBreaker(system.scheduler, 1, 1000.millis.dilated, shortResetTimeout))
def longCallTimeoutCb()(implicit system: ActorSystem, ec: ExecutionContext): Breaker = def longCallTimeoutCb()(implicit system: ActorSystem, ec: ExecutionContext): Breaker =
new Breaker(new CircuitBreaker(system.scheduler, 1, 5 seconds, 500.millis.dilated)) new Breaker(new CircuitBreaker(system.scheduler, 1, 5.seconds, 500.millis.dilated))
val longResetTimeout = 5.seconds.dilated val longResetTimeout = 5.seconds.dilated
def longResetTimeoutCb()(implicit system: ActorSystem, ec: ExecutionContext): Breaker = def longResetTimeoutCb()(implicit system: ActorSystem, ec: ExecutionContext): Breaker =

View file

@ -17,8 +17,6 @@ import scala.concurrent.{ Await, Future, Promise }
import scala.concurrent.ExecutionContextExecutor import scala.concurrent.ExecutionContextExecutor
import scala.concurrent.duration._ import scala.concurrent.duration._
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.actor.{ Actor, Props } import pekko.actor.{ Actor, Props }
import pekko.testkit.{ PekkoSpec, TestLatch } import pekko.testkit.{ PekkoSpec, TestLatch }
@ -41,21 +39,21 @@ class PatternSpec extends PekkoSpec {
"provide Future for stopping an actor" in { "provide Future for stopping an actor" in {
val target = system.actorOf(Props[TargetActor]()) val target = system.actorOf(Props[TargetActor]())
val result = gracefulStop(target, 5 seconds) val result = gracefulStop(target, 5.seconds)
Await.result(result, 6 seconds) should ===(true) Await.result(result, 6.seconds) should ===(true)
} }
"complete Future when actor already terminated" in { "complete Future when actor already terminated" in {
val target = system.actorOf(Props[TargetActor]()) val target = system.actorOf(Props[TargetActor]())
Await.ready(gracefulStop(target, 5 seconds), 6 seconds) Await.ready(gracefulStop(target, 5.seconds), 6.seconds)
Await.ready(gracefulStop(target, 1 millis), 1 second) Await.ready(gracefulStop(target, 1.millis), 1.second)
} }
"complete Future with AskTimeoutException when actor not terminated within timeout" in { "complete Future with AskTimeoutException when actor not terminated within timeout" in {
val target = system.actorOf(Props[TargetActor]()) val target = system.actorOf(Props[TargetActor]())
val latch = TestLatch() val latch = TestLatch()
target ! ((latch, remainingOrDefault)) target ! ((latch, remainingOrDefault))
intercept[AskTimeoutException] { Await.result(gracefulStop(target, 500 millis), remainingOrDefault) } intercept[AskTimeoutException] { Await.result(gracefulStop(target, 500.millis), remainingOrDefault) }
latch.open() latch.open()
} }
} }
@ -63,7 +61,7 @@ class PatternSpec extends PekkoSpec {
"pattern.after" must { "pattern.after" must {
"be completed successfully eventually" in { "be completed successfully eventually" in {
// TODO after is unfortunately shadowed by ScalaTest, fix as part of #3759 // TODO after is unfortunately shadowed by ScalaTest, fix as part of #3759
val f = pekko.pattern.after(1 second, using = system.scheduler)(Future.successful(5)) val f = pekko.pattern.after(1.second, using = system.scheduler)(Future.successful(5))
val r = Future.firstCompletedOf(Seq(Promise[Int]().future, f)) val r = Future.firstCompletedOf(Seq(Promise[Int]().future, f))
Await.result(r, remainingOrDefault) should ===(5) Await.result(r, remainingOrDefault) should ===(5)
@ -72,7 +70,7 @@ class PatternSpec extends PekkoSpec {
"be completed abnormally eventually" in { "be completed abnormally eventually" in {
// TODO after is unfortunately shadowed by ScalaTest, fix as part of #3759 // TODO after is unfortunately shadowed by ScalaTest, fix as part of #3759
val f = val f =
pekko.pattern.after(1 second, using = system.scheduler)(Future.failed(new IllegalStateException("Mexico"))) pekko.pattern.after(1.second, using = system.scheduler)(Future.failed(new IllegalStateException("Mexico")))
val r = Future.firstCompletedOf(Seq(Promise[Int]().future, f)) val r = Future.firstCompletedOf(Seq(Promise[Int]().future, f))
intercept[IllegalStateException] { Await.result(r, remainingOrDefault) }.getMessage should ===("Mexico") intercept[IllegalStateException] { Await.result(r, remainingOrDefault) }.getMessage should ===("Mexico")

View file

@ -16,8 +16,6 @@ package org.apache.pekko.pattern
import scala.concurrent.{ Await, ExecutionContextExecutor, Future } import scala.concurrent.{ Await, ExecutionContextExecutor, Future }
import scala.concurrent.duration._ import scala.concurrent.duration._
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.actor.Scheduler import pekko.actor.Scheduler
import pekko.testkit.PekkoSpec import pekko.testkit.PekkoSpec
@ -30,9 +28,9 @@ class RetrySpec extends PekkoSpec with RetrySupport {
"pattern.retry" must { "pattern.retry" must {
"run a successful Future immediately" in { "run a successful Future immediately" in {
val retried = retry(() => Future.successful(5), 5, 1 second) val retried = retry(() => Future.successful(5), 5, 1.second)
within(3 seconds) { within(3.seconds) {
Await.result(retried, remaining) should ===(5) Await.result(retried, remaining) should ===(5)
} }
} }
@ -46,17 +44,17 @@ class RetrySpec extends PekkoSpec with RetrySupport {
counter counter
}, },
5, 5,
1 second) 1.second)
within(3 seconds) { within(3.seconds) {
Await.result(retried, remaining) should ===(1) Await.result(retried, remaining) should ===(1)
} }
} }
"eventually return a failure for a Future that will never succeed" in { "eventually return a failure for a Future that will never succeed" in {
val retried = retry(() => Future.failed(new IllegalStateException("Mexico")), 5, 100 milliseconds) val retried = retry(() => Future.failed(new IllegalStateException("Mexico")), 5, 100.milliseconds)
within(3 second) { within(3.second) {
intercept[IllegalStateException] { Await.result(retried, remaining) }.getMessage should ===("Mexico") intercept[IllegalStateException] { Await.result(retried, remaining) }.getMessage should ===("Mexico")
} }
} }
@ -71,9 +69,9 @@ class RetrySpec extends PekkoSpec with RetrySupport {
} else Future.successful(5) } else Future.successful(5)
} }
val retried = retry(() => attempt(), 10, 100 milliseconds) val retried = retry(() => attempt(), 10, 100.milliseconds)
within(3 seconds) { within(3.seconds) {
Await.result(retried, remaining) should ===(5) Await.result(retried, remaining) should ===(5)
} }
} }
@ -88,9 +86,9 @@ class RetrySpec extends PekkoSpec with RetrySupport {
} else Future.successful(5) } else Future.successful(5)
} }
val retried = retry(() => attempt(), 5, 100 milliseconds) val retried = retry(() => attempt(), 5, 100.milliseconds)
within(3 seconds) { within(3.seconds) {
intercept[IllegalStateException] { Await.result(retried, remaining) }.getMessage should ===("6") intercept[IllegalStateException] { Await.result(retried, remaining) }.getMessage should ===("6")
} }
} }
@ -111,7 +109,7 @@ class RetrySpec extends PekkoSpec with RetrySupport {
attemptedCount = attempted attemptedCount = attempted
Some(100.milliseconds * attempted) Some(100.milliseconds * attempted)
}) })
within(30000000 seconds) { within(30000000.seconds) {
intercept[IllegalStateException] { Await.result(retried, remaining) }.getMessage should ===("6") intercept[IllegalStateException] { Await.result(retried, remaining) }.getMessage should ===("6")
attemptedCount shouldBe 5 attemptedCount shouldBe 5
} }
@ -129,7 +127,7 @@ class RetrySpec extends PekkoSpec with RetrySupport {
val start = System.currentTimeMillis() val start = System.currentTimeMillis()
val retried = retry(() => attempt(), 999) val retried = retry(() => attempt(), 999)
within(1 seconds) { within(1.seconds) {
intercept[IllegalStateException] { intercept[IllegalStateException] {
Await.result(retried, remaining) Await.result(retried, remaining)
}.getMessage should ===("1000") }.getMessage should ===("1000")
@ -148,9 +146,9 @@ class RetrySpec extends PekkoSpec with RetrySupport {
} else Future.successful(5) } else Future.successful(5)
} }
val retried = retry(() => attempt(), 10, 100 milliseconds) val retried = retry(() => attempt(), 10, 100.milliseconds)
within(3 seconds) { within(3.seconds) {
Await.result(retried, remaining) should ===(5) Await.result(retried, remaining) should ===(5)
} }
} }
@ -161,9 +159,9 @@ class RetrySpec extends PekkoSpec with RetrySupport {
Future.successful(counter.incrementAndGet()) Future.successful(counter.incrementAndGet())
} }
val retried = retry(() => attempt(), (t: Int, _) => t < 5, 10, 100 milliseconds) val retried = retry(() => attempt(), (t: Int, _) => t < 5, 10, 100.milliseconds)
within(3 seconds) { within(3.seconds) {
Await.result(retried, remaining) should ===(5) Await.result(retried, remaining) should ===(5)
} }
} }
@ -178,9 +176,9 @@ class RetrySpec extends PekkoSpec with RetrySupport {
} }
val retried = val retried =
retry(() => attempt(), (_: Int, e) => !e.isInstanceOf[IllegalArgumentException], 10, 100 milliseconds) retry(() => attempt(), (_: Int, e) => !e.isInstanceOf[IllegalArgumentException], 10, 100.milliseconds)
within(3 seconds) { within(3.seconds) {
retried.failed.futureValue shouldBe an[IllegalArgumentException] retried.failed.futureValue shouldBe an[IllegalArgumentException]
counter.get() should ===(1) counter.get() should ===(1)
} }

View file

@ -19,7 +19,6 @@ import scala.concurrent.duration._
import scala.annotation.nowarn import scala.annotation.nowarn
import com.typesafe.config.Config import com.typesafe.config.Config
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.ConfigurationException import pekko.ConfigurationException
@ -142,19 +141,19 @@ class ConfiguredLocalRoutingSpec
"be picked up from Props" in { "be picked up from Props" in {
val actor = system.actorOf(RoundRobinPool(12).props(routeeProps = Props[EchoProps]()), "someOther") val actor = system.actorOf(RoundRobinPool(12).props(routeeProps = Props[EchoProps]()), "someOther")
routerConfig(actor) should ===(RoundRobinPool(12)) routerConfig(actor) should ===(RoundRobinPool(12))
Await.result(gracefulStop(actor, 3 seconds), 3 seconds) Await.result(gracefulStop(actor, 3.seconds), 3.seconds)
} }
"be overridable in config" in { "be overridable in config" in {
val actor = system.actorOf(RoundRobinPool(12).props(routeeProps = Props[EchoProps]()), "config") val actor = system.actorOf(RoundRobinPool(12).props(routeeProps = Props[EchoProps]()), "config")
routerConfig(actor) should ===(RandomPool(nrOfInstances = 4, usePoolDispatcher = true)) routerConfig(actor) should ===(RandomPool(nrOfInstances = 4, usePoolDispatcher = true))
Await.result(gracefulStop(actor, 3 seconds), 3 seconds) Await.result(gracefulStop(actor, 3.seconds), 3.seconds)
} }
"use routees.paths from config" in { "use routees.paths from config" in {
val actor = system.actorOf(RandomPool(12).props(routeeProps = Props[EchoProps]()), "paths") val actor = system.actorOf(RandomPool(12).props(routeeProps = Props[EchoProps]()), "paths")
routerConfig(actor) should ===(RandomGroup(List("/user/service1", "/user/service2"))) routerConfig(actor) should ===(RandomGroup(List("/user/service1", "/user/service2")))
Await.result(gracefulStop(actor, 3 seconds), 3 seconds) Await.result(gracefulStop(actor, 3.seconds), 3.seconds)
} }
"be overridable in explicit deployment" in { "be overridable in explicit deployment" in {
@ -162,7 +161,7 @@ class ConfiguredLocalRoutingSpec
FromConfig.props(routeeProps = Props[EchoProps]()).withDeploy(Deploy(routerConfig = RoundRobinPool(12))), FromConfig.props(routeeProps = Props[EchoProps]()).withDeploy(Deploy(routerConfig = RoundRobinPool(12))),
"someOther") "someOther")
routerConfig(actor) should ===(RoundRobinPool(12)) routerConfig(actor) should ===(RoundRobinPool(12))
Await.result(gracefulStop(actor, 3 seconds), 3 seconds) Await.result(gracefulStop(actor, 3.seconds), 3.seconds)
} }
"be overridable in config even with explicit deployment" in { "be overridable in config even with explicit deployment" in {
@ -170,7 +169,7 @@ class ConfiguredLocalRoutingSpec
FromConfig.props(routeeProps = Props[EchoProps]()).withDeploy(Deploy(routerConfig = RoundRobinPool(12))), FromConfig.props(routeeProps = Props[EchoProps]()).withDeploy(Deploy(routerConfig = RoundRobinPool(12))),
"config") "config")
routerConfig(actor) should ===(RandomPool(nrOfInstances = 4, usePoolDispatcher = true)) routerConfig(actor) should ===(RandomPool(nrOfInstances = 4, usePoolDispatcher = true))
Await.result(gracefulStop(actor, 3 seconds), 3 seconds) Await.result(gracefulStop(actor, 3.seconds), 3.seconds)
} }
"fail with an exception if not correct" in { "fail with an exception if not correct" in {
@ -185,7 +184,7 @@ class ConfiguredLocalRoutingSpec
@nowarn @nowarn
val expc = Set('a', 'b', 'c').map(i => "/user/weird/$" + i) val expc = Set('a', 'b', 'c').map(i => "/user/weird/$" + i)
recv should ===(expc) recv should ===(expc)
expectNoMessage(1 second) expectNoMessage(1.second)
} }
"support custom router" in { "support custom router" in {

View file

@ -18,8 +18,6 @@ import java.util.concurrent.atomic.AtomicInteger
import scala.concurrent.Await import scala.concurrent.Await
import scala.concurrent.duration._ import scala.concurrent.duration._
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.actor.{ Actor, Props } import pekko.actor.{ Actor, Props }
import pekko.pattern.ask import pekko.pattern.ask
@ -48,12 +46,12 @@ class RandomSpec extends PekkoSpec with DefaultTimeout with ImplicitSender {
actor ! "hello" actor ! "hello"
actor ! "hello" actor ! "hello"
within(2 seconds) { within(2.seconds) {
for (_ <- 1 to 5) expectMsg("world") for (_ <- 1 to 5) expectMsg("world")
} }
system.stop(actor) system.stop(actor)
Await.ready(stopLatch, 5 seconds) Await.ready(stopLatch, 5.seconds)
} }
"deliver messages in a random fashion" in { "deliver messages in a random fashion" in {
@ -85,7 +83,7 @@ class RandomSpec extends PekkoSpec with DefaultTimeout with ImplicitSender {
counter.get should ===(connectionCount) counter.get should ===(connectionCount)
actor ! pekko.routing.Broadcast("end") actor ! pekko.routing.Broadcast("end")
Await.ready(doneLatch, 5 seconds) Await.ready(doneLatch, 5.seconds)
replies.values.foreach { _ should be > 0 } replies.values.foreach { _ should be > 0 }
replies.values.sum should ===(iterationCount * connectionCount) replies.values.sum should ===(iterationCount * connectionCount)
@ -106,10 +104,10 @@ class RandomSpec extends PekkoSpec with DefaultTimeout with ImplicitSender {
})), "random-broadcast") })), "random-broadcast")
actor ! pekko.routing.Broadcast("hello") actor ! pekko.routing.Broadcast("hello")
Await.ready(helloLatch, 5 seconds) Await.ready(helloLatch, 5.seconds)
system.stop(actor) system.stop(actor)
Await.ready(stopLatch, 5 seconds) Await.ready(stopLatch, 5.seconds)
} }
} }
} }

View file

@ -17,7 +17,6 @@ import scala.concurrent.Await
import scala.concurrent.duration._ import scala.concurrent.duration._
import com.typesafe.config.{ Config, ConfigFactory } import com.typesafe.config.{ Config, ConfigFactory }
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.actor.{ Actor, ActorRef, ActorSystem, Props } import pekko.actor.{ Actor, ActorRef, ActorSystem, Props }
@ -205,15 +204,15 @@ class ResizerSpec extends PekkoSpec(ResizerSpec.config) with DefaultTimeout with
} }
// 2 more should go through without triggering more // 2 more should go through without triggering more
loop(2, 200 millis) loop(2, 200.millis)
routeeSize(router) should ===(resizer.lowerBound) routeeSize(router) should ===(resizer.lowerBound)
// a whole bunch should max it out // a whole bunch should max it out
loop(20, 500 millis) loop(20, 500.millis)
routeeSize(router) should ===(resizer.upperBound) routeeSize(router) should ===(resizer.upperBound)
} }
"backoff" in within(10 seconds) { "backoff" in within(10.seconds) {
val resizer = DefaultResizer( val resizer = DefaultResizer(
lowerBound = 2, lowerBound = 2,
upperBound = 5, upperBound = 5,
@ -226,25 +225,25 @@ class ResizerSpec extends PekkoSpec(ResizerSpec.config) with DefaultTimeout with
val router = system.actorOf(RoundRobinPool(nrOfInstances = 0, resizer = Some(resizer)).props(Props(new Actor { val router = system.actorOf(RoundRobinPool(nrOfInstances = 0, resizer = Some(resizer)).props(Props(new Actor {
def receive = { def receive = {
case n: Int if n <= 0 => // done case n: Int if n <= 0 => // done
case n: Int => Thread.sleep((n millis).dilated.toMillis) case n: Int => Thread.sleep(n.millis.dilated.toMillis)
} }
}))) })))
// put some pressure on the router // put some pressure on the router
for (_ <- 0 until 15) { for (_ <- 0 until 15) {
router ! 150 router ! 150
Thread.sleep((20 millis).dilated.toMillis) Thread.sleep(20.millis.dilated.toMillis)
} }
val z = routeeSize(router) val z = routeeSize(router)
z should be > 2 z should be > 2
Thread.sleep((300 millis).dilated.toMillis) Thread.sleep(300.millis.dilated.toMillis)
// let it cool down // let it cool down
awaitCond({ awaitCond({
router ! 0 // trigger resize router ! 0 // trigger resize
Thread.sleep((20 millis).dilated.toMillis) Thread.sleep(20.millis.dilated.toMillis)
routeeSize(router) < z routeeSize(router) < z
}, interval = 500.millis.dilated) }, interval = 500.millis.dilated)

View file

@ -18,8 +18,6 @@ import java.util.concurrent.atomic.AtomicInteger
import scala.concurrent.Await import scala.concurrent.Await
import scala.concurrent.duration._ import scala.concurrent.duration._
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.actor.Actor import pekko.actor.Actor
import pekko.actor.ActorRef import pekko.actor.ActorRef
@ -54,10 +52,10 @@ class RoundRobinSpec extends PekkoSpec with DefaultTimeout with ImplicitSender {
actor ! "hello" actor ! "hello"
actor ! "hello" actor ! "hello"
actor ! "hello" actor ! "hello"
Await.ready(helloLatch, 5 seconds) Await.ready(helloLatch, 5.seconds)
system.stop(actor) system.stop(actor)
Await.ready(stopLatch, 5 seconds) Await.ready(stopLatch, 5.seconds)
} }
"deliver messages in a round robin fashion" in { "deliver messages in a round robin fashion" in {
@ -84,7 +82,7 @@ class RoundRobinSpec extends PekkoSpec with DefaultTimeout with ImplicitSender {
counter.get should ===(connectionCount) counter.get should ===(connectionCount)
actor ! pekko.routing.Broadcast("end") actor ! pekko.routing.Broadcast("end")
Await.ready(doneLatch, 5 seconds) Await.ready(doneLatch, 5.seconds)
replies.values.foreach { _ should ===(iterationCount) } replies.values.foreach { _ should ===(iterationCount) }
} }
@ -104,10 +102,10 @@ class RoundRobinSpec extends PekkoSpec with DefaultTimeout with ImplicitSender {
})), "round-robin-broadcast") })), "round-robin-broadcast")
actor ! pekko.routing.Broadcast("hello") actor ! pekko.routing.Broadcast("hello")
Await.ready(helloLatch, 5 seconds) Await.ready(helloLatch, 5.seconds)
system.stop(actor) system.stop(actor)
Await.ready(stopLatch, 5 seconds) Await.ready(stopLatch, 5.seconds)
} }
"be controlled with management messages" in { "be controlled with management messages" in {
@ -156,7 +154,7 @@ class RoundRobinSpec extends PekkoSpec with DefaultTimeout with ImplicitSender {
} }
actor ! pekko.routing.Broadcast("end") actor ! pekko.routing.Broadcast("end")
Await.ready(doneLatch, 5 seconds) Await.ready(doneLatch, 5.seconds)
replies.values.foreach { _ should ===(iterationCount) } replies.values.foreach { _ should ===(iterationCount) }
} }

View file

@ -19,7 +19,6 @@ import scala.concurrent.ExecutionContextExecutor
import scala.concurrent.duration._ import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.ConfigurationException import pekko.ConfigurationException
@ -79,7 +78,7 @@ class RoutingSpec extends PekkoSpec(RoutingSpec.config) with DefaultTimeout with
awaitCond { awaitCond {
router ! "" router ! ""
router ! "" router ! ""
val res = receiveWhile(100 millis, messages = 2) { val res = receiveWhile(100.millis, messages = 2) {
case x: ActorRef => x case x: ActorRef => x
} }
res == Seq(c1, c1) res == Seq(c1, c1)

View file

@ -20,7 +20,6 @@ import java.nio.charset.StandardCharsets
import scala.annotation.nowarn import scala.annotation.nowarn
import scala.concurrent.Await import scala.concurrent.Await
import scala.concurrent.duration._ import scala.concurrent.duration._
import language.postfixOps
import SerializationTests._ import SerializationTests._
import com.typesafe.config._ import com.typesafe.config._
@ -307,7 +306,7 @@ class SerializeSpec extends PekkoSpec(SerializationTests.serializeConf) {
} }
class VerifySerializabilitySpec extends PekkoSpec(SerializationTests.verifySerializabilityConf) { class VerifySerializabilitySpec extends PekkoSpec(SerializationTests.verifySerializabilityConf) {
implicit val timeout: Timeout = Timeout(5 seconds) implicit val timeout: Timeout = Timeout(5.seconds)
"verify config" in { "verify config" in {
system.settings.SerializeAllCreators should ===(true) system.settings.SerializeAllCreators should ===(true)

View file

@ -15,8 +15,6 @@ package org.apache.pekko.util
import scala.concurrent.duration._ import scala.concurrent.duration._
import language.postfixOps
import org.apache.pekko.testkit.PekkoSpec import org.apache.pekko.testkit.PekkoSpec
class DurationSpec extends PekkoSpec { class DurationSpec extends PekkoSpec {
@ -24,8 +22,8 @@ class DurationSpec extends PekkoSpec {
"Duration" must { "Duration" must {
"form a one-dimensional vector field" in { "form a one-dimensional vector field" in {
val zero = 0 seconds val zero = 0.seconds
val one = 1 second val one = 1.second
val two = one + one val two = one + one
val three = 3 * one val three = 3 * one
(0 * one) should ===(zero) (0 * one) should ===(zero)
@ -96,11 +94,11 @@ class DurationSpec extends PekkoSpec {
val dead = 2.seconds.fromNow val dead = 2.seconds.fromNow
val dead2 = 2.seconds(fromNow) val dead2 = 2.seconds(fromNow)
// view bounds vs. very local type inference vs. operator precedence: sigh // view bounds vs. very local type inference vs. operator precedence: sigh
dead.timeLeft should be > (1 second: Duration) dead.timeLeft should be > (1.second: Duration)
dead2.timeLeft should be > (1 second: Duration) dead2.timeLeft should be > (1.second: Duration)
Thread.sleep(1.second.toMillis) Thread.sleep(1.second.toMillis)
dead.timeLeft should be < (1 second: Duration) dead.timeLeft should be < (1.second: Duration)
dead2.timeLeft should be < (1 second: Duration) dead2.timeLeft should be < (1.second: Duration)
} }
} }

View file

@ -113,8 +113,7 @@ class TestConsumer(
case job @ SomeAsyncJob(_, confirmTo, producerId, seqNr) => case job @ SomeAsyncJob(_, confirmTo, producerId, seqNr) =>
// when replacing producer the seqNr may start from 1 again // when replacing producer the seqNr may start from 1 again
val cleanProcessed = val cleanProcessed =
if (seqNr == 1L) processed.filterNot { case (pid, _) => pid == producerId } if (seqNr == 1L) processed.filterNot { case (pid, _) => pid == producerId } else processed
else processed
if (cleanProcessed((producerId, seqNr))) if (cleanProcessed((producerId, seqNr)))
throw new RuntimeException(s"Received duplicate [($producerId,$seqNr)]") throw new RuntimeException(s"Received duplicate [($producerId,$seqNr)]")

View file

@ -100,7 +100,9 @@ private[pekko] object DirectByteBufferPool {
val cleaner = cleanerMethod.invoke(bb) val cleaner = cleanerMethod.invoke(bb)
cleanMethod.invoke(cleaner) cleanMethod.invoke(cleaner)
} }
catch { case NonFatal(_) => /* ok, best effort attempt to cleanup failed */ } catch {
case NonFatal(_) => /* ok, best effort attempt to cleanup failed */
}
} }
} catch { case NonFatal(_) => _ => () /* reflection failed, use no-op fallback */ } } catch { case NonFatal(_) => _ => () /* reflection failed, use no-op fallback */ }

View file

@ -15,7 +15,6 @@ package org.apache.pekko.cluster.metrics
import java.io.File import java.io.File
import scala.language.postfixOps
import scala.util.Failure import scala.util.Failure
import scala.util.Success import scala.util.Success
import scala.util.Try import scala.util.Try
@ -81,7 +80,7 @@ trait SigarProvider {
}) })
.recover { .recover {
case e: Throwable => throw new RuntimeException("Failed to load sigar:", e) case e: Throwable => throw new RuntimeException("Failed to load sigar:", e)
} get }.get
} }
} }

View file

@ -14,7 +14,6 @@
package org.apache.pekko.cluster.metrics package org.apache.pekko.cluster.metrics
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.language.postfixOps
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
@ -113,7 +112,7 @@ abstract class ClusterMetricsEnabledSpec
"Cluster metrics" must { "Cluster metrics" must {
"periodically collect metrics on each node, publish to the event stream, " + "periodically collect metrics on each node, publish to the event stream, " +
"and gossip metrics around the node ring" in within(60 seconds) { "and gossip metrics around the node ring" in within(60.seconds) {
awaitClusterUp(roles: _*) awaitClusterUp(roles: _*)
enterBarrier("cluster-started") enterBarrier("cluster-started")
awaitAssert(clusterView.members.count(_.status == MemberStatus.Up) should ===(roles.size)) awaitAssert(clusterView.members.count(_.status == MemberStatus.Up) should ===(roles.size))
@ -124,7 +123,7 @@ abstract class ClusterMetricsEnabledSpec
collector.sample().metrics.size should be > 3 collector.sample().metrics.size should be > 3
enterBarrier("after") enterBarrier("after")
} }
"reflect the correct number of node metrics in cluster view" in within(30 seconds) { "reflect the correct number of node metrics in cluster view" in within(30.seconds) {
runOn(node2) { runOn(node2) {
cluster.leave(node1) cluster.leave(node1)
} }

View file

@ -21,7 +21,6 @@ import scala.concurrent.duration._
import com.typesafe.config.Config import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.actor._ import pekko.actor._
@ -143,7 +142,7 @@ abstract class AdaptiveLoadBalancingRouterSpec
def receiveReplies(expectedReplies: Int): Map[Address, Int] = { def receiveReplies(expectedReplies: Int): Map[Address, Int] = {
val zero = Map.empty[Address, Int] ++ roles.map(address(_) -> 0) val zero = Map.empty[Address, Int] ++ roles.map(address(_) -> 0)
receiveWhile(5 seconds, messages = expectedReplies) { receiveWhile(5.seconds, messages = expectedReplies) {
case Reply(address) => address case Reply(address) => address
}.foldLeft(zero) { }.foldLeft(zero) {
case (replyMap, address) => replyMap + (address -> (replyMap(address) + 1)) case (replyMap, address) => replyMap + (address -> (replyMap(address) + 1))

View file

@ -19,7 +19,6 @@ import pekko.cluster.Cluster
import pekko.cluster.ClusterEvent.{ CurrentClusterState, MemberUp } import pekko.cluster.ClusterEvent.{ CurrentClusterState, MemberUp }
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.language.postfixOps
//#MultiNodeConfig //#MultiNodeConfig
import org.apache.pekko.remote.testkit.MultiNodeConfig import org.apache.pekko.remote.testkit.MultiNodeConfig
@ -104,7 +103,7 @@ abstract class StatsSampleSpec
"The stats sample" must { "The stats sample" must {
// #startup-cluster // #startup-cluster
"illustrate how to startup cluster" in within(15 seconds) { "illustrate how to startup cluster" in within(15.seconds) {
Cluster(system).subscribe(testActor, classOf[MemberUp]) Cluster(system).subscribe(testActor, classOf[MemberUp])
expectMsgClass(classOf[CurrentClusterState]) expectMsgClass(classOf[CurrentClusterState])
@ -131,7 +130,7 @@ abstract class StatsSampleSpec
// #startup-cluster // #startup-cluster
// #test-statsService // #test-statsService
"show usage of the statsService from one node" in within(15 seconds) { "show usage of the statsService from one node" in within(15.seconds) {
runOn(second) { runOn(second) {
assertServiceOk() assertServiceOk()
} }
@ -151,7 +150,7 @@ abstract class StatsSampleSpec
} }
// #test-statsService // #test-statsService
"show usage of the statsService from all nodes" in within(15 seconds) { "show usage of the statsService from all nodes" in within(15.seconds) {
assertServiceOk() assertServiceOk()
testConductor.enter("done-3") testConductor.enter("done-3")
} }

View file

@ -14,7 +14,6 @@
package org.apache.pekko.cluster.metrics package org.apache.pekko.cluster.metrics
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.cluster.Cluster import pekko.cluster.Cluster
@ -54,11 +53,11 @@ class ClusterMetricsExtensionSpec
"collect metrics after start command" in { "collect metrics after start command" in {
extension.supervisor ! CollectionStartMessage extension.supervisor ! CollectionStartMessage
awaitAssert(metricsNodeCount should ===(nodeCount), 15 seconds) awaitAssert(metricsNodeCount should ===(nodeCount), 15.seconds)
} }
"collect mock sample during a time window" in { "collect mock sample during a time window" in {
awaitAssert(metricsHistorySize should ===(sampleCount), 15 seconds) awaitAssert(metricsHistorySize should ===(sampleCount), 15.seconds)
extension.supervisor ! CollectionStopMessage extension.supervisor ! CollectionStopMessage
awaitSample() awaitSample()
metricsNodeCount should ===(nodeCount) metricsNodeCount should ===(nodeCount)

View file

@ -16,7 +16,6 @@ package org.apache.pekko.cluster.metrics
import scala.concurrent.duration._ import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.dispatch.Dispatchers import pekko.dispatch.Dispatchers
@ -32,7 +31,7 @@ class ClusterMetricsSettingsSpec extends PekkoSpec {
// Extension. // Extension.
MetricsDispatcher should ===(Dispatchers.DefaultDispatcherId) MetricsDispatcher should ===(Dispatchers.DefaultDispatcherId)
PeriodicTasksInitialDelay should ===(1 second) PeriodicTasksInitialDelay should ===(1.second)
NativeLibraryExtractFolder should ===(System.getProperty("user.dir") + "/native") NativeLibraryExtractFolder should ===(System.getProperty("user.dir") + "/native")
// Supervisor. // Supervisor.
@ -44,9 +43,9 @@ class ClusterMetricsSettingsSpec extends PekkoSpec {
// Collector. // Collector.
CollectorEnabled should ===(true) CollectorEnabled should ===(true)
CollectorProvider should ===("") CollectorProvider should ===("")
CollectorSampleInterval should ===(3 seconds) CollectorSampleInterval should ===(3.seconds)
CollectorGossipInterval should ===(3 seconds) CollectorGossipInterval should ===(3.seconds)
CollectorMovingAverageHalfLife should ===(12 seconds) CollectorMovingAverageHalfLife should ===(12.seconds)
} }
} }
} }

View file

@ -14,7 +14,6 @@
package org.apache.pekko.cluster.metrics package org.apache.pekko.cluster.metrics
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.language.postfixOps
import scala.util.Try import scala.util.Try
import scala.annotation.nowarn import scala.annotation.nowarn
@ -103,7 +102,7 @@ class MetricsCollectorSpec
c.processors.isDefined should ===(true) c.processors.isDefined should ===(true)
} }
"collect 50 node metrics samples in an acceptable duration" taggedAs LongRunningTest in within(10 seconds) { "collect 50 node metrics samples in an acceptable duration" taggedAs LongRunningTest in within(10.seconds) {
(1 to 50).foreach { _ => (1 to 50).foreach { _ =>
val sample = collector.sample() val sample = collector.sample()
sample.metrics.size should be >= 3 sample.metrics.size should be >= 3

View file

@ -16,8 +16,6 @@ package org.apache.pekko.cluster.metrics
import java.io.Closeable import java.io.Closeable
import java.util.logging.LogManager import java.util.logging.LogManager
import scala.language.postfixOps
import org.scalatestplus.mockito.MockitoSugar import org.scalatestplus.mockito.MockitoSugar
import org.slf4j.bridge.SLF4JBridgeHandler import org.slf4j.bridge.SLF4JBridgeHandler
@ -80,7 +78,7 @@ case class MockitoSigarProvider(
/** Generate monotonic array from 0 to value. */ /** Generate monotonic array from 0 to value. */
def increase(value: Double): Array[Double] = { def increase(value: Double): Array[Double] = {
val delta = value / steps val delta = value / steps
(0 to steps).map { _ * delta } toArray (0 to steps).map { _ * delta }.toArray
} }
/** Sigar mock instance. */ /** Sigar mock instance. */

View file

@ -312,7 +312,9 @@ class RandomizedSplitBrainResolverIntegrationSpec
(if (cleanSplit) (if (cleanSplit)
s"side1 [${side1.map(_.name).mkString(", ")}], side2 [${side2.map(_.name).mkString(", ")}] " s"side1 [${side1.map(_.name).mkString(", ")}], side2 [${side2.map(_.name).mkString(", ")}] "
else " ") + else " ") +
s", flaky [${flaky.map { case (_, (from, to)) => from.name -> to.map(_.name).mkString("(", ", ", ")") }.mkString("; ")}] " + s", flaky [${flaky.map { case (_, (from, to)) =>
from.name -> to.map(_.name).mkString("(", ", ", ")")
}.mkString("; ")}] " +
s", healLastFlaky [$healLastFlaky] " + s", healLastFlaky [$healLastFlaky] " +
s", delays [${delays.mkString(", ")}]") s", delays [${delays.mkString(", ")}]")

View file

@ -14,7 +14,6 @@
package org.apache.pekko.cluster.sharding package org.apache.pekko.cluster.sharding
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.language.postfixOps
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
import org.apache.pekko import org.apache.pekko
import pekko.actor._ import pekko.actor._
@ -430,7 +429,7 @@ abstract class ClusterShardingSpec(multiNodeConfig: ClusterShardingSpecConfig)
enterBarrier("after-1") enterBarrier("after-1")
} }
"work in single node cluster" in within(20 seconds) { "work in single node cluster" in within(20.seconds) {
join(first, first) join(first, first)
runOn(first) { runOn(first) {
@ -448,7 +447,7 @@ abstract class ClusterShardingSpec(multiNodeConfig: ClusterShardingSpecConfig)
enterBarrier("after-2") enterBarrier("after-2")
} }
"use second node" in within(20 seconds) { "use second node" in within(20.seconds) {
join(second, first) join(second, first)
runOn(second) { runOn(second) {
@ -534,7 +533,7 @@ abstract class ClusterShardingSpec(multiNodeConfig: ClusterShardingSpecConfig)
enterBarrier("after-5") enterBarrier("after-5")
} }
"failover shards on crashed node" in within(30 seconds) { "failover shards on crashed node" in within(30.seconds) {
// mute logging of deadLetters during shutdown of systems // mute logging of deadLetters during shutdown of systems
if (!log.isDebugEnabled) if (!log.isDebugEnabled)
system.eventStream.publish(Mute(DeadLettersFilter[Any])) system.eventStream.publish(Mute(DeadLettersFilter[Any]))
@ -567,7 +566,7 @@ abstract class ClusterShardingSpec(multiNodeConfig: ClusterShardingSpecConfig)
enterBarrier("after-6") enterBarrier("after-6")
} }
"use third and fourth node" in within(15 seconds) { "use third and fourth node" in within(15.seconds) {
join(third, first) join(third, first)
runOn(third) { runOn(third) {
@ -618,7 +617,7 @@ abstract class ClusterShardingSpec(multiNodeConfig: ClusterShardingSpecConfig)
enterBarrier("after-7") enterBarrier("after-7")
} }
"recover coordinator state after coordinator crash" in within(60 seconds) { "recover coordinator state after coordinator crash" in within(60.seconds) {
join(fifth, fourth) join(fifth, fourth)
runOn(controller) { runOn(controller) {
@ -649,7 +648,7 @@ abstract class ClusterShardingSpec(multiNodeConfig: ClusterShardingSpecConfig)
enterBarrier("after-8") enterBarrier("after-8")
} }
"rebalance to nodes with less shards" in within(60 seconds) { "rebalance to nodes with less shards" in within(60.seconds) {
runOn(fourth) { runOn(fourth) {
for (n <- 1 to 10) { for (n <- 1 to 10) {
rebalancingRegion ! EntityEnvelope(n, Increment) rebalancingRegion ! EntityEnvelope(n, Increment)
@ -799,26 +798,26 @@ abstract class ClusterShardingSpec(multiNodeConfig: ClusterShardingSpecConfig)
// clean up shard cache everywhere // clean up shard cache everywhere
runOn(third, fourth, fifth) { runOn(third, fourth, fifth) {
persistentEntitiesRegion ! BeginHandOff("1") persistentEntitiesRegion ! BeginHandOff("1")
expectMsg(10 seconds, "ShardStopped not received", BeginHandOffAck("1")) expectMsg(10.seconds, "ShardStopped not received", BeginHandOffAck("1"))
} }
enterBarrier("everybody-hand-off-ack") enterBarrier("everybody-hand-off-ack")
runOn(third) { runOn(third) {
// Stop the shard cleanly // Stop the shard cleanly
region ! HandOff("1") region ! HandOff("1")
expectMsg(10 seconds, "ShardStopped not received", ShardStopped("1")) expectMsg(10.seconds, "ShardStopped not received", ShardStopped("1"))
val probe = TestProbe() val probe = TestProbe()
awaitAssert({ awaitAssert({
shard.tell(Identify(1), probe.ref) shard.tell(Identify(1), probe.ref)
probe.expectMsg(1 second, "Shard was still around", ActorIdentity(1, None)) probe.expectMsg(1.second, "Shard was still around", ActorIdentity(1, None))
}, 5 seconds, 500 millis) }, 5.seconds, 500.millis)
// Get the path to where the shard now resides // Get the path to where the shard now resides
awaitAssert({ awaitAssert({
persistentEntitiesRegion ! Get(13) persistentEntitiesRegion ! Get(13)
expectMsg(0) expectMsg(0)
}, 5 seconds, 500 millis) }, 5.seconds, 500.millis)
// Check that counter 1 is now alive again, even though we have // Check that counter 1 is now alive again, even though we have
// not sent a message to it via the ShardRegion // not sent a message to it via the ShardRegion
@ -847,7 +846,7 @@ abstract class ClusterShardingSpec(multiNodeConfig: ClusterShardingSpecConfig)
// Check that no counter "1" exists in this shard // Check that no counter "1" exists in this shard
val secondCounter1 = system.actorSelection(lastSender.path.parent / "1") val secondCounter1 = system.actorSelection(lastSender.path.parent / "1")
secondCounter1 ! Identify(3) secondCounter1 ! Identify(3)
expectMsg(3 seconds, ActorIdentity(3, None)) expectMsg(3.seconds, ActorIdentity(3, None))
} }
enterBarrier("after-12") enterBarrier("after-12")
@ -883,24 +882,24 @@ abstract class ClusterShardingSpec(multiNodeConfig: ClusterShardingSpecConfig)
shard.tell(Passivate(Stop), counter1) shard.tell(Passivate(Stop), counter1)
// Watch for the terminated message // Watch for the terminated message
expectTerminated(counter1, 5 seconds) expectTerminated(counter1, 5.seconds)
val probe1 = TestProbe() val probe1 = TestProbe()
awaitAssert({ awaitAssert({
// Check counter 1 is dead // Check counter 1 is dead
counter1.tell(Identify(1), probe1.ref) counter1.tell(Identify(1), probe1.ref)
probe1.expectMsg(1 second, "Entity 1 was still around", ActorIdentity(1, None)) probe1.expectMsg(1.second, "Entity 1 was still around", ActorIdentity(1, None))
}, 5 second, 500 millis) }, 5.second, 500.millis)
// Stop the shard cleanly // Stop the shard cleanly
region ! HandOff("1") region ! HandOff("1")
expectMsg(10 seconds, "ShardStopped not received", ShardStopped("1")) expectMsg(10.seconds, "ShardStopped not received", ShardStopped("1"))
val probe2 = TestProbe() val probe2 = TestProbe()
awaitAssert({ awaitAssert({
shard.tell(Identify(2), probe2.ref) shard.tell(Identify(2), probe2.ref)
probe2.expectMsg(1 second, "Shard was still around", ActorIdentity(2, None)) probe2.expectMsg(1.second, "Shard was still around", ActorIdentity(2, None))
}, 5 seconds, 500 millis) }, 5.seconds, 500.millis)
} }
enterBarrier("shard-shutdown-12") enterBarrier("shard-shutdown-12")
@ -920,8 +919,8 @@ abstract class ClusterShardingSpec(multiNodeConfig: ClusterShardingSpecConfig)
val probe3 = TestProbe() val probe3 = TestProbe()
awaitAssert({ awaitAssert({
system.actorSelection(shard / "13").tell(Identify(4), probe3.ref) system.actorSelection(shard / "13").tell(Identify(4), probe3.ref)
probe3.expectMsgType[ActorIdentity](1 second).ref should not be None probe3.expectMsgType[ActorIdentity](1.second).ref should not be None
}, 5 seconds, 500 millis) }, 5.seconds, 500.millis)
} }
enterBarrier("after-13") enterBarrier("after-13")
@ -946,7 +945,7 @@ abstract class ClusterShardingSpec(multiNodeConfig: ClusterShardingSpecConfig)
val probe = TestProbe() val probe = TestProbe()
awaitAssert({ awaitAssert({
counter1.tell(Identify(1), probe.ref) counter1.tell(Identify(1), probe.ref)
probe.expectMsgType[ActorIdentity](1 second).ref should not be None probe.expectMsgType[ActorIdentity](1.second).ref should not be None
}, 5.seconds, 500.millis) }, 5.seconds, 500.millis)
} }
@ -983,8 +982,8 @@ abstract class ClusterShardingSpec(multiNodeConfig: ClusterShardingSpecConfig)
val probe = TestProbe() val probe = TestProbe()
awaitAssert({ awaitAssert({
counter1.tell(Identify(1), probe.ref) counter1.tell(Identify(1), probe.ref)
probe.expectMsgType[ActorIdentity](1 second).ref should not be None probe.expectMsgType[ActorIdentity](1.second).ref should not be None
}, 5.seconds, 500 millis) }, 5.seconds, 500.millis)
counter1 ! Get(1) counter1 ! Get(1)
expectMsg(2) expectMsg(2)
@ -1017,7 +1016,7 @@ abstract class ClusterShardingSpec(multiNodeConfig: ClusterShardingSpecConfig)
for (n <- 2 to 12) { for (n <- 2 to 12) {
val entity = system.actorSelection(rebalancingPersistentRegion.path / (n % 12).toString / n.toString) val entity = system.actorSelection(rebalancingPersistentRegion.path / (n % 12).toString / n.toString)
entity ! Identify(n) entity ! Identify(n)
receiveOne(3 seconds) match { receiveOne(3.seconds) match {
case ActorIdentity(id, Some(_)) if id == n => count = count + 1 case ActorIdentity(id, Some(_)) if id == n => count = count + 1
case ActorIdentity(_, None) => // Not on the fifth shard case ActorIdentity(_, None) => // Not on the fifth shard
case _ => fail() case _ => fail()

View file

@ -16,7 +16,6 @@ package org.apache.pekko.cluster.client
import scala.annotation.nowarn import scala.annotation.nowarn
import scala.concurrent.Await import scala.concurrent.Await
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.language.postfixOps
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
@ -216,7 +215,7 @@ class ClusterClientSpec extends MultiNodeSpec(ClusterClientSpec) with STMultiNod
"A ClusterClient" must { "A ClusterClient" must {
"startup cluster" in within(30 seconds) { "startup cluster" in within(30.seconds) {
join(first, first) join(first, first)
join(second, first) join(second, first)
join(third, first) join(third, first)
@ -232,7 +231,7 @@ class ClusterClientSpec extends MultiNodeSpec(ClusterClientSpec) with STMultiNod
enterBarrier("after-1") enterBarrier("after-1")
} }
"communicate to actor on any node in cluster" in within(10 seconds) { "communicate to actor on any node in cluster" in within(10.seconds) {
runOn(client) { runOn(client) {
val c = system.actorOf( val c = system.actorOf(
ClusterClient.props(ClusterClientSettings(system).withInitialContacts(initialContacts)), ClusterClient.props(ClusterClientSettings(system).withInitialContacts(initialContacts)),
@ -248,7 +247,7 @@ class ClusterClientSpec extends MultiNodeSpec(ClusterClientSpec) with STMultiNod
enterBarrier("after-2") enterBarrier("after-2")
} }
"work with ask" in within(10 seconds) { "work with ask" in within(10.seconds) {
runOn(client) { runOn(client) {
import pekko.pattern.ask import pekko.pattern.ask
val c = system.actorOf( val c = system.actorOf(
@ -266,7 +265,7 @@ class ClusterClientSpec extends MultiNodeSpec(ClusterClientSpec) with STMultiNod
enterBarrier("after-3") enterBarrier("after-3")
} }
"demonstrate usage" in within(15 seconds) { "demonstrate usage" in within(15.seconds) {
def host1 = first def host1 = first
def host2 = second def host2 = second
def host3 = third def host3 = third
@ -308,7 +307,7 @@ class ClusterClientSpec extends MultiNodeSpec(ClusterClientSpec) with STMultiNod
enterBarrier("after-4") enterBarrier("after-4")
} }
"report events" in within(15 seconds) { "report events" in within(15.seconds) {
runOn(client) { runOn(client) {
implicit val timeout: Timeout = Timeout(1.second.dilated) implicit val timeout: Timeout = Timeout(1.second.dilated)
val client = Await.result(system.actorSelection("/user/client").resolveOne(), timeout.duration) val client = Await.result(system.actorSelection("/user/client").resolveOne(), timeout.duration)
@ -348,7 +347,7 @@ class ClusterClientSpec extends MultiNodeSpec(ClusterClientSpec) with STMultiNod
enterBarrier("after-5") enterBarrier("after-5")
} }
"report a removal of a receptionist" in within(10 seconds) { "report a removal of a receptionist" in within(10.seconds) {
runOn(client) { runOn(client) {
val unreachableContact = node(client) / "system" / "receptionist" val unreachableContact = node(client) / "system" / "receptionist"
val expectedRoles = Set(first, second, third, fourth) val expectedRoles = Set(first, second, third, fourth)

View file

@ -16,7 +16,6 @@ package org.apache.pekko.cluster.pubsub
import scala.concurrent.duration._ import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.actor.Actor import pekko.actor.Actor
@ -186,13 +185,13 @@ class DistributedPubSubMediatorSpec
"A DistributedPubSubMediator" must { "A DistributedPubSubMediator" must {
"startup 2 node cluster" in within(15 seconds) { "startup 2 node cluster" in within(15.seconds) {
join(first, first) join(first, first)
join(second, first) join(second, first)
enterBarrier("after-1") enterBarrier("after-1")
} }
"keep track of added users" in within(15 seconds) { "keep track of added users" in within(15.seconds) {
runOn(first) { runOn(first) {
val u1 = createChatUser("u1") val u1 = createChatUser("u1")
mediator ! Put(u1) mediator ! Put(u1)
@ -242,7 +241,7 @@ class DistributedPubSubMediatorSpec
enterBarrier("after-2") enterBarrier("after-2")
} }
"replicate users to new node" in within(20 seconds) { "replicate users to new node" in within(20.seconds) {
join(third, first) join(third, first)
runOn(third) { runOn(third) {
@ -265,7 +264,7 @@ class DistributedPubSubMediatorSpec
enterBarrier("after-3") enterBarrier("after-3")
} }
"keep track of removed users" in within(15 seconds) { "keep track of removed users" in within(15.seconds) {
runOn(first) { runOn(first) {
val u6 = createChatUser("u6") val u6 = createChatUser("u6")
mediator ! Put(u6) mediator ! Put(u6)
@ -281,7 +280,7 @@ class DistributedPubSubMediatorSpec
enterBarrier("after-4") enterBarrier("after-4")
} }
"remove terminated users" in within(5 seconds) { "remove terminated users" in within(5.seconds) {
runOn(second) { runOn(second) {
chatUser("u3") ! PoisonPill chatUser("u3") ! PoisonPill
} }
@ -290,7 +289,7 @@ class DistributedPubSubMediatorSpec
enterBarrier("after-5") enterBarrier("after-5")
} }
"publish" in within(15 seconds) { "publish" in within(15.seconds) {
runOn(first, second) { runOn(first, second) {
val u7 = createChatUser("u7") val u7 = createChatUser("u7")
mediator ! Put(u7) mediator ! Put(u7)
@ -313,7 +312,7 @@ class DistributedPubSubMediatorSpec
enterBarrier("after-6") enterBarrier("after-6")
} }
"publish to topic" in within(15 seconds) { "publish to topic" in within(15.seconds) {
runOn(first) { runOn(first) {
val s8 = Subscribe("topic1", createChatUser("u8")) val s8 = Subscribe("topic1", createChatUser("u8"))
mediator ! s8 mediator ! s8
@ -352,7 +351,7 @@ class DistributedPubSubMediatorSpec
enterBarrier("after-7") enterBarrier("after-7")
} }
"demonstrate usage of Publish" in within(15 seconds) { "demonstrate usage of Publish" in within(15.seconds) {
def later(): Unit = { def later(): Unit = {
awaitCount(10) awaitCount(10)
} }
@ -379,7 +378,7 @@ class DistributedPubSubMediatorSpec
enterBarrier("after-8") enterBarrier("after-8")
} }
"demonstrate usage of Send" in within(15 seconds) { "demonstrate usage of Send" in within(15.seconds) {
def later(): Unit = { def later(): Unit = {
awaitCount(12) awaitCount(12)
} }
@ -405,7 +404,7 @@ class DistributedPubSubMediatorSpec
enterBarrier("after-8") enterBarrier("after-8")
} }
"send-all to all other nodes" in within(15 seconds) { "send-all to all other nodes" in within(15.seconds) {
runOn(first, second, third) { // create the user on all nodes runOn(first, second, third) { // create the user on all nodes
val u11 = createChatUser("u11") val u11 = createChatUser("u11")
mediator ! Put(u11) mediator ! Put(u11)
@ -428,7 +427,7 @@ class DistributedPubSubMediatorSpec
enterBarrier("after-11") enterBarrier("after-11")
} }
"send one message to each group" in within(20 seconds) { "send one message to each group" in within(20.seconds) {
runOn(first) { runOn(first) {
val u12 = createChatUser("u12") val u12 = createChatUser("u12")
u12 ! JoinGroup("topic2", "group1") u12 ! JoinGroup("topic2", "group1")
@ -517,7 +516,7 @@ class DistributedPubSubMediatorSpec
enterBarrier("after-13") enterBarrier("after-13")
} }
"remove entries when node is removed" in within(30 seconds) { "remove entries when node is removed" in within(30.seconds) {
mediator ! Count mediator ! Count
val countBefore = expectMsgType[Int] val countBefore = expectMsgType[Int]
@ -535,7 +534,7 @@ class DistributedPubSubMediatorSpec
enterBarrier("after-14") enterBarrier("after-14")
} }
"receive proper unsubscribeAck message" in within(15 seconds) { "receive proper unsubscribeAck message" in within(15.seconds) {
runOn(first) { runOn(first) {
val user = createChatUser("u111") val user = createChatUser("u111")
val topic = "sample-topic1" val topic = "sample-topic1"
@ -549,7 +548,7 @@ class DistributedPubSubMediatorSpec
enterBarrier("after-14") enterBarrier("after-14")
} }
"get topics after simple publish" in within(15 seconds) { "get topics after simple publish" in within(15.seconds) {
runOn(first) { runOn(first) {
val s1 = Subscribe("topic_a1", createChatUser("u14")) val s1 = Subscribe("topic_a1", createChatUser("u14"))
mediator ! s1 mediator ! s1
@ -597,7 +596,7 @@ class DistributedPubSubMediatorSpec
} }
"remove topic subscribers when they terminate" in within(15 seconds) { "remove topic subscribers when they terminate" in within(15.seconds) {
runOn(first) { runOn(first) {
val s1 = Subscribe("topic_b1", createChatUser("u18")) val s1 = Subscribe("topic_b1", createChatUser("u18"))
mediator ! s1 mediator ! s1

View file

@ -17,7 +17,6 @@ import scala.concurrent.Await
import scala.concurrent.duration._ import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.actor.Actor import pekko.actor.Actor
@ -93,14 +92,14 @@ class DistributedPubSubRestartSpec
"A Cluster with DistributedPubSub" must { "A Cluster with DistributedPubSub" must {
"startup 3 node cluster" in within(15 seconds) { "startup 3 node cluster" in within(15.seconds) {
join(first, first) join(first, first)
join(second, first) join(second, first)
join(third, first) join(third, first)
enterBarrier("after-1") enterBarrier("after-1")
} }
"handle restart of nodes with same address" in within(30 seconds) { "handle restart of nodes with same address" in within(30.seconds) {
mediator ! Subscribe("topic1", testActor) mediator ! Subscribe("topic1", testActor)
expectMsgType[SubscribeAck] expectMsgType[SubscribeAck]
awaitCount(3) awaitCount(3)

View file

@ -16,7 +16,6 @@ package org.apache.pekko.cluster.singleton
import scala.concurrent.duration._ import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.actor.Actor import pekko.actor.Actor
@ -122,7 +121,7 @@ class ClusterSingletonManagerChaosSpec
"A ClusterSingletonManager in chaotic cluster" must { "A ClusterSingletonManager in chaotic cluster" must {
"startup 6 node cluster" in within(60 seconds) { "startup 6 node cluster" in within(60.seconds) {
val memberProbe = TestProbe() val memberProbe = TestProbe()
Cluster(system).subscribe(memberProbe.ref, classOf[MemberUp]) Cluster(system).subscribe(memberProbe.ref, classOf[MemberUp])
memberProbe.expectMsgClass(classOf[CurrentClusterState]) memberProbe.expectMsgClass(classOf[CurrentClusterState])
@ -157,7 +156,7 @@ class ClusterSingletonManagerChaosSpec
} }
"take over when three oldest nodes crash in 6 nodes cluster" in within(90 seconds) { "take over when three oldest nodes crash in 6 nodes cluster" in within(90.seconds) {
// mute logging of deadLetters during shutdown of systems // mute logging of deadLetters during shutdown of systems
if (!log.isDebugEnabled) if (!log.isDebugEnabled)
system.eventStream.publish(Mute(DeadLettersFilter[Any])) system.eventStream.publish(Mute(DeadLettersFilter[Any]))

View file

@ -16,7 +16,6 @@ package org.apache.pekko.cluster.singleton
import scala.concurrent.duration._ import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.actor.Actor import pekko.actor.Actor
@ -313,13 +312,13 @@ class ClusterSingletonManagerSpec
runOn(controller) { runOn(controller) {
queue ! msg queue ! msg
// make sure it's not terminated, which would be wrong // make sure it's not terminated, which would be wrong
expectNoMessage(1 second) expectNoMessage(1.second)
} }
runOn(oldest) { runOn(oldest) {
expectMsg(5.seconds, msg) expectMsg(5.seconds, msg)
} }
runOn(roles.filterNot(r => r == oldest || r == controller || r == observer): _*) { runOn(roles.filterNot(r => r == oldest || r == controller || r == observer): _*) {
expectNoMessage(1 second) expectNoMessage(1.second)
} }
enterBarrier("after-" + msg + "-verified") enterBarrier("after-" + msg + "-verified")
} }
@ -337,7 +336,7 @@ class ClusterSingletonManagerSpec
"A ClusterSingletonManager" must { "A ClusterSingletonManager" must {
"startup 6 node cluster" in within(60 seconds) { "startup 6 node cluster" in within(60.seconds) {
val memberProbe = TestProbe() val memberProbe = TestProbe()
Cluster(system).subscribe(memberProbe.ref, classOf[MemberUp]) Cluster(system).subscribe(memberProbe.ref, classOf[MemberUp])
@ -387,7 +386,7 @@ class ClusterSingletonManagerSpec
enterBarrier("after-1") enterBarrier("after-1")
} }
"let the proxy route messages to the singleton in a 6 node cluster" in within(60 seconds) { "let the proxy route messages to the singleton in a 6 node cluster" in within(60.seconds) {
verifyProxyMsg(first, first, msg = msg()) verifyProxyMsg(first, first, msg = msg())
verifyProxyMsg(first, second, msg = msg()) verifyProxyMsg(first, second, msg = msg())
verifyProxyMsg(first, third, msg = msg()) verifyProxyMsg(first, third, msg = msg())
@ -396,7 +395,7 @@ class ClusterSingletonManagerSpec
verifyProxyMsg(first, sixth, msg = msg()) verifyProxyMsg(first, sixth, msg = msg())
} }
"hand over when oldest leaves in 6 nodes cluster " in within(30 seconds) { "hand over when oldest leaves in 6 nodes cluster " in within(30.seconds) {
val leaveRole = first val leaveRole = first
runOn(leaveRole) { runOn(leaveRole) {
@ -424,7 +423,7 @@ class ClusterSingletonManagerSpec
enterBarrier("after-leave") enterBarrier("after-leave")
} }
"take over when oldest crashes in 5 nodes cluster" in within(60 seconds) { "take over when oldest crashes in 5 nodes cluster" in within(60.seconds) {
// mute logging of deadLetters during shutdown of systems // mute logging of deadLetters during shutdown of systems
if (!log.isDebugEnabled) if (!log.isDebugEnabled)
system.eventStream.publish(Mute(DeadLettersFilter[Any])) system.eventStream.publish(Mute(DeadLettersFilter[Any]))
@ -439,7 +438,7 @@ class ClusterSingletonManagerSpec
verifyProxyMsg(third, sixth, msg = msg()) verifyProxyMsg(third, sixth, msg = msg())
} }
"take over when two oldest crash in 3 nodes cluster" in within(60 seconds) { "take over when two oldest crash in 3 nodes cluster" in within(60.seconds) {
crash(third, fourth) crash(third, fourth)
verifyRegistration(fifth) verifyRegistration(fifth)
verifyMsg(fifth, msg = msg()) verifyMsg(fifth, msg = msg())
@ -447,7 +446,7 @@ class ClusterSingletonManagerSpec
verifyProxyMsg(fifth, sixth, msg = msg()) verifyProxyMsg(fifth, sixth, msg = msg())
} }
"take over when oldest crashes in 2 nodes cluster" in within(60 seconds) { "take over when oldest crashes in 2 nodes cluster" in within(60.seconds) {
crash(fifth) crash(fifth)
verifyRegistration(sixth) verifyRegistration(sixth)
verifyMsg(sixth, msg = msg()) verifyMsg(sixth, msg = msg())

View file

@ -18,7 +18,6 @@ import scala.collection.immutable.{ SortedSet, VectorBuilder }
import scala.runtime.AbstractFunction5 import scala.runtime.AbstractFunction5
import scala.annotation.nowarn import scala.annotation.nowarn
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.actor.{ Actor, ActorRef, Address } import pekko.actor.{ Actor, ActorRef, Address }
@ -166,7 +165,7 @@ object ClusterEvent {
/** /**
* Java API: get address of current data center leader, or null if none * Java API: get address of current data center leader, or null if none
*/ */
def getLeader: Address = leader orNull def getLeader: Address = leader.orNull
/** /**
* get address of current leader, if any, within the data center that has the given role * get address of current leader, if any, within the data center that has the given role
@ -366,7 +365,7 @@ object ClusterEvent {
* Java API * Java API
* @return address of current leader, or null if none * @return address of current leader, or null if none
*/ */
def getLeader: Address = leader orNull def getLeader: Address = leader.orNull
} }
/** /**
@ -380,7 +379,7 @@ object ClusterEvent {
* Java API * Java API
* @return address of current leader, or null if none * @return address of current leader, or null if none
*/ */
def getLeader: Address = leader orNull def getLeader: Address = leader.orNull
} }
/** /**

View file

@ -52,7 +52,8 @@ class Member private[cluster] (
case _ => false case _ => false
} }
override def toString: String = { override def toString: String = {
s"Member($address, $status${if (dataCenter == ClusterSettings.DefaultDataCenter) "" else s", $dataCenter"}${if (appVersion == Version.Zero) "" s"Member($address, $status${if (dataCenter == ClusterSettings.DefaultDataCenter) ""
else s", $dataCenter"}${if (appVersion == Version.Zero) ""
else s", $appVersion"})" else s", $appVersion"})"
} }

View file

@ -484,7 +484,8 @@ import pekko.remote.artery.ThisActorSystemQuarantinedEvent
log.warning( log.warning(
ClusterLogMarker.sbrDowning(decision), ClusterLogMarker.sbrDowning(decision),
s"SBR took decision $decision and is downing [${nodesToDown.map(_.address).mkString(", ")}]${if (downMyself) " including myself" s"SBR took decision $decision and is downing [${nodesToDown.map(_.address).mkString(", ")}]${if (downMyself)
" including myself"
else ""}, " + else ""}, " +
s"[${strategy.unreachable.size}] unreachable of [${strategy.members.size}] members" + s"[${strategy.unreachable.size}] unreachable of [${strategy.members.size}] members" +
indirectlyConnectedLogMessage + indirectlyConnectedLogMessage +

View file

@ -17,7 +17,6 @@ import java.util.concurrent.TimeoutException
import scala.concurrent.Await import scala.concurrent.Await
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.language.postfixOps
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
import org.scalatest.concurrent.ScalaFutures import org.scalatest.concurrent.ScalaFutures
@ -86,7 +85,7 @@ abstract class ClusterDeathWatchSpec
"An actor watching a remote actor in the cluster" must { "An actor watching a remote actor in the cluster" must {
"receive Terminated when watched node becomes Down/Removed" in within(20 seconds) { "receive Terminated when watched node becomes Down/Removed" in within(20.seconds) {
awaitClusterUp(first, second, third, fourth) awaitClusterUp(first, second, third, fourth)
enterBarrier("cluster-up") enterBarrier("cluster-up")
@ -163,7 +162,7 @@ abstract class ClusterDeathWatchSpec
} }
"not be able to watch an actor before node joins cluster, ClusterRemoteWatcher takes over from RemoteWatcher" in within( "not be able to watch an actor before node joins cluster, ClusterRemoteWatcher takes over from RemoteWatcher" in within(
20 seconds) { 20.seconds) {
runOn(fifth) { runOn(fifth) {
system.actorOf( system.actorOf(
Props(new Actor { def receive = Actor.emptyBehavior }).withDeploy(Deploy.local), Props(new Actor { def receive = Actor.emptyBehavior }).withDeploy(Deploy.local),
@ -253,7 +252,7 @@ abstract class ClusterDeathWatchSpec
enterBarrier("after-4") enterBarrier("after-4")
} }
"be able to shutdown system when using remote deployed actor on node that crash" in within(20 seconds) { "be able to shutdown system when using remote deployed actor on node that crash" in within(20.seconds) {
// fourth actor system will be shutdown, not part of testConductor any more // fourth actor system will be shutdown, not part of testConductor any more
// so we can't use barriers to synchronize with it // so we can't use barriers to synchronize with it
val firstAddress = address(first) val firstAddress = address(first)
@ -298,7 +297,7 @@ abstract class ClusterDeathWatchSpec
endProbe.expectMsg(EndActor.EndAck) endProbe.expectMsg(EndActor.EndAck)
} finally { } finally {
shutdown(endSystem, 10 seconds) shutdown(endSystem, 10.seconds)
} }
// no barrier here, because it is not part of testConductor roles any more // no barrier here, because it is not part of testConductor roles any more

View file

@ -16,7 +16,6 @@ package org.apache.pekko.cluster
import scala.concurrent.duration._ import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.actor.Address import pekko.actor.Address
@ -79,7 +78,7 @@ abstract class ConvergenceSpec(multiNodeConfig: ConvergenceMultiNodeConfig)
runOn(first, second) { runOn(first, second) {
within(28 seconds) { within(28.seconds) {
// third becomes unreachable // third becomes unreachable
awaitAssert(clusterView.unreachableMembers.size should ===(1)) awaitAssert(clusterView.unreachableMembers.size should ===(1))
awaitSeenSameState(first, second) awaitSeenSameState(first, second)

View file

@ -16,7 +16,6 @@ package org.apache.pekko.cluster
import scala.concurrent.duration._ import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.cluster.ClusterEvent.CurrentClusterState import pekko.cluster.ClusterEvent.CurrentClusterState
@ -54,7 +53,7 @@ abstract class InitialHeartbeatSpec extends MultiNodeClusterSpec(InitialHeartbea
awaitClusterUp(first) awaitClusterUp(first)
runOn(first) { runOn(first) {
within(10 seconds) { within(10.seconds) {
awaitAssert({ awaitAssert({
cluster.sendCurrentClusterState(testActor) cluster.sendCurrentClusterState(testActor)
expectMsgType[CurrentClusterState].members.map(_.address) should contain(secondAddress) expectMsgType[CurrentClusterState].members.map(_.address) should contain(secondAddress)
@ -63,7 +62,7 @@ abstract class InitialHeartbeatSpec extends MultiNodeClusterSpec(InitialHeartbea
} }
runOn(second) { runOn(second) {
cluster.join(first) cluster.join(first)
within(10 seconds) { within(10.seconds) {
awaitAssert({ awaitAssert({
cluster.sendCurrentClusterState(testActor) cluster.sendCurrentClusterState(testActor)
expectMsgType[CurrentClusterState].members.map(_.address) should contain(firstAddress) expectMsgType[CurrentClusterState].members.map(_.address) should contain(firstAddress)
@ -81,7 +80,7 @@ abstract class InitialHeartbeatSpec extends MultiNodeClusterSpec(InitialHeartbea
} }
runOn(second) { runOn(second) {
within(15 seconds) { within(15.seconds) {
awaitCond(!cluster.failureDetector.isAvailable(first)) awaitCond(!cluster.failureDetector.isAvailable(first))
} }
} }

View file

@ -16,7 +16,6 @@ package org.apache.pekko.cluster
import scala.concurrent.duration._ import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.remote.testkit.MultiNodeConfig import pekko.remote.testkit.MultiNodeConfig
@ -124,7 +123,7 @@ abstract class LeaderDowningNodeThatIsUnreachableSpec(
runOn(third) { runOn(third) {
enterBarrier("down-second-node") enterBarrier("down-second-node")
awaitMembersUp(numberOfMembers = 2, canNotBePartOfMemberRing = Set(secondAddress), 30 seconds) awaitMembersUp(numberOfMembers = 2, canNotBePartOfMemberRing = Set(secondAddress), 30.seconds)
} }
enterBarrier("await-completion-2") enterBarrier("await-completion-2")

View file

@ -15,8 +15,6 @@ package org.apache.pekko.cluster
import scala.concurrent.duration._ import scala.concurrent.duration._
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.remote.testkit.MultiNodeConfig import pekko.remote.testkit.MultiNodeConfig
import pekko.testkit._ import pekko.testkit._
@ -121,13 +119,13 @@ abstract class LeaderElectionSpec(multiNodeConfig: LeaderElectionMultiNodeConfig
} }
} }
"be able to 're-elect' a single leader after leader has left" taggedAs LongRunningTest in within(30 seconds) { "be able to 're-elect' a single leader after leader has left" taggedAs LongRunningTest in within(30.seconds) {
shutdownLeaderAndVerifyNewLeader(alreadyShutdown = 0) shutdownLeaderAndVerifyNewLeader(alreadyShutdown = 0)
enterBarrier("after-2") enterBarrier("after-2")
} }
"be able to 're-elect' a single leader after leader has left (again)" taggedAs LongRunningTest in within( "be able to 're-elect' a single leader after leader has left (again)" taggedAs LongRunningTest in within(
30 seconds) { 30.seconds) {
shutdownLeaderAndVerifyNewLeader(alreadyShutdown = 1) shutdownLeaderAndVerifyNewLeader(alreadyShutdown = 1)
enterBarrier("after-3") enterBarrier("after-3")
} }

View file

@ -20,7 +20,6 @@ import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
import javax.management.InstanceNotFoundException import javax.management.InstanceNotFoundException
import javax.management.ObjectName import javax.management.ObjectName
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.remote.testkit.MultiNodeConfig import pekko.remote.testkit.MultiNodeConfig
@ -107,7 +106,7 @@ abstract class MBeanSpec extends MultiNodeClusterSpec(MBeanMultiJvmSpec) {
val fourthAddress = address(fourth) val fourthAddress = address(fourth)
"format cluster status as JSON with full reachability info" taggedAs LongRunningTest in within(30 seconds) { "format cluster status as JSON with full reachability info" taggedAs LongRunningTest in within(30.seconds) {
runOn(first) { runOn(first) {
testConductor.exit(fourth, 0).await testConductor.exit(fourth, 0).await
} }
@ -187,7 +186,7 @@ abstract class MBeanSpec extends MultiNodeClusterSpec(MBeanMultiJvmSpec) {
} }
"support down" taggedAs LongRunningTest in within(20 seconds) { "support down" taggedAs LongRunningTest in within(20.seconds) {
// fourth unreachable in previous step // fourth unreachable in previous step
@ -205,7 +204,7 @@ abstract class MBeanSpec extends MultiNodeClusterSpec(MBeanMultiJvmSpec) {
enterBarrier("after-6") enterBarrier("after-6")
} }
"support leave" taggedAs LongRunningTest in within(20 seconds) { "support leave" taggedAs LongRunningTest in within(20.seconds) {
runOn(second) { runOn(second) {
mbeanServer.invoke(mbeanName, "leave", Array(address(third).toString), Array("java.lang.String")) mbeanServer.invoke(mbeanName, "leave", Array(address(third).toString), Array("java.lang.String"))
} }

View file

@ -14,7 +14,6 @@
package org.apache.pekko.cluster package org.apache.pekko.cluster
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.language.postfixOps
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
@ -63,7 +62,7 @@ abstract class MemberWeaklyUpSpec extends MultiNodeClusterSpec(MemberWeaklyUpSpe
} }
"detect network partition and mark nodes on other side as unreachable" taggedAs LongRunningTest in within( "detect network partition and mark nodes on other side as unreachable" taggedAs LongRunningTest in within(
20 seconds) { 20.seconds) {
runOn(first) { runOn(first) {
// split the cluster in two parts (first, second) / (third, fourth, fifth) // split the cluster in two parts (first, second) / (third, fourth, fifth)
for (role1 <- side1; role2 <- side2) { for (role1 <- side1; role2 <- side2) {
@ -83,7 +82,7 @@ abstract class MemberWeaklyUpSpec extends MultiNodeClusterSpec(MemberWeaklyUpSpe
enterBarrier("after-2") enterBarrier("after-2")
} }
"accept joining on each side and set status to WeaklyUp" taggedAs LongRunningTest in within(20 seconds) { "accept joining on each side and set status to WeaklyUp" taggedAs LongRunningTest in within(20.seconds) {
runOn(second) { runOn(second) {
Cluster(system).join(first) Cluster(system).join(first)
} }
@ -113,7 +112,7 @@ abstract class MemberWeaklyUpSpec extends MultiNodeClusterSpec(MemberWeaklyUpSpe
enterBarrier("after-3") enterBarrier("after-3")
} }
"change status to Up after healed network partition" taggedAs LongRunningTest in within(20 seconds) { "change status to Up after healed network partition" taggedAs LongRunningTest in within(20.seconds) {
runOn(first) { runOn(first) {
for (role1 <- side1; role2 <- side2) { for (role1 <- side1; role2 <- side2) {
testConductor.passThrough(role1, role2, Direction.Both).await testConductor.passThrough(role1, role2, Direction.Both).await

View file

@ -17,7 +17,6 @@ import scala.collection.immutable
import scala.concurrent.duration._ import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.actor.Actor import pekko.actor.Actor
@ -84,7 +83,7 @@ abstract class RestartFirstSeedNodeSpec
} }
"Cluster seed nodes" must { "Cluster seed nodes" must {
"be able to restart first seed node and join other seed nodes" taggedAs LongRunningTest in within(40 seconds) { "be able to restart first seed node and join other seed nodes" taggedAs LongRunningTest in within(40.seconds) {
// seed1System is a separate ActorSystem, to be able to simulate restart // seed1System is a separate ActorSystem, to be able to simulate restart
// we must transfer its address to seed2 and seed3 // we must transfer its address to seed2 and seed3
runOn(seed2, seed3) { runOn(seed2, seed3) {
@ -103,7 +102,7 @@ abstract class RestartFirstSeedNodeSpec
seedNode1Address = Cluster(seed1System).selfAddress seedNode1Address = Cluster(seed1System).selfAddress
List(seed2, seed3).foreach { r => List(seed2, seed3).foreach { r =>
system.actorSelection(RootActorPath(r) / "user" / "address-receiver") ! seedNode1Address system.actorSelection(RootActorPath(r) / "user" / "address-receiver") ! seedNode1Address
expectMsg(5 seconds, "ok") expectMsg(5.seconds, "ok")
} }
} }
enterBarrier("seed1-address-transferred") enterBarrier("seed1-address-transferred")

View file

@ -16,7 +16,6 @@ package org.apache.pekko.cluster
import scala.concurrent.duration._ import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.remote.testkit.MultiNodeConfig import pekko.remote.testkit.MultiNodeConfig
@ -77,7 +76,7 @@ abstract class SplitBrainSpec(multiNodeConfig: SplitBrainMultiNodeConfig)
} }
"detect network partition and mark nodes on other side as unreachable and form new cluster" taggedAs LongRunningTest in within( "detect network partition and mark nodes on other side as unreachable and form new cluster" taggedAs LongRunningTest in within(
30 seconds) { 30.seconds) {
enterBarrier("before-split") enterBarrier("before-split")
runOn(first) { runOn(first) {

View file

@ -18,7 +18,6 @@ import java.lang.management.ManagementFactory
import scala.annotation.tailrec import scala.annotation.tailrec
import scala.collection.immutable import scala.collection.immutable
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.language.postfixOps
import com.typesafe.config.Config import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
@ -857,7 +856,7 @@ abstract class StressSpec extends MultiNodeClusterSpec(StressMultiJvmSpec) with
// note: there must be one test step before pending, otherwise afterTermination will not run // note: there must be one test step before pending, otherwise afterTermination will not run
if (isArteryEnabled && isAeronUdpTransport) pending if (isArteryEnabled && isAeronUdpTransport) pending
"join seed nodes" taggedAs LongRunningTest in within(30 seconds) { "join seed nodes" taggedAs LongRunningTest in within(30.seconds) {
val otherNodesJoiningSeedNodes = val otherNodesJoiningSeedNodes =
roles.slice(numberOfSeedNodes, numberOfSeedNodes + numberOfNodesJoiningToSeedNodesInitially) roles.slice(numberOfSeedNodes, numberOfSeedNodes + numberOfNodesJoiningToSeedNodesInitially)

View file

@ -18,7 +18,6 @@ import scala.concurrent.Await
import scala.concurrent.duration._ import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.actor.ActorSystem import pekko.actor.ActorSystem
@ -96,7 +95,7 @@ abstract class UnreachableNodeJoinsAgainSpec extends MultiNodeClusterSpec(Unreac
val allButVictim = allBut(victim, roles) val allButVictim = allBut(victim, roles)
runOn(victim) { runOn(victim) {
allButVictim.foreach(markNodeAsUnavailable(_)) allButVictim.foreach(markNodeAsUnavailable(_))
within(30 seconds) { within(30.seconds) {
// victim becomes all alone // victim becomes all alone
awaitAssert { awaitAssert {
clusterView.unreachableMembers.size should ===(roles.size - 1) clusterView.unreachableMembers.size should ===(roles.size - 1)
@ -107,7 +106,7 @@ abstract class UnreachableNodeJoinsAgainSpec extends MultiNodeClusterSpec(Unreac
runOn(allButVictim: _*) { runOn(allButVictim: _*) {
markNodeAsUnavailable(victim) markNodeAsUnavailable(victim)
within(30 seconds) { within(30.seconds) {
// victim becomes unreachable // victim becomes unreachable
awaitAssert { awaitAssert {
clusterView.unreachableMembers.size should ===(1) clusterView.unreachableMembers.size should ===(1)
@ -132,7 +131,7 @@ abstract class UnreachableNodeJoinsAgainSpec extends MultiNodeClusterSpec(Unreac
runOn(allButVictim: _*) { runOn(allButVictim: _*) {
// eventually removed // eventually removed
awaitMembersUp(roles.size - 1, Set(victim)) awaitMembersUp(roles.size - 1, Set(victim))
awaitAssert(clusterView.unreachableMembers should ===(Set.empty), 15 seconds) awaitAssert(clusterView.unreachableMembers should ===(Set.empty), 15.seconds)
awaitAssert(clusterView.members.map(_.address) should ===(allButVictim.map(address).toSet)) awaitAssert(clusterView.members.map(_.address) should ===(allButVictim.map(address).toSet))
} }
@ -184,14 +183,14 @@ abstract class UnreachableNodeJoinsAgainSpec extends MultiNodeClusterSpec(Unreac
}""") }""")
.withFallback(system.settings.config) .withFallback(system.settings.config)
Await.ready(system.whenTerminated, 10 seconds) Await.ready(system.whenTerminated, 10.seconds)
// create new ActorSystem with same host:port // create new ActorSystem with same host:port
val freshSystem = ActorSystem(system.name, freshConfig) val freshSystem = ActorSystem(system.name, freshConfig)
try { try {
Cluster(freshSystem).join(masterAddress) Cluster(freshSystem).join(masterAddress)
within(30 seconds) { within(30.seconds) {
awaitAssert(Cluster(freshSystem).readView.members.map(_.address) should contain(victimAddress)) awaitAssert(Cluster(freshSystem).readView.members.map(_.address) should contain(victimAddress))
awaitAssert(Cluster(freshSystem).readView.members.size should ===(expectedNumberOfMembers)) awaitAssert(Cluster(freshSystem).readView.members.size should ===(expectedNumberOfMembers))
awaitAssert(Cluster(freshSystem).readView.members.unsorted.map(_.status) should ===(Set(MemberStatus.Up))) awaitAssert(Cluster(freshSystem).readView.members.unsorted.map(_.status) should ===(Set(MemberStatus.Up)))
@ -213,7 +212,7 @@ abstract class UnreachableNodeJoinsAgainSpec extends MultiNodeClusterSpec(Unreac
awaitMembersUp(expectedNumberOfMembers) awaitMembersUp(expectedNumberOfMembers)
// don't end the test until the freshSystem is done // don't end the test until the freshSystem is done
runOn(master) { runOn(master) {
expectMsg(20 seconds, EndActor.End) expectMsg(20.seconds, EndActor.End)
} }
endBarrier() endBarrier()
} }

View file

@ -17,7 +17,6 @@ import scala.concurrent.Await
import scala.concurrent.duration._ import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.actor.Actor import pekko.actor.Actor
@ -132,7 +131,7 @@ abstract class ClusterRoundRobinSpec
def receiveReplies(routeeType: RouteeType, expectedReplies: Int): Map[Address, Int] = { def receiveReplies(routeeType: RouteeType, expectedReplies: Int): Map[Address, Int] = {
val zero = Map.empty[Address, Int] ++ roles.map(address(_) -> 0) val zero = Map.empty[Address, Int] ++ roles.map(address(_) -> 0)
receiveWhile(5 seconds, messages = expectedReplies) { receiveWhile(5.seconds, messages = expectedReplies) {
case Reply(`routeeType`, ref) => fullAddress(ref) case Reply(`routeeType`, ref) => fullAddress(ref)
}.foldLeft(zero) { }.foldLeft(zero) {
case (replyMap, address) => replyMap + (address -> (replyMap(address) + 1)) case (replyMap, address) => replyMap + (address -> (replyMap(address) + 1))

View file

@ -15,7 +15,6 @@ package org.apache.pekko.cluster.routing
import scala.concurrent.Await import scala.concurrent.Await
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.language.postfixOps
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
@ -75,7 +74,7 @@ abstract class UseRoleIgnoredSpec
def receiveReplies(routeeType: RouteeType, expectedReplies: Int): Map[Address, Int] = { def receiveReplies(routeeType: RouteeType, expectedReplies: Int): Map[Address, Int] = {
val zero = Map.empty[Address, Int] ++ roles.map(address(_) -> 0) val zero = Map.empty[Address, Int] ++ roles.map(address(_) -> 0)
receiveWhile(5 seconds, messages = expectedReplies) { receiveWhile(5.seconds, messages = expectedReplies) {
case Reply(`routeeType`, ref) => fullAddress(ref) case Reply(`routeeType`, ref) => fullAddress(ref)
}.foldLeft(zero) { }.foldLeft(zero) {
case (replyMap, address) => replyMap + (address -> (replyMap(address) + 1)) case (replyMap, address) => replyMap + (address -> (replyMap(address) + 1))

View file

@ -17,7 +17,6 @@ import scala.concurrent.duration._
import scala.annotation.nowarn import scala.annotation.nowarn
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.actor.Address import pekko.actor.Address
@ -38,21 +37,21 @@ class ClusterConfigSpec extends PekkoSpec {
LogInfo should ===(true) LogInfo should ===(true)
FailureDetectorConfig.getDouble("threshold") should ===(8.0 +- 0.0001) FailureDetectorConfig.getDouble("threshold") should ===(8.0 +- 0.0001)
FailureDetectorConfig.getInt("max-sample-size") should ===(1000) FailureDetectorConfig.getInt("max-sample-size") should ===(1000)
FailureDetectorConfig.getMillisDuration("min-std-deviation") should ===(100 millis) FailureDetectorConfig.getMillisDuration("min-std-deviation") should ===(100.millis)
FailureDetectorConfig.getMillisDuration("acceptable-heartbeat-pause") should ===(3 seconds) FailureDetectorConfig.getMillisDuration("acceptable-heartbeat-pause") should ===(3.seconds)
FailureDetectorImplementationClass should ===(classOf[PhiAccrualFailureDetector].getName) FailureDetectorImplementationClass should ===(classOf[PhiAccrualFailureDetector].getName)
SeedNodes should ===(Vector.empty[Address]) SeedNodes should ===(Vector.empty[Address])
SeedNodeTimeout should ===(5 seconds) SeedNodeTimeout should ===(5.seconds)
RetryUnsuccessfulJoinAfter should ===(10 seconds) RetryUnsuccessfulJoinAfter should ===(10.seconds)
ShutdownAfterUnsuccessfulJoinSeedNodes should ===(Duration.Undefined) ShutdownAfterUnsuccessfulJoinSeedNodes should ===(Duration.Undefined)
PeriodicTasksInitialDelay should ===(1 seconds) PeriodicTasksInitialDelay should ===(1.seconds)
GossipInterval should ===(1 second) GossipInterval should ===(1.second)
GossipTimeToLive should ===(2 seconds) GossipTimeToLive should ===(2.seconds)
HeartbeatInterval should ===(1 second) HeartbeatInterval should ===(1.second)
MonitoredByNrOfMembers should ===(9) MonitoredByNrOfMembers should ===(9)
HeartbeatExpectedResponseAfter should ===(1 seconds) HeartbeatExpectedResponseAfter should ===(1.seconds)
LeaderActionsInterval should ===(1 second) LeaderActionsInterval should ===(1.second)
UnreachableNodesReaperInterval should ===(1 second) UnreachableNodesReaperInterval should ===(1.second)
PublishStatsInterval should ===(Duration.Undefined) PublishStatsInterval should ===(Duration.Undefined)
DownRemovalMargin should ===(Duration.Zero) DownRemovalMargin should ===(Duration.Zero)
MinNrOfMembers should ===(1) MinNrOfMembers should ===(1)
@ -64,7 +63,7 @@ class ClusterConfigSpec extends PekkoSpec {
UseDispatcher should ===(Dispatchers.InternalDispatcherId) UseDispatcher should ===(Dispatchers.InternalDispatcherId)
GossipDifferentViewProbability should ===(0.8 +- 0.0001) GossipDifferentViewProbability should ===(0.8 +- 0.0001)
ReduceGossipDifferentViewProbability should ===(400) ReduceGossipDifferentViewProbability should ===(400)
SchedulerTickDuration should ===(33 millis) SchedulerTickDuration should ===(33.millis)
SchedulerTicksPerWheel should ===(512) SchedulerTicksPerWheel should ===(512)
} }

View file

@ -15,8 +15,6 @@ package docs.actor
import jdocs.actor.ImmutableMessage import jdocs.actor.ImmutableMessage
import language.postfixOps
//#imports1 //#imports1
import org.apache.pekko import org.apache.pekko
import pekko.actor.Actor import pekko.actor.Actor
@ -336,7 +334,6 @@ final case class Give(thing: Any)
//#fiddle_code //#fiddle_code
import org.apache.pekko.actor.{ Actor, ActorRef, ActorSystem, PoisonPill, Props } import org.apache.pekko.actor.{ Actor, ActorRef, ActorSystem, PoisonPill, Props }
import language.postfixOps
import scala.concurrent.duration._ import scala.concurrent.duration._
case object Ping case object Ping
@ -400,10 +397,10 @@ class ActorDocSpec extends PekkoSpec("""
system.eventStream.subscribe(testActor, classOf[Logging.Info]) system.eventStream.subscribe(testActor, classOf[Logging.Info])
myActor ! "test" myActor ! "test"
expectMsgPF(1 second) { case Logging.Info(_, _, "received test") => true } expectMsgPF(1.second) { case Logging.Info(_, _, "received test") => true }
myActor ! "unknown" myActor ! "unknown"
expectMsgPF(1 second) { case Logging.Info(_, _, "received unknown message") => true } expectMsgPF(1.second) { case Logging.Info(_, _, "received unknown message") => true }
system.eventStream.unsubscribe(testActor) system.eventStream.unsubscribe(testActor)
system.eventStream.publish(TestEvent.UnMute(filter)) system.eventStream.publish(TestEvent.UnMute(filter))
@ -420,7 +417,7 @@ class ActorDocSpec extends PekkoSpec("""
val ponger = system.actorOf(Props(classOf[Ponger], pinger), "ponger") val ponger = system.actorOf(Props(classOf[Ponger], pinger), "ponger")
import system.dispatcher import system.dispatcher
system.scheduler.scheduleOnce(500 millis) { system.scheduler.scheduleOnce(500.millis) {
ponger ! Ping ponger ! Ping
} }
@ -546,9 +543,9 @@ class ActorDocSpec extends PekkoSpec("""
// #using-explicit-timeout // #using-explicit-timeout
import scala.concurrent.duration._ import scala.concurrent.duration._
import org.apache.pekko.pattern.ask import org.apache.pekko.pattern.ask
val future = myActor.ask("hello")(5 seconds) val future = myActor.ask("hello")(5.seconds)
// #using-explicit-timeout // #using-explicit-timeout
Await.result(future, 5 seconds) should be("hello") Await.result(future, 5.seconds) should be("hello")
} }
"using receiveTimeout" in { "using receiveTimeout" in {
@ -557,11 +554,11 @@ class ActorDocSpec extends PekkoSpec("""
import scala.concurrent.duration._ import scala.concurrent.duration._
class MyActor extends Actor { class MyActor extends Actor {
// To set an initial delay // To set an initial delay
context.setReceiveTimeout(30 milliseconds) context.setReceiveTimeout(30.milliseconds)
def receive = { def receive = {
case "Hello" => case "Hello" =>
// To set in a response to a message // To set in a response to a message
context.setReceiveTimeout(100 milliseconds) context.setReceiveTimeout(100.milliseconds)
case ReceiveTimeout => case ReceiveTimeout =>
// To turn it off // To turn it off
context.setReceiveTimeout(Duration.Undefined) context.setReceiveTimeout(Duration.Undefined)
@ -671,8 +668,8 @@ class ActorDocSpec extends PekkoSpec("""
import scala.concurrent.Await import scala.concurrent.Await
try { try {
val stopped: Future[Boolean] = gracefulStop(actorRef, 5 seconds, Manager.Shutdown) val stopped: Future[Boolean] = gracefulStop(actorRef, 5.seconds, Manager.Shutdown)
Await.result(stopped, 6 seconds) Await.result(stopped, 6.seconds)
// the actor has been stopped // the actor has been stopped
} catch { } catch {
// the actor wasn't stopped within 5 seconds // the actor wasn't stopped within 5 seconds

View file

@ -13,8 +13,6 @@
package docs.actor package docs.actor
import language.postfixOps
import org.apache.pekko.testkit.{ PekkoSpec => MyFavoriteTestFrameWorkPlusPekkoTestKit } import org.apache.pekko.testkit.{ PekkoSpec => MyFavoriteTestFrameWorkPlusPekkoTestKit }
import org.apache.pekko.util.ByteString import org.apache.pekko.util.ByteString
@ -81,7 +79,7 @@ class FSMDocSpec extends MyFavoriteTestFrameWorkPlusPekkoTestKit {
// #transition-elided // #transition-elided
// #when-syntax // #when-syntax
when(Active, stateTimeout = 1 second) { when(Active, stateTimeout = 1.second) {
case Event(Flush | StateTimeout, t: Todo) => case Event(Flush | StateTimeout, t: Todo) =>
goto(Idle).using(t.copy(queue = Vector.empty)) goto(Idle).using(t.copy(queue = Vector.empty))
} }
@ -120,13 +118,13 @@ class FSMDocSpec extends MyFavoriteTestFrameWorkPlusPekkoTestKit {
// #modifier-syntax // #modifier-syntax
when(SomeState) { when(SomeState) {
case Event(msg, _) => case Event(msg, _) =>
goto(Processing).using(newData).forMax(5 seconds).replying(WillDo) goto(Processing).using(newData).forMax(5.seconds).replying(WillDo)
} }
// #modifier-syntax // #modifier-syntax
// #transition-syntax // #transition-syntax
onTransition { onTransition {
case Idle -> Active => startTimerWithFixedDelay("timeout", Tick, 1 second) case Idle -> Active => startTimerWithFixedDelay("timeout", Tick, 1.second)
case Active -> _ => cancelTimer("timeout") case Active -> _ => cancelTimer("timeout")
case x -> Idle => log.info("entering Idle from " + x) case x -> Idle => log.info("entering Idle from " + x)
} }

View file

@ -13,8 +13,6 @@
package docs.actor package docs.actor
import language.postfixOps
//#all //#all
//#imports //#imports
import org.apache.pekko import org.apache.pekko
@ -57,7 +55,7 @@ object FaultHandlingDocSample extends App {
class Listener extends Actor with ActorLogging { class Listener extends Actor with ActorLogging {
import Worker._ import Worker._
// If we don't get any progress within 15 seconds then the service is unavailable // If we don't get any progress within 15 seconds then the service is unavailable
context.setReceiveTimeout(15 seconds) context.setReceiveTimeout(15.seconds)
def receive = { def receive = {
case Progress(percent) => case Progress(percent) =>
@ -90,7 +88,7 @@ object Worker {
class Worker extends Actor with ActorLogging { class Worker extends Actor with ActorLogging {
import Worker._ import Worker._
import CounterService._ import CounterService._
implicit val askTimeout: Timeout = Timeout(5 seconds) implicit val askTimeout: Timeout = Timeout(5.seconds)
// Stop the CounterService child if it throws ServiceUnavailable // Stop the CounterService child if it throws ServiceUnavailable
override val supervisorStrategy = OneForOneStrategy() { override val supervisorStrategy = OneForOneStrategy() {
@ -107,7 +105,7 @@ class Worker extends Actor with ActorLogging {
def receive = LoggingReceive { def receive = LoggingReceive {
case Start if progressListener.isEmpty => case Start if progressListener.isEmpty =>
progressListener = Some(sender()) progressListener = Some(sender())
context.system.scheduler.scheduleWithFixedDelay(Duration.Zero, 1 second, self, Do) context.system.scheduler.scheduleWithFixedDelay(Duration.Zero, 1.second, self, Do)
case Do => case Do =>
counterService ! Increment(1) counterService ! Increment(1)
@ -147,7 +145,7 @@ class CounterService extends Actor {
// Restart the storage child when StorageException is thrown. // Restart the storage child when StorageException is thrown.
// After 3 restarts within 5 seconds it will be stopped. // After 3 restarts within 5 seconds it will be stopped.
override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 3, withinTimeRange = 5 seconds) { override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 3, withinTimeRange = 5.seconds) {
case _: Storage.StorageException => Restart case _: Storage.StorageException => Restart
} }
@ -200,7 +198,7 @@ class CounterService extends Actor {
// Tell the counter that there is no storage for the moment // Tell the counter that there is no storage for the moment
counter.foreach { _ ! UseStorage(None) } counter.foreach { _ ! UseStorage(None) }
// Try to re-establish storage after while // Try to re-establish storage after while
context.system.scheduler.scheduleOnce(10 seconds, self, Reconnect) context.system.scheduler.scheduleOnce(10.seconds, self, Reconnect)
case Reconnect => case Reconnect =>
// Re-establish storage after the scheduled delay // Re-establish storage after the scheduled delay

View file

@ -13,7 +13,6 @@
package docs.actor package docs.actor
import language.postfixOps
import org.apache.pekko.actor.{ ActorRef, ActorSystem, Props, Terminated } import org.apache.pekko.actor.{ ActorRef, ActorSystem, Props, Terminated }
import FaultHandlingDocSpec._ import FaultHandlingDocSpec._
@ -39,7 +38,7 @@ object FaultHandlingDocSpec {
import scala.concurrent.duration._ import scala.concurrent.duration._
override val supervisorStrategy = override val supervisorStrategy =
OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) { OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1.minute) {
case _: ArithmeticException => Resume case _: ArithmeticException => Resume
case _: NullPointerException => Restart case _: NullPointerException => Restart
case _: IllegalArgumentException => Stop case _: IllegalArgumentException => Stop
@ -62,7 +61,7 @@ object FaultHandlingDocSpec {
import scala.concurrent.duration._ import scala.concurrent.duration._
override val supervisorStrategy = override val supervisorStrategy =
OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) { OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1.minute) {
case _: ArithmeticException => Resume case _: ArithmeticException => Resume
case _: NullPointerException => Restart case _: NullPointerException => Restart
case _: IllegalArgumentException => Stop case _: IllegalArgumentException => Stop
@ -86,7 +85,7 @@ object FaultHandlingDocSpec {
import scala.concurrent.duration._ import scala.concurrent.duration._
override val supervisorStrategy = override val supervisorStrategy =
OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) { OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1.minute) {
case _: ArithmeticException => Resume case _: ArithmeticException => Resume
case t => case t =>
super.supervisorStrategy.decider.applyOrElse(t, (_: Any) => Escalate) super.supervisorStrategy.decider.applyOrElse(t, (_: Any) => Escalate)

View file

@ -15,8 +15,6 @@ package docs.actor
import docs.actor.SchedulerDocSpec.TickActor import docs.actor.SchedulerDocSpec.TickActor
import language.postfixOps
//#imports1 //#imports1
import org.apache.pekko import org.apache.pekko
import pekko.actor.Actor import pekko.actor.Actor
@ -44,14 +42,14 @@ class SchedulerDocSpec extends PekkoSpec(Map("pekko.loglevel" -> "INFO")) {
import system.dispatcher import system.dispatcher
// Schedules to send the "foo"-message to the testActor after 50ms // Schedules to send the "foo"-message to the testActor after 50ms
system.scheduler.scheduleOnce(50 milliseconds, testActor, "foo") system.scheduler.scheduleOnce(50.milliseconds, testActor, "foo")
// #schedule-one-off-message // #schedule-one-off-message
expectMsg(1 second, "foo") expectMsg(1.second, "foo")
// #schedule-one-off-thunk // #schedule-one-off-thunk
// Schedules a function to be executed (send a message to the testActor) after 50ms // Schedules a function to be executed (send a message to the testActor) after 50ms
system.scheduler.scheduleOnce(50 milliseconds) { system.scheduler.scheduleOnce(50.milliseconds) {
testActor ! System.currentTimeMillis testActor ! System.currentTimeMillis
} }
// #schedule-one-off-thunk // #schedule-one-off-thunk

View file

@ -21,7 +21,6 @@ class SharedMutableStateDocSpec {
import org.apache.pekko.util.Timeout import org.apache.pekko.util.Timeout
import scala.concurrent.Future import scala.concurrent.Future
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.language.postfixOps
import scala.collection.mutable import scala.collection.mutable
case class Message(msg: String) case class Message(msg: String)

View file

@ -13,7 +13,6 @@
package scala.docs.cluster package scala.docs.cluster
import language.postfixOps
import scala.concurrent.duration._ import scala.concurrent.duration._
import org.apache.pekko.actor.Actor import org.apache.pekko.actor.Actor
import org.apache.pekko.actor.ActorRef import org.apache.pekko.actor.ActorRef

View file

@ -13,7 +13,6 @@
package scala.docs.cluster package scala.docs.cluster
import language.postfixOps
import scala.util.Success import scala.util.Success
import scala.concurrent.duration._ import scala.concurrent.duration._
import org.apache.pekko.actor.Actor import org.apache.pekko.actor.Actor

View file

@ -13,8 +13,6 @@
package docs.dispatcher package docs.dispatcher
import language.postfixOps
import org.apache.pekko.testkit.PekkoSpec import org.apache.pekko.testkit.PekkoSpec
import org.apache.pekko.event.Logging import org.apache.pekko.event.Logging
import org.apache.pekko.event.LoggingAdapter import org.apache.pekko.event.LoggingAdapter

View file

@ -13,8 +13,6 @@
package docs.duration package docs.duration
import language.postfixOps
object Scala { object Scala {
// #dsl // #dsl
import scala.concurrent.duration._ import scala.concurrent.duration._
@ -24,7 +22,7 @@ object Scala {
val diff = fivesec - threemillis val diff = fivesec - threemillis
assert(diff < fivesec) assert(diff < fivesec)
val fourmillis = threemillis * 4 / 3 // you cannot write it the other way around val fourmillis = threemillis * 4 / 3 // you cannot write it the other way around
val n = threemillis / (1 millisecond) val n = threemillis / (1.millisecond)
// #dsl // #dsl
// #deadline // #deadline

View file

@ -13,7 +13,6 @@
package docs.future package docs.future
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.testkit._ import pekko.testkit._
import pekko.actor.{ Actor, ActorRef, Props, Status } import pekko.actor.{ Actor, ActorRef, Props, Status }
@ -116,7 +115,7 @@ object FutureDocSpec {
import org.apache.pekko.pattern.{ ask, pipe } import org.apache.pekko.pattern.{ ask, pipe }
implicit val ec: ExecutionContext = context.dispatcher implicit val ec: ExecutionContext = context.dispatcher
implicit val timeout: Timeout = Timeout(5 seconds) implicit val timeout: Timeout = Timeout(5.seconds)
def receive = { def receive = {
case GetUserData => case GetUserData =>
@ -200,7 +199,7 @@ class FutureDocSpec extends PekkoSpec {
} }
future.foreach(println) future.foreach(println)
// #future-eval // #future-eval
Await.result(future, 3 seconds) should be("HelloWorld") Await.result(future, 3.seconds) should be("HelloWorld")
} }
"demonstrate usage of map" in { "demonstrate usage of map" in {
@ -213,7 +212,7 @@ class FutureDocSpec extends PekkoSpec {
} }
f2.foreach(println) f2.foreach(println)
// #map // #map
val result = Await.result(f2, 3 seconds) val result = Await.result(f2, 3.seconds)
result should be(10) result should be(10)
f1.value should be(Some(Success("HelloWorld"))) f1.value should be(Some(Success("HelloWorld")))
} }
@ -231,7 +230,7 @@ class FutureDocSpec extends PekkoSpec {
} }
f3.foreach(println) f3.foreach(println)
// #wrong-nested-map // #wrong-nested-map
Await.ready(f3, 3 seconds) Await.ready(f3, 3.seconds)
} }
"demonstrate usage of flatMap" in { "demonstrate usage of flatMap" in {
@ -247,7 +246,7 @@ class FutureDocSpec extends PekkoSpec {
} }
f3.foreach(println) f3.foreach(println)
// #flat-map // #flat-map
val result = Await.result(f3, 3 seconds) val result = Await.result(f3, 3.seconds)
result should be(30) result should be(30)
} }
@ -265,9 +264,9 @@ class FutureDocSpec extends PekkoSpec {
failedFilter.foreach(println) failedFilter.foreach(println)
// #filter // #filter
val result = Await.result(future2, 3 seconds) val result = Await.result(future2, 3.seconds)
result should be(4) result should be(4)
val result2 = Await.result(failedFilter, 3 seconds) val result2 = Await.result(failedFilter, 3.seconds)
result2 should be(0) // Can only be 0 when there was a MatchError result2 should be(0) // Can only be 0 when there was a MatchError
} }
@ -285,7 +284,7 @@ class FutureDocSpec extends PekkoSpec {
f.foreach(println) f.foreach(println)
// #for-comprehension // #for-comprehension
val result = Await.result(f, 3 seconds) val result = Await.result(f, 3.seconds)
result should be(24) result should be(24)
} }
@ -303,12 +302,12 @@ class FutureDocSpec extends PekkoSpec {
val f1 = ask(actor1, msg1) val f1 = ask(actor1, msg1)
val f2 = ask(actor2, msg2) val f2 = ask(actor2, msg2)
val a = Await.result(f1, 3 seconds).asInstanceOf[Int] val a = Await.result(f1, 3.seconds).asInstanceOf[Int]
val b = Await.result(f2, 3 seconds).asInstanceOf[Int] val b = Await.result(f2, 3.seconds).asInstanceOf[Int]
val f3 = ask(actor3, a + b) val f3 = ask(actor3, a + b)
val result = Await.result(f3, 3 seconds).asInstanceOf[Int] val result = Await.result(f3, 3.seconds).asInstanceOf[Int]
// #composing-wrong // #composing-wrong
result should be(3) result should be(3)
} }
@ -335,7 +334,7 @@ class FutureDocSpec extends PekkoSpec {
f3.foreach(println) f3.foreach(println)
// #composing // #composing
val result = Await.result(f3, 3 seconds).asInstanceOf[Int] val result = Await.result(f3, 3.seconds).asInstanceOf[Int]
result should be(3) result should be(3)
} }
@ -353,7 +352,7 @@ class FutureDocSpec extends PekkoSpec {
val oddSum = futureList.map(_.sum) val oddSum = futureList.map(_.sum)
oddSum.foreach(println) oddSum.foreach(println)
// #sequence-ask // #sequence-ask
Await.result(oddSum, 3 seconds).asInstanceOf[Int] should be(10000) Await.result(oddSum, 3.seconds).asInstanceOf[Int] should be(10000)
} }
"demonstrate usage of sequence" in { "demonstrate usage of sequence" in {
@ -362,7 +361,7 @@ class FutureDocSpec extends PekkoSpec {
val oddSum = futureList.map(_.sum) val oddSum = futureList.map(_.sum)
oddSum.foreach(println) oddSum.foreach(println)
// #sequence // #sequence
Await.result(oddSum, 3 seconds).asInstanceOf[Int] should be(10000) Await.result(oddSum, 3.seconds).asInstanceOf[Int] should be(10000)
} }
"demonstrate usage of traverse" in { "demonstrate usage of traverse" in {
@ -371,7 +370,7 @@ class FutureDocSpec extends PekkoSpec {
val oddSum = futureList.map(_.sum) val oddSum = futureList.map(_.sum)
oddSum.foreach(println) oddSum.foreach(println)
// #traverse // #traverse
Await.result(oddSum, 3 seconds).asInstanceOf[Int] should be(10000) Await.result(oddSum, 3.seconds).asInstanceOf[Int] should be(10000)
} }
"demonstrate usage of fold" in { "demonstrate usage of fold" in {
@ -381,7 +380,7 @@ class FutureDocSpec extends PekkoSpec {
val futureSum = Future.foldLeft(futures)(0)(_ + _) val futureSum = Future.foldLeft(futures)(0)(_ + _)
futureSum.foreach(println) futureSum.foreach(println)
// #fold // #fold
Await.result(futureSum, 3 seconds) should be(1001000) Await.result(futureSum, 3.seconds) should be(1001000)
} }
"demonstrate usage of reduce" in { "demonstrate usage of reduce" in {
@ -391,7 +390,7 @@ class FutureDocSpec extends PekkoSpec {
val futureSum = Future.reduceLeft(futures)(_ + _) val futureSum = Future.reduceLeft(futures)(_ + _)
futureSum.foreach(println) futureSum.foreach(println)
// #reduce // #reduce
Await.result(futureSum, 3 seconds) should be(1001000) Await.result(futureSum, 3.seconds) should be(1001000)
} }
"demonstrate usage of recover" in { "demonstrate usage of recover" in {
@ -419,7 +418,7 @@ class FutureDocSpec extends PekkoSpec {
} }
future.foreach(println) future.foreach(println)
// #try-recover // #try-recover
Await.result(future, 3 seconds) should be(0) Await.result(future, 3.seconds) should be(0)
} }
"demonstrate usage of zip" in { "demonstrate usage of zip" in {
@ -429,7 +428,7 @@ class FutureDocSpec extends PekkoSpec {
val future3 = future1.zip(future2).map { case (a, b) => a + " " + b } val future3 = future1.zip(future2).map { case (a, b) => a + " " + b }
future3.foreach(println) future3.foreach(println)
// #zip // #zip
Await.result(future3, 3 seconds) should be("foo bar") Await.result(future3, 3.seconds) should be("foo bar")
} }
"demonstrate usage of andThen" in { "demonstrate usage of andThen" in {
@ -447,7 +446,7 @@ class FutureDocSpec extends PekkoSpec {
} }
result.foreach(println) result.foreach(println)
// #and-then // #and-then
Await.result(result, 3 seconds) should be("foo bar") Await.result(result, 3.seconds) should be("foo bar")
} }
"demonstrate usage of fallbackTo" in { "demonstrate usage of fallbackTo" in {
@ -458,7 +457,7 @@ class FutureDocSpec extends PekkoSpec {
val future4 = future1.fallbackTo(future2).fallbackTo(future3) val future4 = future1.fallbackTo(future2).fallbackTo(future3)
future4.foreach(println) future4.foreach(println)
// #fallback-to // #fallback-to
Await.result(future4, 3 seconds) should be("foo") Await.result(future4, 3.seconds) should be("foo")
} }
"demonstrate usage of onComplete" in { "demonstrate usage of onComplete" in {
@ -471,7 +470,7 @@ class FutureDocSpec extends PekkoSpec {
case Failure(failure) => doSomethingOnFailure(failure) case Failure(failure) => doSomethingOnFailure(failure)
} }
// #onComplete // #onComplete
Await.result(future, 3 seconds) should be("foo") Await.result(future, 3.seconds) should be("foo")
} }
"demonstrate usage of Future.successful & Future.failed & Future.promise" in { "demonstrate usage of Future.successful & Future.failed & Future.promise" in {
@ -486,9 +485,9 @@ class FutureDocSpec extends PekkoSpec {
val theFuture = promise.future val theFuture = promise.future
promise.success("hello") promise.success("hello")
// #promise // #promise
Await.result(future, 3 seconds) should be("Yay!") Await.result(future, 3.seconds) should be("Yay!")
intercept[IllegalArgumentException] { Await.result(otherFuture, 3 seconds) } intercept[IllegalArgumentException] { Await.result(otherFuture, 3.seconds) }
Await.result(theFuture, 3 seconds) should be("hello") Await.result(theFuture, 3.seconds) should be("hello")
} }
"demonstrate usage of pattern.after" in { "demonstrate usage of pattern.after" in {
@ -501,7 +500,7 @@ class FutureDocSpec extends PekkoSpec {
val future = Future { Thread.sleep(1000); "foo" } val future = Future { Thread.sleep(1000); "foo" }
val result = Future.firstCompletedOf(Seq(future, delayed)) val result = Future.firstCompletedOf(Seq(future, delayed))
// #after // #after
intercept[IllegalStateException] { Await.result(result, 2 second) } intercept[IllegalStateException] { Await.result(result, 2.second) }
} }
"demonstrate pattern.retry" in { "demonstrate pattern.retry" in {
@ -523,10 +522,10 @@ class FutureDocSpec extends PekkoSpec {
} }
// Return a new future that will retry up to 10 times // Return a new future that will retry up to 10 times
val retried: Future[Int] = pekko.pattern.retry(() => futureToAttempt(), attempts = 10, 100 milliseconds) val retried: Future[Int] = pekko.pattern.retry(() => futureToAttempt(), attempts = 10, 100.milliseconds)
// #retry // #retry
Await.result(retried, 1 second) should ===(5) Await.result(retried, 1.second) should ===(5)
} }
"demonstrate context.dispatcher" in { "demonstrate context.dispatcher" in {

View file

@ -18,7 +18,6 @@ import org.apache.pekko.pattern.{ BackoffOpts, BackoffSupervisor }
import org.apache.pekko.persistence._ import org.apache.pekko.persistence._
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.language.postfixOps
object PersistenceDocSpec { object PersistenceDocSpec {

View file

@ -29,8 +29,7 @@ object FoldAsync extends App {
// #foldAsync // #foldAsync
case class Histogram(low: Long = 0, high: Long = 0) { case class Histogram(low: Long = 0, high: Long = 0) {
def add(i: Int): Future[Histogram] = def add(i: Int): Future[Histogram] =
if (i < 100) Future { copy(low = low + 1) } if (i < 100) Future { copy(low = low + 1) } else Future { copy(high = high + 1) }
else Future { copy(high = high + 1) }
} }
Source(1 to 150).foldAsync(Histogram())((acc, n) => acc.add(n)).runForeach(println) Source(1 to 150).foldAsync(Histogram())((acc, n) => acc.add(n)).runForeach(println)

View file

@ -13,8 +13,6 @@
package docs.testkit package docs.testkit
import language.postfixOps
//#testkit-usage //#testkit-usage
import scala.util.Random import scala.util.Random
@ -61,7 +59,7 @@ class TestKitUsageSpec
"An EchoActor" should { "An EchoActor" should {
"Respond with the same message it receives" in { "Respond with the same message it receives" in {
within(500 millis) { within(500.millis) {
echoRef ! "test" echoRef ! "test"
expectMsg("test") expectMsg("test")
} }
@ -69,7 +67,7 @@ class TestKitUsageSpec
} }
"A ForwardingActor" should { "A ForwardingActor" should {
"Forward a message it receives" in { "Forward a message it receives" in {
within(500 millis) { within(500.millis) {
forwardRef ! "test" forwardRef ! "test"
expectMsg("test") expectMsg("test")
} }
@ -78,7 +76,7 @@ class TestKitUsageSpec
"A FilteringActor" should { "A FilteringActor" should {
"Filter all messages, except expected messagetypes it receives" in { "Filter all messages, except expected messagetypes it receives" in {
var messages = Seq[String]() var messages = Seq[String]()
within(500 millis) { within(500.millis) {
filterRef ! "test" filterRef ! "test"
expectMsg("test") expectMsg("test")
filterRef ! 1 filterRef ! 1
@ -89,7 +87,7 @@ class TestKitUsageSpec
filterRef ! "text" filterRef ! "text"
filterRef ! 1 filterRef ! 1
receiveWhile(500 millis) { receiveWhile(500.millis) {
case msg: String => messages = msg +: messages case msg: String => messages = msg +: messages
} }
} }
@ -99,7 +97,7 @@ class TestKitUsageSpec
} }
"A SequencingActor" should { "A SequencingActor" should {
"receive an interesting message at some point " in { "receive an interesting message at some point " in {
within(500 millis) { within(500.millis) {
ignoreMsg { ignoreMsg {
case msg: String => msg != "something" case msg: String => msg != "something"
} }

View file

@ -13,7 +13,6 @@
package docs.testkit package docs.testkit
import language.postfixOps
import scala.util.Success import scala.util.Success
import org.apache.pekko.testkit._ import org.apache.pekko.testkit._
@ -164,7 +163,7 @@ class TestKitDocSpec extends PekkoSpec with DefaultTimeout with ImplicitSender {
assert(fsm.stateName == 1) assert(fsm.stateName == 1)
assert(fsm.isTimerActive("test") == false) assert(fsm.isTimerActive("test") == false)
fsm.startTimerWithFixedDelay("test", 12, 10 millis) fsm.startTimerWithFixedDelay("test", 12, 10.millis)
assert(fsm.isTimerActive("test") == true) assert(fsm.isTimerActive("test") == true)
fsm.cancelTimer("test") fsm.cancelTimer("test")
assert(fsm.isTimerActive("test") == false) assert(fsm.isTimerActive("test") == false)
@ -191,7 +190,7 @@ class TestKitDocSpec extends PekkoSpec with DefaultTimeout with ImplicitSender {
system.eventStream.subscribe(testActor, classOf[UnhandledMessage]) system.eventStream.subscribe(testActor, classOf[UnhandledMessage])
val ref = TestActorRef[MyActor] val ref = TestActorRef[MyActor]
ref.receive(Unknown) ref.receive(Unknown)
expectMsg(1 second, UnhandledMessage(Unknown, system.deadLetters, ref)) expectMsg(1.second, UnhandledMessage(Unknown, system.deadLetters, ref))
// #test-unhandled // #test-unhandled
} }
@ -215,7 +214,7 @@ class TestKitDocSpec extends PekkoSpec with DefaultTimeout with ImplicitSender {
import scala.concurrent.duration._ import scala.concurrent.duration._
val worker = system.actorOf(Props[Worker]()) val worker = system.actorOf(Props[Worker]())
within(200 millis) { within(200.millis) {
worker ! "some work" worker ! "some work"
expectMsg("some result") expectMsg("some result")
expectNoMessage() // will block for the rest of the 200ms expectNoMessage() // will block for the rest of the 200ms
@ -239,8 +238,8 @@ class TestKitDocSpec extends PekkoSpec with DefaultTimeout with ImplicitSender {
val actor = system.actorOf(Props[MyDoubleEcho]()) val actor = system.actorOf(Props[MyDoubleEcho]())
actor ! ((probe1.ref, probe2.ref)) actor ! ((probe1.ref, probe2.ref))
actor ! "hello" actor ! "hello"
probe1.expectMsg(500 millis, "hello") probe1.expectMsg(500.millis, "hello")
probe2.expectMsg(500 millis, "hello") probe2.expectMsg(500.millis, "hello")
// #test-probe // #test-probe
// #test-special-probe // #test-special-probe
@ -285,7 +284,7 @@ class TestKitDocSpec extends PekkoSpec with DefaultTimeout with ImplicitSender {
// #test-probe-reply // #test-probe-reply
val probe = TestProbe() val probe = TestProbe()
val future = probe.ref ? "hello" val future = probe.ref ? "hello"
probe.expectMsg(0 millis, "hello") // TestActor runs on CallingThreadDispatcher probe.expectMsg(0.millis, "hello") // TestActor runs on CallingThreadDispatcher
probe.reply("world") probe.reply("world")
assert(future.isCompleted && future.value.contains(Success("world"))) assert(future.isCompleted && future.value.contains(Success("world")))
// #test-probe-reply // #test-probe-reply
@ -372,7 +371,7 @@ class TestKitDocSpec extends PekkoSpec with DefaultTimeout with ImplicitSender {
intercept[AssertionError] { intercept[AssertionError] {
// #test-within-probe // #test-within-probe
val probe = TestProbe() val probe = TestProbe()
within(1 second) { within(1.second) {
probe.expectMsg("hello") probe.expectMsg("hello")
} }
// #test-within-probe // #test-within-probe

View file

@ -26,7 +26,6 @@ import scala.util.control.NoStackTrace
import RemoteConnection.getAddrString import RemoteConnection.getAddrString
import io.netty.channel.{ Channel, ChannelHandlerContext, ChannelInboundHandlerAdapter } import io.netty.channel.{ Channel, ChannelHandlerContext, ChannelInboundHandlerAdapter }
import io.netty.channel.ChannelHandler.Sharable import io.netty.channel.ChannelHandler.Sharable
import language.postfixOps
import org.apache.pekko import org.apache.pekko
import pekko.ConfigurationException import pekko.ConfigurationException
@ -371,7 +370,7 @@ private[pekko] class ServerFSM(val controller: ActorRef, val channel: Channel)
channel.close() channel.close()
} }
when(Initial, stateTimeout = 10 seconds) { when(Initial, stateTimeout = 10.seconds) {
case Event(Hello(name, address), _) => case Event(Hello(name, address), _) =>
roleName = RoleName(name) roleName = RoleName(name)
controller ! NodeInfo(roleName, address, self) controller ! NodeInfo(roleName, address, self)

View file

@ -252,7 +252,8 @@ final class CommandHandlerWithReplyBuilderByState[Command, Event, S <: State, St
*/ */
def onCommand(predicate: Predicate[Command], handler: JFunction[Command, ReplyEffect[Event, State]]) def onCommand(predicate: Predicate[Command], handler: JFunction[Command, ReplyEffect[Event, State]])
: CommandHandlerWithReplyBuilderByState[Command, Event, S, State] = { : CommandHandlerWithReplyBuilderByState[Command, Event, S, State] = {
addCase(cmd => predicate.test(cmd), addCase(
cmd => predicate.test(cmd),
new BiFunction[S, Command, ReplyEffect[Event, State]] { new BiFunction[S, Command, ReplyEffect[Event, State]] {
override def apply(state: S, cmd: Command): ReplyEffect[Event, State] = handler(cmd) override def apply(state: S, cmd: Command): ReplyEffect[Event, State] = handler(cmd)
}) })

View file

@ -16,7 +16,6 @@ package org.apache.pekko.persistence
import java.util.concurrent.ThreadLocalRandom import java.util.concurrent.ThreadLocalRandom
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.language.postfixOps
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
@ -199,6 +198,6 @@ class AtLeastOnceDeliveryFailureSpec
} }
def expectDone() = within(numMessages.seconds) { def expectDone() = within(numMessages.seconds) {
expectMsgType[Done].ints.sorted should ===(1 to numMessages toVector) expectMsgType[Done].ints.sorted should ===((1 to numMessages).toVector)
} }
} }

View file

@ -19,7 +19,6 @@ import java.util.UUID
import scala.concurrent.Future import scala.concurrent.Future
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.language.postfixOps
import com.typesafe.config.Config import com.typesafe.config.Config
@ -146,7 +145,7 @@ class SnapshotFailureRobustnessSpec
} }
expectMsg("kablama-2") expectMsg("kablama-2")
expectMsg(RecoveryCompleted) expectMsg(RecoveryCompleted)
expectNoMessage(1 second) expectNoMessage(1.second)
} finally { } finally {
system.eventStream.unsubscribe(testActor, classOf[Logging.Error]) system.eventStream.unsubscribe(testActor, classOf[Logging.Error])
system.eventStream.publish(TestEvent.UnMute(EventFilter.error(start = "Error loading snapshot ["))) system.eventStream.publish(TestEvent.UnMute(EventFilter.error(start = "Error loading snapshot [")))

View file

@ -16,7 +16,6 @@ package org.apache.pekko.persistence.fsm
import java.io.File import java.io.File
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.language.postfixOps
import scala.reflect.ClassTag import scala.reflect.ClassTag
import scala.annotation.nowarn import scala.annotation.nowarn
@ -62,7 +61,7 @@ abstract class PersistentFSMSpec(config: Config) extends PersistenceSpec(config)
expectMsg(CurrentState(fsmRef, LookingAround, None)) expectMsg(CurrentState(fsmRef, LookingAround, None))
expectMsg(EmptyShoppingCart) expectMsg(EmptyShoppingCart)
expectMsg(Transition(fsmRef, LookingAround, Shopping, Some(1 second))) expectMsg(Transition(fsmRef, LookingAround, Shopping, Some(1.second)))
expectMsg(NonEmptyShoppingCart(List(shirt))) expectMsg(NonEmptyShoppingCart(List(shirt)))
expectMsg(NonEmptyShoppingCart(List(shirt, shoes))) expectMsg(NonEmptyShoppingCart(List(shirt, shoes)))
expectMsg(NonEmptyShoppingCart(List(shirt, shoes, coat))) expectMsg(NonEmptyShoppingCart(List(shirt, shoes, coat)))
@ -88,11 +87,11 @@ abstract class PersistentFSMSpec(config: Config) extends PersistenceSpec(config)
expectMsg(CurrentState(fsmRef, LookingAround, None)) expectMsg(CurrentState(fsmRef, LookingAround, None))
expectMsg(Transition(fsmRef, LookingAround, Shopping, Some(1 second))) expectMsg(Transition(fsmRef, LookingAround, Shopping, Some(1.second)))
val adjustedMin = 1.second - (System.nanoTime - before).nanos val adjustedMin = 1.second - (System.nanoTime - before).nanos
within(min = adjustedMin, max = remainingOrDefault) { within(min = adjustedMin, max = remainingOrDefault) {
expectMsg(Transition(fsmRef, Shopping, Inactive, Some(2 seconds))) expectMsg(Transition(fsmRef, Shopping, Inactive, Some(2.seconds)))
} }
expectTerminated(fsmRef) expectTerminated(fsmRef)
@ -118,7 +117,7 @@ abstract class PersistentFSMSpec(config: Config) extends PersistenceSpec(config)
expectMsg(CurrentState(fsmRef, LookingAround, None)) expectMsg(CurrentState(fsmRef, LookingAround, None))
expectMsg(EmptyShoppingCart) expectMsg(EmptyShoppingCart)
expectMsg(Transition(fsmRef, LookingAround, Shopping, Some(1 second))) expectMsg(Transition(fsmRef, LookingAround, Shopping, Some(1.second)))
expectMsg(NonEmptyShoppingCart(List(shirt))) expectMsg(NonEmptyShoppingCart(List(shirt)))
expectMsg(NonEmptyShoppingCart(List(shirt, shoes))) expectMsg(NonEmptyShoppingCart(List(shirt, shoes)))
@ -138,7 +137,7 @@ abstract class PersistentFSMSpec(config: Config) extends PersistenceSpec(config)
recoveredFsmRef ! GetCurrentCart recoveredFsmRef ! GetCurrentCart
recoveredFsmRef ! Leave recoveredFsmRef ! Leave
expectMsg(CurrentState(recoveredFsmRef, Shopping, Some(1 second))) expectMsg(CurrentState(recoveredFsmRef, Shopping, Some(1.second)))
expectMsg(NonEmptyShoppingCart(List(shirt, shoes))) expectMsg(NonEmptyShoppingCart(List(shirt, shoes)))
expectMsg(NonEmptyShoppingCart(List(shirt, shoes, coat))) expectMsg(NonEmptyShoppingCart(List(shirt, shoes, coat)))
@ -168,7 +167,7 @@ abstract class PersistentFSMSpec(config: Config) extends PersistenceSpec(config)
fsmRef ! Leave fsmRef ! Leave
expectMsg(CurrentState(fsmRef, LookingAround, None)) expectMsg(CurrentState(fsmRef, LookingAround, None))
expectMsg(Transition(fsmRef, LookingAround, Shopping, Some(1 second))) expectMsg(Transition(fsmRef, LookingAround, Shopping, Some(1.second)))
expectMsg(Transition(fsmRef, Shopping, Paid, None)) expectMsg(Transition(fsmRef, Shopping, Paid, None))
reportActorProbe.expectMsg(PurchaseWasMade(List(shirt, shoes, coat))) reportActorProbe.expectMsg(PurchaseWasMade(List(shirt, shoes, coat)))
expectTerminated(fsmRef) expectTerminated(fsmRef)
@ -192,7 +191,7 @@ abstract class PersistentFSMSpec(config: Config) extends PersistenceSpec(config)
fsmRef ! Leave fsmRef ! Leave
expectMsg(CurrentState(fsmRef, LookingAround, None)) expectMsg(CurrentState(fsmRef, LookingAround, None))
expectMsg(Transition(fsmRef, LookingAround, Shopping, Some(1 second))) expectMsg(Transition(fsmRef, LookingAround, Shopping, Some(1.second)))
reportActorProbe.expectMsg(ShoppingCardDiscarded) reportActorProbe.expectMsg(ShoppingCardDiscarded)
expectTerminated(fsmRef) expectTerminated(fsmRef)
} }
@ -209,9 +208,9 @@ abstract class PersistentFSMSpec(config: Config) extends PersistenceSpec(config)
fsmRef ! AddItem(shirt) fsmRef ! AddItem(shirt)
expectMsg(CurrentState(fsmRef, LookingAround, None)) expectMsg(CurrentState(fsmRef, LookingAround, None))
expectMsg(Transition(fsmRef, LookingAround, Shopping, Some(1 second))) expectMsg(Transition(fsmRef, LookingAround, Shopping, Some(1.second)))
expectNoMessage(0.6 seconds) // arbitrarily chosen delay, less than the timeout, before stopping the FSM expectNoMessage(0.6.seconds) // arbitrarily chosen delay, less than the timeout, before stopping the FSM
fsmRef ! PoisonPill fsmRef ! PoisonPill
expectTerminated(fsmRef) expectTerminated(fsmRef)
@ -221,14 +220,14 @@ abstract class PersistentFSMSpec(config: Config) extends PersistenceSpec(config)
// this isn't when it got into that state, but close enough // this isn't when it got into that state, but close enough
val before = System.nanoTime val before = System.nanoTime
expectMsg(CurrentState(recoveredFsmRef, Shopping, Some(1 second))) expectMsg(CurrentState(recoveredFsmRef, Shopping, Some(1.second)))
val adjustedMin = 1.second - (System.nanoTime - before).nanos val adjustedMin = 1.second - (System.nanoTime - before).nanos
within(min = adjustedMin, max = remainingOrDefault) { within(min = adjustedMin, max = remainingOrDefault) {
expectMsg(Transition(recoveredFsmRef, Shopping, Inactive, Some(2 seconds))) expectMsg(Transition(recoveredFsmRef, Shopping, Inactive, Some(2.seconds)))
} }
expectNoMessage(0.6 seconds) // arbitrarily chosen delay, less than the timeout, before stopping the FSM expectNoMessage(0.6.seconds) // arbitrarily chosen delay, less than the timeout, before stopping the FSM
recoveredFsmRef ! PoisonPill recoveredFsmRef ! PoisonPill
expectTerminated(recoveredFsmRef) expectTerminated(recoveredFsmRef)
@ -236,7 +235,7 @@ abstract class PersistentFSMSpec(config: Config) extends PersistenceSpec(config)
watch(recoveredFsmRef) watch(recoveredFsmRef)
recoveredFsmRef ! SubscribeTransitionCallBack(testActor) recoveredFsmRef ! SubscribeTransitionCallBack(testActor)
expectMsg(CurrentState(recoveredFsmRef, Inactive, Some(2 seconds))) expectMsg(CurrentState(recoveredFsmRef, Inactive, Some(2.seconds)))
expectTerminated(recoveredFsmRef) expectTerminated(recoveredFsmRef)
} }
@ -330,7 +329,7 @@ abstract class PersistentFSMSpec(config: Config) extends PersistenceSpec(config)
expectMsg(NonEmptyShoppingCart(List(shirt, shoes, coat))) expectMsg(NonEmptyShoppingCart(List(shirt, shoes, coat)))
expectMsg(NonEmptyShoppingCart(List(shirt, shoes, coat))) expectMsg(NonEmptyShoppingCart(List(shirt, shoes, coat)))
expectNoMessage(1 second) expectNoMessage(1.second)
fsmRef ! PoisonPill fsmRef ! PoisonPill
expectTerminated(fsmRef) expectTerminated(fsmRef)
@ -499,14 +498,14 @@ object PersistentFSMSpec {
when(LookingAround) { when(LookingAround) {
case Event(AddItem(item), _) => case Event(AddItem(item), _) =>
goto(Shopping).applying(ItemAdded(item)).forMax(1 seconds) goto(Shopping).applying(ItemAdded(item)).forMax(1.seconds)
case Event(GetCurrentCart, data) => case Event(GetCurrentCart, data) =>
stay().replying(data) stay().replying(data)
} }
when(Shopping) { when(Shopping) {
case Event(AddItem(item), _) => case Event(AddItem(item), _) =>
stay().applying(ItemAdded(item)).forMax(1 seconds) stay().applying(ItemAdded(item)).forMax(1.seconds)
case Event(Buy, _) => case Event(Buy, _) =>
// #customer-andthen-example // #customer-andthen-example
goto(Paid).applying(OrderExecuted).andThen { goto(Paid).applying(OrderExecuted).andThen {
@ -529,12 +528,12 @@ object PersistentFSMSpec {
case Event(GetCurrentCart, data) => case Event(GetCurrentCart, data) =>
stay().replying(data) stay().replying(data)
case Event(StateTimeout, _) => case Event(StateTimeout, _) =>
goto(Inactive).forMax(2 seconds) goto(Inactive).forMax(2.seconds)
} }
when(Inactive) { when(Inactive) {
case Event(AddItem(item), _) => case Event(AddItem(item), _) =>
goto(Shopping).applying(ItemAdded(item)).forMax(1 seconds) goto(Shopping).applying(ItemAdded(item)).forMax(1.seconds)
case Event(StateTimeout, _) => case Event(StateTimeout, _) =>
stop().applying(OrderDiscarded).andThen { stop().applying(OrderDiscarded).andThen {
case _ => reportActor ! ShoppingCardDiscarded case _ => reportActor ! ShoppingCardDiscarded

View file

@ -16,7 +16,6 @@ package org.apache.pekko.remote
import scala.concurrent.duration._ import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigFactory
import language.postfixOps
import testkit.MultiNodeConfig import testkit.MultiNodeConfig
import org.apache.pekko import org.apache.pekko
@ -122,7 +121,7 @@ abstract class NewRemoteActorSpec(multiNodeConfig: NewRemoteActorMultiJvmSpec)
enterBarrier("done") enterBarrier("done")
} }
"be able to shutdown system when using remote deployed actor" in within(20 seconds) { "be able to shutdown system when using remote deployed actor" in within(20.seconds) {
runOn(leader) { runOn(leader) {
val actor = system.actorOf(Props[SomeActor](), "service-hello3") val actor = system.actorOf(Props[SomeActor](), "service-hello3")
actor.isInstanceOf[RemoteActorRef] should ===(true) actor.isInstanceOf[RemoteActorRef] should ===(true)

Some files were not shown because too many files have changed in this diff Show more