format source with scalafmt, #2
This commit is contained in:
parent
0e876025e8
commit
15b163da74
980 changed files with 8776 additions and 8578 deletions
|
|
@ -130,7 +130,7 @@ import akka.annotation.InternalApi
|
||||||
// this is backward compatible with the old behaviour, hence it uses the loader used to load the test-kit
|
// this is backward compatible with the old behaviour, hence it uses the loader used to load the test-kit
|
||||||
// which is not necessarily the one used to load the tests...
|
// which is not necessarily the one used to load the tests...
|
||||||
// hence this might not include reference config related to the actually executing test
|
// hence this might not include reference config related to the actually executing test
|
||||||
//todo: might be better NOT to pass any class loader and let typesafeConfig rely on the contextClassLoader
|
// todo: might be better NOT to pass any class loader and let typesafeConfig rely on the contextClassLoader
|
||||||
// (which is usually the system class loader)
|
// (which is usually the system class loader)
|
||||||
def defaultReference: Config = ConfigFactory.defaultReference(getClass.getClassLoader)
|
def defaultReference: Config = ConfigFactory.defaultReference(getClass.getClassLoader)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -137,11 +137,11 @@ private[akka] final class BehaviorTestKitImpl[T](
|
||||||
try {
|
try {
|
||||||
context.setCurrentActorThread()
|
context.setCurrentActorThread()
|
||||||
try {
|
try {
|
||||||
//we need this to handle message adapters related messages
|
// we need this to handle message adapters related messages
|
||||||
val intercepted = BehaviorTestKitImpl.Interceptor.inteceptBehaviour(current, context)
|
val intercepted = BehaviorTestKitImpl.Interceptor.inteceptBehaviour(current, context)
|
||||||
currentUncanonical = Behavior.interpretMessage(intercepted, context, message)
|
currentUncanonical = Behavior.interpretMessage(intercepted, context, message)
|
||||||
//notice we pass current and not intercepted, this way Behaviors.same will be resolved to current which will be intercepted again on the next message
|
// notice we pass current and not intercepted, this way Behaviors.same will be resolved to current which will be intercepted again on the next message
|
||||||
//otherwise we would have risked intercepting an already intercepted behavior (or would have had to explicitly check if the current behavior is already intercepted by us)
|
// otherwise we would have risked intercepting an already intercepted behavior (or would have had to explicitly check if the current behavior is already intercepted by us)
|
||||||
current = Behavior.canonicalize(currentUncanonical, current, context)
|
current = Behavior.canonicalize(currentUncanonical, current, context)
|
||||||
} finally {
|
} finally {
|
||||||
context.clearCurrentActorThread()
|
context.clearCurrentActorThread()
|
||||||
|
|
@ -201,8 +201,8 @@ private[akka] object BehaviorTestKitImpl {
|
||||||
def inteceptBehaviour[T](behavior: Behavior[T], ctx: TypedActorContext[T]): Behavior[T] =
|
def inteceptBehaviour[T](behavior: Behavior[T], ctx: TypedActorContext[T]): Behavior[T] =
|
||||||
Behavior
|
Behavior
|
||||||
.start(Behaviors.intercept { () =>
|
.start(Behaviors.intercept { () =>
|
||||||
this.asInstanceOf[BehaviorInterceptor[Any, T]]
|
this.asInstanceOf[BehaviorInterceptor[Any, T]]
|
||||||
}(behavior), ctx.asInstanceOf[TypedActorContext[Any]])
|
}(behavior), ctx.asInstanceOf[TypedActorContext[Any]])
|
||||||
.unsafeCast[T]
|
.unsafeCast[T]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -166,12 +166,13 @@ private[akka] final class FunctionRef[-T](override val path: ActorPath, send: (T
|
||||||
val i = new BehaviorTestKitImpl[U](system, p, BehaviorImpl.ignore)
|
val i = new BehaviorTestKitImpl[U](system, p, BehaviorImpl.ignore)
|
||||||
_children += p.name -> i
|
_children += p.name -> i
|
||||||
|
|
||||||
new FunctionRef[U](p, (message, _) => {
|
new FunctionRef[U](p,
|
||||||
val m = f(message);
|
(message, _) => {
|
||||||
if (m != null) {
|
val m = f(message);
|
||||||
selfInbox.ref ! m; i.selfInbox().ref ! message
|
if (m != null) {
|
||||||
}
|
selfInbox.ref ! m; i.selfInbox().ref ! message
|
||||||
})
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
|
|
@ -134,8 +134,9 @@ private[akka] final class TestProbeImpl[M](name: String, system: ActorSystem[_])
|
||||||
val prevEnd = end
|
val prevEnd = end
|
||||||
end = start + maxDiff
|
end = start + maxDiff
|
||||||
|
|
||||||
val ret = try f
|
val ret =
|
||||||
finally end = prevEnd
|
try f
|
||||||
|
finally end = prevEnd
|
||||||
|
|
||||||
val diff = now - start
|
val diff = now - start
|
||||||
assert(min <= diff, s"block took ${diff.pretty}, should at least have been $min")
|
assert(min <= diff, s"block took ${diff.pretty}, should at least have been $min")
|
||||||
|
|
|
||||||
|
|
@ -38,8 +38,8 @@ import akka.util.Timeout
|
||||||
*
|
*
|
||||||
* @Test
|
* @Test
|
||||||
* public void testBlah() throws Exception {
|
* public void testBlah() throws Exception {
|
||||||
* // spawn actors etc using the testKit
|
* // spawn actors etc using the testKit
|
||||||
* ActorRef<Message> ref = testKit.spawn(behavior);
|
* ActorRef<Message> ref = testKit.spawn(behavior);
|
||||||
* }
|
* }
|
||||||
* }
|
* }
|
||||||
* }}}
|
* }}}
|
||||||
|
|
|
||||||
|
|
@ -254,8 +254,8 @@ final class ActorTestKit private[akka] (
|
||||||
def stop[T](ref: ActorRef[T], max: FiniteDuration = timeout.duration): Unit =
|
def stop[T](ref: ActorRef[T], max: FiniteDuration = timeout.duration): Unit =
|
||||||
try {
|
try {
|
||||||
Await.result(internalTestKitGuardian.ask { (x: ActorRef[ActorTestKitGuardian.Ack.type]) =>
|
Await.result(internalTestKitGuardian.ask { (x: ActorRef[ActorTestKitGuardian.Ack.type]) =>
|
||||||
ActorTestKitGuardian.StopActor(ref, x)
|
ActorTestKitGuardian.StopActor(ref, x)
|
||||||
}(Timeout(max), scheduler), max)
|
}(Timeout(max), scheduler), max)
|
||||||
} catch {
|
} catch {
|
||||||
case _: TimeoutException =>
|
case _: TimeoutException =>
|
||||||
assert(false, s"timeout ($max) during stop() waiting for actor [${ref.path}] to stop")
|
assert(false, s"timeout ($max) during stop() waiting for actor [${ref.path}] to stop")
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,6 @@ package object scaladsl {
|
||||||
*
|
*
|
||||||
* Uses the scaling factor from the `TestTimeFactor` in the [[TestKitSettings]]
|
* Uses the scaling factor from the `TestTimeFactor` in the [[TestKitSettings]]
|
||||||
* (in implicit scope).
|
* (in implicit scope).
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
implicit class TestDuration(val duration: FiniteDuration) extends AnyVal {
|
implicit class TestDuration(val duration: FiniteDuration) extends AnyVal {
|
||||||
def dilated(implicit settings: TestKitSettings): FiniteDuration = settings.dilated(duration)
|
def dilated(implicit settings: TestKitSettings): FiniteDuration = settings.dilated(duration)
|
||||||
|
|
|
||||||
|
|
@ -82,9 +82,9 @@ class ActorTestKitSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike wi
|
||||||
"spawn a named actor" in {
|
"spawn a named actor" in {
|
||||||
val spawnedWithName = Promise[String]()
|
val spawnedWithName = Promise[String]()
|
||||||
spawn(Behaviors.setup[AnyRef] { context =>
|
spawn(Behaviors.setup[AnyRef] { context =>
|
||||||
spawnedWithName.trySuccess(context.self.path.name)
|
spawnedWithName.trySuccess(context.self.path.name)
|
||||||
Behaviors.empty
|
Behaviors.empty
|
||||||
}, "name")
|
}, "name")
|
||||||
|
|
||||||
spawnedWithName.future.futureValue should ===("name")
|
spawnedWithName.future.futureValue should ===("name")
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -88,8 +88,8 @@ object BehaviorTestKitSpec {
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
case SpawnAdapterWithName(name) =>
|
case SpawnAdapterWithName(name) =>
|
||||||
context.spawnMessageAdapter({ (r: Reproduce) =>
|
context.spawnMessageAdapter({ (r: Reproduce) =>
|
||||||
SpawnAnonymous(r.times)
|
SpawnAnonymous(r.times)
|
||||||
}, name)
|
}, name)
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
case SpawnAndWatchUnwatch(name) =>
|
case SpawnAndWatchUnwatch(name) =>
|
||||||
val c = context.spawn(Child.initial, name)
|
val c = context.spawn(Child.initial, name)
|
||||||
|
|
@ -420,11 +420,11 @@ class BehaviorTestKitSpec extends AnyWordSpec with Matchers with LogCapturing {
|
||||||
testkit.run(ScheduleCommand("abc", 42.seconds, Effect.TimerScheduled.SingleMode, SpawnChild))
|
testkit.run(ScheduleCommand("abc", 42.seconds, Effect.TimerScheduled.SingleMode, SpawnChild))
|
||||||
testkit.expectEffectPF {
|
testkit.expectEffectPF {
|
||||||
case Effect.TimerScheduled(
|
case Effect.TimerScheduled(
|
||||||
"abc",
|
"abc",
|
||||||
SpawnChild,
|
SpawnChild,
|
||||||
finiteDuration,
|
finiteDuration,
|
||||||
Effect.TimerScheduled.SingleMode,
|
Effect.TimerScheduled.SingleMode,
|
||||||
false /*not overriding*/ ) =>
|
false /*not overriding*/ ) =>
|
||||||
finiteDuration should equal(42.seconds)
|
finiteDuration should equal(42.seconds)
|
||||||
}
|
}
|
||||||
testkit.run(IsTimerActive("abc", t.ref))
|
testkit.run(IsTimerActive("abc", t.ref))
|
||||||
|
|
@ -456,7 +456,7 @@ class BehaviorTestKitSpec extends AnyWordSpec with Matchers with LogCapturing {
|
||||||
testkit.expectEffectPF {
|
testkit.expectEffectPF {
|
||||||
case Effect.Spawned(_, "child", _) =>
|
case Effect.Spawned(_, "child", _) =>
|
||||||
}
|
}
|
||||||
//no effect since the timer's mode was single, hence removed after fired
|
// no effect since the timer's mode was single, hence removed after fired
|
||||||
send()
|
send()
|
||||||
testkit.selfInbox().hasMessages should be(false)
|
testkit.selfInbox().hasMessages should be(false)
|
||||||
}
|
}
|
||||||
|
|
@ -485,7 +485,7 @@ class BehaviorTestKitSpec extends AnyWordSpec with Matchers with LogCapturing {
|
||||||
testkit.expectEffect {
|
testkit.expectEffect {
|
||||||
Effect.Stopped("child")
|
Effect.Stopped("child")
|
||||||
}
|
}
|
||||||
//when scheduling with fixed rate the timer remains scheduled
|
// when scheduling with fixed rate the timer remains scheduled
|
||||||
send()
|
send()
|
||||||
testkit.runOne()
|
testkit.runOne()
|
||||||
testkit.expectEffectPF {
|
testkit.expectEffectPF {
|
||||||
|
|
|
||||||
|
|
@ -67,11 +67,11 @@ class TestAppenderSpec
|
||||||
"only filter events for given logger name" in {
|
"only filter events for given logger name" in {
|
||||||
val count = new AtomicInteger
|
val count = new AtomicInteger
|
||||||
LoggingTestKit
|
LoggingTestKit
|
||||||
.custom({
|
.custom {
|
||||||
case logEvent =>
|
case logEvent =>
|
||||||
count.incrementAndGet()
|
count.incrementAndGet()
|
||||||
logEvent.message == "Hello from right logger" && logEvent.loggerName == classOf[AnotherLoggerClass].getName
|
logEvent.message == "Hello from right logger" && logEvent.loggerName == classOf[AnotherLoggerClass].getName
|
||||||
})
|
}
|
||||||
.withOccurrences(2)
|
.withOccurrences(2)
|
||||||
.withLoggerName(classOf[AnotherLoggerClass].getName)
|
.withLoggerName(classOf[AnotherLoggerClass].getName)
|
||||||
.expect {
|
.expect {
|
||||||
|
|
|
||||||
|
|
@ -22,9 +22,9 @@ class TestProbeSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with
|
||||||
probe.fishForMessage(shortDuration) {
|
probe.fishForMessage(shortDuration) {
|
||||||
case _ => FishingOutcomes.complete
|
case _ => FishingOutcomes.complete
|
||||||
}
|
}
|
||||||
probe.awaitAssert({
|
probe.awaitAssert {
|
||||||
"result"
|
"result"
|
||||||
})
|
}
|
||||||
probe.expectMessageType[String]
|
probe.expectMessageType[String]
|
||||||
probe.expectMessage("whoa")
|
probe.expectMessage("whoa")
|
||||||
probe.expectNoMessage()
|
probe.expectNoMessage()
|
||||||
|
|
|
||||||
|
|
@ -27,7 +27,7 @@ import scala.util.Success
|
||||||
import scala.util.Try
|
import scala.util.Try
|
||||||
|
|
||||||
object AsyncTestingExampleSpec {
|
object AsyncTestingExampleSpec {
|
||||||
//#under-test
|
// #under-test
|
||||||
object Echo {
|
object Echo {
|
||||||
case class Ping(message: String, response: ActorRef[Pong])
|
case class Ping(message: String, response: ActorRef[Pong])
|
||||||
case class Pong(message: String)
|
case class Pong(message: String)
|
||||||
|
|
@ -38,9 +38,9 @@ object AsyncTestingExampleSpec {
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#under-test
|
// #under-test
|
||||||
|
|
||||||
//#under-test-2
|
// #under-test-2
|
||||||
case class Message(i: Int, replyTo: ActorRef[Try[Int]])
|
case class Message(i: Int, replyTo: ActorRef[Try[Int]])
|
||||||
|
|
||||||
class Producer(publisher: ActorRef[Message])(implicit scheduler: Scheduler) {
|
class Producer(publisher: ActorRef[Message])(implicit scheduler: Scheduler) {
|
||||||
|
|
@ -54,7 +54,7 @@ object AsyncTestingExampleSpec {
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
//#under-test-2
|
// #under-test-2
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -62,29 +62,29 @@ object AsyncTestingExampleSpec {
|
||||||
class AsyncTestingExampleSpec
|
class AsyncTestingExampleSpec
|
||||||
extends AnyWordSpec
|
extends AnyWordSpec
|
||||||
with BeforeAndAfterAll
|
with BeforeAndAfterAll
|
||||||
//#test-header
|
// #test-header
|
||||||
with LogCapturing
|
with LogCapturing
|
||||||
//#test-header
|
// #test-header
|
||||||
with Matchers {
|
with Matchers {
|
||||||
val testKit = ActorTestKit()
|
val testKit = ActorTestKit()
|
||||||
//#test-header
|
// #test-header
|
||||||
|
|
||||||
import AsyncTestingExampleSpec._
|
import AsyncTestingExampleSpec._
|
||||||
|
|
||||||
"A testkit" must {
|
"A testkit" must {
|
||||||
"support verifying a response" in {
|
"support verifying a response" in {
|
||||||
//#test-spawn
|
// #test-spawn
|
||||||
val pinger = testKit.spawn(Echo(), "ping")
|
val pinger = testKit.spawn(Echo(), "ping")
|
||||||
val probe = testKit.createTestProbe[Echo.Pong]()
|
val probe = testKit.createTestProbe[Echo.Pong]()
|
||||||
pinger ! Echo.Ping("hello", probe.ref)
|
pinger ! Echo.Ping("hello", probe.ref)
|
||||||
probe.expectMessage(Echo.Pong("hello"))
|
probe.expectMessage(Echo.Pong("hello"))
|
||||||
//#test-spawn
|
// #test-spawn
|
||||||
}
|
}
|
||||||
|
|
||||||
"support verifying a response - anonymous" in {
|
"support verifying a response - anonymous" in {
|
||||||
//#test-spawn-anonymous
|
// #test-spawn-anonymous
|
||||||
val pinger = testKit.spawn(Echo())
|
val pinger = testKit.spawn(Echo())
|
||||||
//#test-spawn-anonymous
|
// #test-spawn-anonymous
|
||||||
val probe = testKit.createTestProbe[Echo.Pong]()
|
val probe = testKit.createTestProbe[Echo.Pong]()
|
||||||
pinger ! Echo.Ping("hello", probe.ref)
|
pinger ! Echo.Ping("hello", probe.ref)
|
||||||
probe.expectMessage(Echo.Pong("hello"))
|
probe.expectMessage(Echo.Pong("hello"))
|
||||||
|
|
@ -93,7 +93,7 @@ class AsyncTestingExampleSpec
|
||||||
"be able to stop actors under test" in {
|
"be able to stop actors under test" in {
|
||||||
// Will fail with 'name not unique' exception if the first actor is not fully stopped
|
// Will fail with 'name not unique' exception if the first actor is not fully stopped
|
||||||
val probe = testKit.createTestProbe[Echo.Pong]()
|
val probe = testKit.createTestProbe[Echo.Pong]()
|
||||||
//#test-stop-actors
|
// #test-stop-actors
|
||||||
val pinger1 = testKit.spawn(Echo(), "pinger")
|
val pinger1 = testKit.spawn(Echo(), "pinger")
|
||||||
pinger1 ! Echo.Ping("hello", probe.ref)
|
pinger1 ! Echo.Ping("hello", probe.ref)
|
||||||
probe.expectMessage(Echo.Pong("hello"))
|
probe.expectMessage(Echo.Pong("hello"))
|
||||||
|
|
@ -104,12 +104,12 @@ class AsyncTestingExampleSpec
|
||||||
pinger2 ! Echo.Ping("hello", probe.ref)
|
pinger2 ! Echo.Ping("hello", probe.ref)
|
||||||
probe.expectMessage(Echo.Pong("hello"))
|
probe.expectMessage(Echo.Pong("hello"))
|
||||||
testKit.stop(pinger2, 10.seconds) // Custom timeout
|
testKit.stop(pinger2, 10.seconds) // Custom timeout
|
||||||
//#test-stop-actors
|
// #test-stop-actors
|
||||||
}
|
}
|
||||||
|
|
||||||
"support observing mocked behavior" in {
|
"support observing mocked behavior" in {
|
||||||
|
|
||||||
//#test-observe-mocked-behavior
|
// #test-observe-mocked-behavior
|
||||||
import testKit._
|
import testKit._
|
||||||
|
|
||||||
// simulate the happy path
|
// simulate the happy path
|
||||||
|
|
@ -130,13 +130,13 @@ class AsyncTestingExampleSpec
|
||||||
val msg = probe.expectMessageType[Message]
|
val msg = probe.expectMessageType[Message]
|
||||||
msg.i shouldBe i
|
msg.i shouldBe i
|
||||||
}
|
}
|
||||||
//#test-observe-mocked-behavior
|
// #test-observe-mocked-behavior
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//#test-shutdown
|
// #test-shutdown
|
||||||
override def afterAll(): Unit = testKit.shutdownTestKit()
|
override def afterAll(): Unit = testKit.shutdownTestKit()
|
||||||
//#test-shutdown
|
// #test-shutdown
|
||||||
//#test-header
|
//#test-header
|
||||||
}
|
}
|
||||||
//#test-header
|
//#test-header
|
||||||
|
|
|
||||||
|
|
@ -43,7 +43,7 @@ class ManualTimerExampleSpec
|
||||||
|
|
||||||
manualTime.expectNoMessageFor(10.seconds, probe)
|
manualTime.expectNoMessageFor(10.seconds, probe)
|
||||||
}
|
}
|
||||||
//#manual-scheduling-simple
|
// #manual-scheduling-simple
|
||||||
|
|
||||||
"schedule repeated ticks" in {
|
"schedule repeated ticks" in {
|
||||||
case object Tick
|
case object Tick
|
||||||
|
|
@ -113,7 +113,7 @@ class ManualTimerExampleSpec
|
||||||
probe.expectMessage(Tock(2))
|
probe.expectMessage(Tock(2))
|
||||||
}
|
}
|
||||||
|
|
||||||
//#manual-scheduling-simple
|
// #manual-scheduling-simple
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#manual-scheduling-simple
|
//#manual-scheduling-simple
|
||||||
|
|
|
||||||
|
|
@ -19,13 +19,13 @@ import org.scalatest.matchers.should.Matchers
|
||||||
import org.scalatest.wordspec.AnyWordSpec
|
import org.scalatest.wordspec.AnyWordSpec
|
||||||
|
|
||||||
object SyncTestingExampleSpec {
|
object SyncTestingExampleSpec {
|
||||||
//#child
|
// #child
|
||||||
val childActor = Behaviors.receiveMessage[String] { _ =>
|
val childActor = Behaviors.receiveMessage[String] { _ =>
|
||||||
Behaviors.same[String]
|
Behaviors.same[String]
|
||||||
}
|
}
|
||||||
//#child
|
// #child
|
||||||
|
|
||||||
//#under-test
|
// #under-test
|
||||||
object Hello {
|
object Hello {
|
||||||
sealed trait Command
|
sealed trait Command
|
||||||
case object CreateAnonymousChild extends Command
|
case object CreateAnonymousChild extends Command
|
||||||
|
|
@ -58,7 +58,7 @@ object SyncTestingExampleSpec {
|
||||||
who ! "hello"
|
who ! "hello"
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
}
|
}
|
||||||
//#under-test
|
// #under-test
|
||||||
}
|
}
|
||||||
|
|
||||||
object ConfigAware {
|
object ConfigAware {
|
||||||
|
|
@ -89,57 +89,57 @@ class SyncTestingExampleSpec extends AnyWordSpec with Matchers {
|
||||||
"Typed actor synchronous testing" must {
|
"Typed actor synchronous testing" must {
|
||||||
|
|
||||||
"record spawning" in {
|
"record spawning" in {
|
||||||
//#test-child
|
// #test-child
|
||||||
val testKit = BehaviorTestKit(Hello())
|
val testKit = BehaviorTestKit(Hello())
|
||||||
testKit.run(Hello.CreateChild("child"))
|
testKit.run(Hello.CreateChild("child"))
|
||||||
testKit.expectEffect(Spawned(childActor, "child"))
|
testKit.expectEffect(Spawned(childActor, "child"))
|
||||||
//#test-child
|
// #test-child
|
||||||
}
|
}
|
||||||
|
|
||||||
"record spawning anonymous" in {
|
"record spawning anonymous" in {
|
||||||
//#test-anonymous-child
|
// #test-anonymous-child
|
||||||
val testKit = BehaviorTestKit(Hello())
|
val testKit = BehaviorTestKit(Hello())
|
||||||
testKit.run(Hello.CreateAnonymousChild)
|
testKit.run(Hello.CreateAnonymousChild)
|
||||||
testKit.expectEffect(SpawnedAnonymous(childActor))
|
testKit.expectEffect(SpawnedAnonymous(childActor))
|
||||||
//#test-anonymous-child
|
// #test-anonymous-child
|
||||||
}
|
}
|
||||||
|
|
||||||
"record message sends" in {
|
"record message sends" in {
|
||||||
//#test-message
|
// #test-message
|
||||||
val testKit = BehaviorTestKit(Hello())
|
val testKit = BehaviorTestKit(Hello())
|
||||||
val inbox = TestInbox[String]()
|
val inbox = TestInbox[String]()
|
||||||
testKit.run(Hello.SayHello(inbox.ref))
|
testKit.run(Hello.SayHello(inbox.ref))
|
||||||
inbox.expectMessage("hello")
|
inbox.expectMessage("hello")
|
||||||
//#test-message
|
// #test-message
|
||||||
}
|
}
|
||||||
|
|
||||||
"send a message to a spawned child" in {
|
"send a message to a spawned child" in {
|
||||||
//#test-child-message
|
// #test-child-message
|
||||||
val testKit = BehaviorTestKit(Hello())
|
val testKit = BehaviorTestKit(Hello())
|
||||||
testKit.run(Hello.SayHelloToChild("child"))
|
testKit.run(Hello.SayHelloToChild("child"))
|
||||||
val childInbox = testKit.childInbox[String]("child")
|
val childInbox = testKit.childInbox[String]("child")
|
||||||
childInbox.expectMessage("hello")
|
childInbox.expectMessage("hello")
|
||||||
//#test-child-message
|
// #test-child-message
|
||||||
}
|
}
|
||||||
|
|
||||||
"send a message to an anonymous spawned child" in {
|
"send a message to an anonymous spawned child" in {
|
||||||
//#test-child-message-anonymous
|
// #test-child-message-anonymous
|
||||||
val testKit = BehaviorTestKit(Hello())
|
val testKit = BehaviorTestKit(Hello())
|
||||||
testKit.run(Hello.SayHelloToAnonymousChild)
|
testKit.run(Hello.SayHelloToAnonymousChild)
|
||||||
val child = testKit.expectEffectType[SpawnedAnonymous[String]]
|
val child = testKit.expectEffectType[SpawnedAnonymous[String]]
|
||||||
|
|
||||||
val childInbox = testKit.childInbox(child.ref)
|
val childInbox = testKit.childInbox(child.ref)
|
||||||
childInbox.expectMessage("hello stranger")
|
childInbox.expectMessage("hello stranger")
|
||||||
//#test-child-message-anonymous
|
// #test-child-message-anonymous
|
||||||
}
|
}
|
||||||
|
|
||||||
"log a message to the logger" in {
|
"log a message to the logger" in {
|
||||||
//#test-check-logging
|
// #test-check-logging
|
||||||
val testKit = BehaviorTestKit(Hello())
|
val testKit = BehaviorTestKit(Hello())
|
||||||
val inbox = TestInbox[String]("Inboxer")
|
val inbox = TestInbox[String]("Inboxer")
|
||||||
testKit.run(Hello.LogAndSayHello(inbox.ref))
|
testKit.run(Hello.LogAndSayHello(inbox.ref))
|
||||||
testKit.logEntries() shouldBe Seq(CapturedLogEvent(Level.INFO, "Saying hello to Inboxer"))
|
testKit.logEntries() shouldBe Seq(CapturedLogEvent(Level.INFO, "Saying hello to Inboxer"))
|
||||||
//#test-check-logging
|
// #test-check-logging
|
||||||
}
|
}
|
||||||
|
|
||||||
"has access to the provided config" in {
|
"has access to the provided config" in {
|
||||||
|
|
|
||||||
|
|
@ -8,24 +8,24 @@ object TestConfigExample {
|
||||||
|
|
||||||
def illustrateApplicationConfig(): Unit = {
|
def illustrateApplicationConfig(): Unit = {
|
||||||
|
|
||||||
//#default-application-conf
|
// #default-application-conf
|
||||||
import com.typesafe.config.ConfigFactory
|
import com.typesafe.config.ConfigFactory
|
||||||
|
|
||||||
ConfigFactory.load()
|
ConfigFactory.load()
|
||||||
//#default-application-conf
|
// #default-application-conf
|
||||||
|
|
||||||
//#parse-string
|
// #parse-string
|
||||||
ConfigFactory.parseString("""
|
ConfigFactory.parseString("""
|
||||||
akka.loglevel = DEBUG
|
akka.loglevel = DEBUG
|
||||||
akka.log-config-on-start = on
|
akka.log-config-on-start = on
|
||||||
""")
|
""")
|
||||||
//#parse-string
|
// #parse-string
|
||||||
|
|
||||||
//#fallback-application-conf
|
// #fallback-application-conf
|
||||||
ConfigFactory.parseString("""
|
ConfigFactory.parseString("""
|
||||||
akka.loglevel = DEBUG
|
akka.loglevel = DEBUG
|
||||||
akka.log-config-on-start = on
|
akka.log-config-on-start = on
|
||||||
""").withFallback(ConfigFactory.load())
|
""").withFallback(ConfigFactory.load())
|
||||||
//#fallback-application-conf
|
// #fallback-application-conf
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -18,11 +18,11 @@ class AkkaExceptionSpec extends AnyWordSpec with Matchers {
|
||||||
|
|
||||||
"AkkaException" must {
|
"AkkaException" must {
|
||||||
"have a AkkaException(String msg) constructor to be serialization friendly" in {
|
"have a AkkaException(String msg) constructor to be serialization friendly" in {
|
||||||
//if the call to this method completes, we know what there is at least a single constructor which has
|
// if the call to this method completes, we know what there is at least a single constructor which has
|
||||||
//the expected argument type.
|
// the expected argument type.
|
||||||
verify(classOf[AkkaException])
|
verify(classOf[AkkaException])
|
||||||
|
|
||||||
//lets also try it for the exception that triggered this bug to be discovered.
|
// lets also try it for the exception that triggered this bug to be discovered.
|
||||||
verify(classOf[ActorKilledException])
|
verify(classOf[ActorKilledException])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -169,10 +169,10 @@ class ActorLifeCycleSpec extends AkkaSpec with BeforeAndAfterEach with ImplicitS
|
||||||
Thread.sleep(50)
|
Thread.sleep(50)
|
||||||
"po"
|
"po"
|
||||||
}
|
}
|
||||||
// Here, we implicitly close over the actor instance and access the context
|
// Here, we implicitly close over the actor instance and access the context
|
||||||
// when the flatMap thunk is run. Previously, the context was nulled when the actor
|
// when the flatMap thunk is run. Previously, the context was nulled when the actor
|
||||||
// was terminated. This isn't done any more. Still, the pattern of `import context.dispatcher`
|
// was terminated. This isn't done any more. Still, the pattern of `import context.dispatcher`
|
||||||
// is discouraged as closing over `context` is unsafe in general.
|
// is discouraged as closing over `context` is unsafe in general.
|
||||||
.flatMap(x => Future { x + "ng" } /* implicitly: (this.context.dispatcher) */ )
|
.flatMap(x => Future { x + "ng" } /* implicitly: (this.context.dispatcher) */ )
|
||||||
.recover { case _: NullPointerException => "npe" }
|
.recover { case _: NullPointerException => "npe" }
|
||||||
.pipeTo(replyTo)
|
.pipeTo(replyTo)
|
||||||
|
|
|
||||||
|
|
@ -159,8 +159,8 @@ class ActorRefSpec extends AkkaSpec("""
|
||||||
|
|
||||||
EventFilter[ActorInitializationException](occurrences = 1).intercept {
|
EventFilter[ActorInitializationException](occurrences = 1).intercept {
|
||||||
intercept[akka.actor.ActorInitializationException] {
|
intercept[akka.actor.ActorInitializationException] {
|
||||||
wrap(
|
wrap(result =>
|
||||||
result => actorOf(Props(promiseIntercept(new FailingOuterActor(actorOf(Props(new InnerActor))))(result))))
|
actorOf(Props(promiseIntercept(new FailingOuterActor(actorOf(Props(new InnerActor))))(result))))
|
||||||
}
|
}
|
||||||
|
|
||||||
contextStackMustBeEmpty()
|
contextStackMustBeEmpty()
|
||||||
|
|
@ -168,8 +168,8 @@ class ActorRefSpec extends AkkaSpec("""
|
||||||
|
|
||||||
EventFilter[ActorInitializationException](occurrences = 1).intercept {
|
EventFilter[ActorInitializationException](occurrences = 1).intercept {
|
||||||
intercept[akka.actor.ActorInitializationException] {
|
intercept[akka.actor.ActorInitializationException] {
|
||||||
wrap(
|
wrap(result =>
|
||||||
result => actorOf(Props(new OuterActor(actorOf(Props(promiseIntercept(new FailingInnerActor)(result)))))))
|
actorOf(Props(new OuterActor(actorOf(Props(promiseIntercept(new FailingInnerActor)(result)))))))
|
||||||
}
|
}
|
||||||
|
|
||||||
contextStackMustBeEmpty()
|
contextStackMustBeEmpty()
|
||||||
|
|
@ -196,10 +196,9 @@ class ActorRefSpec extends AkkaSpec("""
|
||||||
|
|
||||||
EventFilter[ActorInitializationException](occurrences = 2).intercept {
|
EventFilter[ActorInitializationException](occurrences = 2).intercept {
|
||||||
intercept[akka.actor.ActorInitializationException] {
|
intercept[akka.actor.ActorInitializationException] {
|
||||||
wrap(
|
wrap(result =>
|
||||||
result =>
|
actorOf(Props(new FailingInheritingOuterActor(
|
||||||
actorOf(Props(new FailingInheritingOuterActor(
|
actorOf(Props(promiseIntercept(new FailingInheritingInnerActor)(result)))))))
|
||||||
actorOf(Props(promiseIntercept(new FailingInheritingInnerActor)(result)))))))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
contextStackMustBeEmpty()
|
contextStackMustBeEmpty()
|
||||||
|
|
@ -247,22 +246,21 @@ class ActorRefSpec extends AkkaSpec("""
|
||||||
|
|
||||||
EventFilter[ActorInitializationException](occurrences = 1).intercept {
|
EventFilter[ActorInitializationException](occurrences = 1).intercept {
|
||||||
intercept[akka.actor.ActorInitializationException] {
|
intercept[akka.actor.ActorInitializationException] {
|
||||||
wrap(
|
wrap(result =>
|
||||||
result =>
|
actorOf(
|
||||||
actorOf(
|
Props(new OuterActor(actorOf(Props(promiseIntercept { new InnerActor; new InnerActor }(result)))))))
|
||||||
Props(new OuterActor(actorOf(Props(promiseIntercept({ new InnerActor; new InnerActor })(result)))))))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
contextStackMustBeEmpty()
|
contextStackMustBeEmpty()
|
||||||
}
|
}
|
||||||
|
|
||||||
EventFilter[ActorInitializationException](occurrences = 1).intercept {
|
EventFilter[ActorInitializationException](occurrences = 1).intercept {
|
||||||
(intercept[java.lang.IllegalStateException] {
|
intercept[java.lang.IllegalStateException] {
|
||||||
wrap(result =>
|
wrap(result =>
|
||||||
actorOf(Props(new OuterActor(actorOf(Props(promiseIntercept({
|
actorOf(Props(new OuterActor(actorOf(Props(promiseIntercept {
|
||||||
throw new IllegalStateException("Ur state be b0rked")
|
throw new IllegalStateException("Ur state be b0rked")
|
||||||
})(result)))))))
|
}(result)))))))
|
||||||
}).getMessage should ===("Ur state be b0rked")
|
}.getMessage should ===("Ur state be b0rked")
|
||||||
|
|
||||||
contextStackMustBeEmpty()
|
contextStackMustBeEmpty()
|
||||||
}
|
}
|
||||||
|
|
@ -272,9 +270,9 @@ class ActorRefSpec extends AkkaSpec("""
|
||||||
EventFilter[ActorInitializationException](occurrences = 1, pattern = "/user/failingActor:").intercept {
|
EventFilter[ActorInitializationException](occurrences = 1, pattern = "/user/failingActor:").intercept {
|
||||||
intercept[java.lang.IllegalStateException] {
|
intercept[java.lang.IllegalStateException] {
|
||||||
wrap(result =>
|
wrap(result =>
|
||||||
system.actorOf(Props(promiseIntercept({
|
system.actorOf(Props(promiseIntercept {
|
||||||
throw new IllegalStateException
|
throw new IllegalStateException
|
||||||
})(result)), "failingActor"))
|
}(result)), "failingActor"))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -325,9 +323,9 @@ class ActorRefSpec extends AkkaSpec("""
|
||||||
|
|
||||||
val in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray))
|
val in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray))
|
||||||
|
|
||||||
(intercept[java.lang.IllegalStateException] {
|
intercept[java.lang.IllegalStateException] {
|
||||||
in.readObject
|
in.readObject
|
||||||
}).getMessage should ===(
|
}.getMessage should ===(
|
||||||
"Trying to deserialize a serialized ActorRef without an ActorSystem in scope." +
|
"Trying to deserialize a serialized ActorRef without an ActorSystem in scope." +
|
||||||
" Use 'akka.serialization.JavaSerializer.currentSystem.withValue(system) { ... }'")
|
" Use 'akka.serialization.JavaSerializer.currentSystem.withValue(system) { ... }'")
|
||||||
}
|
}
|
||||||
|
|
@ -422,8 +420,8 @@ class ActorRefSpec extends AkkaSpec("""
|
||||||
}
|
}
|
||||||
}))
|
}))
|
||||||
|
|
||||||
val ffive = (ref.ask(5)(timeout)).mapTo[String]
|
val ffive = ref.ask(5)(timeout).mapTo[String]
|
||||||
val fnull = (ref.ask(0)(timeout)).mapTo[String]
|
val fnull = ref.ask(0)(timeout).mapTo[String]
|
||||||
ref ! PoisonPill
|
ref ! PoisonPill
|
||||||
|
|
||||||
Await.result(ffive, timeout.duration) should ===("five")
|
Await.result(ffive, timeout.duration) should ===("five")
|
||||||
|
|
@ -459,15 +457,15 @@ class ActorRefSpec extends AkkaSpec("""
|
||||||
"be able to check for existence of children" in {
|
"be able to check for existence of children" in {
|
||||||
val parent = system.actorOf(Props(new Actor {
|
val parent = system.actorOf(Props(new Actor {
|
||||||
|
|
||||||
val child = context.actorOf(Props(new Actor {
|
val child = context.actorOf(Props(new Actor {
|
||||||
def receive = { case _ => }
|
def receive = { case _ => }
|
||||||
}), "child")
|
}), "child")
|
||||||
|
|
||||||
def receive = { case name: String => sender() ! context.child(name).isDefined }
|
def receive = { case name: String => sender() ! context.child(name).isDefined }
|
||||||
}), "parent")
|
}), "parent")
|
||||||
|
|
||||||
assert(Await.result((parent ? "child"), timeout.duration) === true)
|
assert(Await.result(parent ? "child", timeout.duration) === true)
|
||||||
assert(Await.result((parent ? "whatnot"), timeout.duration) === false)
|
assert(Await.result(parent ? "whatnot", timeout.duration) === false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -49,10 +49,11 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout {
|
||||||
val root = sysImpl.lookupRoot
|
val root = sysImpl.lookupRoot
|
||||||
|
|
||||||
def empty(path: String) =
|
def empty(path: String) =
|
||||||
new EmptyLocalActorRef(sysImpl.provider, path match {
|
new EmptyLocalActorRef(sysImpl.provider,
|
||||||
case RelativeActorPath(elems) => sysImpl.lookupRoot.path / elems
|
path match {
|
||||||
case _ => throw new RuntimeException()
|
case RelativeActorPath(elems) => sysImpl.lookupRoot.path / elems
|
||||||
}, system.eventStream)
|
case _ => throw new RuntimeException()
|
||||||
|
}, system.eventStream)
|
||||||
|
|
||||||
val idProbe = TestProbe()
|
val idProbe = TestProbe()
|
||||||
|
|
||||||
|
|
@ -128,7 +129,7 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout {
|
||||||
val a2 = system.actorOf(p, name)
|
val a2 = system.actorOf(p, name)
|
||||||
a2.path should ===(a1.path)
|
a2.path should ===(a1.path)
|
||||||
a2.path.toString should ===(a1.path.toString)
|
a2.path.toString should ===(a1.path.toString)
|
||||||
a2 should not be (a1)
|
a2 should not be a1
|
||||||
a2.toString should not be (a1.toString)
|
a2.toString should not be (a1.toString)
|
||||||
|
|
||||||
watch(a2)
|
watch(a2)
|
||||||
|
|
@ -253,12 +254,12 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout {
|
||||||
}
|
}
|
||||||
def check(looker: ActorRef): Unit = {
|
def check(looker: ActorRef): Unit = {
|
||||||
for ((l, r) <- Seq(
|
for ((l, r) <- Seq(
|
||||||
SelectString("a/b/c") -> None,
|
SelectString("a/b/c") -> None,
|
||||||
SelectString("akka://all-systems/Nobody") -> None,
|
SelectString("akka://all-systems/Nobody") -> None,
|
||||||
SelectPath(system / "hallo") -> None,
|
SelectPath(system / "hallo") -> None,
|
||||||
SelectPath(looker.path.child("hallo")) -> None, // test Java API
|
SelectPath(looker.path.child("hallo")) -> None, // test Java API
|
||||||
SelectPath(looker.path.descendant(Seq("a", "b").asJava)) -> None) // test Java API
|
SelectPath(looker.path.descendant(Seq("a", "b").asJava)) -> None) // test Java API
|
||||||
) checkOne(looker, l, r)
|
) checkOne(looker, l, r)
|
||||||
}
|
}
|
||||||
for (looker <- all) check(looker)
|
for (looker <- all) check(looker)
|
||||||
}
|
}
|
||||||
|
|
@ -289,8 +290,8 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout {
|
||||||
implicit val sender = c1
|
implicit val sender = c1
|
||||||
ActorSelection(c21, "../../*") ! GetSender(testActor)
|
ActorSelection(c21, "../../*") ! GetSender(testActor)
|
||||||
val actors = Set() ++ receiveWhile(messages = 2) {
|
val actors = Set() ++ receiveWhile(messages = 2) {
|
||||||
case `c1` => lastSender
|
case `c1` => lastSender
|
||||||
}
|
}
|
||||||
actors should ===(Set(c1, c2))
|
actors should ===(Set(c1, c2))
|
||||||
expectNoMessage()
|
expectNoMessage()
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -32,10 +32,10 @@ object ActorSystemSpec {
|
||||||
case n: Int =>
|
case n: Int =>
|
||||||
master = sender()
|
master = sender()
|
||||||
terminaters = Set() ++ (for (_ <- 1 to n) yield {
|
terminaters = Set() ++ (for (_ <- 1 to n) yield {
|
||||||
val man = context.watch(context.system.actorOf(Props[Terminater]()))
|
val man = context.watch(context.system.actorOf(Props[Terminater]()))
|
||||||
man ! "run"
|
man ! "run"
|
||||||
man
|
man
|
||||||
})
|
})
|
||||||
case Terminated(child) if terminaters contains child =>
|
case Terminated(child) if terminaters contains child =>
|
||||||
terminaters -= child
|
terminaters -= child
|
||||||
if (terminaters.isEmpty) {
|
if (terminaters.isEmpty) {
|
||||||
|
|
@ -123,14 +123,14 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend
|
||||||
|
|
||||||
"reject invalid names" in {
|
"reject invalid names" in {
|
||||||
for (n <- Seq(
|
for (n <- Seq(
|
||||||
"-hallowelt",
|
"-hallowelt",
|
||||||
"_hallowelt",
|
"_hallowelt",
|
||||||
"hallo*welt",
|
"hallo*welt",
|
||||||
"hallo@welt",
|
"hallo@welt",
|
||||||
"hallo#welt",
|
"hallo#welt",
|
||||||
"hallo$welt",
|
"hallo$welt",
|
||||||
"hallo%welt",
|
"hallo%welt",
|
||||||
"hallo/welt")) intercept[IllegalArgumentException] {
|
"hallo/welt")) intercept[IllegalArgumentException] {
|
||||||
ActorSystem(n)
|
ActorSystem(n)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -24,7 +24,7 @@ class ActorTimeoutSpec extends AkkaSpec {
|
||||||
"use implicitly supplied timeout" in {
|
"use implicitly supplied timeout" in {
|
||||||
implicit val timeout = Timeout(testTimeout)
|
implicit val timeout = Timeout(testTimeout)
|
||||||
val echo = system.actorOf(Props.empty)
|
val echo = system.actorOf(Props.empty)
|
||||||
val f = (echo ? "hallo")
|
val f = echo ? "hallo"
|
||||||
intercept[AskTimeoutException] { Await.result(f, testTimeout + leeway) }
|
intercept[AskTimeoutException] { Await.result(f, testTimeout + leeway) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -28,11 +28,11 @@ object ConsistencySpec {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
"""
|
"""
|
||||||
class CacheMisaligned(var value: Long, var padding1: Long, var padding2: Long, var padding3: Int) //Vars, no final fences
|
class CacheMisaligned(var value: Long, var padding1: Long, var padding2: Long, var padding3: Int) // Vars, no final fences
|
||||||
|
|
||||||
class ConsistencyCheckingActor extends Actor {
|
class ConsistencyCheckingActor extends Actor {
|
||||||
var left = new CacheMisaligned(42, 0, 0, 0) //var
|
var left = new CacheMisaligned(42, 0, 0, 0) // var
|
||||||
var right = new CacheMisaligned(0, 0, 0, 0) //var
|
var right = new CacheMisaligned(0, 0, 0, 0) // var
|
||||||
var lastStep = -1L
|
var lastStep = -1L
|
||||||
def receive = {
|
def receive = {
|
||||||
case step: Long =>
|
case step: Long =>
|
||||||
|
|
|
||||||
|
|
@ -79,7 +79,8 @@ class CoordinatedShutdownSpec
|
||||||
// a, b can be in any order
|
// a, b can be in any order
|
||||||
result2.toSet should ===(Set("a", "b", "c"))
|
result2.toSet should ===(Set("a", "b", "c"))
|
||||||
|
|
||||||
checkTopologicalSort(Map("b" -> phase("a"), "c" -> phase("b"), "d" -> phase("b", "c"), "e" -> phase("d"))) should ===(
|
checkTopologicalSort(Map("b" -> phase("a"), "c" -> phase("b"), "d" -> phase("b", "c"),
|
||||||
|
"e" -> phase("d"))) should ===(
|
||||||
List("a", "b", "c", "d", "e"))
|
List("a", "b", "c", "d", "e"))
|
||||||
|
|
||||||
val result3 =
|
val result3 =
|
||||||
|
|
@ -324,13 +325,14 @@ class CoordinatedShutdownSpec
|
||||||
val shouldBeCancelled = cancellables.zipWithIndex.collect {
|
val shouldBeCancelled = cancellables.zipWithIndex.collect {
|
||||||
case (c, i) if i % 2 == 0 => c
|
case (c, i) if i % 2 == 0 => c
|
||||||
}
|
}
|
||||||
val cancelFutures = for {
|
val cancelFutures =
|
||||||
_ <- cancellables
|
for {
|
||||||
c <- shouldBeCancelled
|
_ <- cancellables
|
||||||
} yield Future {
|
c <- shouldBeCancelled
|
||||||
c.cancel() shouldBe true
|
} yield Future {
|
||||||
Done
|
c.cancel() shouldBe true
|
||||||
}
|
Done
|
||||||
|
}
|
||||||
cancelFutures.foldLeft(Future.successful(Done)) {
|
cancelFutures.foldLeft(Future.successful(Done)) {
|
||||||
case (acc, fut) =>
|
case (acc, fut) =>
|
||||||
acc.flatMap(_ => fut)
|
acc.flatMap(_ => fut)
|
||||||
|
|
@ -785,7 +787,7 @@ class CoordinatedShutdownSpec
|
||||||
withSystemRunning(newSystem, cs)
|
withSystemRunning(newSystem, cs)
|
||||||
|
|
||||||
TestKit.shutdownActorSystem(newSystem)
|
TestKit.shutdownActorSystem(newSystem)
|
||||||
shutdownHooks should have size (0)
|
shutdownHooks should have size 0
|
||||||
|
|
||||||
protected def myHooksCount: Int = synchronized(shutdownHooks.size)
|
protected def myHooksCount: Int = synchronized(shutdownHooks.size)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -39,8 +39,8 @@ object DeathWatchSpec {
|
||||||
def receive = {
|
def receive = {
|
||||||
case "NKOTB" =>
|
case "NKOTB" =>
|
||||||
val currentKid = context.watch(context.actorOf(Props(new Actor {
|
val currentKid = context.watch(context.actorOf(Props(new Actor {
|
||||||
def receive = { case "NKOTB" => context.stop(self) }
|
def receive = { case "NKOTB" => context.stop(self) }
|
||||||
}), "kid"))
|
}), "kid"))
|
||||||
currentKid.forward("NKOTB")
|
currentKid.forward("NKOTB")
|
||||||
context.become {
|
context.become {
|
||||||
case Terminated(`currentKid`) =>
|
case Terminated(`currentKid`) =>
|
||||||
|
|
@ -171,7 +171,7 @@ trait DeathWatchSpec { this: AkkaSpec with ImplicitSender with DefaultTimeout =>
|
||||||
|
|
||||||
monitor2 ! "ping"
|
monitor2 ! "ping"
|
||||||
|
|
||||||
expectMsg("pong") //Needs to be here since watch and unwatch are asynchronous
|
expectMsg("pong") // Needs to be here since watch and unwatch are asynchronous
|
||||||
|
|
||||||
terminal ! PoisonPill
|
terminal ! PoisonPill
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -47,7 +47,8 @@ class DynamicAccessSpec extends AnyWordSpec with Matchers with BeforeAndAfterAll
|
||||||
}
|
}
|
||||||
|
|
||||||
"try different constructors with recoverWith" in {
|
"try different constructors with recoverWith" in {
|
||||||
instantiateWithDefaultOrStringCtor("akka.actor.TestClassWithStringConstructor").get.name shouldBe "string ctor argument"
|
instantiateWithDefaultOrStringCtor(
|
||||||
|
"akka.actor.TestClassWithStringConstructor").get.name shouldBe "string ctor argument"
|
||||||
instantiateWithDefaultOrStringCtor("akka.actor.TestClassWithDefaultConstructor").get.name shouldBe "default"
|
instantiateWithDefaultOrStringCtor("akka.actor.TestClassWithDefaultConstructor").get.name shouldBe "default"
|
||||||
instantiateWithDefaultOrStringCtor("akka.actor.foo.NonExistingClass") match {
|
instantiateWithDefaultOrStringCtor("akka.actor.foo.NonExistingClass") match {
|
||||||
case Failure(t) =>
|
case Failure(t) =>
|
||||||
|
|
|
||||||
|
|
@ -44,7 +44,7 @@ object FSMActorSpec {
|
||||||
soFar + digit match {
|
soFar + digit match {
|
||||||
case incomplete if incomplete.length < code.length =>
|
case incomplete if incomplete.length < code.length =>
|
||||||
stay().using(CodeState(incomplete, code))
|
stay().using(CodeState(incomplete, code))
|
||||||
case codeTry if (codeTry == code) => {
|
case codeTry if codeTry == code => {
|
||||||
doUnlock()
|
doUnlock()
|
||||||
goto(Open).using(CodeState("", code)).forMax(timeout)
|
goto(Open).using(CodeState("", code)).forMax(timeout)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -17,7 +17,7 @@ class HotSwapSpec extends AkkaSpec with ImplicitSender {
|
||||||
"be able to become in its constructor" in {
|
"be able to become in its constructor" in {
|
||||||
val a = system.actorOf(Props(new Becomer {
|
val a = system.actorOf(Props(new Becomer {
|
||||||
context.become { case always => sender() ! always }
|
context.become { case always => sender() ! always }
|
||||||
def receive = { case _ => sender() ! "FAILURE" }
|
def receive = { case _ => sender() ! "FAILURE" }
|
||||||
}))
|
}))
|
||||||
a ! "pigdog"
|
a ! "pigdog"
|
||||||
expectMsg("pigdog")
|
expectMsg("pigdog")
|
||||||
|
|
@ -25,7 +25,7 @@ class HotSwapSpec extends AkkaSpec with ImplicitSender {
|
||||||
|
|
||||||
"be able to become multiple times in its constructor" in {
|
"be able to become multiple times in its constructor" in {
|
||||||
val a = system.actorOf(Props(new Becomer {
|
val a = system.actorOf(Props(new Becomer {
|
||||||
for (i <- 1 to 4) context.become({ case always => sender() ! s"$i:$always" })
|
for (i <- 1 to 4) context.become { case always => sender() ! s"$i:$always" }
|
||||||
def receive = { case _ => sender() ! "FAILURE" }
|
def receive = { case _ => sender() ! "FAILURE" }
|
||||||
}))
|
}))
|
||||||
a ! "pigdog"
|
a ! "pigdog"
|
||||||
|
|
@ -35,7 +35,7 @@ class HotSwapSpec extends AkkaSpec with ImplicitSender {
|
||||||
"be able to become with stacking in its constructor" in {
|
"be able to become with stacking in its constructor" in {
|
||||||
val a = system.actorOf(Props(new Becomer {
|
val a = system.actorOf(Props(new Becomer {
|
||||||
context.become({ case always => sender() ! "pigdog:" + always; context.unbecome() }, false)
|
context.become({ case always => sender() ! "pigdog:" + always; context.unbecome() }, false)
|
||||||
def receive = { case always => sender() ! "badass:" + always }
|
def receive = { case always => sender() ! "badass:" + always }
|
||||||
}))
|
}))
|
||||||
a ! "pigdog"
|
a ! "pigdog"
|
||||||
expectMsg("pigdog:pigdog")
|
expectMsg("pigdog:pigdog")
|
||||||
|
|
@ -62,7 +62,7 @@ class HotSwapSpec extends AkkaSpec with ImplicitSender {
|
||||||
val a = system.actorOf(Props(new Actor {
|
val a = system.actorOf(Props(new Actor {
|
||||||
def receive = {
|
def receive = {
|
||||||
case "init" => sender() ! "init"
|
case "init" => sender() ! "init"
|
||||||
case "swap" => context.become({ case x: String => context.sender() ! x })
|
case "swap" => context.become { case x: String => context.sender() ! x }
|
||||||
}
|
}
|
||||||
}))
|
}))
|
||||||
|
|
||||||
|
|
@ -78,10 +78,10 @@ class HotSwapSpec extends AkkaSpec with ImplicitSender {
|
||||||
def receive = {
|
def receive = {
|
||||||
case "init" => sender() ! "init"
|
case "init" => sender() ! "init"
|
||||||
case "swap" =>
|
case "swap" =>
|
||||||
context.become({
|
context.become {
|
||||||
case "swapped" => sender() ! "swapped"
|
case "swapped" => sender() ! "swapped"
|
||||||
case "revert" => context.unbecome()
|
case "revert" => context.unbecome()
|
||||||
})
|
}
|
||||||
}
|
}
|
||||||
}))
|
}))
|
||||||
|
|
||||||
|
|
@ -103,11 +103,11 @@ class HotSwapSpec extends AkkaSpec with ImplicitSender {
|
||||||
def receive = {
|
def receive = {
|
||||||
case "state" => sender() ! "0"
|
case "state" => sender() ! "0"
|
||||||
case "swap" =>
|
case "swap" =>
|
||||||
context.become({
|
context.become {
|
||||||
case "state" => sender() ! "1"
|
case "state" => sender() ! "1"
|
||||||
case "swapped" => sender() ! "swapped"
|
case "swapped" => sender() ! "swapped"
|
||||||
case "crash" => throw new Exception("Crash (expected)!")
|
case "crash" => throw new Exception("Crash (expected)!")
|
||||||
})
|
}
|
||||||
sender() ! "swapped"
|
sender() ! "swapped"
|
||||||
}
|
}
|
||||||
}))
|
}))
|
||||||
|
|
|
||||||
|
|
@ -113,10 +113,10 @@ class LocalActorRefProviderSpec extends AkkaSpec(LocalActorRefProviderSpec.confi
|
||||||
// the fields are cleared after the Terminated message has been sent,
|
// the fields are cleared after the Terminated message has been sent,
|
||||||
// so we need to check for a reasonable time after we receive it
|
// so we need to check for a reasonable time after we receive it
|
||||||
awaitAssert({
|
awaitAssert({
|
||||||
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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -135,11 +135,11 @@ class LocalActorRefProviderSpec extends AkkaSpec(LocalActorRefProviderSpec.confi
|
||||||
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))
|
||||||
val set: Set[Any] = Set() ++ actors.map(a =>
|
val set: Set[Any] = Set() ++ actors.map(a =>
|
||||||
Await.ready(a, timeout.duration).value match {
|
Await.ready(a, timeout.duration).value match {
|
||||||
case Some(Success(_: ActorRef)) => 1
|
case Some(Success(_: ActorRef)) => 1
|
||||||
case Some(Failure(_: InvalidActorNameException)) => 2
|
case Some(Failure(_: InvalidActorNameException)) => 2
|
||||||
case x => x
|
case x => x
|
||||||
})
|
})
|
||||||
set should ===(Set[Any](1, 2))
|
set should ===(Set[Any](1, 2))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -50,7 +50,7 @@ class ProviderSelectionSpec extends AbstractSpec {
|
||||||
|
|
||||||
"create a Custom ProviderSelection and set custom provider fqcn in Settings" in {
|
"create a Custom ProviderSelection and set custom provider fqcn in Settings" in {
|
||||||
val other = "other.ActorRefProvider"
|
val other = "other.ActorRefProvider"
|
||||||
val ps = ProviderSelection.Custom(other) //checked by dynamicAccess
|
val ps = ProviderSelection.Custom(other) // checked by dynamicAccess
|
||||||
ps.fqcn shouldEqual "other.ActorRefProvider"
|
ps.fqcn shouldEqual "other.ActorRefProvider"
|
||||||
ps.hasCluster shouldBe false
|
ps.hasCluster shouldBe false
|
||||||
settingsWith(other).ProviderClass shouldEqual ps.fqcn
|
settingsWith(other).ProviderClass shouldEqual ps.fqcn
|
||||||
|
|
|
||||||
|
|
@ -240,11 +240,12 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
|
||||||
"stop continuous scheduling if the task throws exception" taggedAs TimingTest in {
|
"stop continuous scheduling if the task throws exception" taggedAs TimingTest in {
|
||||||
EventFilter[Exception]("TEST", occurrences = 1).intercept {
|
EventFilter[Exception]("TEST", occurrences = 1).intercept {
|
||||||
val count = new AtomicInteger(0)
|
val count = new AtomicInteger(0)
|
||||||
collectCancellable(scheduleAdapter.schedule(Duration.Zero, 20.millis, () => {
|
collectCancellable(scheduleAdapter.schedule(Duration.Zero, 20.millis,
|
||||||
val c = count.incrementAndGet()
|
() => {
|
||||||
testActor ! c
|
val c = count.incrementAndGet()
|
||||||
if (c == 3) throw new RuntimeException("TEST") with NoStackTrace
|
testActor ! c
|
||||||
}))
|
if (c == 3) throw new RuntimeException("TEST") with NoStackTrace
|
||||||
|
}))
|
||||||
expectMsg(1)
|
expectMsg(1)
|
||||||
expectMsg(2)
|
expectMsg(2)
|
||||||
expectMsg(3)
|
expectMsg(3)
|
||||||
|
|
@ -256,24 +257,26 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
|
||||||
// when first throws
|
// when first throws
|
||||||
EventFilter[Exception]("TEST-1", occurrences = 1).intercept {
|
EventFilter[Exception]("TEST-1", occurrences = 1).intercept {
|
||||||
val count1 = new AtomicInteger(0)
|
val count1 = new AtomicInteger(0)
|
||||||
collectCancellable(scheduleAdapter.schedule(Duration.Zero, 20.millis, () => {
|
collectCancellable(scheduleAdapter.schedule(Duration.Zero, 20.millis,
|
||||||
val c = count1.incrementAndGet()
|
() => {
|
||||||
if (c == 1)
|
val c = count1.incrementAndGet()
|
||||||
throw new IllegalStateException("TEST-1") with NoStackTrace
|
if (c == 1)
|
||||||
else
|
throw new IllegalStateException("TEST-1") with NoStackTrace
|
||||||
testActor ! c
|
else
|
||||||
}))
|
testActor ! c
|
||||||
|
}))
|
||||||
expectNoMessage(200.millis)
|
expectNoMessage(200.millis)
|
||||||
}
|
}
|
||||||
|
|
||||||
// when later
|
// when later
|
||||||
EventFilter[Exception]("TEST-3", occurrences = 1).intercept {
|
EventFilter[Exception]("TEST-3", occurrences = 1).intercept {
|
||||||
val count2 = new AtomicInteger(0)
|
val count2 = new AtomicInteger(0)
|
||||||
collectCancellable(scheduleAdapter.schedule(Duration.Zero, 20.millis, () => {
|
collectCancellable(scheduleAdapter.schedule(Duration.Zero, 20.millis,
|
||||||
val c = count2.incrementAndGet()
|
() => {
|
||||||
testActor ! c
|
val c = count2.incrementAndGet()
|
||||||
if (c == 3) throw new IllegalStateException("TEST-3") with NoStackTrace
|
testActor ! c
|
||||||
}))
|
if (c == 3) throw new IllegalStateException("TEST-3") with NoStackTrace
|
||||||
|
}))
|
||||||
expectMsg(1)
|
expectMsg(1)
|
||||||
expectMsg(2)
|
expectMsg(2)
|
||||||
expectMsg(3)
|
expectMsg(3)
|
||||||
|
|
@ -286,9 +289,10 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
|
||||||
|
|
||||||
val initialDelay = 200.millis.dilated
|
val initialDelay = 200.millis.dilated
|
||||||
val delay = 10.millis.dilated
|
val delay = 10.millis.dilated
|
||||||
val timeout = collectCancellable(scheduleAdapter.schedule(initialDelay, delay, () => {
|
val timeout = collectCancellable(scheduleAdapter.schedule(initialDelay, delay,
|
||||||
ticks.incrementAndGet()
|
() => {
|
||||||
}))
|
ticks.incrementAndGet()
|
||||||
|
}))
|
||||||
Thread.sleep(10.millis.dilated.toMillis)
|
Thread.sleep(10.millis.dilated.toMillis)
|
||||||
timeout.cancel()
|
timeout.cancel()
|
||||||
Thread.sleep((initialDelay + 100.millis.dilated).toMillis)
|
Thread.sleep((initialDelay + 100.millis.dilated).toMillis)
|
||||||
|
|
@ -301,9 +305,10 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
|
||||||
|
|
||||||
val initialDelay = 90.millis.dilated
|
val initialDelay = 90.millis.dilated
|
||||||
val delay = 500.millis.dilated
|
val delay = 500.millis.dilated
|
||||||
val timeout = collectCancellable(scheduleAdapter.schedule(initialDelay, delay, () => {
|
val timeout = collectCancellable(scheduleAdapter.schedule(initialDelay, delay,
|
||||||
ticks.incrementAndGet()
|
() => {
|
||||||
}))
|
ticks.incrementAndGet()
|
||||||
|
}))
|
||||||
Thread.sleep((initialDelay + 200.millis.dilated).toMillis)
|
Thread.sleep((initialDelay + 200.millis.dilated).toMillis)
|
||||||
timeout.cancel()
|
timeout.cancel()
|
||||||
Thread.sleep((delay + 100.millis.dilated).toMillis)
|
Thread.sleep((delay + 100.millis.dilated).toMillis)
|
||||||
|
|
@ -473,9 +478,10 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev
|
||||||
val counter = new AtomicInteger
|
val counter = new AtomicInteger
|
||||||
val terminated = Future {
|
val terminated = Future {
|
||||||
var rounds = 0
|
var rounds = 0
|
||||||
while (Try(sched.scheduleOnce(Duration.Zero, new Scheduler.TaskRunOnClose {
|
while (Try(sched.scheduleOnce(Duration.Zero,
|
||||||
override def run(): Unit = ()
|
new Scheduler.TaskRunOnClose {
|
||||||
})(localEC)).isSuccess) {
|
override def run(): Unit = ()
|
||||||
|
})(localEC)).isSuccess) {
|
||||||
Thread.sleep(1)
|
Thread.sleep(1)
|
||||||
driver.wakeUp(step)
|
driver.wakeUp(step)
|
||||||
rounds += 1
|
rounds += 1
|
||||||
|
|
@ -485,9 +491,10 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev
|
||||||
def delay = if (ThreadLocalRandom.current.nextBoolean) step * 2 else step
|
def delay = if (ThreadLocalRandom.current.nextBoolean) step * 2 else step
|
||||||
val N = 1000000
|
val N = 1000000
|
||||||
(1 to N).foreach(_ =>
|
(1 to N).foreach(_ =>
|
||||||
sched.scheduleOnce(delay, new Scheduler.TaskRunOnClose {
|
sched.scheduleOnce(delay,
|
||||||
override def run(): Unit = counter.incrementAndGet()
|
new Scheduler.TaskRunOnClose {
|
||||||
}))
|
override def run(): Unit = counter.incrementAndGet()
|
||||||
|
}))
|
||||||
sched.close()
|
sched.close()
|
||||||
Await.result(terminated, 3.seconds.dilated) should be > 10
|
Await.result(terminated, 3.seconds.dilated) should be > 10
|
||||||
awaitAssert(counter.get should ===(N))
|
awaitAssert(counter.get should ===(N))
|
||||||
|
|
@ -614,9 +621,10 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev
|
||||||
var overrun = headroom
|
var overrun = headroom
|
||||||
val cap = 1000000
|
val cap = 1000000
|
||||||
val (success, failure) = Iterator
|
val (success, failure) = Iterator
|
||||||
.continually(Try(sched.scheduleOnce(100.millis, new Scheduler.TaskRunOnClose {
|
.continually(Try(sched.scheduleOnce(100.millis,
|
||||||
override def run(): Unit = counter.incrementAndGet()
|
new Scheduler.TaskRunOnClose {
|
||||||
})))
|
override def run(): Unit = counter.incrementAndGet()
|
||||||
|
})))
|
||||||
.take(cap)
|
.take(cap)
|
||||||
.takeWhile(_.isSuccess || { overrun -= 1; overrun >= 0 })
|
.takeWhile(_.isSuccess || { overrun -= 1; overrun >= 0 })
|
||||||
.partition(_.isSuccess)
|
.partition(_.isSuccess)
|
||||||
|
|
@ -632,9 +640,10 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev
|
||||||
import system.dispatcher
|
import system.dispatcher
|
||||||
val counter = new AtomicInteger()
|
val counter = new AtomicInteger()
|
||||||
sched.scheduleOnce(10.seconds)(counter.incrementAndGet())
|
sched.scheduleOnce(10.seconds)(counter.incrementAndGet())
|
||||||
sched.scheduleOnce(10.seconds, new Scheduler.TaskRunOnClose {
|
sched.scheduleOnce(10.seconds,
|
||||||
override def run(): Unit = counter.incrementAndGet()
|
new Scheduler.TaskRunOnClose {
|
||||||
})
|
override def run(): Unit = counter.incrementAndGet()
|
||||||
|
})
|
||||||
driver.close()
|
driver.close()
|
||||||
sched.close()
|
sched.close()
|
||||||
counter.get should ===(1)
|
counter.get should ===(1)
|
||||||
|
|
|
||||||
|
|
@ -170,7 +170,7 @@ object SupervisorHierarchySpec {
|
||||||
val sizes = s / kids
|
val sizes = s / kids
|
||||||
var rest = s % kids
|
var rest = s % kids
|
||||||
val propsTemplate = Props.empty.withDispatcher("hierarchy")
|
val propsTemplate = Props.empty.withDispatcher("hierarchy")
|
||||||
(1 to kids).iterator.map { (id) =>
|
(1 to kids).iterator.map { id =>
|
||||||
val kidSize = if (rest > 0) {
|
val kidSize = if (rest > 0) {
|
||||||
rest -= 1; sizes + 1
|
rest -= 1; sizes + 1
|
||||||
} else sizes
|
} else sizes
|
||||||
|
|
@ -821,14 +821,15 @@ class SupervisorHierarchySpec extends AkkaSpec(SupervisorHierarchySpec.config) w
|
||||||
|
|
||||||
"suspend children while failing" taggedAs LongRunningTest in {
|
"suspend children while failing" taggedAs LongRunningTest in {
|
||||||
val latch = TestLatch()
|
val latch = TestLatch()
|
||||||
val slowResumer = system.actorOf(Props(new Actor {
|
val slowResumer = system.actorOf(
|
||||||
override def supervisorStrategy = OneForOneStrategy() {
|
Props(new Actor {
|
||||||
case _ => Await.ready(latch, 4.seconds.dilated); SupervisorStrategy.Resume
|
override def supervisorStrategy = OneForOneStrategy() {
|
||||||
}
|
case _ => Await.ready(latch, 4.seconds.dilated); SupervisorStrategy.Resume
|
||||||
def receive = {
|
}
|
||||||
case "spawn" => sender() ! context.actorOf(Props[Resumer]())
|
def receive = {
|
||||||
}
|
case "spawn" => sender() ! context.actorOf(Props[Resumer]())
|
||||||
}), "slowResumer")
|
}
|
||||||
|
}), "slowResumer")
|
||||||
slowResumer ! "spawn"
|
slowResumer ! "spawn"
|
||||||
val boss = expectMsgType[ActorRef]
|
val boss = expectMsgType[ActorRef]
|
||||||
boss ! "spawn"
|
boss ! "spawn"
|
||||||
|
|
@ -867,24 +868,24 @@ class SupervisorHierarchySpec extends AkkaSpec(SupervisorHierarchySpec.config) w
|
||||||
}
|
}
|
||||||
|
|
||||||
val child = context.actorOf(Props(new Actor {
|
val child = context.actorOf(Props(new Actor {
|
||||||
val ca = createAttempt.incrementAndGet()
|
val ca = createAttempt.incrementAndGet()
|
||||||
|
|
||||||
if (ca <= 6 && ca % 3 == 0)
|
if (ca <= 6 && ca % 3 == 0)
|
||||||
context.actorOf(Props(new Actor { override def receive = { case _ => } }), "workingChild")
|
context.actorOf(Props(new Actor { override def receive = { case _ => } }), "workingChild")
|
||||||
|
|
||||||
if (ca < 6) {
|
if (ca < 6) {
|
||||||
throw new IllegalArgumentException("OH NO!")
|
throw new IllegalArgumentException("OH NO!")
|
||||||
}
|
}
|
||||||
override def preStart() = {
|
override def preStart() = {
|
||||||
preStartCalled.incrementAndGet()
|
preStartCalled.incrementAndGet()
|
||||||
}
|
}
|
||||||
override def postRestart(reason: Throwable) = {
|
override def postRestart(reason: Throwable) = {
|
||||||
postRestartCalled.incrementAndGet()
|
postRestartCalled.incrementAndGet()
|
||||||
}
|
}
|
||||||
override def receive = {
|
override def receive = {
|
||||||
case m => sender() ! m
|
case m => sender() ! m
|
||||||
}
|
}
|
||||||
}), "failChild")
|
}), "failChild")
|
||||||
|
|
||||||
override def receive = {
|
override def receive = {
|
||||||
case m => child.forward(m)
|
case m => child.forward(m)
|
||||||
|
|
|
||||||
|
|
@ -197,7 +197,7 @@ class SupervisorSpec
|
||||||
|
|
||||||
def kill(pingPongActor: ActorRef) = {
|
def kill(pingPongActor: ActorRef) = {
|
||||||
val result = pingPongActor.?(DieReply)(DilatedTimeout)
|
val result = pingPongActor.?(DieReply)(DilatedTimeout)
|
||||||
expectMsg(Timeout, ExceptionMessage) //this is sent from PingPongActor's postRestart()
|
expectMsg(Timeout, ExceptionMessage) // this is sent from PingPongActor's postRestart()
|
||||||
intercept[RuntimeException] { Await.result(result, DilatedTimeout) }
|
intercept[RuntimeException] { Await.result(result, DilatedTimeout) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -218,7 +218,7 @@ class SupervisorSpec
|
||||||
}
|
}
|
||||||
|
|
||||||
"restart properly when same instance is returned" in {
|
"restart properly when same instance is returned" in {
|
||||||
val restarts = 3 //max number of restarts
|
val restarts = 3 // max number of restarts
|
||||||
lazy val childInstance = new Actor {
|
lazy val childInstance = new Actor {
|
||||||
var preRestarts = 0
|
var preRestarts = 0
|
||||||
var postRestarts = 0
|
var postRestarts = 0
|
||||||
|
|
@ -439,17 +439,17 @@ class SupervisorSpec
|
||||||
|
|
||||||
"not lose system messages when a NonFatal exception occurs when processing a system message" in {
|
"not lose system messages when a NonFatal exception occurs when processing a system message" in {
|
||||||
val parent = system.actorOf(Props(new Actor {
|
val parent = system.actorOf(Props(new Actor {
|
||||||
override val supervisorStrategy = OneForOneStrategy()({
|
override val supervisorStrategy = OneForOneStrategy() {
|
||||||
case e: IllegalStateException if e.getMessage == "OHNOES" => throw e
|
case e: IllegalStateException if e.getMessage == "OHNOES" => throw e
|
||||||
case _ => SupervisorStrategy.Restart
|
case _ => SupervisorStrategy.Restart
|
||||||
})
|
}
|
||||||
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"))
|
||||||
|
|
||||||
override def postRestart(reason: Throwable): Unit = testActor ! "parent restarted"
|
override def postRestart(reason: Throwable): Unit = testActor ! "parent restarted"
|
||||||
|
|
||||||
|
|
@ -559,7 +559,7 @@ class SupervisorSpec
|
||||||
|
|
||||||
val pingpong = child(supervisor, Props(new PingPongActor(testActor)))
|
val pingpong = child(supervisor, Props(new PingPongActor(testActor)))
|
||||||
|
|
||||||
//impossible to confirm if the restart window is infinite, so making sure maxNrOfRetries is respected correctly
|
// impossible to confirm if the restart window is infinite, so making sure maxNrOfRetries is respected correctly
|
||||||
kill(pingpong)
|
kill(pingpong)
|
||||||
kill(pingpong)
|
kill(pingpong)
|
||||||
kill(pingpong)
|
kill(pingpong)
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,7 @@ class Ticket669Spec extends AkkaSpec with BeforeAndAfterAll with ImplicitSender
|
||||||
|
|
||||||
// TODO: does this really make sense?
|
// TODO: does this really make sense?
|
||||||
override def atStartup(): Unit = {
|
override def atStartup(): Unit = {
|
||||||
Thread.interrupted() //remove interrupted status.
|
Thread.interrupted() // remove interrupted status.
|
||||||
}
|
}
|
||||||
|
|
||||||
"A supervised actor with lifecycle PERMANENT" should {
|
"A supervised actor with lifecycle PERMANENT" should {
|
||||||
|
|
|
||||||
|
|
@ -177,7 +177,7 @@ object TypedActorSpec {
|
||||||
}
|
}
|
||||||
|
|
||||||
class StackedImpl extends Stacked {
|
class StackedImpl extends Stacked {
|
||||||
override def stacked: String = "FOOBAR" //Uppercase
|
override def stacked: String = "FOOBAR" // Uppercase
|
||||||
}
|
}
|
||||||
|
|
||||||
trait LifeCycles {
|
trait LifeCycles {
|
||||||
|
|
@ -410,18 +410,18 @@ class TypedActorSpec
|
||||||
|
|
||||||
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
|
||||||
|
|
||||||
intercept[IllegalStateException] { t.failingJOptionPigdog() }.getMessage should ===("expected")
|
intercept[IllegalStateException] { t.failingJOptionPigdog() }.getMessage should ===("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
|
||||||
|
|
||||||
intercept[IllegalStateException] { t.failingOptionPigdog() }.getMessage should ===("expected")
|
intercept[IllegalStateException] { t.failingOptionPigdog() }.getMessage should ===("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
|
||||||
|
|
||||||
mustStop(t)
|
mustStop(t)
|
||||||
}
|
}
|
||||||
|
|
@ -559,14 +559,14 @@ class TypedActorSpec
|
||||||
t.crash()
|
t.crash()
|
||||||
}
|
}
|
||||||
|
|
||||||
//Sneak in a check for the Receiver override
|
// Sneak in a check for the Receiver override
|
||||||
val ref = ta.getActorRefFor(t)
|
val ref = ta.getActorRefFor(t)
|
||||||
|
|
||||||
ref.tell("pigdog", testActor)
|
ref.tell("pigdog", testActor)
|
||||||
|
|
||||||
expectMsg(timeout.duration, "dogpig")
|
expectMsg(timeout.duration, "dogpig")
|
||||||
|
|
||||||
//Done with that now
|
// Done with that now
|
||||||
|
|
||||||
ta.poisonPill(t)
|
ta.poisonPill(t)
|
||||||
latch.await(10, TimeUnit.SECONDS) should ===(true)
|
latch.await(10, TimeUnit.SECONDS) should ===(true)
|
||||||
|
|
|
||||||
|
|
@ -25,7 +25,7 @@ object UidClashTest {
|
||||||
val eventStream: EventStream)
|
val eventStream: EventStream)
|
||||||
extends MinimalActorRef {
|
extends MinimalActorRef {
|
||||||
|
|
||||||
//Ignore everything
|
// Ignore everything
|
||||||
override def isTerminated: Boolean = true
|
override def isTerminated: Boolean = true
|
||||||
override def sendSystemMessage(message: SystemMessage): Unit = ()
|
override def sendSystemMessage(message: SystemMessage): Unit = ()
|
||||||
override def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit = ()
|
override def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit = ()
|
||||||
|
|
|
||||||
|
|
@ -261,9 +261,9 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa
|
||||||
|
|
||||||
def awaitStarted(ref: ActorRef): Unit = {
|
def awaitStarted(ref: ActorRef): Unit = {
|
||||||
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
|
||||||
|
|
@ -647,7 +647,7 @@ class BalancingDispatcherModelSpec extends ActorModelSpec(BalancingDispatcherMod
|
||||||
system.stop(a)
|
system.stop(a)
|
||||||
system.stop(b)
|
system.stop(b)
|
||||||
|
|
||||||
while (!a.isTerminated && !b.isTerminated) {} //Busy wait for termination
|
while (!a.isTerminated && !b.isTerminated) {} // Busy wait for termination
|
||||||
|
|
||||||
assertRefDefaultZero(a)(registers = 1, unregisters = 1, msgsReceived = 1, msgsProcessed = 1)
|
assertRefDefaultZero(a)(registers = 1, unregisters = 1, msgsReceived = 1, msgsProcessed = 1)
|
||||||
assertRefDefaultZero(b)(registers = 1, unregisters = 1, msgsReceived = 1, msgsProcessed = 1)
|
assertRefDefaultZero(b)(registers = 1, unregisters = 1, msgsReceived = 1, msgsProcessed = 1)
|
||||||
|
|
|
||||||
|
|
@ -175,7 +175,7 @@ class DispatchersSpec extends AkkaSpec(DispatchersSpec.config) with ImplicitSend
|
||||||
}
|
}
|
||||||
|
|
||||||
"get the correct types of dispatchers" in {
|
"get the correct types of dispatchers" in {
|
||||||
//All created/obtained dispatchers are of the expected type/instance
|
// All created/obtained dispatchers are of the expected type/instance
|
||||||
assert(typesAndValidators.forall(tuple => tuple._2(allDispatchers(tuple._1))))
|
assert(typesAndValidators.forall(tuple => tuple._2(allDispatchers(tuple._1))))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -89,7 +89,7 @@ class ConfigSpec extends AkkaSpec(ConfigFactory.defaultReference(ActorSystem.fin
|
||||||
{
|
{
|
||||||
val c = config.getConfig("akka.actor.default-dispatcher")
|
val c = config.getConfig("akka.actor.default-dispatcher")
|
||||||
|
|
||||||
//General dispatcher config
|
// General dispatcher config
|
||||||
|
|
||||||
{
|
{
|
||||||
c.getString("type") should ===("Dispatcher")
|
c.getString("type") should ===("Dispatcher")
|
||||||
|
|
@ -100,13 +100,13 @@ class ConfigSpec extends AkkaSpec(ConfigFactory.defaultReference(ActorSystem.fin
|
||||||
c.getBoolean("attempt-teamwork") should ===(true)
|
c.getBoolean("attempt-teamwork") should ===(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
//Default executor config
|
// Default executor config
|
||||||
{
|
{
|
||||||
val pool = c.getConfig("default-executor")
|
val pool = c.getConfig("default-executor")
|
||||||
pool.getString("fallback") should ===("fork-join-executor")
|
pool.getString("fallback") should ===("fork-join-executor")
|
||||||
}
|
}
|
||||||
|
|
||||||
//Fork join executor config
|
// Fork join executor config
|
||||||
|
|
||||||
{
|
{
|
||||||
val pool = c.getConfig("fork-join-executor")
|
val pool = c.getConfig("fork-join-executor")
|
||||||
|
|
@ -116,7 +116,7 @@ class ConfigSpec extends AkkaSpec(ConfigFactory.defaultReference(ActorSystem.fin
|
||||||
pool.getString("task-peeking-mode") should be("FIFO")
|
pool.getString("task-peeking-mode") should be("FIFO")
|
||||||
}
|
}
|
||||||
|
|
||||||
//Thread pool executor config
|
// Thread pool executor config
|
||||||
|
|
||||||
{
|
{
|
||||||
val pool = c.getConfig("thread-pool-executor")
|
val pool = c.getConfig("thread-pool-executor")
|
||||||
|
|
|
||||||
|
|
@ -27,16 +27,16 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout {
|
||||||
val es = Executors.newCachedThreadPool()
|
val es = Executors.newCachedThreadPool()
|
||||||
try {
|
try {
|
||||||
val executor: Executor with ExecutionContext = ExecutionContext.fromExecutor(es)
|
val executor: Executor with ExecutionContext = ExecutionContext.fromExecutor(es)
|
||||||
executor should not be (null)
|
executor should not be null
|
||||||
|
|
||||||
val executorService: ExecutorService with ExecutionContext = ExecutionContext.fromExecutorService(es)
|
val executorService: ExecutorService with ExecutionContext = ExecutionContext.fromExecutorService(es)
|
||||||
executorService should not be (null)
|
executorService should not be null
|
||||||
|
|
||||||
val jExecutor: ExecutionContextExecutor = ExecutionContext.fromExecutor(es)
|
val jExecutor: ExecutionContextExecutor = ExecutionContext.fromExecutor(es)
|
||||||
jExecutor should not be (null)
|
jExecutor should not be null
|
||||||
|
|
||||||
val jExecutorService: ExecutionContextExecutorService = ExecutionContexts.fromExecutorService(es)
|
val jExecutorService: ExecutionContextExecutorService = ExecutionContexts.fromExecutorService(es)
|
||||||
jExecutorService should not be (null)
|
jExecutorService should not be null
|
||||||
} finally {
|
} finally {
|
||||||
es.shutdown
|
es.shutdown
|
||||||
}
|
}
|
||||||
|
|
@ -60,7 +60,7 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout {
|
||||||
(1 to 100).foreach { _ =>
|
(1 to 100).foreach { _ =>
|
||||||
batchable {
|
batchable {
|
||||||
if (callingThreadLock.get != 0) p.tryFailure(new IllegalStateException("Batch was executed inline!"))
|
if (callingThreadLock.get != 0) p.tryFailure(new IllegalStateException("Batch was executed inline!"))
|
||||||
else if (count.incrementAndGet == 100) p.trySuccess(()) //Done
|
else if (count.incrementAndGet == 100) p.trySuccess(()) // Done
|
||||||
else if (lock.compareAndSet(0, 1)) {
|
else if (lock.compareAndSet(0, 1)) {
|
||||||
try Thread.sleep(10)
|
try Thread.sleep(10)
|
||||||
finally lock.compareAndSet(1, 0)
|
finally lock.compareAndSet(1, 0)
|
||||||
|
|
|
||||||
|
|
@ -82,7 +82,7 @@ abstract class MailboxSpec extends AkkaSpec with BeforeAndAfterAll with BeforeAn
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//CANDIDATE FOR TESTKIT
|
// CANDIDATE FOR TESTKIT
|
||||||
def spawn[T <: AnyRef](fun: => T): Future[T] = Future(fun)(ExecutionContext.global)
|
def spawn[T <: AnyRef](fun: => T): Future[T] = Future(fun)(ExecutionContext.global)
|
||||||
|
|
||||||
def createMessageInvocation(msg: Any): Envelope = Envelope(msg, system.deadLetters, system)
|
def createMessageInvocation(msg: Any): Envelope = Envelope(msg, system.deadLetters, system)
|
||||||
|
|
@ -138,7 +138,7 @@ abstract class MailboxSpec extends AkkaSpec with BeforeAndAfterAll with BeforeAn
|
||||||
val q = factory(config)
|
val q = factory(config)
|
||||||
ensureInitialMailboxState(config, q)
|
ensureInitialMailboxState(config, q)
|
||||||
|
|
||||||
EventFilter.warning(pattern = "received dead letter", occurrences = (enqueueN - dequeueN)).intercept {
|
EventFilter.warning(pattern = "received dead letter", occurrences = enqueueN - dequeueN).intercept {
|
||||||
|
|
||||||
def createProducer(fromNum: Int, toNum: Int): Future[Vector[Envelope]] = spawn {
|
def createProducer(fromNum: Int, toNum: Int): Future[Vector[Envelope]] = spawn {
|
||||||
val messages = Vector() ++ (for (i <- fromNum to toNum) yield createMessageInvocation(i))
|
val messages = Vector() ++ (for (i <- fromNum to toNum) yield createMessageInvocation(i))
|
||||||
|
|
@ -171,13 +171,13 @@ abstract class MailboxSpec extends AkkaSpec with BeforeAndAfterAll with BeforeAn
|
||||||
val ps = producers.map(Await.result(_, remainingOrDefault))
|
val ps = producers.map(Await.result(_, remainingOrDefault))
|
||||||
val cs = consumers.map(Await.result(_, remainingOrDefault))
|
val cs = consumers.map(Await.result(_, remainingOrDefault))
|
||||||
|
|
||||||
ps.map(_.size).sum should ===(enqueueN) //Must have produced 1000 messages
|
ps.map(_.size).sum should ===(enqueueN) // Must have produced 1000 messages
|
||||||
cs.map(_.size).sum should ===(dequeueN) //Must have consumed all produced messages
|
cs.map(_.size).sum should ===(dequeueN) // Must have consumed all produced messages
|
||||||
//No message is allowed to be consumed by more than one consumer
|
// No message is allowed to be consumed by more than one consumer
|
||||||
cs.flatten.distinct.size should ===(dequeueN)
|
cs.flatten.distinct.size should ===(dequeueN)
|
||||||
//All consumed messages should have been produced
|
// All consumed messages should have been produced
|
||||||
cs.flatten.diff(ps.flatten).size should ===(0)
|
cs.flatten.diff(ps.flatten).size should ===(0)
|
||||||
//The ones that were produced and not consumed
|
// The ones that were produced and not consumed
|
||||||
ps.flatten.diff(cs.flatten).size should ===(enqueueN - dequeueN)
|
ps.flatten.diff(cs.flatten).size should ===(enqueueN - dequeueN)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -248,9 +248,9 @@ class CustomMailboxSpec extends AkkaSpec(CustomMailboxSpec.config) {
|
||||||
"support custom mailboxType" in {
|
"support custom mailboxType" in {
|
||||||
val actor = system.actorOf(Props.empty.withDispatcher("my-dispatcher"))
|
val actor = system.actorOf(Props.empty.withDispatcher("my-dispatcher"))
|
||||||
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])
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -28,17 +28,17 @@ object PriorityDispatcherSpec {
|
||||||
|
|
||||||
class Unbounded(@unused settings: ActorSystem.Settings, @unused config: Config)
|
class Unbounded(@unused settings: ActorSystem.Settings, @unused config: Config)
|
||||||
extends UnboundedPriorityMailbox(PriorityGenerator({
|
extends UnboundedPriorityMailbox(PriorityGenerator({
|
||||||
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))
|
}: Any => Int))
|
||||||
|
|
||||||
class Bounded(@unused settings: ActorSystem.Settings, @unused config: Config)
|
class Bounded(@unused settings: ActorSystem.Settings, @unused config: Config)
|
||||||
extends BoundedPriorityMailbox(PriorityGenerator({
|
extends BoundedPriorityMailbox(PriorityGenerator({
|
||||||
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)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -35,11 +35,11 @@ object StablePriorityDispatcherSpec {
|
||||||
|
|
||||||
class Bounded(@unused settings: ActorSystem.Settings, @unused config: Config)
|
class Bounded(@unused settings: ActorSystem.Settings, @unused config: Config)
|
||||||
extends BoundedStablePriorityMailbox(PriorityGenerator({
|
extends BoundedStablePriorityMailbox(PriorityGenerator({
|
||||||
case i: Int if i <= 100 => i // Small integers have high priority
|
case i: Int if i <= 100 => i // Small integers have high priority
|
||||||
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)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -308,7 +308,7 @@ class ScanningEventBusSpec extends EventBusSpec("ScanningEventBus") {
|
||||||
|
|
||||||
def createNewEventBus(): BusType = new MyScanningEventBus
|
def createNewEventBus(): BusType = new MyScanningEventBus
|
||||||
|
|
||||||
def createEvents(numberOfEvents: Int) = (0 until numberOfEvents)
|
def createEvents(numberOfEvents: Int) = 0 until numberOfEvents
|
||||||
|
|
||||||
def createSubscriber(pipeTo: ActorRef) = new Procedure[Int] { def apply(i: Int) = pipeTo ! i }
|
def createSubscriber(pipeTo: ActorRef) = new Procedure[Int] { def apply(i: Int) = pipeTo ! i }
|
||||||
|
|
||||||
|
|
@ -339,7 +339,7 @@ class LookupEventBusSpec extends EventBusSpec("LookupEventBus") {
|
||||||
|
|
||||||
def createNewEventBus(): BusType = new MyLookupEventBus
|
def createNewEventBus(): BusType = new MyLookupEventBus
|
||||||
|
|
||||||
def createEvents(numberOfEvents: Int) = (0 until numberOfEvents)
|
def createEvents(numberOfEvents: Int) = 0 until numberOfEvents
|
||||||
|
|
||||||
def createSubscriber(pipeTo: ActorRef) = new Procedure[Int] { def apply(i: Int) = pipeTo ! i }
|
def createSubscriber(pipeTo: ActorRef) = new Procedure[Int] { def apply(i: Int) = pipeTo ! i }
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -74,10 +74,10 @@ class EventStreamSpec extends AkkaSpec(EventStreamSpec.config) {
|
||||||
"An EventStream" must {
|
"An EventStream" must {
|
||||||
|
|
||||||
"manage subscriptions" in {
|
"manage subscriptions" in {
|
||||||
//#event-bus-start-unsubscriber-scala
|
// #event-bus-start-unsubscriber-scala
|
||||||
val bus = new EventStream(system, true)
|
val bus = new EventStream(system, true)
|
||||||
bus.startUnsubscriber()
|
bus.startUnsubscriber()
|
||||||
//#event-bus-start-unsubscriber-scala
|
// #event-bus-start-unsubscriber-scala
|
||||||
|
|
||||||
bus.subscribe(testActor, classOf[M])
|
bus.subscribe(testActor, classOf[M])
|
||||||
bus.publish(M(42))
|
bus.publish(M(42))
|
||||||
|
|
@ -294,8 +294,8 @@ class EventStreamSpec extends AkkaSpec(EventStreamSpec.config) {
|
||||||
val tm = new A
|
val tm = new A
|
||||||
|
|
||||||
val target = sys.actorOf(Props(new Actor {
|
val target = sys.actorOf(Props(new Actor {
|
||||||
def receive = { case in => a1.ref.forward(in) }
|
def receive = { case in => a1.ref.forward(in) }
|
||||||
}), "to-be-killed")
|
}), "to-be-killed")
|
||||||
|
|
||||||
es.subscribe(a2.ref, classOf[Any])
|
es.subscribe(a2.ref, classOf[Any])
|
||||||
es.subscribe(target, classOf[A]) should ===(true)
|
es.subscribe(target, classOf[A]) should ===(true)
|
||||||
|
|
@ -322,8 +322,8 @@ class EventStreamSpec extends AkkaSpec(EventStreamSpec.config) {
|
||||||
val probe = TestProbe()
|
val probe = TestProbe()
|
||||||
|
|
||||||
val terminated = system.actorOf(Props(new Actor {
|
val terminated = system.actorOf(Props(new Actor {
|
||||||
def receive = { case _ => }
|
def receive = { case _ => }
|
||||||
}), "to-be-killed")
|
}), "to-be-killed")
|
||||||
|
|
||||||
watch(terminated)
|
watch(terminated)
|
||||||
terminated ! PoisonPill
|
terminated ! PoisonPill
|
||||||
|
|
|
||||||
|
|
@ -96,7 +96,7 @@ object LoggerSpec {
|
||||||
sender() ! LoggerInitialized
|
sender() ! LoggerInitialized
|
||||||
case SetTarget(ref, `qualifier`) =>
|
case SetTarget(ref, `qualifier`) =>
|
||||||
target = Some(ref)
|
target = Some(ref)
|
||||||
ref ! ("OK")
|
ref ! "OK"
|
||||||
case event: LogEvent if !event.mdc.isEmpty =>
|
case event: LogEvent if !event.mdc.isEmpty =>
|
||||||
print(event)
|
print(event)
|
||||||
target.foreach { _ ! event }
|
target.foreach { _ ! event }
|
||||||
|
|
@ -173,7 +173,7 @@ class LoggerSpec extends AnyWordSpec with Matchers {
|
||||||
|
|
||||||
"log messages to standard output" in {
|
"log messages to standard output" in {
|
||||||
val out = createSystemAndLogToBuffer("defaultLogger", defaultConfig, true)
|
val out = createSystemAndLogToBuffer("defaultLogger", defaultConfig, true)
|
||||||
out.size should be > (0)
|
out.size should be > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
"drain logger queue on system.terminate" in {
|
"drain logger queue on system.terminate" in {
|
||||||
|
|
|
||||||
|
|
@ -68,9 +68,10 @@ class LoggingReceiveSpec extends AnyWordSpec with BeforeAndAfterAll {
|
||||||
system.eventStream.subscribe(testActor, classOf[UnhandledMessage])
|
system.eventStream.subscribe(testActor, classOf[UnhandledMessage])
|
||||||
val a = system.actorOf(Props(new Actor {
|
val a = system.actorOf(Props(new Actor {
|
||||||
def receive =
|
def receive =
|
||||||
new LoggingReceive(Some("funky"), {
|
new LoggingReceive(Some("funky"),
|
||||||
case null =>
|
{
|
||||||
})
|
case null =>
|
||||||
|
})
|
||||||
}))
|
}))
|
||||||
a ! "hallo"
|
a ! "hallo"
|
||||||
expectMsg(
|
expectMsg(
|
||||||
|
|
|
||||||
|
|
@ -58,9 +58,9 @@ class JavaLoggerSpec extends AkkaSpec(JavaLoggerSpec.config) {
|
||||||
|
|
||||||
val record = expectMsgType[logging.LogRecord]
|
val record = expectMsgType[logging.LogRecord]
|
||||||
|
|
||||||
record should not be (null)
|
record should not be null
|
||||||
record.getMillis should not be (0)
|
record.getMillis should not be 0
|
||||||
record.getThreadID should not be (0)
|
record.getThreadID should not be 0
|
||||||
record.getLevel should ===(logging.Level.SEVERE)
|
record.getLevel should ===(logging.Level.SEVERE)
|
||||||
record.getMessage should ===("Simulated error")
|
record.getMessage should ===("Simulated error")
|
||||||
record.getThrown.getClass should ===(classOf[JavaLoggerSpec.SimulatedExc])
|
record.getThrown.getClass should ===(classOf[JavaLoggerSpec.SimulatedExc])
|
||||||
|
|
@ -73,9 +73,9 @@ class JavaLoggerSpec extends AkkaSpec(JavaLoggerSpec.config) {
|
||||||
|
|
||||||
val record = expectMsgType[logging.LogRecord]
|
val record = expectMsgType[logging.LogRecord]
|
||||||
|
|
||||||
record should not be (null)
|
record should not be null
|
||||||
record.getMillis should not be (0)
|
record.getMillis should not be 0
|
||||||
record.getThreadID should not be (0)
|
record.getThreadID should not be 0
|
||||||
record.getLevel should ===(logging.Level.INFO)
|
record.getLevel should ===(logging.Level.INFO)
|
||||||
record.getMessage should ===("3 is the magic number")
|
record.getMessage should ===("3 is the magic number")
|
||||||
record.getThrown should ===(null)
|
record.getThrown should ===(null)
|
||||||
|
|
|
||||||
|
|
@ -380,32 +380,33 @@ class TcpConnectionSpec extends AkkaSpec("""
|
||||||
override implicit lazy val system: ActorSystem = ActorSystem("respectPullModeTest", config)
|
override implicit lazy val system: ActorSystem = ActorSystem("respectPullModeTest", config)
|
||||||
|
|
||||||
try run {
|
try run {
|
||||||
val maxBufferSize = 1 * 1024
|
val maxBufferSize = 1 * 1024
|
||||||
val ts = "t" * maxBufferSize
|
val ts = "t" * maxBufferSize
|
||||||
val us = "u" * (maxBufferSize / 2)
|
val us = "u" * (maxBufferSize / 2)
|
||||||
|
|
||||||
// send a batch that is bigger than the default buffer to make sure we don't recurse and
|
// send a batch that is bigger than the default buffer to make sure we don't recurse and
|
||||||
// send more than one Received messages
|
// send more than one Received messages
|
||||||
serverSideChannel.write(ByteBuffer.wrap((ts ++ us).getBytes("ASCII")))
|
serverSideChannel.write(ByteBuffer.wrap((ts ++ us).getBytes("ASCII")))
|
||||||
connectionHandler.expectNoMessage(100.millis)
|
connectionHandler.expectNoMessage(100.millis)
|
||||||
|
|
||||||
connectionActor ! ResumeReading
|
connectionActor ! ResumeReading
|
||||||
connectionHandler.expectMsgType[Received].data.decodeString("ASCII") should ===(ts)
|
connectionHandler.expectMsgType[Received].data.decodeString("ASCII") should ===(ts)
|
||||||
|
|
||||||
connectionHandler.expectNoMessage(100.millis)
|
connectionHandler.expectNoMessage(100.millis)
|
||||||
|
|
||||||
connectionActor ! ResumeReading
|
connectionActor ! ResumeReading
|
||||||
connectionHandler.expectMsgType[Received].data.decodeString("ASCII") should ===(us)
|
connectionHandler.expectMsgType[Received].data.decodeString("ASCII") should ===(us)
|
||||||
|
|
||||||
connectionHandler.expectNoMessage(100.millis)
|
connectionHandler.expectNoMessage(100.millis)
|
||||||
|
|
||||||
val vs = "v" * (maxBufferSize / 2)
|
val vs = "v" * (maxBufferSize / 2)
|
||||||
serverSideChannel.write(ByteBuffer.wrap(vs.getBytes("ASCII")))
|
serverSideChannel.write(ByteBuffer.wrap(vs.getBytes("ASCII")))
|
||||||
|
|
||||||
connectionActor ! ResumeReading
|
connectionActor ! ResumeReading
|
||||||
|
|
||||||
connectionHandler.expectMsgType[Received].data.decodeString("ASCII") should ===(vs)
|
connectionHandler.expectMsgType[Received].data.decodeString("ASCII") should ===(vs)
|
||||||
} finally shutdown(system)
|
}
|
||||||
|
finally shutdown(system)
|
||||||
}
|
}
|
||||||
|
|
||||||
"close the connection and reply with `Closed` upon reception of a `Close` command" in
|
"close the connection and reply with `Closed` upon reception of a `Close` command" in
|
||||||
|
|
@ -653,7 +654,7 @@ class TcpConnectionSpec extends AkkaSpec("""
|
||||||
override lazy val connectionActor =
|
override lazy val connectionActor =
|
||||||
createConnectionActor(serverAddress = UnboundAddress, timeout = Option(100.millis))
|
createConnectionActor(serverAddress = UnboundAddress, timeout = Option(100.millis))
|
||||||
run {
|
run {
|
||||||
connectionActor.toString should not be ("")
|
connectionActor.toString should not be ""
|
||||||
userHandler.expectMsg(CommandFailed(Connect(UnboundAddress, timeout = Option(100.millis))))
|
userHandler.expectMsg(CommandFailed(Connect(UnboundAddress, timeout = Option(100.millis))))
|
||||||
watch(connectionActor)
|
watch(connectionActor)
|
||||||
expectTerminated(connectionActor)
|
expectTerminated(connectionActor)
|
||||||
|
|
@ -982,7 +983,7 @@ class TcpConnectionSpec extends AkkaSpec("""
|
||||||
override def run(body: => Unit): Unit = super.run {
|
override def run(body: => Unit): Unit = super.run {
|
||||||
try {
|
try {
|
||||||
serverSideChannel.configureBlocking(false)
|
serverSideChannel.configureBlocking(false)
|
||||||
serverSideChannel should not be (null)
|
serverSideChannel should not be null
|
||||||
|
|
||||||
interestCallReceiver.expectMsg(OP_CONNECT)
|
interestCallReceiver.expectMsg(OP_CONNECT)
|
||||||
selector.send(connectionActor, ChannelConnectable)
|
selector.send(connectionActor, ChannelConnectable)
|
||||||
|
|
|
||||||
|
|
@ -50,7 +50,7 @@ trait TcpIntegrationSpecSupport { this: AkkaSpec =>
|
||||||
connectCommander.sender() ! Register(clientHandler.ref)
|
connectCommander.sender() ! Register(clientHandler.ref)
|
||||||
|
|
||||||
bindHandler.expectMsgType[Connected] match {
|
bindHandler.expectMsgType[Connected] match {
|
||||||
case Connected(`localAddress`, `endpoint`) => //ok
|
case Connected(`localAddress`, `endpoint`) => // ok
|
||||||
case other => fail(s"No match: ${other}")
|
case other => fail(s"No match: ${other}")
|
||||||
}
|
}
|
||||||
val serverHandler = TestProbe()
|
val serverHandler = TestProbe()
|
||||||
|
|
|
||||||
|
|
@ -116,7 +116,7 @@ class AsyncDnsResolverIntegrationSpec
|
||||||
val answer = (IO(Dns) ? DnsProtocol.Resolve(name)).mapTo[DnsProtocol.Resolved].futureValue
|
val answer = (IO(Dns) ? DnsProtocol.Resolve(name)).mapTo[DnsProtocol.Resolved].futureValue
|
||||||
answer.name shouldEqual name
|
answer.name shouldEqual name
|
||||||
answer.records.collect { case r: CNameRecord => r.canonicalName }.toSet shouldEqual Set("a-single.bar.example")
|
answer.records.collect { case r: CNameRecord => r.canonicalName }.toSet shouldEqual Set("a-single.bar.example")
|
||||||
answer.records.collect { case r: ARecord => r.ip }.toSet shouldEqual Set(InetAddress.getByName("192.168.2.20"))
|
answer.records.collect { case r: ARecord => r.ip }.toSet shouldEqual Set(InetAddress.getByName("192.168.2.20"))
|
||||||
}
|
}
|
||||||
|
|
||||||
"resolve internal CNAME record" in {
|
"resolve internal CNAME record" in {
|
||||||
|
|
@ -124,7 +124,7 @@ class AsyncDnsResolverIntegrationSpec
|
||||||
val answer = resolve(name)
|
val answer = resolve(name)
|
||||||
answer.name shouldEqual name
|
answer.name shouldEqual name
|
||||||
answer.records.collect { case r: CNameRecord => r.canonicalName }.toSet shouldEqual Set("a-double.foo.test")
|
answer.records.collect { case r: CNameRecord => r.canonicalName }.toSet shouldEqual Set("a-double.foo.test")
|
||||||
answer.records.collect { case r: ARecord => r.ip }.toSet shouldEqual Set(
|
answer.records.collect { case r: ARecord => r.ip }.toSet shouldEqual Set(
|
||||||
InetAddress.getByName("192.168.1.21"),
|
InetAddress.getByName("192.168.1.21"),
|
||||||
InetAddress.getByName("192.168.1.22"))
|
InetAddress.getByName("192.168.1.22"))
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -227,8 +227,9 @@ class AsyncDnsResolverSpec extends AkkaSpec("""
|
||||||
|
|
||||||
def resolver(clients: List[ActorRef], config: Config): ActorRef = {
|
def resolver(clients: List[ActorRef], config: Config): ActorRef = {
|
||||||
val settings = new DnsSettings(system.asInstanceOf[ExtendedActorSystem], config)
|
val settings = new DnsSettings(system.asInstanceOf[ExtendedActorSystem], config)
|
||||||
system.actorOf(Props(new AsyncDnsResolver(settings, new SimpleDnsCache(), (_, _) => {
|
system.actorOf(Props(new AsyncDnsResolver(settings, new SimpleDnsCache(),
|
||||||
clients
|
(_, _) => {
|
||||||
})))
|
clients
|
||||||
|
})))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -133,8 +133,8 @@ class AskSpec extends AkkaSpec("""
|
||||||
system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter])
|
system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter])
|
||||||
|
|
||||||
val echo = system.actorOf(Props(new Actor {
|
val echo = system.actorOf(Props(new Actor {
|
||||||
def receive = { case x => context.actorSelection(sender().path) ! x }
|
def receive = { case x => context.actorSelection(sender().path) ! x }
|
||||||
}), "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")
|
||||||
|
|
@ -164,13 +164,13 @@ class AskSpec extends AkkaSpec("""
|
||||||
system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter])
|
system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter])
|
||||||
|
|
||||||
val echo = system.actorOf(Props(new Actor {
|
val echo = system.actorOf(Props(new Actor {
|
||||||
def receive = {
|
def receive = {
|
||||||
case x =>
|
case x =>
|
||||||
val name = sender().path.name
|
val name = sender().path.name
|
||||||
val parent = sender().path.parent
|
val parent = sender().path.parent
|
||||||
context.actorSelection(parent / ".." / "temp" / name) ! x
|
context.actorSelection(parent / ".." / "temp" / name) ! x
|
||||||
}
|
}
|
||||||
}), "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")
|
||||||
|
|
@ -185,12 +185,12 @@ class AskSpec extends AkkaSpec("""
|
||||||
system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter])
|
system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter])
|
||||||
|
|
||||||
val echo = system.actorOf(Props(new Actor {
|
val echo = system.actorOf(Props(new Actor {
|
||||||
def receive = {
|
def receive = {
|
||||||
case x =>
|
case x =>
|
||||||
val parent = sender().path.parent
|
val parent = sender().path.parent
|
||||||
context.actorSelection(parent / "missing") ! x
|
context.actorSelection(parent / "missing") ! x
|
||||||
}
|
}
|
||||||
}), "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")
|
||||||
|
|
@ -204,11 +204,11 @@ class AskSpec extends AkkaSpec("""
|
||||||
system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter])
|
system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter])
|
||||||
|
|
||||||
val echo = system.actorOf(Props(new Actor {
|
val echo = system.actorOf(Props(new Actor {
|
||||||
def receive = {
|
def receive = {
|
||||||
case x =>
|
case x =>
|
||||||
context.actorSelection(sender().path / "missing") ! x
|
context.actorSelection(sender().path / "missing") ! x
|
||||||
}
|
}
|
||||||
}), "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))
|
||||||
|
|
@ -242,10 +242,10 @@ class AskSpec extends AkkaSpec("""
|
||||||
val p = TestProbe()
|
val p = TestProbe()
|
||||||
|
|
||||||
val act = system.actorOf(Props(new Actor {
|
val act = system.actorOf(Props(new Actor {
|
||||||
def receive = {
|
def receive = {
|
||||||
case msg => p.ref ! sender() -> msg
|
case msg => p.ref ! sender() -> msg
|
||||||
}
|
}
|
||||||
}), "myName")
|
}), "myName")
|
||||||
|
|
||||||
(act ? "ask").mapTo[String]
|
(act ? "ask").mapTo[String]
|
||||||
val (promiseActorRef, "ask") = p.expectMsgType[(ActorRef, String)]
|
val (promiseActorRef, "ask") = p.expectMsgType[(ActorRef, String)]
|
||||||
|
|
|
||||||
|
|
@ -273,9 +273,9 @@ class BackoffOnRestartSupervisorSpec extends AkkaSpec("""
|
||||||
|
|
||||||
// note that the message could be lost (dead letters) because ended up with previous crashed child
|
// note that the message could be lost (dead letters) because ended up with previous crashed child
|
||||||
probe.awaitAssert({
|
probe.awaitAssert({
|
||||||
supervisor ! "PING"
|
supervisor ! "PING"
|
||||||
probe.expectMsg("PING")
|
probe.expectMsg("PING")
|
||||||
}, 1.second)
|
}, 1.second)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -253,7 +253,7 @@ class BackoffSupervisorSpec extends AkkaSpec with ImplicitSender with Eventually
|
||||||
}
|
}
|
||||||
|
|
||||||
EventFilter.warning(pattern = ".*boom.*", occurrences = 1).intercept {
|
EventFilter.warning(pattern = ".*boom.*", occurrences = 1).intercept {
|
||||||
supervisor ! "boom" //this will be sent to deadLetters
|
supervisor ! "boom" // this will be sent to deadLetters
|
||||||
expectNoMessage(500.milliseconds)
|
expectNoMessage(500.milliseconds)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -24,9 +24,9 @@ class CircuitBreakerMTSpec extends AkkaSpec {
|
||||||
// returns true if the breaker is open
|
// returns true if the breaker is open
|
||||||
def failingCall(): Boolean =
|
def failingCall(): Boolean =
|
||||||
Await.result(breaker.withCircuitBreaker(Future.failed(new RuntimeException("FAIL"))).recover {
|
Await.result(breaker.withCircuitBreaker(Future.failed(new RuntimeException("FAIL"))).recover {
|
||||||
case _: CircuitBreakerOpenException => true
|
case _: CircuitBreakerOpenException => true
|
||||||
case _ => false
|
case _ => false
|
||||||
}, remainingOrDefault)
|
}, remainingOrDefault)
|
||||||
|
|
||||||
// fire some failing calls
|
// fire some failing calls
|
||||||
(1 to (maxFailures + 1)).foreach { _ =>
|
(1 to (maxFailures + 1)).foreach { _ =>
|
||||||
|
|
|
||||||
|
|
@ -349,7 +349,7 @@ class CircuitBreakerSpec extends AkkaSpec("""
|
||||||
breaker().currentFailureCount should ===(0)
|
breaker().currentFailureCount should ===(0)
|
||||||
intercept[TestException] {
|
intercept[TestException] {
|
||||||
val ct = Thread.currentThread() // Ensure that the thunk is executed in the tests thread
|
val ct = Thread.currentThread() // Ensure that the thunk is executed in the tests thread
|
||||||
breaker().withSyncCircuitBreaker({ if (Thread.currentThread() eq ct) throwException else "fail" })
|
breaker().withSyncCircuitBreaker { if (Thread.currentThread() eq ct) throwException else "fail" }
|
||||||
}
|
}
|
||||||
breaker().currentFailureCount should ===(1)
|
breaker().currentFailureCount should ===(1)
|
||||||
breaker().withSyncCircuitBreaker(sayHi)
|
breaker().withSyncCircuitBreaker(sayHi)
|
||||||
|
|
@ -362,7 +362,7 @@ class CircuitBreakerSpec extends AkkaSpec("""
|
||||||
breaker().currentFailureCount should ===(0)
|
breaker().currentFailureCount should ===(0)
|
||||||
intercept[TestException] {
|
intercept[TestException] {
|
||||||
val ct = Thread.currentThread() // Ensure that the thunk is executed in the tests thread
|
val ct = Thread.currentThread() // Ensure that the thunk is executed in the tests thread
|
||||||
breaker().withSyncCircuitBreaker({ if (Thread.currentThread() eq ct) throwException else "fail" })
|
breaker().withSyncCircuitBreaker { if (Thread.currentThread() eq ct) throwException else "fail" }
|
||||||
}
|
}
|
||||||
breaker().currentFailureCount should ===(1)
|
breaker().currentFailureCount should ===(1)
|
||||||
|
|
||||||
|
|
@ -385,7 +385,7 @@ class CircuitBreakerSpec extends AkkaSpec("""
|
||||||
breaker().currentFailureCount should ===(0)
|
breaker().currentFailureCount should ===(0)
|
||||||
intercept[TestException] {
|
intercept[TestException] {
|
||||||
val ct = Thread.currentThread() // Ensure that the thunk is executed in the tests thread
|
val ct = Thread.currentThread() // Ensure that the thunk is executed in the tests thread
|
||||||
breaker().withSyncCircuitBreaker({ if (Thread.currentThread() eq ct) throwException else "fail" })
|
breaker().withSyncCircuitBreaker { if (Thread.currentThread() eq ct) throwException else "fail" }
|
||||||
}
|
}
|
||||||
breaker().currentFailureCount should ===(1)
|
breaker().currentFailureCount should ===(1)
|
||||||
breaker().succeed()
|
breaker().succeed()
|
||||||
|
|
|
||||||
|
|
@ -29,10 +29,10 @@ class RetrySpec extends AkkaSpec with RetrySupport {
|
||||||
@volatile var counter = 0
|
@volatile var counter = 0
|
||||||
val retried = retry(
|
val retried = retry(
|
||||||
() =>
|
() =>
|
||||||
Future.successful({
|
Future.successful {
|
||||||
counter += 1
|
counter += 1
|
||||||
counter
|
counter
|
||||||
}),
|
},
|
||||||
5,
|
5,
|
||||||
1 second)
|
1 second)
|
||||||
|
|
||||||
|
|
@ -94,10 +94,11 @@ class RetrySpec extends AkkaSpec with RetrySupport {
|
||||||
} else Future.successful(5)
|
} else Future.successful(5)
|
||||||
}
|
}
|
||||||
|
|
||||||
val retried = retry(() => attempt(), 5, attempted => {
|
val retried = retry(() => attempt(), 5,
|
||||||
attemptedCount = attempted
|
attempted => {
|
||||||
Some(100.milliseconds * attempted)
|
attemptedCount = 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
|
||||||
|
|
|
||||||
|
|
@ -37,10 +37,10 @@ class ExplicitAskSpec extends AkkaSpec {
|
||||||
implicit val timeout: Timeout = Timeout(5.seconds)
|
implicit val timeout: Timeout = Timeout(5.seconds)
|
||||||
|
|
||||||
val target = system.actorOf(Props(new Actor {
|
val target = system.actorOf(Props(new Actor {
|
||||||
def receive = {
|
def receive = {
|
||||||
case Request(respondTo) => respondTo ! Response(self)
|
case Request(respondTo) => respondTo ! Response(self)
|
||||||
}
|
}
|
||||||
}), "select-echo")
|
}), "select-echo")
|
||||||
|
|
||||||
val selection = system.actorSelection("/user/select-echo")
|
val selection = system.actorSelection("/user/select-echo")
|
||||||
val f = selection ? (respondTo => Request(respondTo))
|
val f = selection ? (respondTo => Request(respondTo))
|
||||||
|
|
|
||||||
|
|
@ -232,12 +232,12 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT
|
||||||
val resizer = DefaultOptimalSizeExploringResizer()
|
val resizer = DefaultOptimalSizeExploringResizer()
|
||||||
val router = TestRouter(routees(2))
|
val router = TestRouter(routees(2))
|
||||||
val msgs1 = router.sendToAll(await = true)
|
val msgs1 = router.sendToAll(await = true)
|
||||||
val msgs2 = router.sendToAll(await = false) //make sure the routees are still busy after the first batch of messages get processed.
|
val msgs2 = router.sendToAll(await = false) // make sure the routees are still busy after the first batch of messages get processed.
|
||||||
|
|
||||||
val before = System.nanoTime()
|
val before = System.nanoTime()
|
||||||
resizer.reportMessageCount(router.routees, router.msgs.size) //updates the records
|
resizer.reportMessageCount(router.routees, router.msgs.size) // updates the records
|
||||||
|
|
||||||
msgs1.foreach(_.second.open()) //process two messages
|
msgs1.foreach(_.second.open()) // process two messages
|
||||||
|
|
||||||
// make sure some time passes in-between
|
// make sure some time passes in-between
|
||||||
Thread.sleep(300)
|
Thread.sleep(300)
|
||||||
|
|
@ -263,12 +263,12 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT
|
||||||
|
|
||||||
val router = TestRouter(routees(2))
|
val router = TestRouter(routees(2))
|
||||||
val msgs1 = router.sendToAll(await = true)
|
val msgs1 = router.sendToAll(await = true)
|
||||||
val msgs2 = router.sendToAll(await = false) //make sure the routees are still busy after the first batch of messages get processed.
|
val msgs2 = router.sendToAll(await = false) // make sure the routees are still busy after the first batch of messages get processed.
|
||||||
|
|
||||||
val before = System.nanoTime()
|
val before = System.nanoTime()
|
||||||
resizer.reportMessageCount(router.routees, router.msgs.size) //updates the records
|
resizer.reportMessageCount(router.routees, router.msgs.size) // updates the records
|
||||||
|
|
||||||
msgs1.foreach(_.second.open()) //process two messages
|
msgs1.foreach(_.second.open()) // process two messages
|
||||||
|
|
||||||
// make sure some time passes in-between
|
// make sure some time passes in-between
|
||||||
Thread.sleep(300)
|
Thread.sleep(300)
|
||||||
|
|
|
||||||
|
|
@ -23,14 +23,14 @@ class RandomSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
|
||||||
val stopLatch = new TestLatch(7)
|
val stopLatch = new TestLatch(7)
|
||||||
|
|
||||||
val actor = system.actorOf(RandomPool(7).props(Props(new Actor {
|
val actor = system.actorOf(RandomPool(7).props(Props(new Actor {
|
||||||
def receive = {
|
def receive = {
|
||||||
case "hello" => sender() ! "world"
|
case "hello" => sender() ! "world"
|
||||||
}
|
}
|
||||||
|
|
||||||
override def postStop(): Unit = {
|
override def postStop(): Unit = {
|
||||||
stopLatch.countDown()
|
stopLatch.countDown()
|
||||||
}
|
}
|
||||||
})), "random-shutdown")
|
})), "random-shutdown")
|
||||||
|
|
||||||
actor ! "hello"
|
actor ! "hello"
|
||||||
actor ! "hello"
|
actor ! "hello"
|
||||||
|
|
@ -58,12 +58,12 @@ class RandomSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
|
||||||
}
|
}
|
||||||
|
|
||||||
val actor = system.actorOf(RandomPool(connectionCount).props(routeeProps = Props(new Actor {
|
val actor = system.actorOf(RandomPool(connectionCount).props(routeeProps = Props(new Actor {
|
||||||
lazy val id = counter.getAndIncrement()
|
lazy val id = counter.getAndIncrement()
|
||||||
def receive = {
|
def receive = {
|
||||||
case "hit" => sender() ! id
|
case "hit" => sender() ! id
|
||||||
case "end" => doneLatch.countDown()
|
case "end" => doneLatch.countDown()
|
||||||
}
|
}
|
||||||
})), name = "random")
|
})), name = "random")
|
||||||
|
|
||||||
for (_ <- 0 until iterationCount) {
|
for (_ <- 0 until iterationCount) {
|
||||||
for (_ <- 0 until connectionCount) {
|
for (_ <- 0 until connectionCount) {
|
||||||
|
|
@ -77,7 +77,7 @@ class RandomSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
|
||||||
actor ! akka.routing.Broadcast("end")
|
actor ! akka.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)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -86,14 +86,14 @@ class RandomSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
|
||||||
val stopLatch = new TestLatch(6)
|
val stopLatch = new TestLatch(6)
|
||||||
|
|
||||||
val actor = system.actorOf(RandomPool(6).props(routeeProps = Props(new Actor {
|
val actor = system.actorOf(RandomPool(6).props(routeeProps = Props(new Actor {
|
||||||
def receive = {
|
def receive = {
|
||||||
case "hello" => helloLatch.countDown()
|
case "hello" => helloLatch.countDown()
|
||||||
}
|
}
|
||||||
|
|
||||||
override def postStop(): Unit = {
|
override def postStop(): Unit = {
|
||||||
stopLatch.countDown()
|
stopLatch.countDown()
|
||||||
}
|
}
|
||||||
})), "random-broadcast")
|
})), "random-broadcast")
|
||||||
|
|
||||||
actor ! akka.routing.Broadcast("hello")
|
actor ! akka.routing.Broadcast("hello")
|
||||||
Await.ready(helloLatch, 5 seconds)
|
Await.ready(helloLatch, 5 seconds)
|
||||||
|
|
|
||||||
|
|
@ -227,16 +227,16 @@ class ResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultTimeout with
|
||||||
}
|
}
|
||||||
|
|
||||||
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)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -30,14 +30,14 @@ class RoundRobinSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
|
||||||
val stopLatch = new TestLatch(5)
|
val stopLatch = new TestLatch(5)
|
||||||
|
|
||||||
val actor = system.actorOf(RoundRobinPool(5).props(routeeProps = Props(new Actor {
|
val actor = system.actorOf(RoundRobinPool(5).props(routeeProps = Props(new Actor {
|
||||||
def receive = {
|
def receive = {
|
||||||
case "hello" => helloLatch.countDown()
|
case "hello" => helloLatch.countDown()
|
||||||
}
|
}
|
||||||
|
|
||||||
override def postStop(): Unit = {
|
override def postStop(): Unit = {
|
||||||
stopLatch.countDown()
|
stopLatch.countDown()
|
||||||
}
|
}
|
||||||
})), "round-robin-shutdown")
|
})), "round-robin-shutdown")
|
||||||
|
|
||||||
actor ! "hello"
|
actor ! "hello"
|
||||||
actor ! "hello"
|
actor ! "hello"
|
||||||
|
|
@ -59,12 +59,12 @@ class RoundRobinSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
|
||||||
var replies: Map[Int, Int] = Map.empty.withDefaultValue(0)
|
var replies: Map[Int, Int] = Map.empty.withDefaultValue(0)
|
||||||
|
|
||||||
val actor = system.actorOf(RoundRobinPool(connectionCount).props(routeeProps = Props(new Actor {
|
val actor = system.actorOf(RoundRobinPool(connectionCount).props(routeeProps = Props(new Actor {
|
||||||
lazy val id = counter.getAndIncrement()
|
lazy val id = counter.getAndIncrement()
|
||||||
def receive = {
|
def receive = {
|
||||||
case "hit" => sender() ! id
|
case "hit" => sender() ! id
|
||||||
case "end" => doneLatch.countDown()
|
case "end" => doneLatch.countDown()
|
||||||
}
|
}
|
||||||
})), "round-robin")
|
})), "round-robin")
|
||||||
|
|
||||||
for (_ <- 1 to iterationCount; _ <- 1 to connectionCount) {
|
for (_ <- 1 to iterationCount; _ <- 1 to connectionCount) {
|
||||||
val id = Await.result((actor ? "hit").mapTo[Int], timeout.duration)
|
val id = Await.result((actor ? "hit").mapTo[Int], timeout.duration)
|
||||||
|
|
@ -84,14 +84,14 @@ class RoundRobinSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
|
||||||
val stopLatch = new TestLatch(5)
|
val stopLatch = new TestLatch(5)
|
||||||
|
|
||||||
val actor = system.actorOf(RoundRobinPool(5).props(routeeProps = Props(new Actor {
|
val actor = system.actorOf(RoundRobinPool(5).props(routeeProps = Props(new Actor {
|
||||||
def receive = {
|
def receive = {
|
||||||
case "hello" => helloLatch.countDown()
|
case "hello" => helloLatch.countDown()
|
||||||
}
|
}
|
||||||
|
|
||||||
override def postStop(): Unit = {
|
override def postStop(): Unit = {
|
||||||
stopLatch.countDown()
|
stopLatch.countDown()
|
||||||
}
|
}
|
||||||
})), "round-robin-broadcast")
|
})), "round-robin-broadcast")
|
||||||
|
|
||||||
actor ! akka.routing.Broadcast("hello")
|
actor ! akka.routing.Broadcast("hello")
|
||||||
Await.ready(helloLatch, 5 seconds)
|
Await.ready(helloLatch, 5 seconds)
|
||||||
|
|
@ -102,8 +102,8 @@ class RoundRobinSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
|
||||||
|
|
||||||
"be controlled with management messages" in {
|
"be controlled with management messages" in {
|
||||||
val actor = system.actorOf(RoundRobinPool(3).props(routeeProps = Props(new Actor {
|
val actor = system.actorOf(RoundRobinPool(3).props(routeeProps = Props(new Actor {
|
||||||
def receive = Actor.emptyBehavior
|
def receive = Actor.emptyBehavior
|
||||||
})), "round-robin-managed")
|
})), "round-robin-managed")
|
||||||
|
|
||||||
routeeSize(actor) should ===(3)
|
routeeSize(actor) should ===(3)
|
||||||
actor ! AdjustPoolSize(+4)
|
actor ! AdjustPoolSize(+4)
|
||||||
|
|
@ -130,11 +130,11 @@ class RoundRobinSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
|
||||||
|
|
||||||
val paths = (1 to connectionCount).map { n =>
|
val paths = (1 to connectionCount).map { n =>
|
||||||
val ref = system.actorOf(Props(new Actor {
|
val ref = system.actorOf(Props(new Actor {
|
||||||
def receive = {
|
def receive = {
|
||||||
case "hit" => sender() ! self.path.name
|
case "hit" => sender() ! self.path.name
|
||||||
case "end" => doneLatch.countDown()
|
case "end" => doneLatch.countDown()
|
||||||
}
|
}
|
||||||
}), name = "target-" + n)
|
}), name = "target-" + n)
|
||||||
ref.path.toStringWithoutAddress
|
ref.path.toStringWithoutAddress
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -136,15 +136,15 @@ class RoutingSpec extends AkkaSpec(RoutingSpec.config) with DefaultTimeout with
|
||||||
}
|
}
|
||||||
|
|
||||||
"set supplied supervisorStrategy" in {
|
"set supplied supervisorStrategy" in {
|
||||||
//#supervision
|
// #supervision
|
||||||
val escalator = OneForOneStrategy() {
|
val escalator = OneForOneStrategy() {
|
||||||
//#custom-strategy
|
// #custom-strategy
|
||||||
case e => testActor ! e; SupervisorStrategy.Escalate
|
case e => testActor ! e; SupervisorStrategy.Escalate
|
||||||
//#custom-strategy
|
// #custom-strategy
|
||||||
}
|
}
|
||||||
val router =
|
val router =
|
||||||
system.actorOf(RoundRobinPool(1, supervisorStrategy = escalator).props(routeeProps = Props[TestActor]()))
|
system.actorOf(RoundRobinPool(1, supervisorStrategy = escalator).props(routeeProps = Props[TestActor]()))
|
||||||
//#supervision
|
// #supervision
|
||||||
router ! GetRoutees
|
router ! GetRoutees
|
||||||
EventFilter[ActorKilledException](occurrences = 1).intercept {
|
EventFilter[ActorKilledException](occurrences = 1).intercept {
|
||||||
expectMsgType[Routees].routees.head.send(Kill, testActor)
|
expectMsgType[Routees].routees.head.send(Kill, testActor)
|
||||||
|
|
|
||||||
|
|
@ -28,9 +28,9 @@ object ScatterGatherFirstCompletedSpec {
|
||||||
system.actorOf(
|
system.actorOf(
|
||||||
Props(new Actor {
|
Props(new Actor {
|
||||||
def receive = {
|
def receive = {
|
||||||
case Stop(None) => context.stop(self)
|
case Stop(None) => context.stop(self)
|
||||||
case Stop(Some(_id)) if (_id == id) => context.stop(self)
|
case Stop(Some(_id)) if _id == id => context.stop(self)
|
||||||
case _id: Int if (_id == id) =>
|
case _id: Int if _id == id =>
|
||||||
case _ => {
|
case _ => {
|
||||||
Thread.sleep(100 * id)
|
Thread.sleep(100 * id)
|
||||||
sender() ! id
|
sender() ! id
|
||||||
|
|
|
||||||
|
|
@ -51,15 +51,15 @@ class SmallestMailboxSpec extends AkkaSpec with DefaultTimeout with ImplicitSend
|
||||||
busy.countDown()
|
busy.countDown()
|
||||||
|
|
||||||
val busyPath = usedActors.get(0)
|
val busyPath = usedActors.get(0)
|
||||||
busyPath should not be (null)
|
busyPath should not be null
|
||||||
|
|
||||||
val path1 = usedActors.get(1)
|
val path1 = usedActors.get(1)
|
||||||
val path2 = usedActors.get(2)
|
val path2 = usedActors.get(2)
|
||||||
val path3 = usedActors.get(3)
|
val path3 = usedActors.get(3)
|
||||||
|
|
||||||
path1 should not be (busyPath)
|
path1 should not be busyPath
|
||||||
path2 should not be (busyPath)
|
path2 should not be busyPath
|
||||||
path3 should not be (busyPath)
|
path3 should not be busyPath
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -17,17 +17,17 @@ import akka.testkit._
|
||||||
object TailChoppingSpec {
|
object TailChoppingSpec {
|
||||||
def newActor(id: Int, sleepTime: Duration)(implicit system: ActorSystem) =
|
def newActor(id: Int, sleepTime: Duration)(implicit system: ActorSystem) =
|
||||||
system.actorOf(Props(new Actor {
|
system.actorOf(Props(new Actor {
|
||||||
var times: Int = _
|
var times: Int = _
|
||||||
|
|
||||||
def receive = {
|
def receive = {
|
||||||
case "stop" => context.stop(self)
|
case "stop" => context.stop(self)
|
||||||
case "times" => sender() ! times
|
case "times" => sender() ! times
|
||||||
case _ =>
|
case _ =>
|
||||||
times += 1
|
times += 1
|
||||||
Thread.sleep(sleepTime.toMillis)
|
Thread.sleep(sleepTime.toMillis)
|
||||||
sender() ! "ack"
|
sender() ! "ack"
|
||||||
}
|
}
|
||||||
}), "Actor:" + id)
|
}), "Actor:" + id)
|
||||||
}
|
}
|
||||||
|
|
||||||
class TailChoppingSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
|
class TailChoppingSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
|
||||||
|
|
|
||||||
|
|
@ -183,7 +183,7 @@ class BoundedBlockingQueueSpec
|
||||||
// queue.take() must happen first
|
// queue.take() must happen first
|
||||||
Thread.sleep(50) // this is why this test is tagged as TimingTest
|
Thread.sleep(50) // this is why this test is tagged as TimingTest
|
||||||
events should contain(awaitNotEmpty)
|
events should contain(awaitNotEmpty)
|
||||||
events should not contain (poll)
|
events should not contain poll
|
||||||
}
|
}
|
||||||
|
|
||||||
"block until the backing queue is non-empty" taggedAs TimingTest in {
|
"block until the backing queue is non-empty" taggedAs TimingTest in {
|
||||||
|
|
@ -557,7 +557,7 @@ class BoundedBlockingQueueSpec
|
||||||
val target = mutable.Buffer[String]()
|
val target = mutable.Buffer[String]()
|
||||||
elems.foreach(queue.put)
|
elems.foreach(queue.put)
|
||||||
queue.drainTo(target.asJava)
|
queue.drainTo(target.asJava)
|
||||||
elems should contain theSameElementsAs (target)
|
elems should contain theSameElementsAs target
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -617,7 +617,7 @@ class BoundedBlockingQueueSpec
|
||||||
queue.retainAll(elems.asJava) should equal(true)
|
queue.retainAll(elems.asJava) should equal(true)
|
||||||
queue.remainingCapacity() should equal(1)
|
queue.remainingCapacity() should equal(1)
|
||||||
queue.toArray() shouldNot contain("Akka")
|
queue.toArray() shouldNot contain("Akka")
|
||||||
queue.toArray() should contain theSameElementsAs (elems)
|
queue.toArray() should contain theSameElementsAs elems
|
||||||
}
|
}
|
||||||
|
|
||||||
"return false if no elements were removed" in {
|
"return false if no elements were removed" in {
|
||||||
|
|
|
||||||
|
|
@ -313,10 +313,10 @@ class ByteStringSpec extends AnyWordSpec with Matchers with Checkers {
|
||||||
for (i <- 0 until data.length) builder.putLongPart(data(i), nBytes)(byteOrder)
|
for (i <- 0 until data.length) builder.putLongPart(data(i), nBytes)(byteOrder)
|
||||||
|
|
||||||
reference.zipWithIndex
|
reference.zipWithIndex
|
||||||
.collect({ // Since there is no partial put on LongBuffer, we need to collect only the interesting bytes
|
.collect { // Since there is no partial put on LongBuffer, we need to collect only the interesting bytes
|
||||||
case (r, i) if byteOrder == ByteOrder.LITTLE_ENDIAN && i % elemSize < nBytes => r
|
case (r, i) if byteOrder == ByteOrder.LITTLE_ENDIAN && i % elemSize < nBytes => r
|
||||||
case (r, i) if byteOrder == ByteOrder.BIG_ENDIAN && i % elemSize >= (elemSize - nBytes) => r
|
case (r, i) if byteOrder == ByteOrder.BIG_ENDIAN && i % elemSize >= (elemSize - nBytes) => r
|
||||||
})
|
}
|
||||||
.toSeq == builder.result()
|
.toSeq == builder.result()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -886,13 +886,13 @@ class ByteStringSpec extends AnyWordSpec with Matchers with Checkers {
|
||||||
|
|
||||||
"calling span" in {
|
"calling span" in {
|
||||||
check { (a: ByteString, b: Byte) =>
|
check { (a: ByteString, b: Byte) =>
|
||||||
likeVector(a)({ _.span(_ != b) match { case (a, b) => (a, b) } })
|
likeVector(a) { _.span(_ != b) match { case (a, b) => (a, b) } }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
"calling takeWhile" in {
|
"calling takeWhile" in {
|
||||||
check { (a: ByteString, b: Byte) =>
|
check { (a: ByteString, b: Byte) =>
|
||||||
likeVector(a)({ _.takeWhile(_ != b) })
|
likeVector(a) { _.takeWhile(_ != b) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
"calling dropWhile" in {
|
"calling dropWhile" in {
|
||||||
|
|
@ -940,9 +940,9 @@ class ByteStringSpec extends AnyWordSpec with Matchers with Checkers {
|
||||||
check { (slice: ByteStringSlice) =>
|
check { (slice: ByteStringSlice) =>
|
||||||
slice match {
|
slice match {
|
||||||
case (xs, from, until) =>
|
case (xs, from, until) =>
|
||||||
likeVector(xs)({
|
likeVector(xs) {
|
||||||
_.slice(from, until)
|
_.slice(from, until)
|
||||||
})
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -951,9 +951,9 @@ class ByteStringSpec extends AnyWordSpec with Matchers with Checkers {
|
||||||
check { (slice: ByteStringSlice) =>
|
check { (slice: ByteStringSlice) =>
|
||||||
slice match {
|
slice match {
|
||||||
case (xs, from, until) =>
|
case (xs, from, until) =>
|
||||||
likeVector(xs)({
|
likeVector(xs) {
|
||||||
_.drop(from).take(until - from)
|
_.drop(from).take(until - from)
|
||||||
})
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -970,11 +970,11 @@ class ByteStringSpec extends AnyWordSpec with Matchers with Checkers {
|
||||||
check { (slice: ByteStringSlice) =>
|
check { (slice: ByteStringSlice) =>
|
||||||
slice match {
|
slice match {
|
||||||
case (xs, from, until) =>
|
case (xs, from, until) =>
|
||||||
likeVector(xs)({ it =>
|
likeVector(xs) { it =>
|
||||||
val array = new Array[Byte](xs.length)
|
val array = new Array[Byte](xs.length)
|
||||||
it.copyToArray(array, from, until)
|
it.copyToArray(array, from, until)
|
||||||
array.toSeq
|
array.toSeq
|
||||||
})
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1114,8 +1114,8 @@ class ByteStringSpec extends AnyWordSpec with Matchers with Checkers {
|
||||||
slice match {
|
slice match {
|
||||||
case (xs, from, until) =>
|
case (xs, from, until) =>
|
||||||
likeVecIt(xs)({
|
likeVecIt(xs)({
|
||||||
_.slice(from, until).toSeq
|
_.slice(from, until).toSeq
|
||||||
}, strict = false)
|
}, strict = false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1125,8 +1125,8 @@ class ByteStringSpec extends AnyWordSpec with Matchers with Checkers {
|
||||||
slice match {
|
slice match {
|
||||||
case (xs, from, until) =>
|
case (xs, from, until) =>
|
||||||
likeVecIt(xs)({
|
likeVecIt(xs)({
|
||||||
_.drop(from).take(until - from).toSeq
|
_.drop(from).take(until - from).toSeq
|
||||||
}, strict = false)
|
}, strict = false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1136,10 +1136,10 @@ class ByteStringSpec extends AnyWordSpec with Matchers with Checkers {
|
||||||
slice match {
|
slice match {
|
||||||
case (xs, from, until) =>
|
case (xs, from, until) =>
|
||||||
likeVecIt(xs)({ it =>
|
likeVecIt(xs)({ it =>
|
||||||
val array = new Array[Byte](xs.length)
|
val array = new Array[Byte](xs.length)
|
||||||
it.slice(from, until).copyToArray(array, from, until)
|
it.slice(from, until).copyToArray(array, from, until)
|
||||||
array.toSeq
|
array.toSeq
|
||||||
}, strict = false)
|
}, strict = false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -44,52 +44,52 @@ class FrequencyListSpec extends AnyWordSpec with Matchers {
|
||||||
check(frequency, Nil)
|
check(frequency, Nil)
|
||||||
|
|
||||||
frequency.update("a")
|
frequency.update("a")
|
||||||
check(frequency, List( /* 1: */ "a"))
|
check(frequency, List(/* 1: */ "a"))
|
||||||
|
|
||||||
frequency.update("b").update("c")
|
frequency.update("b").update("c")
|
||||||
check(frequency, List( /* 1: */ "a", "b", "c"))
|
check(frequency, List(/* 1: */ "a", "b", "c"))
|
||||||
|
|
||||||
frequency.update("a").update("c")
|
frequency.update("a").update("c")
|
||||||
check(frequency, List( /* 1: */ "b", /* 2: */ "a", "c"))
|
check(frequency, List(/* 1: */ "b", /* 2: */ "a", "c"))
|
||||||
|
|
||||||
frequency.update("d").update("e").update("f").update("g")
|
frequency.update("d").update("e").update("f").update("g")
|
||||||
check(frequency, List( /* 1: */ "b", "d", "e", "f", "g", /* 2: */ "a", "c"))
|
check(frequency, List(/* 1: */ "b", "d", "e", "f", "g", /* 2: */ "a", "c"))
|
||||||
|
|
||||||
frequency.update("c").update("f")
|
frequency.update("c").update("f")
|
||||||
check(frequency, List( /* 1: */ "b", "d", "e", "g", /* 2: */ "a", "f", /* 3: */ "c"))
|
check(frequency, List(/* 1: */ "b", "d", "e", "g", /* 2: */ "a", "f", /* 3: */ "c"))
|
||||||
|
|
||||||
frequency.remove("d").remove("g").remove("b").remove("f")
|
frequency.remove("d").remove("g").remove("b").remove("f")
|
||||||
check(frequency, List( /* 1: */ "e", /* 2: */ "a", /* 3: */ "c"))
|
check(frequency, List(/* 1: */ "e", /* 2: */ "a", /* 3: */ "c"))
|
||||||
|
|
||||||
frequency.update("e").update("h").update("i")
|
frequency.update("e").update("h").update("i")
|
||||||
check(frequency, List( /* 1: */ "h", "i", /* 2: */ "a", "e", /* 3: */ "c"))
|
check(frequency, List(/* 1: */ "h", "i", /* 2: */ "a", "e", /* 3: */ "c"))
|
||||||
|
|
||||||
frequency.removeLeastFrequent(3) shouldBe List("h", "i", "a")
|
frequency.removeLeastFrequent(3) shouldBe List("h", "i", "a")
|
||||||
check(frequency, List( /* 2: */ "e", /* 3: */ "c"))
|
check(frequency, List(/* 2: */ "e", /* 3: */ "c"))
|
||||||
|
|
||||||
frequency.update("j").update("k").update("l").update("m")
|
frequency.update("j").update("k").update("l").update("m")
|
||||||
check(frequency, List( /* 1: */ "j", "k", "l", "m", /* 2: */ "e", /* 3: */ "c"))
|
check(frequency, List(/* 1: */ "j", "k", "l", "m", /* 2: */ "e", /* 3: */ "c"))
|
||||||
|
|
||||||
frequency.removeLeastFrequent(skip = OptionVal.Some("j")) shouldBe List("k")
|
frequency.removeLeastFrequent(skip = OptionVal.Some("j")) shouldBe List("k")
|
||||||
check(frequency, List( /* 1: */ "j", "l", "m", /* 2: */ "e", /* 3: */ "c"))
|
check(frequency, List(/* 1: */ "j", "l", "m", /* 2: */ "e", /* 3: */ "c"))
|
||||||
|
|
||||||
frequency.removeLeastFrequent(2, skip = OptionVal.Some("l")) shouldBe List("j", "m")
|
frequency.removeLeastFrequent(2, skip = OptionVal.Some("l")) shouldBe List("j", "m")
|
||||||
check(frequency, List( /* 1: */ "l", /* 2: */ "e", /* 3: */ "c"))
|
check(frequency, List(/* 1: */ "l", /* 2: */ "e", /* 3: */ "c"))
|
||||||
|
|
||||||
frequency.update("n").update("o").update("p").update("e").update("o").update("l")
|
frequency.update("n").update("o").update("p").update("e").update("o").update("l")
|
||||||
check(frequency, List( /* 1: */ "n", "p", /* 2: */ "o", "l", /* 3: */ "c", "e"))
|
check(frequency, List(/* 1: */ "n", "p", /* 2: */ "o", "l", /* 3: */ "c", "e"))
|
||||||
|
|
||||||
frequency.removeMostFrequent(3) shouldBe List("e", "c", "l")
|
frequency.removeMostFrequent(3) shouldBe List("e", "c", "l")
|
||||||
check(frequency, List( /* 1: */ "n", "p", /* 2: */ "o"))
|
check(frequency, List(/* 1: */ "n", "p", /* 2: */ "o"))
|
||||||
|
|
||||||
frequency.update("q").update("r").update("p").update("o").update("n")
|
frequency.update("q").update("r").update("p").update("o").update("n")
|
||||||
check(frequency, List( /* 1: */ "q", "r", /* 2: */ "p", "n", /* 3: */ "o"))
|
check(frequency, List(/* 1: */ "q", "r", /* 2: */ "p", "n", /* 3: */ "o"))
|
||||||
|
|
||||||
frequency.removeMostFrequent(skip = OptionVal.Some("o")) shouldBe List("n")
|
frequency.removeMostFrequent(skip = OptionVal.Some("o")) shouldBe List("n")
|
||||||
check(frequency, List( /* 1: */ "q", "r", /* 2: */ "p", /* 3: */ "o"))
|
check(frequency, List(/* 1: */ "q", "r", /* 2: */ "p", /* 3: */ "o"))
|
||||||
|
|
||||||
frequency.removeMostFrequent(2, skip = OptionVal.Some("p")) shouldBe List("o", "r")
|
frequency.removeMostFrequent(2, skip = OptionVal.Some("p")) shouldBe List("o", "r")
|
||||||
check(frequency, List( /* 1: */ "q", /* 2: */ "p"))
|
check(frequency, List(/* 1: */ "q", /* 2: */ "p"))
|
||||||
}
|
}
|
||||||
|
|
||||||
"track overall recency of elements when enabled" in {
|
"track overall recency of elements when enabled" in {
|
||||||
|
|
@ -100,72 +100,72 @@ class FrequencyListSpec extends AnyWordSpec with Matchers {
|
||||||
|
|
||||||
clock.tick() // time = 1
|
clock.tick() // time = 1
|
||||||
frequency.update("a")
|
frequency.update("a")
|
||||||
check(frequency, List( /* 1: */ "a"))
|
check(frequency, List(/* 1: */ "a"))
|
||||||
checkRecency(frequency, List("a"))
|
checkRecency(frequency, List("a"))
|
||||||
|
|
||||||
clock.tick() // time = 2
|
clock.tick() // time = 2
|
||||||
frequency.update("b").update("c")
|
frequency.update("b").update("c")
|
||||||
check(frequency, List( /* 1: */ "a", "b", "c"))
|
check(frequency, List(/* 1: */ "a", "b", "c"))
|
||||||
checkRecency(frequency, List("a", "b", "c"))
|
checkRecency(frequency, List("a", "b", "c"))
|
||||||
|
|
||||||
clock.tick() // time = 3
|
clock.tick() // time = 3
|
||||||
frequency.update("a").update("c")
|
frequency.update("a").update("c")
|
||||||
check(frequency, List( /* 1: */ "b", /* 2: */ "a", "c"))
|
check(frequency, List(/* 1: */ "b", /* 2: */ "a", "c"))
|
||||||
checkRecency(frequency, List("b", "a", "c"))
|
checkRecency(frequency, List("b", "a", "c"))
|
||||||
|
|
||||||
clock.tick() // time = 4
|
clock.tick() // time = 4
|
||||||
frequency.update("d").update("e").update("f")
|
frequency.update("d").update("e").update("f")
|
||||||
check(frequency, List( /* 1: */ "b", "d", "e", "f", /* 2: */ "a", "c"))
|
check(frequency, List(/* 1: */ "b", "d", "e", "f", /* 2: */ "a", "c"))
|
||||||
checkRecency(frequency, List("b", "a", "c", "d", "e", "f"))
|
checkRecency(frequency, List("b", "a", "c", "d", "e", "f"))
|
||||||
|
|
||||||
clock.tick() // time = 5
|
clock.tick() // time = 5
|
||||||
frequency.update("c").update("f")
|
frequency.update("c").update("f")
|
||||||
check(frequency, List( /* 1: */ "b", "d", "e", /* 2: */ "a", "f", /* 3: */ "c"))
|
check(frequency, List(/* 1: */ "b", "d", "e", /* 2: */ "a", "f", /* 3: */ "c"))
|
||||||
checkRecency(frequency, List("b", "a", "d", "e", "c", "f"))
|
checkRecency(frequency, List("b", "a", "d", "e", "c", "f"))
|
||||||
|
|
||||||
clock.tick() // time = 6
|
clock.tick() // time = 6
|
||||||
frequency.remove("d").remove("b").remove("f")
|
frequency.remove("d").remove("b").remove("f")
|
||||||
check(frequency, List( /* 1: */ "e", /* 2: */ "a", /* 3: */ "c"))
|
check(frequency, List(/* 1: */ "e", /* 2: */ "a", /* 3: */ "c"))
|
||||||
checkRecency(frequency, List("a", "e", "c"))
|
checkRecency(frequency, List("a", "e", "c"))
|
||||||
|
|
||||||
clock.tick() // time = 7
|
clock.tick() // time = 7
|
||||||
frequency.update("e").update("h").update("i")
|
frequency.update("e").update("h").update("i")
|
||||||
check(frequency, List( /* 1: */ "h", "i", /* 2: */ "a", "e", /* 3: */ "c"))
|
check(frequency, List(/* 1: */ "h", "i", /* 2: */ "a", "e", /* 3: */ "c"))
|
||||||
checkRecency(frequency, List("a", "c", "e", "h", "i"))
|
checkRecency(frequency, List("a", "c", "e", "h", "i"))
|
||||||
|
|
||||||
clock.tick() // time = 8
|
clock.tick() // time = 8
|
||||||
frequency.removeOverallLeastRecent() shouldBe List("a")
|
frequency.removeOverallLeastRecent() shouldBe List("a")
|
||||||
check(frequency, List( /* 1: */ "h", "i", /* 2: */ "e", /* 3: */ "c"))
|
check(frequency, List(/* 1: */ "h", "i", /* 2: */ "e", /* 3: */ "c"))
|
||||||
checkRecency(frequency, List("c", "e", "h", "i"))
|
checkRecency(frequency, List("c", "e", "h", "i"))
|
||||||
|
|
||||||
clock.tick() // time = 9
|
clock.tick() // time = 9
|
||||||
frequency.update("i").update("j").update("k")
|
frequency.update("i").update("j").update("k")
|
||||||
check(frequency, List( /* 1: */ "h", "j", "k", /* 2: */ "e", "i", /* 3: */ "c"))
|
check(frequency, List(/* 1: */ "h", "j", "k", /* 2: */ "e", "i", /* 3: */ "c"))
|
||||||
checkRecency(frequency, List("c", "e", "h", "i", "j", "k"))
|
checkRecency(frequency, List("c", "e", "h", "i", "j", "k"))
|
||||||
|
|
||||||
clock.tick() // time = 10
|
clock.tick() // time = 10
|
||||||
frequency.removeOverallMostRecent() shouldBe List("k")
|
frequency.removeOverallMostRecent() shouldBe List("k")
|
||||||
check(frequency, List( /* 1: */ "h", "j", /* 2: */ "e", "i", /* 3: */ "c"))
|
check(frequency, List(/* 1: */ "h", "j", /* 2: */ "e", "i", /* 3: */ "c"))
|
||||||
checkRecency(frequency, List("c", "e", "h", "i", "j"))
|
checkRecency(frequency, List("c", "e", "h", "i", "j"))
|
||||||
|
|
||||||
clock.tick() // time = 11
|
clock.tick() // time = 11
|
||||||
frequency.removeOverallLeastRecentOutside(3.seconds) shouldBe List("c", "e", "h")
|
frequency.removeOverallLeastRecentOutside(3.seconds) shouldBe List("c", "e", "h")
|
||||||
check(frequency, List( /* 1: */ "j", /* 2: */ "i"))
|
check(frequency, List(/* 1: */ "j", /* 2: */ "i"))
|
||||||
checkRecency(frequency, List("i", "j"))
|
checkRecency(frequency, List("i", "j"))
|
||||||
|
|
||||||
clock.tick() // time = 12
|
clock.tick() // time = 12
|
||||||
frequency.update("l").update("m")
|
frequency.update("l").update("m")
|
||||||
check(frequency, List( /* 1: */ "j", "l", "m", /* 2: */ "i"))
|
check(frequency, List(/* 1: */ "j", "l", "m", /* 2: */ "i"))
|
||||||
checkRecency(frequency, List("i", "j", "l", "m"))
|
checkRecency(frequency, List("i", "j", "l", "m"))
|
||||||
|
|
||||||
clock.tick() // time = 13
|
clock.tick() // time = 13
|
||||||
frequency.removeOverallMostRecentWithin(3.seconds) shouldBe List("m", "l")
|
frequency.removeOverallMostRecentWithin(3.seconds) shouldBe List("m", "l")
|
||||||
check(frequency, List( /* 1: */ "j", /* 2: */ "i"))
|
check(frequency, List(/* 1: */ "j", /* 2: */ "i"))
|
||||||
checkRecency(frequency, List("i", "j"))
|
checkRecency(frequency, List("i", "j"))
|
||||||
|
|
||||||
clock.tick() // time = 14
|
clock.tick() // time = 14
|
||||||
frequency.update("n").update("o").update("n")
|
frequency.update("n").update("o").update("n")
|
||||||
check(frequency, List( /* 1: */ "j", "o", /* 2: */ "i", "n"))
|
check(frequency, List(/* 1: */ "j", "o", /* 2: */ "i", "n"))
|
||||||
checkRecency(frequency, List("i", "j", "o", "n"))
|
checkRecency(frequency, List("i", "j", "o", "n"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -177,80 +177,80 @@ class FrequencyListSpec extends AnyWordSpec with Matchers {
|
||||||
check(aging, Nil)
|
check(aging, Nil)
|
||||||
|
|
||||||
for (_ <- 1 to 10) regular.update("a").update("b").update("c")
|
for (_ <- 1 to 10) regular.update("a").update("b").update("c")
|
||||||
check(regular, List( /*10*/ "a", "b", "c"))
|
check(regular, List(/*10*/ "a", "b", "c"))
|
||||||
|
|
||||||
for (_ <- 1 to 10) aging.update("a").update("b").update("c")
|
for (_ <- 1 to 10) aging.update("a").update("b").update("c")
|
||||||
check(aging, List( /*10+0*/ "a", "b", "c"))
|
check(aging, List(/*10+0*/ "a", "b", "c"))
|
||||||
|
|
||||||
// age = 0
|
// age = 0
|
||||||
|
|
||||||
regular.update("x").update("y").update("z")
|
regular.update("x").update("y").update("z")
|
||||||
check(regular, List( /*1*/ "x", "y", "z", /*10*/ "a", "b", "c"))
|
check(regular, List(/*1*/ "x", "y", "z", /*10*/ "a", "b", "c"))
|
||||||
|
|
||||||
aging.update("x").update("y").update("z")
|
aging.update("x").update("y").update("z")
|
||||||
check(aging, List( /*1+0*/ "x", "y", "z", /*10+0*/ "a", "b", "c"))
|
check(aging, List(/*1+0*/ "x", "y", "z", /*10+0*/ "a", "b", "c"))
|
||||||
|
|
||||||
regular.removeLeastFrequent() shouldBe List("x")
|
regular.removeLeastFrequent() shouldBe List("x")
|
||||||
check(regular, List( /*1*/ "y", "z", /*10*/ "a", "b", "c"))
|
check(regular, List(/*1*/ "y", "z", /*10*/ "a", "b", "c"))
|
||||||
|
|
||||||
aging.removeLeastFrequent() shouldBe List("x")
|
aging.removeLeastFrequent() shouldBe List("x")
|
||||||
check(aging, List( /*1+0*/ "y", "z", /*10+0*/ "a", "b", "c"))
|
check(aging, List(/*1+0*/ "y", "z", /*10+0*/ "a", "b", "c"))
|
||||||
|
|
||||||
// age = 1 (from last removal of "x")
|
// age = 1 (from last removal of "x")
|
||||||
|
|
||||||
regular.update("x").update("y").update("z").update("z")
|
regular.update("x").update("y").update("z").update("z")
|
||||||
check(regular, List( /*1*/ "x", /*2*/ "y", /*3*/ "z", /*10*/ "a", "b", "c"))
|
check(regular, List(/*1*/ "x", /*2*/ "y", /*3*/ "z", /*10*/ "a", "b", "c"))
|
||||||
|
|
||||||
aging.update("x").update("y").update("z").update("z")
|
aging.update("x").update("y").update("z").update("z")
|
||||||
check(aging, List( /*1+1*/ "x", /*2+1*/ "y", /*3+1*/ "z", /*10+0*/ "a", "b", "c"))
|
check(aging, List(/*1+1*/ "x", /*2+1*/ "y", /*3+1*/ "z", /*10+0*/ "a", "b", "c"))
|
||||||
|
|
||||||
regular.removeLeastFrequent(2) shouldBe List("x", "y")
|
regular.removeLeastFrequent(2) shouldBe List("x", "y")
|
||||||
check(regular, List( /*3*/ "z", /*10*/ "a", "b", "c"))
|
check(regular, List(/*3*/ "z", /*10*/ "a", "b", "c"))
|
||||||
|
|
||||||
aging.removeLeastFrequent(2) shouldBe List("x", "y")
|
aging.removeLeastFrequent(2) shouldBe List("x", "y")
|
||||||
check(aging, List( /*3+1*/ "z", /*10+0*/ "a", "b", "c"))
|
check(aging, List(/*3+1*/ "z", /*10+0*/ "a", "b", "c"))
|
||||||
|
|
||||||
// age = 3 (from last removal of "y")
|
// age = 3 (from last removal of "y")
|
||||||
|
|
||||||
regular.update("x").update("y").update("z")
|
regular.update("x").update("y").update("z")
|
||||||
check(regular, List( /*1*/ "x", "y", /*4*/ "z", /*10*/ "a", "b", "c"))
|
check(regular, List(/*1*/ "x", "y", /*4*/ "z", /*10*/ "a", "b", "c"))
|
||||||
|
|
||||||
aging.update("x").update("y").update("z")
|
aging.update("x").update("y").update("z")
|
||||||
check(aging, List( /*1+3*/ "x", "y", /*4+3*/ "z", /*10+0*/ "a", "b", "c"))
|
check(aging, List(/*1+3*/ "x", "y", /*4+3*/ "z", /*10+0*/ "a", "b", "c"))
|
||||||
|
|
||||||
regular.removeLeastFrequent(3) shouldBe List("x", "y", "z")
|
regular.removeLeastFrequent(3) shouldBe List("x", "y", "z")
|
||||||
check(regular, List( /*10*/ "a", "b", "c"))
|
check(regular, List(/*10*/ "a", "b", "c"))
|
||||||
|
|
||||||
aging.removeLeastFrequent(3) shouldBe List("x", "y", "z")
|
aging.removeLeastFrequent(3) shouldBe List("x", "y", "z")
|
||||||
check(aging, List( /*10+0*/ "a", "b", "c"))
|
check(aging, List(/*10+0*/ "a", "b", "c"))
|
||||||
|
|
||||||
// age = 7 (from last removal of "z")
|
// age = 7 (from last removal of "z")
|
||||||
|
|
||||||
regular.update("x").update("y").update("y").update("z").update("z").update("z")
|
regular.update("x").update("y").update("y").update("z").update("z").update("z")
|
||||||
check(regular, List( /*1*/ "x", /*2*/ "y", /*3*/ "z", /*10*/ "a", "b", "c"))
|
check(regular, List(/*1*/ "x", /*2*/ "y", /*3*/ "z", /*10*/ "a", "b", "c"))
|
||||||
|
|
||||||
aging.update("x").update("y").update("y").update("z").update("z").update("z")
|
aging.update("x").update("y").update("y").update("z").update("z").update("z")
|
||||||
check(aging, List( /*1+7*/ "x", /*2+7*/ "y", /*10+0*/ "a", "b", "c", /*3+7*/ "z"))
|
check(aging, List(/*1+7*/ "x", /*2+7*/ "y", /*10+0*/ "a", "b", "c", /*3+7*/ "z"))
|
||||||
|
|
||||||
regular.removeLeastFrequent(2) shouldBe List("x", "y")
|
regular.removeLeastFrequent(2) shouldBe List("x", "y")
|
||||||
check(regular, List( /*3*/ "z", /*10*/ "a", "b", "c"))
|
check(regular, List(/*3*/ "z", /*10*/ "a", "b", "c"))
|
||||||
|
|
||||||
aging.removeLeastFrequent(2) shouldBe List("x", "y")
|
aging.removeLeastFrequent(2) shouldBe List("x", "y")
|
||||||
check(aging, List( /*10+0*/ "a", "b", "c", /*3+7*/ "z"))
|
check(aging, List(/*10+0*/ "a", "b", "c", /*3+7*/ "z"))
|
||||||
|
|
||||||
// age = 9 (from last removal of "y")
|
// age = 9 (from last removal of "y")
|
||||||
|
|
||||||
regular.update("x").update("y").update("z")
|
regular.update("x").update("y").update("z")
|
||||||
check(regular, List( /*1*/ "x", "y", /*4*/ "z", /*10*/ "a", "b", "c"))
|
check(regular, List(/*1*/ "x", "y", /*4*/ "z", /*10*/ "a", "b", "c"))
|
||||||
|
|
||||||
aging.update("x").update("y").update("z")
|
aging.update("x").update("y").update("z")
|
||||||
check(aging, List( /*10+0*/ "a", "b", "c", /*1+9*/ "x", "y", /*4+9*/ "z"))
|
check(aging, List(/*10+0*/ "a", "b", "c", /*1+9*/ "x", "y", /*4+9*/ "z"))
|
||||||
|
|
||||||
regular.removeLeastFrequent(3) shouldBe List("x", "y", "z")
|
regular.removeLeastFrequent(3) shouldBe List("x", "y", "z")
|
||||||
check(regular, List( /*10*/ "a", "b", "c"))
|
check(regular, List(/*10*/ "a", "b", "c"))
|
||||||
|
|
||||||
aging.removeLeastFrequent(3) shouldBe List("a", "b", "c")
|
aging.removeLeastFrequent(3) shouldBe List("a", "b", "c")
|
||||||
check(aging, List( /*1+9*/ "x", "y", /*4+9*/ "z"))
|
check(aging, List(/*1+9*/ "x", "y", /*4+9*/ "z"))
|
||||||
|
|
||||||
// age = 10 (from last removal of "c")
|
// age = 10 (from last removal of "c")
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -19,9 +19,10 @@ import akka.testkit.DefaultTimeout
|
||||||
class IndexSpec extends AkkaSpec with Matchers with DefaultTimeout {
|
class IndexSpec extends AkkaSpec with Matchers with DefaultTimeout {
|
||||||
implicit val ec: ExecutionContextExecutor = system.dispatcher
|
implicit val ec: ExecutionContextExecutor = system.dispatcher
|
||||||
private def emptyIndex =
|
private def emptyIndex =
|
||||||
new Index[String, Int](100, new Comparator[Int] {
|
new Index[String, Int](100,
|
||||||
override def compare(a: Int, b: Int): Int = Integer.compare(a, b)
|
new Comparator[Int] {
|
||||||
})
|
override def compare(a: Int, b: Int): Int = Integer.compare(a, b)
|
||||||
|
})
|
||||||
|
|
||||||
private def indexWithValues = {
|
private def indexWithValues = {
|
||||||
val index = emptyIndex
|
val index = emptyIndex
|
||||||
|
|
@ -58,11 +59,11 @@ class IndexSpec extends AkkaSpec with Matchers with DefaultTimeout {
|
||||||
index.put("s1", 2)
|
index.put("s1", 2)
|
||||||
index.put("s2", 1)
|
index.put("s2", 1)
|
||||||
index.put("s2", 2)
|
index.put("s2", 2)
|
||||||
//Remove value
|
// Remove value
|
||||||
index.remove("s1", 1) should ===(true)
|
index.remove("s1", 1) should ===(true)
|
||||||
index.remove("s1", 1) should ===(false)
|
index.remove("s1", 1) should ===(false)
|
||||||
index.valueIterator("s1").toSet should ===(Set(2))
|
index.valueIterator("s1").toSet should ===(Set(2))
|
||||||
//Remove key
|
// Remove key
|
||||||
index.remove("s2") match {
|
index.remove("s2") match {
|
||||||
case Some(iter) => iter.toSet should ===(Set(1, 2))
|
case Some(iter) => iter.toSet should ===(Set(1, 2))
|
||||||
case None => fail()
|
case None => fail()
|
||||||
|
|
@ -101,16 +102,17 @@ class IndexSpec extends AkkaSpec with Matchers with DefaultTimeout {
|
||||||
index.isEmpty should ===(true)
|
index.isEmpty should ===(true)
|
||||||
}
|
}
|
||||||
"be able to be accessed in parallel" in {
|
"be able to be accessed in parallel" in {
|
||||||
val index = new Index[Int, Int](100, new Comparator[Int] {
|
val index = new Index[Int, Int](100,
|
||||||
override def compare(a: Int, b: Int): Int = Integer.compare(a, b)
|
new Comparator[Int] {
|
||||||
})
|
override def compare(a: Int, b: Int): Int = Integer.compare(a, b)
|
||||||
|
})
|
||||||
val nrOfTasks = 10000
|
val nrOfTasks = 10000
|
||||||
val nrOfKeys = 10
|
val nrOfKeys = 10
|
||||||
val nrOfValues = 10
|
val nrOfValues = 10
|
||||||
//Fill index
|
// Fill index
|
||||||
for (key <- 0 until nrOfKeys; value <- 0 until nrOfValues)
|
for (key <- 0 until nrOfKeys; value <- 0 until nrOfValues)
|
||||||
index.put(key, value)
|
index.put(key, value)
|
||||||
//Tasks to be executed in parallel
|
// Tasks to be executed in parallel
|
||||||
def putTask() = Future {
|
def putTask() = Future {
|
||||||
index.put(Random.nextInt(nrOfKeys), Random.nextInt(nrOfValues))
|
index.put(Random.nextInt(nrOfKeys), Random.nextInt(nrOfValues))
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -488,9 +488,9 @@ class DeferredScalaBehaviorSpec extends ImmutableWithSignalScalaBehaviorSpec {
|
||||||
override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = {
|
override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = {
|
||||||
val inbox = TestInbox[Done]("deferredListener")
|
val inbox = TestInbox[Done]("deferredListener")
|
||||||
(SBehaviors.setup(_ => {
|
(SBehaviors.setup(_ => {
|
||||||
inbox.ref ! Done
|
inbox.ref ! Done
|
||||||
super.behavior(monitor)._1
|
super.behavior(monitor)._1
|
||||||
}), inbox)
|
}), inbox)
|
||||||
}
|
}
|
||||||
|
|
||||||
override def checkAux(signal: Signal, aux: Aux): Unit =
|
override def checkAux(signal: Signal, aux: Aux): Unit =
|
||||||
|
|
@ -594,10 +594,12 @@ class ImmutableJavaBehaviorSpec extends Messages with Become with Stoppable {
|
||||||
class TransformMessagesJavaBehaviorSpec extends ImmutableWithSignalJavaBehaviorSpec with Reuse with Siphon {
|
class TransformMessagesJavaBehaviorSpec extends ImmutableWithSignalJavaBehaviorSpec with Reuse with Siphon {
|
||||||
override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = {
|
override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = {
|
||||||
val inbox = TestInbox[Command]("transformMessagesListener")
|
val inbox = TestInbox[Command]("transformMessagesListener")
|
||||||
JBehaviors.transformMessages(classOf[Command], super.behavior(monitor)._1, pf(_.`match`(classOf[Command], fi(x => {
|
JBehaviors.transformMessages(classOf[Command], super.behavior(monitor)._1,
|
||||||
inbox.ref ! x
|
pf(_.`match`(classOf[Command],
|
||||||
x
|
fi(x => {
|
||||||
})))) -> inbox
|
inbox.ref ! x
|
||||||
|
x
|
||||||
|
})))) -> inbox
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -607,9 +609,9 @@ class DeferredJavaBehaviorSpec extends ImmutableWithSignalJavaBehaviorSpec {
|
||||||
override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = {
|
override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = {
|
||||||
val inbox = TestInbox[Done]("deferredListener")
|
val inbox = TestInbox[Done]("deferredListener")
|
||||||
(JBehaviors.setup(_ => {
|
(JBehaviors.setup(_ => {
|
||||||
inbox.ref ! Done
|
inbox.ref ! Done
|
||||||
super.behavior(monitor)._1
|
super.behavior(monitor)._1
|
||||||
}), inbox)
|
}), inbox)
|
||||||
}
|
}
|
||||||
|
|
||||||
override def checkAux(signal: Signal, aux: Aux): Unit =
|
override def checkAux(signal: Signal, aux: Aux): Unit =
|
||||||
|
|
|
||||||
|
|
@ -120,10 +120,11 @@ class DeferredSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with L
|
||||||
// monitor is implemented with tap, so this is testing both
|
// monitor is implemented with tap, so this is testing both
|
||||||
val probe = TestProbe[Event]("evt")
|
val probe = TestProbe[Event]("evt")
|
||||||
val monitorProbe = TestProbe[Command]("monitor")
|
val monitorProbe = TestProbe[Command]("monitor")
|
||||||
val behv = Behaviors.monitor(monitorProbe.ref, Behaviors.setup[Command] { _ =>
|
val behv = Behaviors.monitor(monitorProbe.ref,
|
||||||
probe.ref ! Started
|
Behaviors.setup[Command] { _ =>
|
||||||
target(probe.ref)
|
probe.ref ! Started
|
||||||
})
|
target(probe.ref)
|
||||||
|
})
|
||||||
probe.expectNoMessage() // not yet
|
probe.expectNoMessage() // not yet
|
||||||
val ref = spawn(behv)
|
val ref = spawn(behv)
|
||||||
// it's supposed to be created immediately (not waiting for first message)
|
// it's supposed to be created immediately (not waiting for first message)
|
||||||
|
|
|
||||||
|
|
@ -483,10 +483,11 @@ class InterceptSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with
|
||||||
"be possible to combine with MDC" in {
|
"be possible to combine with MDC" in {
|
||||||
val probe = createTestProbe[String]()
|
val probe = createTestProbe[String]()
|
||||||
val ref = spawn(Behaviors.setup[Command] { _ =>
|
val ref = spawn(Behaviors.setup[Command] { _ =>
|
||||||
Behaviors.withMdc(staticMdc = Map("x" -> "y"), mdcForMessage = (msg: Command) => {
|
Behaviors.withMdc(staticMdc = Map("x" -> "y"),
|
||||||
probe.ref ! s"mdc:${msg.s.toUpperCase()}"
|
mdcForMessage = (msg: Command) => {
|
||||||
Map("msg" -> msg.s.toUpperCase())
|
probe.ref ! s"mdc:${msg.s.toUpperCase()}"
|
||||||
}) {
|
Map("msg" -> msg.s.toUpperCase())
|
||||||
|
}) {
|
||||||
MultiProtocol(probe.ref)
|
MultiProtocol(probe.ref)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -66,14 +66,14 @@ class MailboxSelectorSpec extends ScalaTestWithActorTestKit("""
|
||||||
val latch = new CountDownLatch(1)
|
val latch = new CountDownLatch(1)
|
||||||
val probe = testKit.createTestProbe[String]()
|
val probe = testKit.createTestProbe[String]()
|
||||||
val actor = spawn(Behaviors.receiveMessage[String] {
|
val actor = spawn(Behaviors.receiveMessage[String] {
|
||||||
case "one" =>
|
case "one" =>
|
||||||
// block here so we can fill mailbox up
|
// block here so we can fill mailbox up
|
||||||
probe ! "blocking-on-one"
|
probe ! "blocking-on-one"
|
||||||
latch.await(10, TimeUnit.SECONDS)
|
latch.await(10, TimeUnit.SECONDS)
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
case _ =>
|
case _ =>
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
}, MailboxSelector.bounded(2))
|
}, MailboxSelector.bounded(2))
|
||||||
actor ! "one" // actor will block here
|
actor ! "one" // actor will block here
|
||||||
probe.expectMessage("blocking-on-one")
|
probe.expectMessage("blocking-on-one")
|
||||||
actor ! "two"
|
actor ! "two"
|
||||||
|
|
|
||||||
|
|
@ -160,14 +160,14 @@ class WatchSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with LogC
|
||||||
spawn(
|
spawn(
|
||||||
Behaviors.setup[Any] { context =>
|
Behaviors.setup[Any] { context =>
|
||||||
val middleManagement = context.spawn(Behaviors.setup[Any] { context =>
|
val middleManagement = context.spawn(Behaviors.setup[Any] { context =>
|
||||||
val sixPackJoe = context.spawn(Behaviors.receive[Any]((_, _) => throw ex), "joe")
|
val sixPackJoe = context.spawn(Behaviors.receive[Any]((_, _) => throw ex), "joe")
|
||||||
context.watch(sixPackJoe)
|
context.watch(sixPackJoe)
|
||||||
|
|
||||||
Behaviors.receive[Any] { (_, message) =>
|
Behaviors.receive[Any] { (_, message) =>
|
||||||
sixPackJoe ! message
|
sixPackJoe ! message
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
} // no handling of terminated, even though we watched!!!
|
} // no handling of terminated, even though we watched!!!
|
||||||
}, "middle-management")
|
}, "middle-management")
|
||||||
|
|
||||||
context.watch(middleManagement)
|
context.watch(middleManagement)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -103,7 +103,8 @@ 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 } else processed
|
if (seqNr == 1L) processed.filterNot { case (pid, _) => pid == producerId }
|
||||||
|
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)]")
|
||||||
|
|
|
||||||
|
|
@ -62,10 +62,11 @@ class ActorSystemSpec
|
||||||
|
|
||||||
"An ActorSystem" must {
|
"An ActorSystem" must {
|
||||||
"start the guardian actor and terminate when it terminates" in {
|
"start the guardian actor and terminate when it terminates" in {
|
||||||
withSystem("a", Behaviors.receiveMessage[Probe] { p =>
|
withSystem("a",
|
||||||
p.replyTo ! p.message
|
Behaviors.receiveMessage[Probe] { p =>
|
||||||
Behaviors.stopped
|
p.replyTo ! p.message
|
||||||
}, doTerminate = false) { sys =>
|
Behaviors.stopped
|
||||||
|
}, doTerminate = false) { sys =>
|
||||||
val inbox = TestInbox[String]("a")
|
val inbox = TestInbox[String]("a")
|
||||||
sys ! Probe("hello", inbox.ref)
|
sys ! Probe("hello", inbox.ref)
|
||||||
eventually {
|
eventually {
|
||||||
|
|
@ -92,13 +93,13 @@ class ActorSystemSpec
|
||||||
"terminate the guardian actor" in {
|
"terminate the guardian actor" in {
|
||||||
val inbox = TestInbox[String]("terminate")
|
val inbox = TestInbox[String]("terminate")
|
||||||
val sys = system(Behaviors.setup[Any] { _ =>
|
val sys = system(Behaviors.setup[Any] { _ =>
|
||||||
inbox.ref ! "started"
|
inbox.ref ! "started"
|
||||||
Behaviors.receiveSignal {
|
Behaviors.receiveSignal {
|
||||||
case (_, PostStop) =>
|
case (_, PostStop) =>
|
||||||
inbox.ref ! "done"
|
inbox.ref ! "done"
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
}
|
}
|
||||||
}, "terminate")
|
}, "terminate")
|
||||||
|
|
||||||
eventually {
|
eventually {
|
||||||
inbox.hasMessages should ===(true)
|
inbox.hasMessages should ===(true)
|
||||||
|
|
@ -114,8 +115,8 @@ class ActorSystemSpec
|
||||||
|
|
||||||
"be able to terminate immediately" in {
|
"be able to terminate immediately" in {
|
||||||
val sys = system(Behaviors.receiveMessage[Probe] { _ =>
|
val sys = system(Behaviors.receiveMessage[Probe] { _ =>
|
||||||
Behaviors.unhandled
|
Behaviors.unhandled
|
||||||
}, "terminate")
|
}, "terminate")
|
||||||
// for this case the guardian might not have been started before
|
// for this case the guardian might not have been started before
|
||||||
// the system terminates and then it will not receive PostStop, which
|
// the system terminates and then it will not receive PostStop, which
|
||||||
// is OK since it wasn't really started yet
|
// is OK since it wasn't really started yet
|
||||||
|
|
|
||||||
|
|
@ -72,10 +72,11 @@ class AdaptationFailureSpec extends ScalaTestWithActorTestKit with AnyWordSpecLi
|
||||||
val probe = createTestProbe[Any]()
|
val probe = createTestProbe[Any]()
|
||||||
val threw = Promise[Done]()
|
val threw = Promise[Done]()
|
||||||
val ref = spawn(Behaviors.setup[Any] { ctx =>
|
val ref = spawn(Behaviors.setup[Any] { ctx =>
|
||||||
val adapter = ctx.messageAdapter[Any](classOf[Any], { _ =>
|
val adapter = ctx.messageAdapter[Any](classOf[Any],
|
||||||
threw.success(Done)
|
{ _ =>
|
||||||
throw TestException("boom")
|
threw.success(Done)
|
||||||
})
|
throw TestException("boom")
|
||||||
|
})
|
||||||
adapter ! "go boom"
|
adapter ! "go boom"
|
||||||
behavior
|
behavior
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -44,9 +44,9 @@ class ActorContextAskSpec
|
||||||
case class Pong(selfName: String, threadName: String)
|
case class Pong(selfName: String, threadName: String)
|
||||||
|
|
||||||
val pingPong = spawn(Behaviors.receive[Ping] { (context, message) =>
|
val pingPong = spawn(Behaviors.receive[Ping] { (context, message) =>
|
||||||
message.sender ! Pong(context.self.path.name, Thread.currentThread().getName)
|
message.sender ! Pong(context.self.path.name, Thread.currentThread().getName)
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
}, "ping-pong", Props.empty.withDispatcherFromConfig("ping-pong-dispatcher"))
|
}, "ping-pong", Props.empty.withDispatcherFromConfig("ping-pong-dispatcher"))
|
||||||
|
|
||||||
val probe = TestProbe[Pong]()
|
val probe = TestProbe[Pong]()
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -119,43 +119,43 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit("""
|
||||||
}
|
}
|
||||||
|
|
||||||
"contain the class name where the first log was called" in {
|
"contain the class name where the first log was called" in {
|
||||||
val eventFilter = LoggingTestKit.custom({
|
val eventFilter = LoggingTestKit.custom {
|
||||||
case event if event.loggerName == classOf[ActorLoggingSpec].getName =>
|
case event if event.loggerName == classOf[ActorLoggingSpec].getName =>
|
||||||
true
|
true
|
||||||
case event =>
|
case event =>
|
||||||
println(event.loggerName)
|
println(event.loggerName)
|
||||||
false
|
false
|
||||||
})
|
}
|
||||||
|
|
||||||
eventFilter.expect(spawn(Behaviors.setup[String] { context =>
|
eventFilter.expect(spawn(Behaviors.setup[String] { context =>
|
||||||
context.log.info("Started")
|
context.log.info("Started")
|
||||||
|
|
||||||
Behaviors.receive { (context, message) =>
|
Behaviors.receive { (context, message) =>
|
||||||
context.log.info("got message {}", message)
|
context.log.info("got message {}", message)
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
}
|
}
|
||||||
}, "the-actor-with-class"))
|
}, "the-actor-with-class"))
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
"contain the object class name where the first log was called" in {
|
"contain the object class name where the first log was called" in {
|
||||||
val eventFilter = LoggingTestKit.custom({
|
val eventFilter = LoggingTestKit.custom {
|
||||||
case event if event.loggerName == WhereTheBehaviorIsDefined.getClass.getName => true
|
case event if event.loggerName == WhereTheBehaviorIsDefined.getClass.getName => true
|
||||||
case other =>
|
case other =>
|
||||||
println(other.loggerName)
|
println(other.loggerName)
|
||||||
false
|
false
|
||||||
})
|
}
|
||||||
|
|
||||||
eventFilter.expect(spawn(WhereTheBehaviorIsDefined.behavior, "the-actor-with-object"))
|
eventFilter.expect(spawn(WhereTheBehaviorIsDefined.behavior, "the-actor-with-object"))
|
||||||
}
|
}
|
||||||
|
|
||||||
"contain the abstract behavior class name where the first log was called" in {
|
"contain the abstract behavior class name where the first log was called" in {
|
||||||
val eventFilter = LoggingTestKit.custom({
|
val eventFilter = LoggingTestKit.custom {
|
||||||
case event if event.loggerName == classOf[BehaviorWhereTheLoggerIsUsed].getName => true
|
case event if event.loggerName == classOf[BehaviorWhereTheLoggerIsUsed].getName => true
|
||||||
case other =>
|
case other =>
|
||||||
println(other.loggerName)
|
println(other.loggerName)
|
||||||
false
|
false
|
||||||
})
|
}
|
||||||
|
|
||||||
eventFilter.expect {
|
eventFilter.expect {
|
||||||
spawn(Behaviors.setup[String](context => new BehaviorWhereTheLoggerIsUsed(context)), "the-actor-with-behavior")
|
spawn(Behaviors.setup[String](context => new BehaviorWhereTheLoggerIsUsed(context)), "the-actor-with-behavior")
|
||||||
|
|
@ -200,7 +200,7 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit("""
|
||||||
true // any is fine, we're just after the right count of statements reaching the listener
|
true // any is fine, we're just after the right count of statements reaching the listener
|
||||||
}
|
}
|
||||||
.withOccurrences(36)
|
.withOccurrences(36)
|
||||||
.expect({
|
.expect {
|
||||||
spawn(Behaviors.setup[String] {
|
spawn(Behaviors.setup[String] {
|
||||||
context =>
|
context =>
|
||||||
context.log.debug("message")
|
context.log.debug("message")
|
||||||
|
|
@ -247,7 +247,7 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit("""
|
||||||
|
|
||||||
Behaviors.stopped
|
Behaviors.stopped
|
||||||
})
|
})
|
||||||
})
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
"use Slf4jLogger from akka-slf4j automatically" in {
|
"use Slf4jLogger from akka-slf4j automatically" in {
|
||||||
|
|
@ -490,8 +490,7 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit("""
|
||||||
Map(
|
Map(
|
||||||
ActorMdc.AkkaAddressKey -> system.classicSystem.asInstanceOf[ExtendedActorSystem].provider.addressString,
|
ActorMdc.AkkaAddressKey -> system.classicSystem.asInstanceOf[ExtendedActorSystem].provider.addressString,
|
||||||
ActorMdc.AkkaSourceKey -> actorPath.get.toString,
|
ActorMdc.AkkaSourceKey -> actorPath.get.toString,
|
||||||
ActorMdc.SourceActorSystemKey -> system.name)
|
ActorMdc.SourceActorSystemKey -> system.name))
|
||||||
)
|
|
||||||
true
|
true
|
||||||
} catch {
|
} catch {
|
||||||
case ex: Throwable =>
|
case ex: Throwable =>
|
||||||
|
|
|
||||||
|
|
@ -23,16 +23,16 @@ final class GracefulStopSpec extends ScalaTestWithActorTestKit with AnyWordSpecL
|
||||||
val behavior =
|
val behavior =
|
||||||
Behaviors.setup[akka.NotUsed] { context =>
|
Behaviors.setup[akka.NotUsed] { context =>
|
||||||
context.spawn[NotUsed](Behaviors.receiveSignal {
|
context.spawn[NotUsed](Behaviors.receiveSignal {
|
||||||
case (_, PostStop) =>
|
case (_, PostStop) =>
|
||||||
probe.ref ! "child-done"
|
probe.ref ! "child-done"
|
||||||
Behaviors.stopped
|
Behaviors.stopped
|
||||||
}, "child1")
|
}, "child1")
|
||||||
|
|
||||||
context.spawn[NotUsed](Behaviors.receiveSignal {
|
context.spawn[NotUsed](Behaviors.receiveSignal {
|
||||||
case (_, PostStop) =>
|
case (_, PostStop) =>
|
||||||
probe.ref ! "child-done"
|
probe.ref ! "child-done"
|
||||||
Behaviors.stopped
|
Behaviors.stopped
|
||||||
}, "child2")
|
}, "child2")
|
||||||
|
|
||||||
Behaviors.stopped { () =>
|
Behaviors.stopped { () =>
|
||||||
// cleanup function body
|
// cleanup function body
|
||||||
|
|
|
||||||
|
|
@ -70,9 +70,9 @@ class MessageAdapterSpec
|
||||||
case class AnotherPong(selfName: String, threadName: String)
|
case class AnotherPong(selfName: String, threadName: String)
|
||||||
|
|
||||||
val pingPong = spawn(Behaviors.receive[Ping] { (context, message) =>
|
val pingPong = spawn(Behaviors.receive[Ping] { (context, message) =>
|
||||||
message.sender ! Pong(context.self.path.name, Thread.currentThread().getName)
|
message.sender ! Pong(context.self.path.name, Thread.currentThread().getName)
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
}, "ping-pong", Props.empty.withDispatcherFromConfig("ping-pong-dispatcher"))
|
}, "ping-pong", Props.empty.withDispatcherFromConfig("ping-pong-dispatcher"))
|
||||||
|
|
||||||
val probe = TestProbe[AnotherPong]()
|
val probe = TestProbe[AnotherPong]()
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -35,8 +35,8 @@ final class OnSignalSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike
|
||||||
def stopper(probe: TestProbe[Done], children: Int) = Behaviors.setup[String] { ctx =>
|
def stopper(probe: TestProbe[Done], children: Int) = Behaviors.setup[String] { ctx =>
|
||||||
(0 until children).foreach { i =>
|
(0 until children).foreach { i =>
|
||||||
ctx.spawn(Behaviors.receiveMessage[String] { _ =>
|
ctx.spawn(Behaviors.receiveMessage[String] { _ =>
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
}, s"$i")
|
}, s"$i")
|
||||||
}
|
}
|
||||||
Behaviors
|
Behaviors
|
||||||
.receiveMessagePartial[String] {
|
.receiveMessagePartial[String] {
|
||||||
|
|
|
||||||
|
|
@ -213,12 +213,12 @@ class AdapterSpec extends AnyWordSpec with Matchers with BeforeAndAfterAll with
|
||||||
var systemN: akka.actor.typed.ActorSystem[Done] = null
|
var systemN: akka.actor.typed.ActorSystem[Done] = null
|
||||||
try {
|
try {
|
||||||
systemN = ActorSystem.create(Behaviors.receive[Done] { (context, message) =>
|
systemN = ActorSystem.create(Behaviors.receive[Done] { (context, message) =>
|
||||||
context.self ! Done
|
context.self ! Done
|
||||||
message match {
|
message match {
|
||||||
case Done => Behaviors.stopped
|
case Done => Behaviors.stopped
|
||||||
}
|
}
|
||||||
|
|
||||||
}, "AdapterSpec-stopping-guardian-2")
|
}, "AdapterSpec-stopping-guardian-2")
|
||||||
|
|
||||||
} finally if (system != null) TestKit.shutdownActorSystem(systemN.toClassic)
|
} finally if (system != null) TestKit.shutdownActorSystem(systemN.toClassic)
|
||||||
}
|
}
|
||||||
|
|
@ -231,7 +231,7 @@ class AdapterSpec extends AnyWordSpec with Matchers with BeforeAndAfterAll with
|
||||||
}
|
}
|
||||||
|
|
||||||
"allow seamless access to untyped extensions" in {
|
"allow seamless access to untyped extensions" in {
|
||||||
SerializationExtension(typedSystem) should not be (null)
|
SerializationExtension(typedSystem) should not be null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,7 @@ import org.scalatest.wordspec.AnyWordSpecLike
|
||||||
|
|
||||||
object AggregatorSpec {
|
object AggregatorSpec {
|
||||||
object IllustrateUsage {
|
object IllustrateUsage {
|
||||||
//#usage
|
// #usage
|
||||||
object Hotel1 {
|
object Hotel1 {
|
||||||
final case class RequestQuote(replyTo: ActorRef[Quote])
|
final case class RequestQuote(replyTo: ActorRef[Quote])
|
||||||
final case class Quote(hotel: String, price: BigDecimal)
|
final case class Quote(hotel: String, price: BigDecimal)
|
||||||
|
|
@ -65,7 +65,7 @@ object AggregatorSpec {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#usage
|
// #usage
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -42,7 +42,7 @@ object DispatchersDocSpec {
|
||||||
val yourBehavior: Behavior[String] = Behaviors.same
|
val yourBehavior: Behavior[String] = Behaviors.same
|
||||||
|
|
||||||
val example = Behaviors.receive[Any] { (context, _) =>
|
val example = Behaviors.receive[Any] { (context, _) =>
|
||||||
//#spawn-dispatcher
|
// #spawn-dispatcher
|
||||||
import akka.actor.typed.DispatcherSelector
|
import akka.actor.typed.DispatcherSelector
|
||||||
|
|
||||||
context.spawn(yourBehavior, "DefaultDispatcher")
|
context.spawn(yourBehavior, "DefaultDispatcher")
|
||||||
|
|
@ -50,7 +50,7 @@ object DispatchersDocSpec {
|
||||||
context.spawn(yourBehavior, "BlockingDispatcher", DispatcherSelector.blocking())
|
context.spawn(yourBehavior, "BlockingDispatcher", DispatcherSelector.blocking())
|
||||||
context.spawn(yourBehavior, "ParentDispatcher", DispatcherSelector.sameAsParent())
|
context.spawn(yourBehavior, "ParentDispatcher", DispatcherSelector.sameAsParent())
|
||||||
context.spawn(yourBehavior, "DispatcherFromConfig", DispatcherSelector.fromConfig("your-dispatcher"))
|
context.spawn(yourBehavior, "DispatcherFromConfig", DispatcherSelector.fromConfig("your-dispatcher"))
|
||||||
//#spawn-dispatcher
|
// #spawn-dispatcher
|
||||||
|
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -16,10 +16,10 @@ import org.scalatest.wordspec.AnyWordSpecLike
|
||||||
|
|
||||||
object FSMDocSpec {
|
object FSMDocSpec {
|
||||||
|
|
||||||
//#simple-state
|
// #simple-state
|
||||||
//#simple-events
|
// #simple-events
|
||||||
object Buncher {
|
object Buncher {
|
||||||
//#simple-state
|
// #simple-state
|
||||||
|
|
||||||
// FSM event becomes the type of the message Actor supports
|
// FSM event becomes the type of the message Actor supports
|
||||||
sealed trait Event
|
sealed trait Event
|
||||||
|
|
@ -27,17 +27,17 @@ object FSMDocSpec {
|
||||||
final case class Queue(obj: Any) extends Event
|
final case class Queue(obj: Any) extends Event
|
||||||
case object Flush extends Event
|
case object Flush extends Event
|
||||||
private case object Timeout extends Event
|
private case object Timeout extends Event
|
||||||
//#simple-events
|
// #simple-events
|
||||||
|
|
||||||
//#storing-state
|
// #storing-state
|
||||||
sealed trait Data
|
sealed trait Data
|
||||||
case object Uninitialized extends Data
|
case object Uninitialized extends Data
|
||||||
final case class Todo(target: ActorRef[Batch], queue: immutable.Seq[Any]) extends Data
|
final case class Todo(target: ActorRef[Batch], queue: immutable.Seq[Any]) extends Data
|
||||||
|
|
||||||
final case class Batch(obj: immutable.Seq[Any])
|
final case class Batch(obj: immutable.Seq[Any])
|
||||||
//#storing-state
|
// #storing-state
|
||||||
|
|
||||||
//#simple-state
|
// #simple-state
|
||||||
// states of the FSM represented as behaviors
|
// states of the FSM represented as behaviors
|
||||||
|
|
||||||
// initial state
|
// initial state
|
||||||
|
|
@ -67,10 +67,10 @@ object FSMDocSpec {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//#simple-events
|
// #simple-events
|
||||||
}
|
}
|
||||||
//#simple-events
|
// #simple-events
|
||||||
//#simple-state
|
// #simple-state
|
||||||
}
|
}
|
||||||
|
|
||||||
class FSMDocSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with LogCapturing {
|
class FSMDocSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with LogCapturing {
|
||||||
|
|
|
||||||
|
|
@ -22,7 +22,7 @@ import akka.actor.testkit.typed.scaladsl.ScalaTestWithActorTestKit
|
||||||
|
|
||||||
object GracefulStopDocSpec {
|
object GracefulStopDocSpec {
|
||||||
|
|
||||||
//#master-actor
|
// #master-actor
|
||||||
|
|
||||||
object MasterControlProgram {
|
object MasterControlProgram {
|
||||||
sealed trait Command
|
sealed trait Command
|
||||||
|
|
@ -51,9 +51,9 @@ object GracefulStopDocSpec {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#master-actor
|
// #master-actor
|
||||||
|
|
||||||
//#worker-actor
|
// #worker-actor
|
||||||
|
|
||||||
object Job {
|
object Job {
|
||||||
sealed trait Command
|
sealed trait Command
|
||||||
|
|
@ -66,10 +66,10 @@ object GracefulStopDocSpec {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#worker-actor
|
// #worker-actor
|
||||||
|
|
||||||
object IllustrateWatch {
|
object IllustrateWatch {
|
||||||
//#master-actor-watch
|
// #master-actor-watch
|
||||||
|
|
||||||
object MasterControlProgram {
|
object MasterControlProgram {
|
||||||
sealed trait Command
|
sealed trait Command
|
||||||
|
|
@ -93,11 +93,11 @@ object GracefulStopDocSpec {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#master-actor-watch
|
// #master-actor-watch
|
||||||
}
|
}
|
||||||
|
|
||||||
object IllustrateWatchWith {
|
object IllustrateWatchWith {
|
||||||
//#master-actor-watchWith
|
// #master-actor-watchWith
|
||||||
|
|
||||||
object MasterControlProgram {
|
object MasterControlProgram {
|
||||||
sealed trait Command
|
sealed trait Command
|
||||||
|
|
@ -121,7 +121,7 @@ object GracefulStopDocSpec {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#master-actor-watchWith
|
// #master-actor-watchWith
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
@ -133,7 +133,7 @@ class GracefulStopDocSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike
|
||||||
"Graceful stop example" must {
|
"Graceful stop example" must {
|
||||||
|
|
||||||
"start some workers" in {
|
"start some workers" in {
|
||||||
//#start-workers
|
// #start-workers
|
||||||
import MasterControlProgram._
|
import MasterControlProgram._
|
||||||
|
|
||||||
val system: ActorSystem[Command] = ActorSystem(MasterControlProgram(), "B6700")
|
val system: ActorSystem[Command] = ActorSystem(MasterControlProgram(), "B6700")
|
||||||
|
|
@ -148,7 +148,7 @@ class GracefulStopDocSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike
|
||||||
system.terminate()
|
system.terminate()
|
||||||
|
|
||||||
Await.result(system.whenTerminated, 3.seconds)
|
Await.result(system.whenTerminated, 3.seconds)
|
||||||
//#start-workers
|
// #start-workers
|
||||||
}
|
}
|
||||||
|
|
||||||
"gracefully stop workers and master" in {
|
"gracefully stop workers and master" in {
|
||||||
|
|
|
||||||
|
|
@ -170,7 +170,7 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with AnyWordSpec
|
||||||
|
|
||||||
"contain a sample for scheduling messages to self" in {
|
"contain a sample for scheduling messages to self" in {
|
||||||
|
|
||||||
//#timer
|
// #timer
|
||||||
object Buncher {
|
object Buncher {
|
||||||
|
|
||||||
sealed trait Command
|
sealed trait Command
|
||||||
|
|
@ -214,7 +214,7 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with AnyWordSpec
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#timer
|
// #timer
|
||||||
|
|
||||||
val probe = createTestProbe[Buncher.Batch]()
|
val probe = createTestProbe[Buncher.Batch]()
|
||||||
val buncher: ActorRef[Buncher.Command] = spawn(Buncher(probe.ref, 1.second, 10))
|
val buncher: ActorRef[Buncher.Command] = spawn(Buncher(probe.ref, 1.second, 10))
|
||||||
|
|
@ -581,7 +581,7 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with AnyWordSpec
|
||||||
}
|
}
|
||||||
|
|
||||||
"contain a sample for pipeToSelf" in {
|
"contain a sample for pipeToSelf" in {
|
||||||
//#pipeToSelf
|
// #pipeToSelf
|
||||||
|
|
||||||
trait CustomerDataAccess {
|
trait CustomerDataAccess {
|
||||||
def update(value: Customer): Future[Done]
|
def update(value: Customer): Future[Done]
|
||||||
|
|
@ -632,7 +632,7 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with AnyWordSpec
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#pipeToSelf
|
// #pipeToSelf
|
||||||
|
|
||||||
val dataAccess = new CustomerDataAccess {
|
val dataAccess = new CustomerDataAccess {
|
||||||
override def update(value: Customer): Future[Done] = Future.successful(Done)
|
override def update(value: Customer): Future[Done] = Future.successful(Done)
|
||||||
|
|
|
||||||
|
|
@ -109,7 +109,7 @@ object IntroSpec {
|
||||||
|
|
||||||
final case class SayHello(name: String)
|
final case class SayHello(name: String)
|
||||||
|
|
||||||
//#hello-world-main-with-dispatchers
|
// #hello-world-main-with-dispatchers
|
||||||
def apply(): Behavior[SayHello] =
|
def apply(): Behavior[SayHello] =
|
||||||
Behaviors.setup { context =>
|
Behaviors.setup { context =>
|
||||||
val dispatcherPath = "akka.actor.default-blocking-io-dispatcher"
|
val dispatcherPath = "akka.actor.default-blocking-io-dispatcher"
|
||||||
|
|
@ -124,21 +124,21 @@ object IntroSpec {
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#hello-world-main-with-dispatchers
|
// #hello-world-main-with-dispatchers
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//#chatroom-protocol
|
// #chatroom-protocol
|
||||||
//#chatroom-behavior
|
// #chatroom-behavior
|
||||||
object ChatRoom {
|
object ChatRoom {
|
||||||
//#chatroom-behavior
|
// #chatroom-behavior
|
||||||
sealed trait RoomCommand
|
sealed trait RoomCommand
|
||||||
final case class GetSession(screenName: String, replyTo: ActorRef[SessionEvent]) extends RoomCommand
|
final case class GetSession(screenName: String, replyTo: ActorRef[SessionEvent]) extends RoomCommand
|
||||||
//#chatroom-protocol
|
// #chatroom-protocol
|
||||||
//#chatroom-behavior
|
// #chatroom-behavior
|
||||||
private final case class PublishSessionMessage(screenName: String, message: String) extends RoomCommand
|
private final case class PublishSessionMessage(screenName: String, message: String) extends RoomCommand
|
||||||
//#chatroom-behavior
|
// #chatroom-behavior
|
||||||
//#chatroom-protocol
|
// #chatroom-protocol
|
||||||
|
|
||||||
sealed trait SessionEvent
|
sealed trait SessionEvent
|
||||||
final case class SessionGranted(handle: ActorRef[PostMessage]) extends SessionEvent
|
final case class SessionGranted(handle: ActorRef[PostMessage]) extends SessionEvent
|
||||||
|
|
@ -148,8 +148,8 @@ object IntroSpec {
|
||||||
sealed trait SessionCommand
|
sealed trait SessionCommand
|
||||||
final case class PostMessage(message: String) extends SessionCommand
|
final case class PostMessage(message: String) extends SessionCommand
|
||||||
private final case class NotifyClient(message: MessagePosted) extends SessionCommand
|
private final case class NotifyClient(message: MessagePosted) extends SessionCommand
|
||||||
//#chatroom-protocol
|
// #chatroom-protocol
|
||||||
//#chatroom-behavior
|
// #chatroom-behavior
|
||||||
|
|
||||||
def apply(): Behavior[RoomCommand] =
|
def apply(): Behavior[RoomCommand] =
|
||||||
chatRoom(List.empty)
|
chatRoom(List.empty)
|
||||||
|
|
@ -185,24 +185,24 @@ object IntroSpec {
|
||||||
client ! message
|
client ! message
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
}
|
}
|
||||||
//#chatroom-protocol
|
// #chatroom-protocol
|
||||||
}
|
}
|
||||||
//#chatroom-behavior
|
// #chatroom-behavior
|
||||||
//#chatroom-protocol
|
// #chatroom-protocol
|
||||||
|
|
||||||
//#chatroom-gabbler
|
// #chatroom-gabbler
|
||||||
object Gabbler {
|
object Gabbler {
|
||||||
import ChatRoom._
|
import ChatRoom._
|
||||||
|
|
||||||
def apply(): Behavior[SessionEvent] =
|
def apply(): Behavior[SessionEvent] =
|
||||||
Behaviors.setup { context =>
|
Behaviors.setup { context =>
|
||||||
Behaviors.receiveMessage {
|
Behaviors.receiveMessage {
|
||||||
//#chatroom-gabbler
|
// #chatroom-gabbler
|
||||||
// We document that the compiler warns about the missing handler for `SessionDenied`
|
// We document that the compiler warns about the missing handler for `SessionDenied`
|
||||||
case SessionDenied(reason) =>
|
case SessionDenied(reason) =>
|
||||||
context.log.info("cannot start chat room session: {}", reason)
|
context.log.info("cannot start chat room session: {}", reason)
|
||||||
Behaviors.stopped
|
Behaviors.stopped
|
||||||
//#chatroom-gabbler
|
// #chatroom-gabbler
|
||||||
case SessionGranted(handle) =>
|
case SessionGranted(handle) =>
|
||||||
handle ! PostMessage("Hello World!")
|
handle ! PostMessage("Hello World!")
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
|
|
@ -212,9 +212,9 @@ object IntroSpec {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#chatroom-gabbler
|
// #chatroom-gabbler
|
||||||
|
|
||||||
//#chatroom-main
|
// #chatroom-main
|
||||||
object Main {
|
object Main {
|
||||||
def apply(): Behavior[NotUsed] =
|
def apply(): Behavior[NotUsed] =
|
||||||
Behaviors.setup { context =>
|
Behaviors.setup { context =>
|
||||||
|
|
@ -234,7 +234,7 @@ object IntroSpec {
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
//#chatroom-main
|
// #chatroom-main
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -244,7 +244,7 @@ class IntroSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with LogC
|
||||||
|
|
||||||
"Intro sample" must {
|
"Intro sample" must {
|
||||||
"say hello" in {
|
"say hello" in {
|
||||||
//#hello-world
|
// #hello-world
|
||||||
|
|
||||||
val system: ActorSystem[HelloWorldMain.SayHello] =
|
val system: ActorSystem[HelloWorldMain.SayHello] =
|
||||||
ActorSystem(HelloWorldMain(), "hello")
|
ActorSystem(HelloWorldMain(), "hello")
|
||||||
|
|
@ -252,7 +252,7 @@ class IntroSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with LogC
|
||||||
system ! HelloWorldMain.SayHello("World")
|
system ! HelloWorldMain.SayHello("World")
|
||||||
system ! HelloWorldMain.SayHello("Akka")
|
system ! HelloWorldMain.SayHello("Akka")
|
||||||
|
|
||||||
//#hello-world
|
// #hello-world
|
||||||
|
|
||||||
Thread.sleep(500) // it will not fail if too short
|
Thread.sleep(500) // it will not fail if too short
|
||||||
ActorTestKit.shutdown(system)
|
ActorTestKit.shutdown(system)
|
||||||
|
|
|
||||||
|
|
@ -26,14 +26,14 @@ object LoggingDocExamples {
|
||||||
|
|
||||||
def howToUse(): Unit = {
|
def howToUse(): Unit = {
|
||||||
|
|
||||||
//#context-log
|
// #context-log
|
||||||
Behaviors.receive[String] { (context, message) =>
|
Behaviors.receive[String] { (context, message) =>
|
||||||
context.log.info("Received message: {}", message)
|
context.log.info("Received message: {}", message)
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
}
|
}
|
||||||
//#context-log
|
// #context-log
|
||||||
|
|
||||||
//#logger-name
|
// #logger-name
|
||||||
Behaviors.setup[String] { context =>
|
Behaviors.setup[String] { context =>
|
||||||
context.setLoggerName("com.myservice.BackendManager")
|
context.setLoggerName("com.myservice.BackendManager")
|
||||||
context.log.info("Starting up")
|
context.log.info("Starting up")
|
||||||
|
|
@ -43,9 +43,9 @@ object LoggingDocExamples {
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#logger-name
|
// #logger-name
|
||||||
|
|
||||||
//#logger-factory
|
// #logger-factory
|
||||||
val log = LoggerFactory.getLogger("com.myservice.BackendTask")
|
val log = LoggerFactory.getLogger("com.myservice.BackendTask")
|
||||||
|
|
||||||
Future {
|
Future {
|
||||||
|
|
@ -55,21 +55,21 @@ object LoggingDocExamples {
|
||||||
case Success(result) => log.info("Task completed: {}", result)
|
case Success(result) => log.info("Task completed: {}", result)
|
||||||
case Failure(exc) => log.error("Task failed", exc)
|
case Failure(exc) => log.error("Task failed", exc)
|
||||||
}
|
}
|
||||||
//#logger-factory
|
// #logger-factory
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
def placeholders(): Unit = {
|
def placeholders(): Unit = {
|
||||||
//#info2
|
// #info2
|
||||||
import akka.actor.typed.scaladsl.LoggerOps
|
import akka.actor.typed.scaladsl.LoggerOps
|
||||||
|
|
||||||
Behaviors.receive[String] { (context, message) =>
|
Behaviors.receive[String] { (context, message) =>
|
||||||
context.log.info2("{} received message: {}", context.self.path.name, message)
|
context.log.info2("{} received message: {}", context.self.path.name, message)
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
}
|
}
|
||||||
//#info2
|
// #info2
|
||||||
|
|
||||||
//#infoN
|
// #infoN
|
||||||
import akka.actor.typed.scaladsl.LoggerOps
|
import akka.actor.typed.scaladsl.LoggerOps
|
||||||
|
|
||||||
Behaviors.receive[String] { (context, message) =>
|
Behaviors.receive[String] { (context, message) =>
|
||||||
|
|
@ -80,23 +80,23 @@ object LoggingDocExamples {
|
||||||
message.take(10))
|
message.take(10))
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
}
|
}
|
||||||
//#infoN
|
// #infoN
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
def logMessages(): Unit = {
|
def logMessages(): Unit = {
|
||||||
//#logMessages
|
// #logMessages
|
||||||
import akka.actor.typed.LogOptions
|
import akka.actor.typed.LogOptions
|
||||||
import org.slf4j.event.Level
|
import org.slf4j.event.Level
|
||||||
|
|
||||||
Behaviors.logMessages(LogOptions().withLevel(Level.TRACE), BackendManager())
|
Behaviors.logMessages(LogOptions().withLevel(Level.TRACE), BackendManager())
|
||||||
//#logMessages
|
// #logMessages
|
||||||
}
|
}
|
||||||
|
|
||||||
def withMdc(): Unit = {
|
def withMdc(): Unit = {
|
||||||
val system: ActorSystem[_] = ???
|
val system: ActorSystem[_] = ???
|
||||||
|
|
||||||
//#withMdc
|
// #withMdc
|
||||||
val staticMdc = Map("startTime" -> system.startTime.toString)
|
val staticMdc = Map("startTime" -> system.startTime.toString)
|
||||||
Behaviors.withMdc[BackendManager.Command](
|
Behaviors.withMdc[BackendManager.Command](
|
||||||
staticMdc,
|
staticMdc,
|
||||||
|
|
@ -104,7 +104,7 @@ object LoggingDocExamples {
|
||||||
(msg: BackendManager.Command) => Map("identifier" -> msg.identifier, "upTime" -> system.uptime.toString)) {
|
(msg: BackendManager.Command) => Map("identifier" -> msg.identifier, "upTime" -> system.uptime.toString)) {
|
||||||
BackendManager()
|
BackendManager()
|
||||||
}
|
}
|
||||||
//#withMdc
|
// #withMdc
|
||||||
}
|
}
|
||||||
|
|
||||||
def logging(): Unit = {
|
def logging(): Unit = {
|
||||||
|
|
@ -112,18 +112,18 @@ object LoggingDocExamples {
|
||||||
final case class Message(s: String)
|
final case class Message(s: String)
|
||||||
val ref: ActorRef[Message] = ???
|
val ref: ActorRef[Message] = ???
|
||||||
|
|
||||||
//#test-logging
|
// #test-logging
|
||||||
import akka.actor.testkit.typed.scaladsl.LoggingTestKit
|
import akka.actor.testkit.typed.scaladsl.LoggingTestKit
|
||||||
|
|
||||||
// implicit ActorSystem is needed, but that is given by ScalaTestWithActorTestKit
|
// implicit ActorSystem is needed, but that is given by ScalaTestWithActorTestKit
|
||||||
//implicit val system: ActorSystem[_]
|
// implicit val system: ActorSystem[_]
|
||||||
|
|
||||||
LoggingTestKit.info("Received message").expect {
|
LoggingTestKit.info("Received message").expect {
|
||||||
ref ! Message("hello")
|
ref ! Message("hello")
|
||||||
}
|
}
|
||||||
//#test-logging
|
// #test-logging
|
||||||
|
|
||||||
//#test-logging-criteria
|
// #test-logging-criteria
|
||||||
LoggingTestKit
|
LoggingTestKit
|
||||||
.error[IllegalArgumentException]
|
.error[IllegalArgumentException]
|
||||||
.withMessageRegex(".*was rejected.*expecting ascii input.*")
|
.withMessageRegex(".*was rejected.*expecting ascii input.*")
|
||||||
|
|
@ -138,15 +138,15 @@ object LoggingDocExamples {
|
||||||
ref ! Message("hellö")
|
ref ! Message("hellö")
|
||||||
ref ! Message("hejdå")
|
ref ! Message("hejdå")
|
||||||
}
|
}
|
||||||
//#test-logging-criteria
|
// #test-logging-criteria
|
||||||
}
|
}
|
||||||
|
|
||||||
def tagsExample(): Unit = {
|
def tagsExample(): Unit = {
|
||||||
Behaviors.setup[AnyRef] { context =>
|
Behaviors.setup[AnyRef] { context =>
|
||||||
val myBehavior = Behaviors.empty[AnyRef]
|
val myBehavior = Behaviors.empty[AnyRef]
|
||||||
//#tags
|
// #tags
|
||||||
context.spawn(myBehavior, "MyActor", ActorTags("processing"))
|
context.spawn(myBehavior, "MyActor", ActorTags("processing"))
|
||||||
//#tags
|
// #tags
|
||||||
Behaviors.stopped
|
Behaviors.stopped
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -22,17 +22,17 @@ import org.scalatest.wordspec.AnyWordSpecLike
|
||||||
|
|
||||||
object OOIntroSpec {
|
object OOIntroSpec {
|
||||||
|
|
||||||
//#chatroom-protocol
|
// #chatroom-protocol
|
||||||
//#chatroom-behavior
|
// #chatroom-behavior
|
||||||
object ChatRoom {
|
object ChatRoom {
|
||||||
//#chatroom-behavior
|
// #chatroom-behavior
|
||||||
sealed trait RoomCommand
|
sealed trait RoomCommand
|
||||||
final case class GetSession(screenName: String, replyTo: ActorRef[SessionEvent]) extends RoomCommand
|
final case class GetSession(screenName: String, replyTo: ActorRef[SessionEvent]) extends RoomCommand
|
||||||
//#chatroom-protocol
|
// #chatroom-protocol
|
||||||
//#chatroom-behavior
|
// #chatroom-behavior
|
||||||
private final case class PublishSessionMessage(screenName: String, message: String) extends RoomCommand
|
private final case class PublishSessionMessage(screenName: String, message: String) extends RoomCommand
|
||||||
//#chatroom-behavior
|
// #chatroom-behavior
|
||||||
//#chatroom-protocol
|
// #chatroom-protocol
|
||||||
|
|
||||||
sealed trait SessionEvent
|
sealed trait SessionEvent
|
||||||
final case class SessionGranted(handle: ActorRef[PostMessage]) extends SessionEvent
|
final case class SessionGranted(handle: ActorRef[PostMessage]) extends SessionEvent
|
||||||
|
|
@ -42,8 +42,8 @@ object OOIntroSpec {
|
||||||
sealed trait SessionCommand
|
sealed trait SessionCommand
|
||||||
final case class PostMessage(message: String) extends SessionCommand
|
final case class PostMessage(message: String) extends SessionCommand
|
||||||
private final case class NotifyClient(message: MessagePosted) extends SessionCommand
|
private final case class NotifyClient(message: MessagePosted) extends SessionCommand
|
||||||
//#chatroom-protocol
|
// #chatroom-protocol
|
||||||
//#chatroom-behavior
|
// #chatroom-behavior
|
||||||
|
|
||||||
def apply(): Behavior[RoomCommand] =
|
def apply(): Behavior[RoomCommand] =
|
||||||
Behaviors.setup(context => new ChatRoomBehavior(context))
|
Behaviors.setup(context => new ChatRoomBehavior(context))
|
||||||
|
|
@ -96,12 +96,12 @@ object OOIntroSpec {
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#chatroom-protocol
|
// #chatroom-protocol
|
||||||
}
|
}
|
||||||
//#chatroom-protocol
|
// #chatroom-protocol
|
||||||
//#chatroom-behavior
|
// #chatroom-behavior
|
||||||
|
|
||||||
//#chatroom-gabbler
|
// #chatroom-gabbler
|
||||||
object Gabbler {
|
object Gabbler {
|
||||||
import ChatRoom._
|
import ChatRoom._
|
||||||
|
|
||||||
|
|
@ -119,10 +119,10 @@ object OOIntroSpec {
|
||||||
Behaviors.stopped
|
Behaviors.stopped
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#chatroom-gabbler
|
// #chatroom-gabbler
|
||||||
}
|
}
|
||||||
|
|
||||||
//#chatroom-main
|
// #chatroom-main
|
||||||
object Main {
|
object Main {
|
||||||
def apply(): Behavior[NotUsed] =
|
def apply(): Behavior[NotUsed] =
|
||||||
Behaviors.setup { context =>
|
Behaviors.setup { context =>
|
||||||
|
|
@ -142,7 +142,7 @@ object OOIntroSpec {
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
//#chatroom-main
|
// #chatroom-main
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -33,7 +33,7 @@ object RouterSpec {
|
||||||
|
|
||||||
// #routee
|
// #routee
|
||||||
|
|
||||||
//intentionally out of the routee section
|
// intentionally out of the routee section
|
||||||
class DoBroadcastLog(text: String) extends Worker.DoLog(text)
|
class DoBroadcastLog(text: String) extends Worker.DoLog(text)
|
||||||
object DoBroadcastLog {
|
object DoBroadcastLog {
|
||||||
def apply(text: String) = new DoBroadcastLog(text)
|
def apply(text: String) = new DoBroadcastLog(text)
|
||||||
|
|
@ -93,17 +93,17 @@ class RouterSpec extends ScalaTestWithActorTestKit("akka.loglevel=warning") with
|
||||||
|
|
||||||
val alternativeRouter = ctx.spawn(alternativePool, "alternative-pool")
|
val alternativeRouter = ctx.spawn(alternativePool, "alternative-pool")
|
||||||
alternativeRouter ! Worker.DoLog("msg")
|
alternativeRouter ! Worker.DoLog("msg")
|
||||||
//#pool
|
// #pool
|
||||||
|
|
||||||
// #broadcast
|
// #broadcast
|
||||||
val poolWithBroadcast = pool.withBroadcastPredicate(_.isInstanceOf[DoBroadcastLog])
|
val poolWithBroadcast = pool.withBroadcastPredicate(_.isInstanceOf[DoBroadcastLog])
|
||||||
val routerWithBroadcast = ctx.spawn(poolWithBroadcast, "pool-with-broadcast")
|
val routerWithBroadcast = ctx.spawn(poolWithBroadcast, "pool-with-broadcast")
|
||||||
//this will be sent to all 4 routees
|
// this will be sent to all 4 routees
|
||||||
routerWithBroadcast ! DoBroadcastLog("msg")
|
routerWithBroadcast ! DoBroadcastLog("msg")
|
||||||
Behaviors.empty
|
Behaviors.empty
|
||||||
// #broadcast
|
// #broadcast
|
||||||
}
|
}
|
||||||
//#pool
|
// #pool
|
||||||
)
|
)
|
||||||
|
|
||||||
probe.receiveMessages(15)
|
probe.receiveMessages(15)
|
||||||
|
|
@ -164,17 +164,17 @@ class RouterSpec extends ScalaTestWithActorTestKit("akka.loglevel=warning") with
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//registering proxies
|
// registering proxies
|
||||||
val proxy1 = spawn(Proxy(probe1.ref))
|
val proxy1 = spawn(Proxy(probe1.ref))
|
||||||
val proxy2 = spawn(Proxy(probe2.ref))
|
val proxy2 = spawn(Proxy(probe2.ref))
|
||||||
val waiterProbe = createTestProbe[Receptionist.Registered]()
|
val waiterProbe = createTestProbe[Receptionist.Registered]()
|
||||||
|
|
||||||
system.receptionist ! Receptionist.Register(Proxy.RegisteringKey, proxy1, waiterProbe.ref)
|
system.receptionist ! Receptionist.Register(Proxy.RegisteringKey, proxy1, waiterProbe.ref)
|
||||||
system.receptionist ! Receptionist.Register(Proxy.RegisteringKey, proxy2, waiterProbe.ref)
|
system.receptionist ! Receptionist.Register(Proxy.RegisteringKey, proxy2, waiterProbe.ref)
|
||||||
//wait until both registrations get Receptionist.Registered
|
// wait until both registrations get Receptionist.Registered
|
||||||
waiterProbe.receiveMessages(2)
|
waiterProbe.receiveMessages(2)
|
||||||
|
|
||||||
//messages sent to a router with consistent hashing
|
// messages sent to a router with consistent hashing
|
||||||
// #consistent-hashing
|
// #consistent-hashing
|
||||||
val router = spawn(Routers.group(Proxy.RegisteringKey).withConsistentHashingRouting(10, Proxy.mapping))
|
val router = spawn(Routers.group(Proxy.RegisteringKey).withConsistentHashingRouting(10, Proxy.mapping))
|
||||||
|
|
||||||
|
|
@ -185,8 +185,8 @@ class RouterSpec extends ScalaTestWithActorTestKit("akka.loglevel=warning") with
|
||||||
router ! Proxy.Message("zh3", "Text4")
|
router ! Proxy.Message("zh3", "Text4")
|
||||||
// the hash is calculated over the Proxy.Message first parameter obtained through the Proxy.mapping function
|
// the hash is calculated over the Proxy.Message first parameter obtained through the Proxy.mapping function
|
||||||
// #consistent-hashing
|
// #consistent-hashing
|
||||||
//Then messages with equal Message.id reach the same actor
|
// Then messages with equal Message.id reach the same actor
|
||||||
//so the first message in each probe queue is equal to its second
|
// so the first message in each probe queue is equal to its second
|
||||||
probe1.receiveMessage() shouldBe probe1.receiveMessage()
|
probe1.receiveMessage() shouldBe probe1.receiveMessage()
|
||||||
probe2.receiveMessage() shouldBe probe2.receiveMessage()
|
probe2.receiveMessage() shouldBe probe2.receiveMessage()
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -34,7 +34,7 @@ object SpawnProtocolDocSpec {
|
||||||
|
|
||||||
// Silent because we want to name the unused 'context' parameter
|
// Silent because we want to name the unused 'context' parameter
|
||||||
@nowarn("msg=never used")
|
@nowarn("msg=never used")
|
||||||
//#main
|
// #main
|
||||||
object HelloWorldMain {
|
object HelloWorldMain {
|
||||||
def apply(): Behavior[SpawnProtocol.Command] =
|
def apply(): Behavior[SpawnProtocol.Command] =
|
||||||
Behaviors.setup { context =>
|
Behaviors.setup { context =>
|
||||||
|
|
@ -44,7 +44,7 @@ object SpawnProtocolDocSpec {
|
||||||
SpawnProtocol()
|
SpawnProtocol()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#main
|
// #main
|
||||||
}
|
}
|
||||||
|
|
||||||
class SpawnProtocolDocSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with LogCapturing {
|
class SpawnProtocolDocSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with LogCapturing {
|
||||||
|
|
@ -53,7 +53,7 @@ class SpawnProtocolDocSpec extends ScalaTestWithActorTestKit with AnyWordSpecLik
|
||||||
|
|
||||||
"ActorSystem with SpawnProtocol" must {
|
"ActorSystem with SpawnProtocol" must {
|
||||||
"be able to spawn actors" in {
|
"be able to spawn actors" in {
|
||||||
//#system-spawn
|
// #system-spawn
|
||||||
|
|
||||||
implicit val system: ActorSystem[SpawnProtocol.Command] =
|
implicit val system: ActorSystem[SpawnProtocol.Command] =
|
||||||
ActorSystem(HelloWorldMain(), "hello")
|
ActorSystem(HelloWorldMain(), "hello")
|
||||||
|
|
@ -78,7 +78,7 @@ class SpawnProtocolDocSpec extends ScalaTestWithActorTestKit with AnyWordSpecLik
|
||||||
greeterRef ! HelloWorld.Greet("Akka", replyToRef)
|
greeterRef ! HelloWorld.Greet("Akka", replyToRef)
|
||||||
}
|
}
|
||||||
|
|
||||||
//#system-spawn
|
// #system-spawn
|
||||||
|
|
||||||
Thread.sleep(500) // it will not fail if too short
|
Thread.sleep(500) // it will not fail if too short
|
||||||
ActorTestKit.shutdown(system)
|
ActorTestKit.shutdown(system)
|
||||||
|
|
|
||||||
|
|
@ -31,15 +31,15 @@ object StyleGuideDocExamples {
|
||||||
|
|
||||||
object FunctionalStyle {
|
object FunctionalStyle {
|
||||||
|
|
||||||
//#fun-style
|
// #fun-style
|
||||||
|
|
||||||
//#messages
|
// #messages
|
||||||
object Counter {
|
object Counter {
|
||||||
sealed trait Command
|
sealed trait Command
|
||||||
case object Increment extends Command
|
case object Increment extends Command
|
||||||
final case class GetValue(replyTo: ActorRef[Value]) extends Command
|
final case class GetValue(replyTo: ActorRef[Value]) extends Command
|
||||||
final case class Value(n: Int)
|
final case class Value(n: Int)
|
||||||
//#messages
|
// #messages
|
||||||
|
|
||||||
def apply(): Behavior[Command] =
|
def apply(): Behavior[Command] =
|
||||||
counter(0)
|
counter(0)
|
||||||
|
|
@ -56,16 +56,16 @@ object StyleGuideDocExamples {
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#messages
|
// #messages
|
||||||
}
|
}
|
||||||
//#messages
|
// #messages
|
||||||
//#fun-style
|
// #fun-style
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
object OOStyle {
|
object OOStyle {
|
||||||
|
|
||||||
//#oo-style
|
// #oo-style
|
||||||
|
|
||||||
object Counter {
|
object Counter {
|
||||||
sealed trait Command
|
sealed trait Command
|
||||||
|
|
@ -95,7 +95,7 @@ object StyleGuideDocExamples {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#oo-style
|
// #oo-style
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -270,7 +270,7 @@ object StyleGuideDocExamples {
|
||||||
}
|
}
|
||||||
|
|
||||||
object FactoryMethod {
|
object FactoryMethod {
|
||||||
//#behavior-factory-method
|
// #behavior-factory-method
|
||||||
object CountDown {
|
object CountDown {
|
||||||
sealed trait Command
|
sealed trait Command
|
||||||
case object Down extends Command
|
case object Down extends Command
|
||||||
|
|
@ -284,7 +284,7 @@ object StyleGuideDocExamples {
|
||||||
import CountDown._
|
import CountDown._
|
||||||
|
|
||||||
private def counter(remaining: Int): Behavior[Command] = {
|
private def counter(remaining: Int): Behavior[Command] = {
|
||||||
//#exhastivness-check
|
// #exhastivness-check
|
||||||
Behaviors.receiveMessage {
|
Behaviors.receiveMessage {
|
||||||
case Down =>
|
case Down =>
|
||||||
if (remaining == 1) {
|
if (remaining == 1) {
|
||||||
|
|
@ -293,28 +293,28 @@ object StyleGuideDocExamples {
|
||||||
} else
|
} else
|
||||||
counter(remaining - 1)
|
counter(remaining - 1)
|
||||||
}
|
}
|
||||||
//#exhastivness-check
|
// #exhastivness-check
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
//#behavior-factory-method
|
// #behavior-factory-method
|
||||||
|
|
||||||
object Usage {
|
object Usage {
|
||||||
val context: ActorContext[_] = ???
|
val context: ActorContext[_] = ???
|
||||||
val doneRef: ActorRef[Done] = ???
|
val doneRef: ActorRef[Done] = ???
|
||||||
|
|
||||||
//#behavior-factory-method-spawn
|
// #behavior-factory-method-spawn
|
||||||
val countDown = context.spawn(CountDown(100, doneRef), "countDown")
|
val countDown = context.spawn(CountDown(100, doneRef), "countDown")
|
||||||
//#behavior-factory-method-spawn
|
// #behavior-factory-method-spawn
|
||||||
|
|
||||||
//#message-prefix-in-tell
|
// #message-prefix-in-tell
|
||||||
countDown ! CountDown.Down
|
countDown ! CountDown.Down
|
||||||
//#message-prefix-in-tell
|
// #message-prefix-in-tell
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
object Messages {
|
object Messages {
|
||||||
//#message-protocol
|
// #message-protocol
|
||||||
object CounterProtocol {
|
object CounterProtocol {
|
||||||
sealed trait Command
|
sealed trait Command
|
||||||
|
|
||||||
|
|
@ -325,11 +325,11 @@ object StyleGuideDocExamples {
|
||||||
case object Confirmed extends OperationResult
|
case object Confirmed extends OperationResult
|
||||||
final case class Rejected(reason: String) extends OperationResult
|
final case class Rejected(reason: String) extends OperationResult
|
||||||
}
|
}
|
||||||
//#message-protocol
|
// #message-protocol
|
||||||
}
|
}
|
||||||
|
|
||||||
object PublicVsPrivateMessages1 {
|
object PublicVsPrivateMessages1 {
|
||||||
//#public-private-messages-1
|
// #public-private-messages-1
|
||||||
object Counter {
|
object Counter {
|
||||||
sealed trait Command
|
sealed trait Command
|
||||||
case object Increment extends Command
|
case object Increment extends Command
|
||||||
|
|
@ -366,11 +366,11 @@ object StyleGuideDocExamples {
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#public-private-messages-1
|
// #public-private-messages-1
|
||||||
}
|
}
|
||||||
|
|
||||||
object PublicVsPrivateMessages2 {
|
object PublicVsPrivateMessages2 {
|
||||||
//#public-private-messages-2
|
// #public-private-messages-2
|
||||||
// above example is preferred, but this is possible and not wrong
|
// above example is preferred, but this is possible and not wrong
|
||||||
object Counter {
|
object Counter {
|
||||||
// The type of all public and private messages the Counter actor handles
|
// The type of all public and private messages the Counter actor handles
|
||||||
|
|
@ -417,7 +417,7 @@ object StyleGuideDocExamples {
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#public-private-messages-2
|
// #public-private-messages-2
|
||||||
}
|
}
|
||||||
|
|
||||||
object Ask {
|
object Ask {
|
||||||
|
|
@ -425,7 +425,7 @@ object StyleGuideDocExamples {
|
||||||
|
|
||||||
implicit val system: ActorSystem[Nothing] = ???
|
implicit val system: ActorSystem[Nothing] = ???
|
||||||
|
|
||||||
//#ask-1
|
// #ask-1
|
||||||
import akka.actor.typed.scaladsl.AskPattern._
|
import akka.actor.typed.scaladsl.AskPattern._
|
||||||
import akka.util.Timeout
|
import akka.util.Timeout
|
||||||
|
|
||||||
|
|
@ -433,11 +433,11 @@ object StyleGuideDocExamples {
|
||||||
val counter: ActorRef[Command] = ???
|
val counter: ActorRef[Command] = ???
|
||||||
|
|
||||||
val result: Future[OperationResult] = counter.ask(replyTo => Increment(delta = 2, replyTo))
|
val result: Future[OperationResult] = counter.ask(replyTo => Increment(delta = 2, replyTo))
|
||||||
//#ask-1
|
// #ask-1
|
||||||
|
|
||||||
//#ask-2
|
// #ask-2
|
||||||
val result2: Future[OperationResult] = counter.ask(Increment(delta = 2, _))
|
val result2: Future[OperationResult] = counter.ask(Increment(delta = 2, _))
|
||||||
//#ask-2
|
// #ask-2
|
||||||
|
|
||||||
/*
|
/*
|
||||||
//#ask-3
|
//#ask-3
|
||||||
|
|
@ -446,26 +446,26 @@ object StyleGuideDocExamples {
|
||||||
//#ask-3
|
//#ask-3
|
||||||
*/
|
*/
|
||||||
|
|
||||||
//#ask-4
|
// #ask-4
|
||||||
val result3: Future[OperationResult] = counter ? (Increment(delta = 2, _))
|
val result3: Future[OperationResult] = counter ? (Increment(delta = 2, _))
|
||||||
//#ask-4
|
// #ask-4
|
||||||
}
|
}
|
||||||
|
|
||||||
object ExhaustivenessCheck {
|
object ExhaustivenessCheck {
|
||||||
|
|
||||||
object CountDown {
|
object CountDown {
|
||||||
//#messages-sealed
|
// #messages-sealed
|
||||||
sealed trait Command
|
sealed trait Command
|
||||||
case object Down extends Command
|
case object Down extends Command
|
||||||
final case class GetValue(replyTo: ActorRef[Value]) extends Command
|
final case class GetValue(replyTo: ActorRef[Value]) extends Command
|
||||||
final case class Value(n: Int)
|
final case class Value(n: Int)
|
||||||
//#messages-sealed
|
// #messages-sealed
|
||||||
}
|
}
|
||||||
|
|
||||||
class CountDown() {
|
class CountDown() {
|
||||||
import CountDown._
|
import CountDown._
|
||||||
|
|
||||||
//#pattern-match-unhandled
|
// #pattern-match-unhandled
|
||||||
val zero: Behavior[Command] = {
|
val zero: Behavior[Command] = {
|
||||||
Behaviors.receiveMessage {
|
Behaviors.receiveMessage {
|
||||||
case GetValue(replyTo) =>
|
case GetValue(replyTo) =>
|
||||||
|
|
@ -475,11 +475,11 @@ object StyleGuideDocExamples {
|
||||||
Behaviors.unhandled
|
Behaviors.unhandled
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#pattern-match-unhandled
|
// #pattern-match-unhandled
|
||||||
|
|
||||||
@nowarn
|
@nowarn
|
||||||
object partial {
|
object partial {
|
||||||
//#pattern-match-partial
|
// #pattern-match-partial
|
||||||
val zero: Behavior[Command] = {
|
val zero: Behavior[Command] = {
|
||||||
Behaviors.receiveMessagePartial {
|
Behaviors.receiveMessagePartial {
|
||||||
case GetValue(replyTo) =>
|
case GetValue(replyTo) =>
|
||||||
|
|
@ -487,7 +487,7 @@ object StyleGuideDocExamples {
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#pattern-match-partial
|
// #pattern-match-partial
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
@ -495,22 +495,22 @@ object StyleGuideDocExamples {
|
||||||
|
|
||||||
object BehaviorCompositionWithPartialFunction {
|
object BehaviorCompositionWithPartialFunction {
|
||||||
|
|
||||||
//#messages-sealed-composition
|
// #messages-sealed-composition
|
||||||
sealed trait Command
|
sealed trait Command
|
||||||
case object Down extends Command
|
case object Down extends Command
|
||||||
final case class GetValue(replyTo: ActorRef[Value]) extends Command
|
final case class GetValue(replyTo: ActorRef[Value]) extends Command
|
||||||
final case class Value(n: Int)
|
final case class Value(n: Int)
|
||||||
//#messages-sealed-composition
|
// #messages-sealed-composition
|
||||||
|
|
||||||
//#get-handler-partial
|
// #get-handler-partial
|
||||||
def getHandler(value: Int): PartialFunction[Command, Behavior[Command]] = {
|
def getHandler(value: Int): PartialFunction[Command, Behavior[Command]] = {
|
||||||
case GetValue(replyTo) =>
|
case GetValue(replyTo) =>
|
||||||
replyTo ! Value(value)
|
replyTo ! Value(value)
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
}
|
}
|
||||||
//#get-handler-partial
|
// #get-handler-partial
|
||||||
|
|
||||||
//#set-handler-non-zero-partial
|
// #set-handler-non-zero-partial
|
||||||
def setHandlerNotZero(value: Int): PartialFunction[Command, Behavior[Command]] = {
|
def setHandlerNotZero(value: Int): PartialFunction[Command, Behavior[Command]] = {
|
||||||
case Down =>
|
case Down =>
|
||||||
if (value == 1)
|
if (value == 1)
|
||||||
|
|
@ -518,17 +518,17 @@ object StyleGuideDocExamples {
|
||||||
else
|
else
|
||||||
nonZero(value - 1)
|
nonZero(value - 1)
|
||||||
}
|
}
|
||||||
//#set-handler-non-zero-partial
|
// #set-handler-non-zero-partial
|
||||||
|
|
||||||
//#set-handler-zero-partial
|
// #set-handler-zero-partial
|
||||||
def setHandlerZero(log: Logger): PartialFunction[Command, Behavior[Command]] = {
|
def setHandlerZero(log: Logger): PartialFunction[Command, Behavior[Command]] = {
|
||||||
case Down =>
|
case Down =>
|
||||||
log.error("Counter is already at zero!")
|
log.error("Counter is already at zero!")
|
||||||
Behaviors.same
|
Behaviors.same
|
||||||
}
|
}
|
||||||
//#set-handler-zero-partial
|
// #set-handler-zero-partial
|
||||||
|
|
||||||
//#top-level-behaviors-partial
|
// #top-level-behaviors-partial
|
||||||
val zero: Behavior[Command] = Behaviors.setup { context =>
|
val zero: Behavior[Command] = Behaviors.setup { context =>
|
||||||
Behaviors.receiveMessagePartial(getHandler(0).orElse(setHandlerZero(context.log)))
|
Behaviors.receiveMessagePartial(getHandler(0).orElse(setHandlerZero(context.log)))
|
||||||
}
|
}
|
||||||
|
|
@ -538,13 +538,13 @@ object StyleGuideDocExamples {
|
||||||
|
|
||||||
// Default Initial Behavior for this actor
|
// Default Initial Behavior for this actor
|
||||||
def apply(initialCapacity: Int): Behavior[Command] = nonZero(initialCapacity)
|
def apply(initialCapacity: Int): Behavior[Command] = nonZero(initialCapacity)
|
||||||
//#top-level-behaviors-partial
|
// #top-level-behaviors-partial
|
||||||
}
|
}
|
||||||
|
|
||||||
object NestingSample1 {
|
object NestingSample1 {
|
||||||
sealed trait Command
|
sealed trait Command
|
||||||
|
|
||||||
//#nesting
|
// #nesting
|
||||||
def apply(): Behavior[Command] =
|
def apply(): Behavior[Command] =
|
||||||
Behaviors.setup[Command](context =>
|
Behaviors.setup[Command](context =>
|
||||||
Behaviors.withStash(100)(stash =>
|
Behaviors.withStash(100)(stash =>
|
||||||
|
|
@ -552,19 +552,19 @@ object StyleGuideDocExamples {
|
||||||
context.log.debug("Starting up")
|
context.log.debug("Starting up")
|
||||||
|
|
||||||
// behavior using context, stash and timers ...
|
// behavior using context, stash and timers ...
|
||||||
//#nesting
|
// #nesting
|
||||||
timers.isTimerActive("aa")
|
timers.isTimerActive("aa")
|
||||||
stash.isEmpty
|
stash.isEmpty
|
||||||
Behaviors.empty
|
Behaviors.empty
|
||||||
//#nesting
|
// #nesting
|
||||||
}))
|
}))
|
||||||
//#nesting
|
// #nesting
|
||||||
}
|
}
|
||||||
|
|
||||||
object NestingSample2 {
|
object NestingSample2 {
|
||||||
sealed trait Command
|
sealed trait Command
|
||||||
|
|
||||||
//#nesting-supervise
|
// #nesting-supervise
|
||||||
def apply(): Behavior[Command] =
|
def apply(): Behavior[Command] =
|
||||||
Behaviors.setup { context =>
|
Behaviors.setup { context =>
|
||||||
// only run on initial actor start, not on crash-restart
|
// only run on initial actor start, not on crash-restart
|
||||||
|
|
@ -575,13 +575,13 @@ object StyleGuideDocExamples {
|
||||||
// every time the actor crashes and restarts a new stash is created (previous stash is lost)
|
// every time the actor crashes and restarts a new stash is created (previous stash is lost)
|
||||||
context.log.debug("Starting up with stash")
|
context.log.debug("Starting up with stash")
|
||||||
// Behaviors.receiveMessage { ... }
|
// Behaviors.receiveMessage { ... }
|
||||||
//#nesting-supervise
|
// #nesting-supervise
|
||||||
stash.isEmpty
|
stash.isEmpty
|
||||||
Behaviors.empty
|
Behaviors.empty
|
||||||
//#nesting-supervise
|
// #nesting-supervise
|
||||||
})
|
})
|
||||||
.onFailure[RuntimeException](SupervisorStrategy.restart)
|
.onFailure[RuntimeException](SupervisorStrategy.restart)
|
||||||
}
|
}
|
||||||
//#nesting-supervise
|
// #nesting-supervise
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -26,7 +26,7 @@ object ClassicWatchingTypedSpec {
|
||||||
def props() = classic.Props(new Classic)
|
def props() = classic.Props(new Classic)
|
||||||
}
|
}
|
||||||
|
|
||||||
//#classic-watch
|
// #classic-watch
|
||||||
class Classic extends classic.Actor with ActorLogging {
|
class Classic extends classic.Actor with ActorLogging {
|
||||||
// context.spawn is an implicit extension method
|
// context.spawn is an implicit extension method
|
||||||
val second: ActorRef[Typed.Command] =
|
val second: ActorRef[Typed.Command] =
|
||||||
|
|
@ -51,9 +51,9 @@ object ClassicWatchingTypedSpec {
|
||||||
context.stop(self)
|
context.stop(self)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#classic-watch
|
// #classic-watch
|
||||||
|
|
||||||
//#typed
|
// #typed
|
||||||
object Typed {
|
object Typed {
|
||||||
sealed trait Command
|
sealed trait Command
|
||||||
final case class Ping(replyTo: ActorRef[Pong.type]) extends Command
|
final case class Ping(replyTo: ActorRef[Pong.type]) extends Command
|
||||||
|
|
@ -70,7 +70,7 @@ object ClassicWatchingTypedSpec {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#typed
|
// #typed
|
||||||
}
|
}
|
||||||
|
|
||||||
class ClassicWatchingTypedSpec extends AnyWordSpec with LogCapturing {
|
class ClassicWatchingTypedSpec extends AnyWordSpec with LogCapturing {
|
||||||
|
|
@ -80,9 +80,9 @@ class ClassicWatchingTypedSpec extends AnyWordSpec with LogCapturing {
|
||||||
"Classic -> Typed" must {
|
"Classic -> Typed" must {
|
||||||
"support creating, watching and messaging" in {
|
"support creating, watching and messaging" in {
|
||||||
val system = classic.ActorSystem("Coexistence")
|
val system = classic.ActorSystem("Coexistence")
|
||||||
//#create-classic
|
// #create-classic
|
||||||
val classicActor = system.actorOf(Classic.props())
|
val classicActor = system.actorOf(Classic.props())
|
||||||
//#create-classic
|
// #create-classic
|
||||||
val probe = TestProbe()(system)
|
val probe = TestProbe()(system)
|
||||||
probe.watch(classicActor)
|
probe.watch(classicActor)
|
||||||
probe.expectTerminated(classicActor, 200.millis)
|
probe.expectTerminated(classicActor, 200.millis)
|
||||||
|
|
@ -90,11 +90,11 @@ class ClassicWatchingTypedSpec extends AnyWordSpec with LogCapturing {
|
||||||
}
|
}
|
||||||
|
|
||||||
"support converting a classic actor system to an actor system" in {
|
"support converting a classic actor system to an actor system" in {
|
||||||
//#convert-classic
|
// #convert-classic
|
||||||
|
|
||||||
val system = akka.actor.ActorSystem("ClassicToTypedSystem")
|
val system = akka.actor.ActorSystem("ClassicToTypedSystem")
|
||||||
val typedSystem: ActorSystem[Nothing] = system.toTyped
|
val typedSystem: ActorSystem[Nothing] = system.toTyped
|
||||||
//#convert-classic
|
// #convert-classic
|
||||||
typedSystem.scheduler // remove compile warning
|
typedSystem.scheduler // remove compile warning
|
||||||
TestKit.shutdownActorSystem(system)
|
TestKit.shutdownActorSystem(system)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,7 @@ import scala.concurrent.duration._
|
||||||
|
|
||||||
object TypedWatchingClassicSpec {
|
object TypedWatchingClassicSpec {
|
||||||
|
|
||||||
//#typed
|
// #typed
|
||||||
object Typed {
|
object Typed {
|
||||||
final case class Ping(replyTo: akka.actor.typed.ActorRef[Pong.type])
|
final case class Ping(replyTo: akka.actor.typed.ActorRef[Pong.type])
|
||||||
sealed trait Command
|
sealed trait Command
|
||||||
|
|
@ -52,9 +52,9 @@ object TypedWatchingClassicSpec {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#typed
|
// #typed
|
||||||
|
|
||||||
//#classic
|
// #classic
|
||||||
object Classic {
|
object Classic {
|
||||||
def props(): classic.Props = classic.Props(new Classic)
|
def props(): classic.Props = classic.Props(new Classic)
|
||||||
}
|
}
|
||||||
|
|
@ -64,7 +64,7 @@ object TypedWatchingClassicSpec {
|
||||||
replyTo ! Typed.Pong
|
replyTo ! Typed.Pong
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#classic
|
// #classic
|
||||||
}
|
}
|
||||||
|
|
||||||
class TypedWatchingClassicSpec extends AnyWordSpec with LogCapturing {
|
class TypedWatchingClassicSpec extends AnyWordSpec with LogCapturing {
|
||||||
|
|
@ -73,10 +73,10 @@ class TypedWatchingClassicSpec extends AnyWordSpec with LogCapturing {
|
||||||
|
|
||||||
"Typed -> Classic" must {
|
"Typed -> Classic" must {
|
||||||
"support creating, watching and messaging" in {
|
"support creating, watching and messaging" in {
|
||||||
//#create
|
// #create
|
||||||
val system = classic.ActorSystem("TypedWatchingClassic")
|
val system = classic.ActorSystem("TypedWatchingClassic")
|
||||||
val typed = system.spawn(Typed.behavior, "Typed")
|
val typed = system.spawn(Typed.behavior, "Typed")
|
||||||
//#create
|
// #create
|
||||||
val probe = TestProbe()(system)
|
val probe = TestProbe()(system)
|
||||||
probe.watch(typed.toClassic)
|
probe.watch(typed.toClassic)
|
||||||
probe.expectTerminated(typed.toClassic, 200.millis)
|
probe.expectTerminated(typed.toClassic, 200.millis)
|
||||||
|
|
|
||||||
|
|
@ -51,10 +51,10 @@ object ExtensionDocSpec {
|
||||||
|
|
||||||
val initialBehavior: Behavior[Any] = Behaviors.empty[Any]
|
val initialBehavior: Behavior[Any] = Behaviors.empty[Any]
|
||||||
|
|
||||||
//#usage
|
// #usage
|
||||||
Behaviors.setup[Any] { ctx =>
|
Behaviors.setup[Any] { ctx =>
|
||||||
DatabasePool(ctx.system).connection().executeQuery("insert into...")
|
DatabasePool(ctx.system).connection().executeQuery("insert into...")
|
||||||
initialBehavior
|
initialBehavior
|
||||||
}
|
}
|
||||||
//#usage
|
// #usage
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,7 @@ import akka.actor.Props
|
||||||
|
|
||||||
object ClassicSample {
|
object ClassicSample {
|
||||||
|
|
||||||
//#hello-world-actor
|
// #hello-world-actor
|
||||||
object HelloWorld {
|
object HelloWorld {
|
||||||
final case class Greet(whom: String)
|
final case class Greet(whom: String)
|
||||||
final case class Greeted(whom: String)
|
final case class Greeted(whom: String)
|
||||||
|
|
@ -27,11 +27,11 @@ object ClassicSample {
|
||||||
|
|
||||||
override def receive: Receive = {
|
override def receive: Receive = {
|
||||||
case Greet(whom) =>
|
case Greet(whom) =>
|
||||||
//#fiddle_code
|
// #fiddle_code
|
||||||
log.info("Hello {}!", whom)
|
log.info("Hello {}!", whom)
|
||||||
sender() ! Greeted(whom)
|
sender() ! Greeted(whom)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#hello-world-actor
|
// #hello-world-actor
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,7 @@ import akka.actor.typed.scaladsl.Behaviors
|
||||||
|
|
||||||
object TypedSample {
|
object TypedSample {
|
||||||
|
|
||||||
//#hello-world-actor
|
// #hello-world-actor
|
||||||
object HelloWorld {
|
object HelloWorld {
|
||||||
final case class Greet(whom: String, replyTo: ActorRef[Greeted])
|
final case class Greet(whom: String, replyTo: ActorRef[Greeted])
|
||||||
final case class Greeted(whom: String, from: ActorRef[Greet])
|
final case class Greeted(whom: String, from: ActorRef[Greet])
|
||||||
|
|
@ -33,9 +33,9 @@ object TypedSample {
|
||||||
this
|
this
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#hello-world-actor
|
// #hello-world-actor
|
||||||
|
|
||||||
//#children
|
// #children
|
||||||
object Parent {
|
object Parent {
|
||||||
sealed trait Command
|
sealed trait Command
|
||||||
case class DelegateToChild(name: String, message: Child.Command) extends Command
|
case class DelegateToChild(name: String, message: Child.Command) extends Command
|
||||||
|
|
@ -66,7 +66,7 @@ object TypedSample {
|
||||||
updated(Map.empty)
|
updated(Map.empty)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//#children
|
// #children
|
||||||
|
|
||||||
object Child {
|
object Child {
|
||||||
sealed trait Command
|
sealed trait Command
|
||||||
|
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue