Merge branch master into bs-iterators

Resolved Conflicts:
	akka-actor/src/main/scala/akka/util/ByteString.scala
This commit is contained in:
Oliver Schulz 2012-07-01 17:29:12 +02:00
commit 777addc66c
515 changed files with 24722 additions and 18241 deletions

View file

@ -1,180 +0,0 @@
/**
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.docs.serialization
import org.scalatest.matchers.MustMatchers
import akka.testkit._
import akka.actor.{ ActorRef, ActorSystem }
//#imports
import akka.serialization._
import com.typesafe.config.ConfigFactory
//#imports
//#my-own-serializer
class MyOwnSerializer extends Serializer {
// This is whether "fromBinary" requires a "clazz" or not
def includeManifest: Boolean = false
// Pick a unique identifier for your Serializer,
// you've got a couple of billions to choose from,
// 0 - 16 is reserved by Akka itself
def identifier = 1234567
// "toBinary" serializes the given object to an Array of Bytes
def toBinary(obj: AnyRef): Array[Byte] = {
// Put the code that serializes the object here
//#...
Array[Byte]()
//#...
}
// "fromBinary" deserializes the given array,
// using the type hint (if any, see "includeManifest" above)
// into the optionally provided classLoader.
def fromBinary(bytes: Array[Byte],
clazz: Option[Class[_]]): AnyRef = {
// Put your code that deserializes here
//#...
null
//#...
}
}
//#my-own-serializer
trait MyOwnSerializable
case class Customer(name: String) extends MyOwnSerializable
class SerializationDocSpec extends AkkaSpec {
"demonstrate configuration of serialize messages" in {
//#serialize-messages-config
val config = ConfigFactory.parseString("""
akka {
actor {
serialize-messages = on
}
}
""")
//#serialize-messages-config
val a = ActorSystem("system", config)
a.settings.SerializeAllMessages must be(true)
a.shutdown()
}
"demonstrate configuration of serialize creators" in {
//#serialize-creators-config
val config = ConfigFactory.parseString("""
akka {
actor {
serialize-creators = on
}
}
""")
//#serialize-creators-config
val a = ActorSystem("system", config)
a.settings.SerializeAllCreators must be(true)
a.shutdown()
}
"demonstrate configuration of serializers" in {
//#serialize-serializers-config
val config = ConfigFactory.parseString("""
akka {
actor {
serializers {
java = "akka.serialization.JavaSerializer"
proto = "akka.serialization.ProtobufSerializer"
myown = "akka.docs.serialization.MyOwnSerializer"
}
}
}
""")
//#serialize-serializers-config
val a = ActorSystem("system", config)
a.shutdown()
}
"demonstrate configuration of serialization-bindings" in {
//#serialization-bindings-config
val config = ConfigFactory.parseString("""
akka {
actor {
serializers {
java = "akka.serialization.JavaSerializer"
proto = "akka.serialization.ProtobufSerializer"
myown = "akka.docs.serialization.MyOwnSerializer"
}
serialization-bindings {
"java.lang.String" = java
"akka.docs.serialization.Customer" = java
"com.google.protobuf.Message" = proto
"akka.docs.serialization.MyOwnSerializable" = myown
"java.lang.Boolean" = myown
}
}
}
""")
//#serialization-bindings-config
val a = ActorSystem("system", config)
SerializationExtension(a).serializerFor(classOf[String]).getClass must equal(classOf[JavaSerializer])
SerializationExtension(a).serializerFor(classOf[Customer]).getClass must equal(classOf[JavaSerializer])
SerializationExtension(a).serializerFor(classOf[java.lang.Boolean]).getClass must equal(classOf[MyOwnSerializer])
a.shutdown()
}
"demonstrate the programmatic API" in {
//#programmatic
val system = ActorSystem("example")
// Get the Serialization Extension
val serialization = SerializationExtension(system)
// Have something to serialize
val original = "woohoo"
// Find the Serializer for it
val serializer = serialization.findSerializerFor(original)
// Turn it into bytes
val bytes = serializer.toBinary(original)
// Turn it back into an object
val back = serializer.fromBinary(bytes, manifest = None)
// Voilá!
back must equal(original)
//#programmatic
system.shutdown()
}
"demonstrate serialization of ActorRefs" in {
val theActorRef: ActorRef = system.deadLetters
val theActorSystem: ActorSystem = system
//#actorref-serializer
// Serialize
// (beneath toBinary)
// If there is no transportAddress,
// it means that either this Serializer isn't called
// within a piece of code that sets it,
// so either you need to supply your own,
// or simply use the local path.
val identifier: String = Serialization.currentTransportAddress.value match {
case null theActorRef.path.toString
case address theActorRef.path.toStringWithAddress(address)
}
// Then just serialize the identifier however you like
// Deserialize
// (beneath fromBinary)
val deserializedActorRef = theActorSystem actorFor identifier
// Then just use the ActorRef
//#actorref-serializer
}
}

View file

@ -1,7 +1,7 @@
/**
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.docs.actor
package docs.actor
//#imports1
import akka.actor.Actor
@ -326,14 +326,13 @@ class ActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
//#gracefulStop
import akka.pattern.gracefulStop
import akka.dispatch.Await
import akka.actor.ActorTimeoutException
try {
val stopped: Future[Boolean] = gracefulStop(actorRef, 5 seconds)(system)
Await.result(stopped, 6 seconds)
// the actor has been stopped
} catch {
case e: ActorTimeoutException // the actor wasn't stopped within 5 seconds
case e: akka.pattern.AskTimeoutException // the actor wasn't stopped within 5 seconds
}
//#gracefulStop
}

View file

@ -1,7 +1,7 @@
/**
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.docs.actor
package docs.actor
//#test-code
import akka.testkit.AkkaSpec

View file

@ -1,7 +1,7 @@
/**
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.docs.actor
package docs.actor
//#all
//#imports

View file

@ -1,7 +1,7 @@
/**
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.docs.actor
package docs.actor
//#testkit
import akka.testkit.{ AkkaSpec, ImplicitSender, EventFilter }
@ -111,7 +111,7 @@ class FaultHandlingDocSpec extends AkkaSpec with ImplicitSender {
//#stop
watch(child) // have testActor watch child
child ! new IllegalArgumentException // break it
expectMsg(Terminated(child))
expectMsg(Terminated(child)(existenceConfirmed = true))
child.isTerminated must be(true)
//#stop
}
@ -125,7 +125,7 @@ class FaultHandlingDocSpec extends AkkaSpec with ImplicitSender {
expectMsg(0)
child2 ! new Exception("CRASH") // escalate failure
expectMsg(Terminated(child2))
expectMsg(Terminated(child2)(existenceConfirmed = true))
//#escalate-kill
//#escalate-restart
val supervisor2 = system.actorOf(Props[Supervisor2], "supervisor2")

View file

@ -1,7 +1,7 @@
/**
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.docs.actor
package docs.actor
//#imports1
import akka.actor.Actor

View file

@ -1,7 +1,7 @@
/**
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.docs.actor
package docs.actor
//#imports
import akka.dispatch.{ Promise, Future, Await }
@ -151,6 +151,18 @@ class TypedActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
//#typed-actor-remote
}
"create hierarchies" in {
try {
//#typed-actor-hierarchy
//Inside your Typed Actor
val childSquarer: Squarer = TypedActor(TypedActor.context).typedActorOf(TypedProps[SquarerImpl]())
//Use "childSquarer" as a Squarer
//#typed-actor-hierarchy
} catch {
case e: Exception //ignore
}
}
"supercharge" in {
//#typed-actor-supercharge-usage
val awesomeFooBar: Foo with Bar = TypedActor(system).typedActorOf(TypedProps[FooBar]())

View file

@ -1,7 +1,7 @@
/**
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.docs.actor
package docs.actor
import akka.actor._
import scala.collection.mutable.ListBuffer

View file

@ -1,7 +1,7 @@
/**
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.docs.agent
package docs.agent
import akka.agent.Agent
import akka.util.duration._

View file

@ -1,4 +1,4 @@
package akka.docs.camel
package docs.camel
object Consumers {
{

View file

@ -1,4 +1,4 @@
package akka.docs.camel
package docs.camel
object Introduction {
{

View file

@ -1,7 +1,7 @@
/**
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.docs.dispatcher
package docs.dispatcher
import org.scalatest.{ BeforeAndAfterAll, WordSpec }
import org.scalatest.matchers.MustMatchers
@ -91,13 +91,13 @@ object DispatcherDocSpec {
//#prio-dispatcher-config
prio-dispatcher {
mailbox-type = "akka.docs.dispatcher.DispatcherDocSpec$MyPrioMailbox"
mailbox-type = "docs.dispatcher.DispatcherDocSpec$MyPrioMailbox"
}
//#prio-dispatcher-config
//#prio-dispatcher-config-java
prio-dispatcher-java {
mailbox-type = "akka.docs.dispatcher.DispatcherDocTestBase$MyPrioMailbox"
mailbox-type = "docs.dispatcher.DispatcherDocTestBase$MyPrioMailbox"
//Other dispatcher configuration goes here
}
//#prio-dispatcher-config-java
@ -134,8 +134,8 @@ object DispatcherDocSpec {
}
//#mailbox-implementation-example
case class MyUnboundedMailbox() extends akka.dispatch.MailboxType {
import akka.actor.ActorContext
class MyUnboundedMailbox extends akka.dispatch.MailboxType {
import akka.actor.{ ActorRef, ActorSystem }
import com.typesafe.config.Config
import java.util.concurrent.ConcurrentLinkedQueue
import akka.dispatch.{
@ -149,12 +149,12 @@ object DispatcherDocSpec {
def this(settings: ActorSystem.Settings, config: Config) = this()
// The create method is called to create the MessageQueue
final override def create(owner: Option[ActorContext]): MessageQueue =
final override def create(owner: Option[ActorRef], system: Option[ActorSystem]): MessageQueue =
new QueueBasedMessageQueue with UnboundedMessageQueueSemantics {
final val queue = new ConcurrentLinkedQueue[Envelope]()
}
//#mailbox-implementation-example
}
//#mailbox-implementation-example
}
class DispatcherDocSpec extends AkkaSpec(DispatcherDocSpec.config) {

View file

@ -1,7 +1,7 @@
/**
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.docs.event
package docs.event
import akka.testkit.AkkaSpec
import akka.actor.Actor

View file

@ -1,7 +1,7 @@
/**
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.docs.extension
package docs.extension
import java.util.concurrent.atomic.AtomicLong
import akka.actor.Actor
@ -45,7 +45,7 @@ object ExtensionDocSpec {
val config = """
//#config
akka {
extensions = ["akka.docs.extension.CountExtension$"]
extensions = ["docs.extension.CountExtension$"]
}
//#config
"""

View file

@ -1,7 +1,7 @@
/**
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.docs.extension
package docs.extension
//#imports
import akka.actor.Extension

View file

@ -1,7 +1,7 @@
/**
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.docs.future
package docs.future
import org.scalatest.{ BeforeAndAfterAll, WordSpec }
import org.scalatest.matchers.MustMatchers

View file

@ -1,7 +1,7 @@
/**
* Copyright (C) 2009-2011 Typesafe Inc. <http://www.typesafe.com>
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.docs.io
package docs.io
//#imports
import akka.actor._

View file

@ -0,0 +1,16 @@
/**
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
package docs.pattern
// this part will not appear in the docs
//#all-of-it
class ScalaTemplate {
println("Hello, Template!")
//#uninteresting-stuff
// dont show this plumbimg
//#uninteresting-stuff
}
//#all-of-it

View file

@ -1,7 +1,7 @@
/**
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.docs.remoting
package docs.remoting
import akka.actor.{ ExtendedActorSystem, ActorSystem, Actor, ActorRef }
import akka.testkit.{ AkkaSpec, ImplicitSender }

View file

@ -1,7 +1,7 @@
/**
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.docs.routing
package docs.routing
import RouterDocSpec.MyActor
import akka.actor.{ Props, Actor }

View file

@ -1,7 +1,7 @@
/**
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.docs.routing
package docs.routing
import akka.routing.{ ScatterGatherFirstCompletedRouter, BroadcastRouter, RandomRouter, RoundRobinRouter }
import annotation.tailrec

View file

@ -1,7 +1,7 @@
/**
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.docs.routing
package docs.routing
import akka.actor.{ Actor, Props, ActorSystem }
import com.typesafe.config.ConfigFactory

View file

@ -1,7 +1,7 @@
/**
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.docs.routing
package docs.routing
import akka.routing.RoundRobinRouter
import akka.actor.{ ActorRef, Props, Actor, ActorSystem }
@ -29,7 +29,7 @@ object RoutingProgrammaticallyExample extends App {
val actor2 = system.actorOf(Props[ExampleActor1])
val actor3 = system.actorOf(Props[ExampleActor1])
val routees = Vector[ActorRef](actor1, actor2, actor3)
val router2 = system.actorOf(Props[ExampleActor1].withRouter(
val router2 = system.actorOf(Props().withRouter(
RoundRobinRouter(routees = routees)))
//#programmaticRoutingRoutees
1 to 6 foreach { i router2 ! Message1(i) }

View file

@ -0,0 +1,227 @@
/**
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
//#extract-transport
package object akka {
// needs to be inside the akka package because accessing unsupported API !
def transportOf(system: actor.ExtendedActorSystem): remote.RemoteTransport =
system.provider match {
case r: remote.RemoteActorRefProvider r.transport
case _
throw new UnsupportedOperationException(
"this method requires the RemoteActorRefProvider to be configured")
}
}
//#extract-transport
package docs.serialization {
import org.scalatest.matchers.MustMatchers
import akka.testkit._
//#imports
import akka.actor.{ ActorRef, ActorSystem }
import akka.serialization._
import com.typesafe.config.ConfigFactory
//#imports
import akka.actor.ExtensionKey
import akka.actor.ExtendedActorSystem
import akka.actor.Extension
import akka.actor.Address
import akka.remote.RemoteActorRefProvider
//#my-own-serializer
class MyOwnSerializer extends Serializer {
// This is whether "fromBinary" requires a "clazz" or not
def includeManifest: Boolean = false
// Pick a unique identifier for your Serializer,
// you've got a couple of billions to choose from,
// 0 - 16 is reserved by Akka itself
def identifier = 1234567
// "toBinary" serializes the given object to an Array of Bytes
def toBinary(obj: AnyRef): Array[Byte] = {
// Put the code that serializes the object here
//#...
Array[Byte]()
//#...
}
// "fromBinary" deserializes the given array,
// using the type hint (if any, see "includeManifest" above)
// into the optionally provided classLoader.
def fromBinary(bytes: Array[Byte],
clazz: Option[Class[_]]): AnyRef = {
// Put your code that deserializes here
//#...
null
//#...
}
}
//#my-own-serializer
trait MyOwnSerializable
case class Customer(name: String) extends MyOwnSerializable
class SerializationDocSpec extends AkkaSpec {
"demonstrate configuration of serialize messages" in {
//#serialize-messages-config
val config = ConfigFactory.parseString("""
akka {
actor {
serialize-messages = on
}
}
""")
//#serialize-messages-config
val a = ActorSystem("system", config)
a.settings.SerializeAllMessages must be(true)
a.shutdown()
}
"demonstrate configuration of serialize creators" in {
//#serialize-creators-config
val config = ConfigFactory.parseString("""
akka {
actor {
serialize-creators = on
}
}
""")
//#serialize-creators-config
val a = ActorSystem("system", config)
a.settings.SerializeAllCreators must be(true)
a.shutdown()
}
"demonstrate configuration of serializers" in {
//#serialize-serializers-config
val config = ConfigFactory.parseString("""
akka {
actor {
serializers {
java = "akka.serialization.JavaSerializer"
proto = "akka.serialization.ProtobufSerializer"
myown = "docs.serialization.MyOwnSerializer"
}
}
}
""")
//#serialize-serializers-config
val a = ActorSystem("system", config)
a.shutdown()
}
"demonstrate configuration of serialization-bindings" in {
//#serialization-bindings-config
val config = ConfigFactory.parseString("""
akka {
actor {
serializers {
java = "akka.serialization.JavaSerializer"
proto = "akka.serialization.ProtobufSerializer"
myown = "docs.serialization.MyOwnSerializer"
}
serialization-bindings {
"java.lang.String" = java
"docs.serialization.Customer" = java
"com.google.protobuf.Message" = proto
"docs.serialization.MyOwnSerializable" = myown
"java.lang.Boolean" = myown
}
}
}
""")
//#serialization-bindings-config
val a = ActorSystem("system", config)
SerializationExtension(a).serializerFor(classOf[String]).getClass must equal(classOf[JavaSerializer])
SerializationExtension(a).serializerFor(classOf[Customer]).getClass must equal(classOf[JavaSerializer])
SerializationExtension(a).serializerFor(classOf[java.lang.Boolean]).getClass must equal(classOf[MyOwnSerializer])
a.shutdown()
}
"demonstrate the programmatic API" in {
//#programmatic
val system = ActorSystem("example")
// Get the Serialization Extension
val serialization = SerializationExtension(system)
// Have something to serialize
val original = "woohoo"
// Find the Serializer for it
val serializer = serialization.findSerializerFor(original)
// Turn it into bytes
val bytes = serializer.toBinary(original)
// Turn it back into an object
val back = serializer.fromBinary(bytes, manifest = None)
// Voilá!
back must equal(original)
//#programmatic
system.shutdown()
}
"demonstrate serialization of ActorRefs" in {
val theActorRef: ActorRef = system.deadLetters
val theActorSystem: ActorSystem = system
//#actorref-serializer
// Serialize
// (beneath toBinary)
// If there is no transportAddress,
// it means that either this Serializer isn't called
// within a piece of code that sets it,
// so either you need to supply your own,
// or simply use the local path.
val identifier: String = Serialization.currentTransportAddress.value match {
case null theActorRef.path.toString
case address theActorRef.path.toStringWithAddress(address)
}
// Then just serialize the identifier however you like
// Deserialize
// (beneath fromBinary)
val deserializedActorRef = theActorSystem actorFor identifier
// Then just use the ActorRef
//#actorref-serializer
//#external-address
object ExternalAddress extends ExtensionKey[ExternalAddressExt]
class ExternalAddressExt(system: ExtendedActorSystem) extends Extension {
def addressFor(remoteAddr: Address): Address =
system.provider.getExternalAddressFor(remoteAddr) getOrElse
(throw new UnsupportedOperationException("cannot send to " + remoteAddr))
}
def serializeTo(ref: ActorRef, remote: Address): String =
ref.path.toStringWithAddress(ExternalAddress(theActorSystem).addressFor(remote))
//#external-address
}
"demonstrate how to do default Akka serialization of ActorRef" in {
val theActorSystem: ActorSystem = system
//#external-address-default
object ExternalAddress extends ExtensionKey[ExternalAddressExt]
class ExternalAddressExt(system: ExtendedActorSystem) extends Extension {
def addressForAkka: Address = akka.transportOf(system).address
}
def serializeAkkaDefault(ref: ActorRef): String =
ref.path.toStringWithAddress(ExternalAddress(theActorSystem).addressForAkka)
//#external-address-default
}
}
}

View file

@ -1,7 +1,7 @@
/**
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.docs.testkit
package docs.testkit
//#plain-spec
import akka.actor.ActorSystem

View file

@ -0,0 +1,36 @@
package docs.testkit
import org.specs2.Specification
import org.specs2.specification.{ Step, Scope }
import akka.actor.{ Props, ActorSystem, Actor }
import akka.testkit.{ TestKit, ImplicitSender }
class Specs2DemoAcceptance extends Specification {
def is =
"This is a specification of basic TestKit interop" ^
p ^
"A TestKit should" ^
"work properly with Specs2 acceptance tests" ! e1 ^
"correctly convert durations" ! e2 ^
Step(system.shutdown()) ^ end // do not forget to shutdown!
val system = ActorSystem()
// an alternative to mixing in NoTimeConversions
implicit def d2d(d: org.specs2.time.Duration): akka.util.FiniteDuration =
akka.util.Duration(d.inMilliseconds, "millis")
def e1 = new TestKit(system) with Scope with ImplicitSender {
within(1 second) {
system.actorOf(Props(new Actor {
def receive = { case x sender ! x }
})) ! "hallo"
expectMsgType[String] must be equalTo "hallo"
}
}
def e2 = ((1 second): akka.util.Duration).toMillis must be equalTo 1000
}

View file

@ -0,0 +1,35 @@
package docs.testkit
import org.specs2.mutable.Specification
import org.specs2.specification.Scope
import org.specs2.time.NoTimeConversions
import akka.actor.{ Props, ActorSystem, Actor }
import akka.testkit.{ TestKit, ImplicitSender }
import akka.util.duration._
class Specs2DemoUnitSpec extends Specification with NoTimeConversions {
val system = ActorSystem()
/*
* this is needed if different test cases would clash when run concurrently,
* e.g. when creating specifically named top-level actors; leave out otherwise
*/
sequential
"A TestKit" should {
"work properly with Specs2 unit tests" in
new TestKit(system) with Scope with ImplicitSender {
within(1 second) {
system.actorOf(Props(new Actor {
def receive = { case x sender ! x }
})) ! "hallo"
expectMsgType[String] must be equalTo "hallo"
}
}
}
step(system.shutdown) // do not forget to shutdown!
}

