本文整理汇总了Scala中akka.testkit.TestProbe类的典型用法代码示例。如果您正苦于以下问题:Scala TestProbe类的具体用法?Scala TestProbe怎么用?Scala TestProbe使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了TestProbe类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: ApiSpec
//设置package包名称以及导入依赖的类
package au.csiro.data61.magda.registry
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.testkit.TestProbe
import ch.qos.logback.classic.{Level, Logger}
import org.flywaydb.core.Flyway
import org.scalatest.Matchers
import org.scalatest.fixture.FunSpec
import org.slf4j.LoggerFactory
import scala.concurrent.duration._
import scalikejdbc._
abstract class ApiSpec extends FunSpec with ScalatestRouteTest with Matchers with Protocols with SprayJsonSupport {
case class FixtureParam(api: Api, webHookActorProbe: TestProbe)
val databaseUrl = Option(System.getenv("npm_package_config_databaseUrl")).getOrElse("jdbc:postgresql://localhost:5432/postgres")
// Stop Flyway from producing so much spam that Travis terminates the process.
LoggerFactory.getLogger("org.flywaydb").asInstanceOf[Logger].setLevel(Level.WARN)
val flyway = new Flyway()
flyway.setDataSource(databaseUrl, "postgres", "")
flyway.setSchemas("test")
flyway.setLocations("classpath:/sql")
override def testConfigSource =
s"""
|db.default.url = "${databaseUrl}?currentSchema=test"
|authorization.skip = true
|akka.loglevel = INFO
""".stripMargin
override def withFixture(test: OneArgTest) = {
val webHookActorProbe = TestProbe()
val api = new Api(webHookActorProbe.ref, testConfig, system, executor, materializer)
webHookActorProbe.expectMsg(1 millis, WebHookActor.Process)
DB localTx { implicit session =>
sql"DROP SCHEMA IF EXISTS test CASCADE".update.apply()
sql"CREATE SCHEMA test".update.apply()
}
flyway.migrate()
super.withFixture(test.toNoArgTest(FixtureParam(api, webHookActorProbe)))
}
}
示例2: CapacityLimitSpec
//设置package包名称以及导入依赖的类
package akka.io
import akka.testkit.{ TestProbe, AkkaSpec }
import akka.testkit.SocketUtil._
import Tcp._
class CapacityLimitSpec extends AkkaSpec("""
akka.loglevel = ERROR
akka.io.tcp.max-channels = 4
akka.actor.serialize-creators = on
""")
with TcpIntegrationSpecSupport {
"The TCP transport implementation" should {
"reply with CommandFailed to a Bind or Connect command if max-channels capacity has been reached" in new TestSetup {
establishNewClientConnection()
// we now have three channels registered: a listener, a server connection and a client connection
// so register one more channel
val commander = TestProbe()
val addresses = temporaryServerAddresses(2)
commander.send(IO(Tcp), Bind(bindHandler.ref, addresses(0)))
commander.expectMsg(Bound(addresses(0)))
// we are now at the configured max-channel capacity of 4
val bindToFail = Bind(bindHandler.ref, addresses(1))
commander.send(IO(Tcp), bindToFail)
commander.expectMsgType[CommandFailed].cmd should be theSameInstanceAs (bindToFail)
val connectToFail = Connect(endpoint)
commander.send(IO(Tcp), connectToFail)
commander.expectMsgType[CommandFailed].cmd should be theSameInstanceAs (connectToFail)
}
}
}
示例3: TestSetup
//设置package包名称以及导入依赖的类
package akka.io
import scala.annotation.tailrec
import scala.collection.immutable
import akka.testkit.{ AkkaSpec, TestProbe }
import akka.actor.ActorRef
import akka.io.Inet.SocketOption
import akka.testkit.SocketUtil._
import Tcp._
trait TcpIntegrationSpecSupport { _: AkkaSpec ?
class TestSetup(shouldBindServer: Boolean = true) {
val bindHandler = TestProbe()
val endpoint = temporaryServerAddress()
if (shouldBindServer) bindServer()
def bindServer(): Unit = {
val bindCommander = TestProbe()
bindCommander.send(IO(Tcp), Bind(bindHandler.ref, endpoint, options = bindOptions))
bindCommander.expectMsg(Bound(endpoint))
}
def establishNewClientConnection(): (TestProbe, ActorRef, TestProbe, ActorRef) = {
val connectCommander = TestProbe()
connectCommander.send(IO(Tcp), Connect(endpoint, options = connectOptions))
val Connected(`endpoint`, localAddress) = connectCommander.expectMsgType[Connected]
val clientHandler = TestProbe()
connectCommander.sender() ! Register(clientHandler.ref)
val Connected(`localAddress`, `endpoint`) = bindHandler.expectMsgType[Connected]
val serverHandler = TestProbe()
bindHandler.sender() ! Register(serverHandler.ref)
(clientHandler, connectCommander.sender(), serverHandler, bindHandler.sender())
}
@tailrec final def expectReceivedData(handler: TestProbe, remaining: Int): Unit =
if (remaining > 0) {
val recv = handler.expectMsgType[Received]
expectReceivedData(handler, remaining - recv.data.size)
}
def connectOptions: immutable.Traversable[SocketOption] = Nil
}
}
示例4: LogSourceSpec
//设置package包名称以及导入依赖的类
package akka.remote
import scala.concurrent.duration._
import akka.testkit.AkkaSpec
import akka.actor.Actor
import akka.actor.ActorLogging
import akka.actor.Props
import akka.event.Logging
import akka.testkit.ImplicitSender
import akka.testkit.TestProbe
import akka.actor.Deploy
import akka.event.Logging.Info
import akka.actor.ExtendedActorSystem
object LogSourceSpec {
class Reporter extends Actor with ActorLogging {
def receive = {
case s: String ?
log.info(s)
}
}
}
@org.junit.runner.RunWith(classOf[org.scalatest.junit.JUnitRunner])
class LogSourceSpec extends AkkaSpec(
"""
akka.loglevel = INFO
akka.actor.provider = "akka.remote.RemoteActorRefProvider"
akka.remote.netty.tcp.port = 0
""") {
import LogSourceSpec._
val reporter = system.actorOf(Props[Reporter], "reporter")
val logProbe = TestProbe()
system.eventStream.subscribe(system.actorOf(Props(new Actor {
def receive = {
case i @ Info(_, _, msg: String) if msg contains "hello" ? logProbe.ref ! i
case _ ?
}
}).withDeploy(Deploy.local), "logSniffer"), classOf[Logging.Info])
"Log events" must {
"should include host and port for local LogSource" in {
reporter ! "hello"
val info = logProbe.expectMsgType[Info]
info.message should be("hello")
val defaultAddress = system.asInstanceOf[ExtendedActorSystem].provider.getDefaultAddress
info.logSource should include(defaultAddress.toString)
}
}
}
示例5: NetworkBrokerLifetimeSpec
//设置package包名称以及导入依赖的类
package net.ruippeixotog.scalafbp.runtime
import scala.language.reflectiveCalls
import akka.actor.{ Actor, Props, Terminated }
import akka.testkit.TestProbe
class NetworkBrokerLifetimeSpec extends NetworkBrokerSpec {
"A NetworkBroker" should {
"manage the lifetime of the components" in {
"instantiate all components in a graph when the network starts" in new BrokerInstance {
def _graph = graph
lazy val probe = TestProbe()
def instanceProps(id: String) = Props(new Actor {
probe.ref ! s"started_$id"
def receive = Actor.ignoringBehavior
})
lazy val graph = new TwoNodeGraph {
behavior(n1, instanceProps("n1"))
behavior(n2, instanceProps("n2"))
}
probe must receive.allOf("started_n1", "started_n2")
}
"terminate the network when all components terminate" in new BrokerInstance {
def _graph = graph
lazy val instanceProps = Props(new Actor {
context.stop(self)
def receive = Actor.ignoringBehavior
})
lazy val graph = new TwoNodeGraph {
behavior(n1, instanceProps)
behavior(n2, instanceProps)
}
lifeProbe must receive.like { case Terminated(`broker`) => ok }
}
}
}
}
示例6: NetworkBrokerSpec
//设置package包名称以及导入依赖的类
package net.ruippeixotog.scalafbp.runtime
import akka.actor.Props
import akka.testkit.TestProbe
import org.specs2.specification.Scope
import spray.json.DefaultJsonProtocol._
import net.ruippeixotog.akka.testkit.specs2.mutable.AkkaSpecification
import net.ruippeixotog.scalafbp.component.PortDataMarshaller
import net.ruippeixotog.scalafbp.component.core.Repeat
abstract class NetworkBrokerSpec extends AkkaSpecification {
class SingleNodeGraph extends GraphTemplate {
val n1 = node[String](1, 1)
}
class TwoNodeGraph extends GraphTemplate {
val n1, n2 = node[String](1, 1)
}
class ThreeNodeGraph extends GraphTemplate {
val n1, n2, n3 = node[String](1, 1)
}
class ChainGraph[A: PortDataMarshaller] extends GraphTemplate {
val inNode = node(Repeat)
val outNode = node[A](1, 1)
initial("init") ~> (inNode, "in")
(inNode, "out") ~> (outNode, 1)
}
class TwoToTwoGraph extends GraphTemplate {
val inNode1, inNode2, outNode1, outNode2 = node[String](1, 1)
(inNode1, 1) ~> (outNode1, 1) <~ (inNode2, 1)
(inNode1, 1) ~> (outNode2, 1) <~ (inNode2, 1)
}
abstract class BrokerInstance(dynamic: Boolean = false) extends Scope {
def _graph: GraphTemplate
def externalProbe: TestProbe = null
val lifeProbe, outputProbe = TestProbe()
val broker = system.actorOf(Props(
new NetworkBroker(_graph, dynamic, outputProbe.ref, Option(externalProbe).map(_.ref))))
lifeProbe.watch(broker)
}
}
示例7: HttpClientAsActorSpec
//设置package包名称以及导入依赖的类
package com.scalaio.http.client
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.testkit.{TestKit, TestProbe}
import com.scalaio.http.client.actor.HttpClientAsActor
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}
class HttpClientAsActorSpec() extends TestKit(ActorSystem("MySpec"))
with WordSpecLike with Matchers with BeforeAndAfterAll {
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
override def afterAll {
// helps avoid abrupt system closure
Http()
.shutdownAllConnectionPools()
.onComplete { _ => system.terminate() }
}
"An Http actor" must {
"consume http endpoints" in {
val worker = TestProbe("worker")
// when
system.actorOf(HttpClientAsActor.props(worker.ref), "httpClientActor")
// then
val responseMessage = worker.expectMsgType[String](5.seconds)
responseMessage shouldBe "sunt aut facere repellat provident occaecati excepturi optio reprehenderit"
}
}
}
示例8: WireTransferSpec
//设置package包名称以及导入依赖的类
package akka
import BankAccount.{BankAccount, WireTransfer}
import akka.actor.{ActorSystem, Props}
import akka.testkit.{ImplicitSender, TestKit, TestProbe}
import org.scalatest._
class WireTransferSpec(_system: ActorSystem) extends TestKit(_system)
with FlatSpecLike
with ImplicitSender
with Matchers
with BeforeAndAfterAll {
def this() = this(ActorSystem("WireTransferSpec"))
override def afterAll {
TestKit.shutdownActorSystem(system)
}
it should "transfer money from A to B in case of sufficient funds on A" in {
val accountA = TestProbe()
val accountB = TestProbe()
val transfer = system.actorOf(Props[WireTransfer])
transfer ! WireTransfer.Transfer(accountA.ref, accountB.ref, 20)
accountA.expectMsg(BankAccount.Withdraw(20))
accountA.reply(BankAccount.Done)
accountB.expectMsg(BankAccount.Deposit(20))
accountB.reply(BankAccount.Done)
expectMsg(WireTransfer.Done)
}
it should "not transfer money from A to B in case of insufficient funds on A" in {
val accountA = TestProbe()
val accountB = TestProbe()
val transfer = system.actorOf(Props[WireTransfer])
transfer ! WireTransfer.Transfer(accountA.ref, accountB.ref, 20)
accountA.expectMsg(BankAccount.Withdraw(20))
accountA.reply(BankAccount.Failed)
expectMsg(WireTransfer.Failed)
}
}
示例9: SqsSpec
//设置package包名称以及导入依赖的类
package com.taxis99.amazon.sqs
import akka.testkit.TestProbe
import com.typesafe.config.ConfigFactory
import it.IntegrationSpec
import it.mocks.{TestConsumer, TestProducer, TestType}
import scala.collection.JavaConverters._
import scala.concurrent.duration._
class SqsSpec extends IntegrationSpec {
val queueName = "integration-test-q"
val config = ConfigFactory.parseMap(Map[String, String](
s"sqs.$queueName" -> queueName
).asJava)
implicit val sqs = new SqsClient(config)
val probe = TestProbe()
val consumer = new TestConsumer(queueName, probe.ref)
val producer = new TestProducer(queueName)
it should "consume the message produce by the producer to the queue" in {
val msg = TestType("bar", 100)
producer.produce(msg) map { _ =>
probe expectMsg (10.seconds, msg)
succeed
}
}
}
示例10: SnsSpec
//设置package包名称以及导入依赖的类
import akka.testkit.TestProbe
import com.taxis99.amazon.sns.SnsClient
import com.taxis99.amazon.sqs.SqsClient
import com.typesafe.config.ConfigFactory
import it.IntegrationSpec
import it.mocks.{TestConsumer, TestPublisher, TestType}
import scala.collection.JavaConverters._
import scala.concurrent.duration._
class SnsSpec extends IntegrationSpec {
val config = ConfigFactory.parseMap(Map(
"sns.topic" -> "integration-test-topic",
"sqs.q1" -> "sns-test-q-1",
"sqs.q2" -> "sns-test-q-2"
).asJava)
implicit val sqs = new SqsClient(config)
implicit val sns = new SnsClient(config)
val probeA = TestProbe()
val probeB = TestProbe()
val publisher = new TestPublisher("topic")
val consumer1 = new TestConsumer("q1", probeA.ref)
val consumer2 = new TestConsumer("q2", probeB.ref)
it should "publish a message to an topic and deliver to all queues subscribed" in {
val msg = TestType("bar", 100)
publisher.publish(msg) map { _ =>
probeA expectMsg (10.seconds, msg)
probeB expectMsg (10.seconds, msg)
succeed
}
}
}
示例11: ReaperUTest
//设置package包名称以及导入依赖的类
package com.example.util
import akka.actor.{ActorSystem, Props}
import akka.testkit.{ImplicitSender, TestKit, TestProbe}
import com.example.StopSystemAfterAll
import org.scalatest.{FlatSpecLike, ShouldMatchers}
class ReaperUTest
extends TestKit(ActorSystem("testsystem"))
with FlatSpecLike
with ShouldMatchers
with StopSystemAfterAll
with ImplicitSender {
import Reaper._
override def afterAll(): Unit = {
system.shutdown()
super.afterAll()
}
trait ReaperFixture {
val reaper = system.actorOf(Props(new TestReaper(testActor)))
val actor1 = TestProbe()
val actor2 = TestProbe()
val actor3 = TestProbe()
val actor4 = TestProbe()
}
"The Reaper" should "call the allSoulsReaped method after all watched actors are dead" in new ReaperFixture {
reaper ! WatchMe(actor3.ref)
reaper ! WatchMe(actor1.ref)
system.stop(actor1.ref)
system.stop(actor3.ref)
expectMsg("Dead")
}
it should "fail to call the allSoulsReaped method if not all watched actors are dead" in new ReaperFixture {
reaper ! WatchMe(actor3.ref)
reaper ! WatchMe(actor1.ref)
system.stop(actor1.ref)
expectNoMsg()
}
}
示例12: UserSocketSpec
//设置package包名称以及导入依赖的类
package actors
import actors.UserSocket.{ChatMessage, Message}
import akka.actor._
import akka.cluster.pubsub.DistributedPubSub
import akka.cluster.pubsub.DistributedPubSubMediator.{SubscribeAck, Subscribe}
import akka.testkit.TestProbe
import org.specs2.mutable._
import play.api.libs.json._
import scala.language.postfixOps
class UserSocketSpec extends Specification {
val UserId = "user1"
"A user socket" should {
val topic = "chat"
"send chat message to all subscribers" in new AkkaTestkitSpecs2Support {
implicit val messageWrites = Json.writes[Message]
val mediator = DistributedPubSub(system).mediator
val browser = TestProbe()
val chatMember1 = TestProbe()
val chatMember2 = TestProbe()
mediator ! Subscribe(topic, chatMember1.ref)
mediator ! Subscribe(topic, chatMember2.ref)
val socket = system.actorOf(UserSocket.props("user1")(browser.ref), "userSocket")
val message = "hello"
socket ! Json.toJson(Message(message))
chatMember1.ignoreMsg({ case SubscribeAck => true })
chatMember1.expectMsg(ChatMessage(UserId, message))
chatMember2.ignoreMsg({ case SubscribeAck => true })
chatMember2.expectMsg(ChatMessage(UserId, message))
}
"forward chat message to browser" in new AkkaTestkitSpecs2Support {
val browser = TestProbe()
val socket = system.actorOf(UserSocket.props(UserId)(browser.ref), "userSocket")
val chatMessage = ChatMessage(UserId, "There is important thing to do!")
socket ! chatMessage
browser.expectMsg(Json.toJson(chatMessage))
}
}
}
示例13: ProbeActor
//设置package包名称以及导入依赖的类
package mesosphere.marathon.core.leadership.impl
import akka.actor.{ ActorRef, Props, Actor }
import akka.event.LoggingReceive
import akka.testkit.TestProbe
object ProbeActor {
def props(testProbe: TestProbe): Props = Props(new ProbeActor(testProbe))
case class PreStart(self: ActorRef)
case class PostStop(self: ActorRef)
}
class ProbeActor(testProbe: TestProbe) extends Actor {
override def preStart(): Unit = {
testProbe.ref ! ProbeActor.PreStart(self)
}
override def postStop(): Unit = {
testProbe.ref ! ProbeActor.PostStop(self)
}
override def receive: Receive = LoggingReceive {
case any: Any =>
testProbe.ref.forward(any)
}
}
示例14: CaptureEvents
//设置package包名称以及导入依赖的类
package mesosphere.marathon.test
import akka.actor.ActorDSL._
import akka.actor.{ ActorSystem, PoisonPill, Terminated }
import akka.event.EventStream
import akka.testkit.TestProbe
import mesosphere.marathon.core.event.MarathonEvent
import scala.collection.immutable.Seq
import scala.concurrent.Await
import scala.concurrent.duration.Duration
class CaptureEvents(eventStream: EventStream) {
def forBlock(block: => Unit): Seq[MarathonEvent] = {
implicit val actorSystem = ActorSystem("captureEvents")
// yes, this is ugly. Since we only access it in the actor until it terminates, we do have
// the correct thread sync boundaries in place.
var capture = Vector.empty[MarathonEvent]
val captureEventsActor = actor {
new Act {
become {
case captureMe: MarathonEvent => capture :+= captureMe
}
}
}
eventStream.subscribe(captureEventsActor, classOf[MarathonEvent])
eventStream.subscribe(captureEventsActor, classOf[String])
try {
block
} finally {
eventStream.unsubscribe(captureEventsActor)
captureEventsActor ! PoisonPill
val probe = TestProbe()
probe.watch(captureEventsActor)
probe.expectMsgClass(classOf[Terminated])
Await.result(actorSystem.terminate(), Duration.Inf)
}
capture
}
}
示例15: StopActorTest
//设置package包名称以及导入依赖的类
package mesosphere.marathon.upgrade
import akka.actor.{ ActorRef, Props }
import akka.testkit.TestActor.{ AutoPilot, NoAutoPilot }
import akka.testkit.TestProbe
import mesosphere.marathon.test.MarathonActorSupport
import mesosphere.marathon.upgrade.DeploymentActor.Cancel
import org.scalatest.{ FunSuiteLike, Matchers }
import scala.concurrent.duration._
import scala.concurrent.{ Await, Promise }
class StopActorTest extends MarathonActorSupport with FunSuiteLike with Matchers {
test("Stop") {
val promise = Promise[Boolean]()
val probe = TestProbe()
probe.setAutoPilot(new AutoPilot {
def run(sender: ActorRef, msg: Any): AutoPilot = msg match {
case Cancel(reason) =>
system.stop(probe.ref)
NoAutoPilot
}
})
val ref = system.actorOf(Props(classOf[StopActor], probe.ref, promise, new Exception))
watch(ref)
expectTerminated(ref)
Await.result(promise.future, 5.seconds) should be(true)
}
}