View file

@ -0,0 +1,156 @@
/**
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
package docs.testkit
//#testkit-usage
import scala.util.Random
import org.scalatest.BeforeAndAfterAll
import org.scalatest.WordSpec
import org.scalatest.matchers.ShouldMatchers
import com.typesafe.config.ConfigFactory
import akka.actor.Actor
import akka.actor.ActorRef
import akka.actor.ActorSystem
import akka.actor.Props
import akka.testkit.DefaultTimeout
import akka.testkit.ImplicitSender
import akka.testkit.TestKit
import akka.util.duration._
/**
* a Test to show some TestKit examples
*/
class TestKitUsageSpec
extends TestKit(ActorSystem("TestKitUsageSpec",
ConfigFactory.parseString(TestKitUsageSpec.config)))
with DefaultTimeout with ImplicitSender
with WordSpec with ShouldMatchers with BeforeAndAfterAll {
import TestKitUsageSpec._
val echoRef = system.actorOf(Props(new EchoActor))
val forwardRef = system.actorOf(Props(new ForwardingActor(testActor)))
val filterRef = system.actorOf(Props(new FilteringActor(testActor)))
val randomHead = Random.nextInt(6)
val randomTail = Random.nextInt(10)
val headList = Seq().padTo(randomHead, "0")
val tailList = Seq().padTo(randomTail, "1")
val seqRef = system.actorOf(Props(new SequencingActor(testActor, headList, tailList)))
override def afterAll {
system.shutdown()
}
"An EchoActor" should {
"Respond with the same message it receives" in {
within(500 millis) {
echoRef ! "test"
expectMsg("test")
}
}
}
"A ForwardingActor" should {
"Forward a message it receives" in {
within(500 millis) {
forwardRef ! "test"
expectMsg("test")
}
}
}
"A FilteringActor" should {
"Filter all messages, except expected messagetypes it receives" in {
var messages = Seq[String]()
within(500 millis) {
filterRef ! "test"
expectMsg("test")
filterRef ! 1
expectNoMsg
filterRef ! "some"
filterRef ! "more"
filterRef ! 1
filterRef ! "text"
filterRef ! 1
receiveWhile(500 millis) {
case msg: String messages = msg +: messages
}
}
messages.length should be(3)
messages.reverse should be(Seq("some", "more", "text"))
}
}
"A SequencingActor" should {
"receive an interesting message at some point " in {
within(500 millis) {
ignoreMsg {
case msg: String msg != "something"
}
seqRef ! "something"
expectMsg("something")
ignoreMsg {
case msg: String msg == "1"
}
expectNoMsg
ignoreNoMsg
}
}
}
}
object TestKitUsageSpec {
// Define your test specific configuration here
val config = """
akka {
loglevel = "WARNING"
}
"""
/**
* An Actor that echoes everything you send to it
*/
class EchoActor extends Actor {
def receive = {
case msg sender ! msg
}
}
/**
* An Actor that forwards every message to a next Actor
*/
class ForwardingActor(next: ActorRef) extends Actor {
def receive = {
case msg next ! msg
}
}
/**
* An Actor that only forwards certain messages to a next Actor
*/
class FilteringActor(next: ActorRef) extends Actor {
def receive = {
case msg: String next ! msg
case _ None
}
}
/**
* An actor that sends a sequence of messages with a random head list, an
* interesting value and a random tail list. The idea is that you would
* like to test that the interesting value is received and that you cant
* be bothered with the rest
*/
class SequencingActor(next: ActorRef, head: Seq[String], tail: Seq[String])
extends Actor {
def receive = {
case msg {
head foreach { next ! _ }
next ! msg
tail foreach { next ! _ }
}
}
}
}
//#testkit-usage

View file

@ -1,7 +1,7 @@
/**
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.docs.testkit
package docs.testkit
//#imports-test-probe
import akka.testkit.TestProbe
@ -14,6 +14,8 @@ import akka.dispatch.Futures
import akka.testkit.AkkaSpec
import akka.testkit.DefaultTimeout
import akka.testkit.ImplicitSender
import akka.util.NonFatal
object TestkitDocSpec {
case object Say42
case object Unknown
@ -208,7 +210,7 @@ class TestkitDocSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
val probe = TestProbe()
val future = probe.ref ? "hello"
probe.expectMsg(0 millis, "hello") // TestActor runs on CallingThreadDispatcher
probe.sender ! "world"
probe.reply("world")
assert(future.isCompleted && future.value == Some(Right("world")))
//#test-probe-reply
}
@ -252,4 +254,22 @@ class TestkitDocSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
//#event-filter
}
"demonstrate TestKitBase" in {
//#test-kit-base
import akka.testkit.TestKitBase
class MyTest extends TestKitBase {
implicit lazy val system = ActorSystem()
//#put-your-test-code-here
val probe = TestProbe()
probe.send(testActor, "hello")
try expectMsg("hello") catch { case NonFatal(e) system.shutdown(); throw e }
//#put-your-test-code-here
system.shutdown()
}
//#test-kit-base
}
}

View file

@ -2,7 +2,7 @@
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.docs.transactor
package docs.transactor
import akka.actor._
import akka.transactor._

View file

@ -1,7 +1,7 @@
/**
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.docs.zeromq
package docs.zeromq
import akka.actor.Actor
import akka.actor.Props