akka.actor.actorRef2Scala Scala Examples

The following examples show how to use akka.actor.actorRef2Scala. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: ProjectionNodeTest.scala    From ingraph   with Eclipse Public License 1.0 5 votes vote down vote up
package ingraph.ire.nodes.unary

import akka.actor.{ActorSystem, Props, actorRef2Scala}
import akka.testkit.{ImplicitSender, TestActors, TestKit}
import ingraph.ire.messages.ChangeSet
import ingraph.ire.util.TestUtil._
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

class ProjectionNodeTest(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
  with WordSpecLike with Matchers with BeforeAndAfterAll {

  def this() = this(ActorSystem("MySpec"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "Projection" must {
    "select the values" in {
      val changes = ChangeSet(
        positive = tupleBag(tuple(15, 16, 17, 18), tuple(4, 5, 6, 7)),
        negative = tupleBag(tuple(-0, -1, -2, -3), tuple(-10, -11, -12, -13))
      )
      val selectionMask = functionMask(0, 2)
      val expectedChanges = ChangeSet(
        positive = tupleBag(tuple(15, 17), tuple(4, 6)),
        negative = tupleBag(tuple(-0, -2), tuple(-10, -12))
      )
      val echoActor = system.actorOf(TestActors.echoActorProps)
      val selector = system.actorOf(Props(new ProjectionNode(echoActor ! _, selectionMask)), name = "testSelector")

      selector ! changes
      expectMsg(expectedChanges)
      selector ! changes
      expectMsg(expectedChanges)
    }

    val changeSet = ChangeSet(
      positive = tupleBag(tuple(0, "something")),
      negative = tupleBag(tuple(0, "something else"))
    )

    "do projection with equal length" in {
      val echoActor = system.actorOf(TestActors.echoActorProps)
      val checker = system.actorOf(Props(new ProjectionNode(echoActor ! _, functionMask(1, 0)))) // swap attributes

      checker ! changeSet
      expectMsg(ChangeSet(
        positive = tupleBag(tuple("something", 0)),
        negative = tupleBag(tuple("something else", 0))
      ))
    }

    "do projection with lesser length" in {
      val echoActor = system.actorOf(TestActors.echoActorProps)
      val checker = system.actorOf(Props(new ProjectionNode(echoActor ! _, functionMask(1))))

      checker ! changeSet
      expectMsg(ChangeSet(
        positive = tupleBag(tuple("something")),
        negative = tupleBag(tuple("something else"))
      ))
    }
  }
} 
Example 2
Source File: PortfolioSpec.scala    From Scalaprof   with GNU General Public License v2.0 5 votes vote down vote up
package com.phasmid.hedge_fund.portfolio

import org.scalatest.{ WordSpecLike, Matchers, BeforeAndAfterAll, Inside }
import akka.actor.{ ActorSystem, Actor, Props, ActorRef }
import akka.testkit._
import scala.concurrent.duration._
import org.scalatest.Inside
import akka.actor.actorRef2Scala
import com.phasmid.hedge_fund.HedgeFund
import com.phasmid.hedge_fund.actors._
import com.typesafe.config.ConfigFactory
import com.phasmid.hedge_fund.model.GoogleOptionModel


class PortfolioSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
    with WordSpecLike with Matchers with Inside with BeforeAndAfterAll {

  def this() = this(ActorSystem("MockPortfolioBlackboard"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }
  
  "read portfolio" in {
    val config = ConfigFactory.load
    val portfolio = HedgeFund.getPortfolio(config)
    portfolio.name shouldEqual "Test Portfolio"
    println(s"portfolio: $portfolio")
  }

  "send back" in {
    val model = new GoogleOptionModel()
    val blackboard = system.actorOf(Props.create(classOf[MockPortfolioBlackboard], testActor), "blackboard")
    blackboard ! CandidateOption(model, "XX375", true, Map("strike" -> "45.2"), Map("underlying_id" -> "1234", "Sharpe" -> 0.45, "EV" -> 37132000000.0, "EBITDA" -> 3046000000.0))
    val confirmationMsg = expectMsgClass(3.seconds, classOf[Confirmation])
    println("confirmation msg received: " + confirmationMsg)
    inside(confirmationMsg) {
      case Confirmation(id, model, details) =>
        println(s"confirmation1 details: $details")
        id shouldEqual "XX375"
        blackboard ! KnowledgeUpdate(model, "XX", Map("id" -> "1234"))
        val confirmationMsg2 = expectMsgClass(3.seconds, classOf[Confirmation])
        println("confirmation msg2 received: " + confirmationMsg2)
        // Note that the key "id" is in the model for symbols, not options
        blackboard ! OptionQuery("id", "1234")
        val responseMsg = expectMsgClass(3.seconds, classOf[QueryResponse])
        println("msg received: " + responseMsg)
        inside(responseMsg) {
          case QueryResponseValid(symbol, attributes) =>
            symbol shouldEqual "XX"
            println(s"attributes: $attributes")
        }
    }
  }
}

class MockPortfolioBlackboard(testActor: ActorRef) extends Blackboard(Map(classOf[KnowledgeUpdate] -> "marketData", classOf[SymbolQuery] -> "marketData", classOf[OptionQuery] -> "marketData", classOf[CandidateOption] -> "optionAnalyzer", classOf[PortfolioUpdate] -> "updateLogger", classOf[Confirmation] -> "updateLogger"),
  Map("marketData" -> classOf[MarketData], "optionAnalyzer" -> classOf[OptionAnalyzer], "updateLogger" -> classOf[UpdateLogger])) {

  override def receive =
    {
      case msg: Confirmation => testActor forward msg
      case msg: QueryResponse => testActor forward msg
      case msg => super.receive(msg)
    }
} 
Example 3
Source File: OptionAnalyzerSpec.scala    From Scalaprof   with GNU General Public License v2.0 5 votes vote down vote up
package com.phasmid.hedge_fund.actors

import org.scalatest.{ WordSpecLike, Matchers, BeforeAndAfterAll, Inside }
import akka.actor.{ ActorSystem, Actor, Props, ActorRef }
import akka.testkit._
import scala.concurrent.duration._
import org.scalatest.Inside
import akka.actor.actorRef2Scala
import com.phasmid.hedge_fund.model._


class OptionAnalyzerSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
    with WordSpecLike with Matchers with Inside with BeforeAndAfterAll {

  def this() = this(ActorSystem("OptionAnalyzerSpec"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "send back" in {
    val model = new GoogleOptionModel()
    val blackboard = system.actorOf(Props.create(classOf[MockAnalyzerBlackboard], testActor), "blackboard")
    blackboard ! CandidateOption(model, "XX375", true, Map("strike" -> "54.2"), Map("underlying_id" -> "1234", "Sharpe" -> 0.45, "EV" -> "37.132B", "EBITDA" -> "3.046B"))
    val confirmationMsg = expectMsgClass(3.seconds, classOf[Confirmation])
    println("confirmation msg received: " + confirmationMsg)
    inside(confirmationMsg) {
      case Confirmation(id, model, details) =>
        println(s"confirmation1 details: $details")
        id shouldEqual "XX375"
        blackboard ! KnowledgeUpdate(model, "XX", Map("id" -> "1234"))
        val confirmationMsg2 = expectMsgClass(3.seconds, classOf[Confirmation])
        println("confirmation msg2 received: " + confirmationMsg2)
        // Note that the key "id" is in the model for symbols, not options
        blackboard ! OptionQuery("id", "1234")
        val responseMsg = expectMsgClass(3.seconds, classOf[QueryResponseValid])
        println("msg received: " + responseMsg)
        inside(responseMsg) {
          case QueryResponseValid(symbol, attributes) =>
            symbol shouldEqual "XX"
            println(s"attributes: $attributes")
        }
    }
  }
}

class MockAnalyzerBlackboard(testActor: ActorRef) extends Blackboard(Map(classOf[KnowledgeUpdate] -> "marketData", classOf[SymbolQuery] -> "marketData", classOf[OptionQuery] -> "marketData", classOf[CandidateOption] -> "optionAnalyzer", classOf[Confirmation] -> "updateLogger"),
  Map("marketData" -> classOf[MarketData], "optionAnalyzer" -> classOf[OptionAnalyzer], "updateLogger" -> classOf[UpdateLogger])) {

  override def receive =
    {
      case msg: Confirmation => testActor forward msg
      case msg: QueryResponseValid => testActor forward msg
      case msg => super.receive(msg)
    }
} 
Example 4
Source File: ZeroMQWordCount.scala    From BigDatalog   with Apache License 2.0 5 votes vote down vote up
// scalastyle:off println
package org.apache.spark.examples.streaming

import akka.actor.ActorSystem
import akka.actor.actorRef2Scala
import akka.zeromq._
import akka.zeromq.Subscribe
import akka.util.ByteString

import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.zeromq._

import scala.language.implicitConversions
import org.apache.spark.SparkConf


// scalastyle:on
object ZeroMQWordCount {
  def main(args: Array[String]) {
    if (args.length < 2) {
      System.err.println("Usage: ZeroMQWordCount <zeroMQurl> <topic>")
      System.exit(1)
    }
    StreamingExamples.setStreamingLogLevels()
    val Seq(url, topic) = args.toSeq
    val sparkConf = new SparkConf().setAppName("ZeroMQWordCount")
    // Create the context and set the batch size
    val ssc = new StreamingContext(sparkConf, Seconds(2))

    def bytesToStringIterator(x: Seq[ByteString]): Iterator[String] = x.map(_.utf8String).iterator

    // For this stream, a zeroMQ publisher should be running.
    val lines = ZeroMQUtils.createStream(ssc, url, Subscribe(topic), bytesToStringIterator _)
    val words = lines.flatMap(_.split(" "))
    val wordCounts = words.map(x => (x, 1)).reduceByKey(_ + _)
    wordCounts.print()
    ssc.start()
    ssc.awaitTermination()
  }
}
// scalastyle:on println 
Example 5
Source File: InputTransactionFactoryTest.scala    From ingraph   with Eclipse Public License 1.0 5 votes vote down vote up
package ingraph.ire.nodes

import akka.actor.{ActorSystem, actorRef2Scala}
import akka.testkit.{ImplicitSender, TestActors, TestKit}
import ingraph.ire.inputs.InputTransactionFactory
import ingraph.ire.messages.ChangeSet
import ingraph.ire.util.TestUtil._
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

class InputTransactionFactoryTest(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
  with WordSpecLike with Matchers with BeforeAndAfterAll {
  def this() = this(ActorSystem())

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "InputTransactionFactory" must {

    "send incoming data after subscription" in {
      val input = new InputTransactionFactory
      val echoActor = system.actorOf(TestActors.echoActorProps)
      input.subscribe(Map("test" -> (echoActor ! _)))
      val inputTransaction = input.newInputTransaction
      inputTransaction.add("test", tuple(6, 1L))
      inputTransaction.add("test", tuple(6, 2L))
      inputTransaction.sendAll
      expectMsg(ChangeSet(positive = tupleBag(tuple(6, 2), tuple(6, 1))))
    }

    "do no splitting in batch" in {
      val input = new InputTransactionFactory
      val echoActor = system.actorOf(TestActors.echoActorProps)
      input.subscribe(Map("test" -> (echoActor ! _)))
      val inputTransaction = input.newInputTransaction
      for (i <- 1 to 3) {
        inputTransaction.add("test", tuple(6, i))
      }
      inputTransaction.sendAll
      expectMsg(ChangeSet(positive = tupleBag(tuple(6, 3), tuple(6, 2), tuple(6, 1))))
    }

  }

} 
Example 6
Source File: SizingTest.scala    From ingraph   with Eclipse Public License 1.0 5 votes vote down vote up
package ingraph.ire.nodes

import akka.actor.{ActorRef, Props, actorRef2Scala}
import ingraph.ire.datatypes.{JoinCache, Tuple}
import ingraph.ire.engine.RelationalEngine
import ingraph.ire.inputs.InputTransactionFactory
import ingraph.ire.messages.{ChangeSet, Primary, Secondary, Terminator}
import ingraph.ire.nodes.binary.JoinNode
import ingraph.ire.nodes.unary.{ProductionNode, SelectionNode}
import ingraph.ire.util.SizeCounter
import ingraph.ire.util.TestUtil.{mask, tuple}
import ingraph.ire.messages.Terminator
import ingraph.ire.nodes.unary.SelectionNode
import org.scalatest.WordSpec
import org.scalatest.concurrent.TimeLimits

import scala.collection.mutable

class SizingTest extends WordSpec with TimeLimits {

  import ingraph.ire.util.Utils.conversions._
  class TestQuery1 extends RelationalEngine {
    override val production: ActorRef = system.actorOf(Props(new ProductionNode("TestQuery")))
    override val inputLookup: Map[String, (ChangeSet) => Unit] = Map(
      "testval" -> ((cs: ChangeSet) => { joiner ! Primary(cs); joiner ! Secondary(cs) })
    )
    override val terminator: Terminator = Terminator(Vector(forwarder ! _), production)
    val forwarder = newLocal(Props(new SelectionNode(production, a => true)))
    val joiner = newLocal(Props(new JoinNode(forwarder, 2, 2, mask(0), mask(0))), "joiner")
  }

  "SizeCounter" should {
    "count" in {
      val data = mutable.HashMap[Tuple, Int]()
      data(tuple(5, 6, 7)) = 8
      data(tuple(5, 6, 9)) = 10
      assert(SizeCounter.count(data.keys) == 6)
    }

    "count deeper" in {
      val data = new JoinCache
      data.addBinding(tuple(2, 3), tuple(3, 4))
      data.addBinding(tuple(2, 3), tuple(3, 5))
      data.addBinding(tuple(2, 3), tuple(3, 6))
      data.addBinding(tuple(3, 2), tuple(2, 5))
      assert(SizeCounter.countDeeper(data.values) == 8)
    }

    "measure size" in {
      val input = new InputTransactionFactory
      val query = new TestQuery1
      input.subscribe(query.inputLookup)
      val inputTransaction = input.newInputTransaction
      inputTransaction.add("testval", tuple(5, 5))
      inputTransaction.add("testval", tuple(5, 6))
      inputTransaction.add("testval", tuple(5, 7))
      inputTransaction.sendAll()
      assert(query.getCounts == 12)
    }
  }
} 
Example 7
Source File: UnionNodeTest.scala    From ingraph   with Eclipse Public License 1.0 5 votes vote down vote up
package ingraph.ire.nodes.binary

import akka.actor.{ActorSystem, Props, actorRef2Scala}
import akka.testkit.{ImplicitSender, TestActors, TestKit}
import ingraph.ire.messages.{ChangeSet, Primary, Secondary}
import ingraph.ire.util.TestUtil._
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

class UnionNodeTest(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
  with WordSpecLike with Matchers with BeforeAndAfterAll {

  def this() = this(ActorSystem("MySpec"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "Union" must {
    "do simple set unions 0" in {
      val prim = ChangeSet(
        positive = tupleBag(tuple(1, 2), tuple(1, 3))
      )
      val sec = ChangeSet(
        positive = tupleBag(tuple(1, 2), tuple(1, 4))
      )
      val echoActor = system.actorOf(TestActors.echoActorProps)
      val union = system.actorOf(Props(new UnionNode(echoActor ! _, all = false)))

      union ! Primary(prim)
      expectMsg(ChangeSet(positive = tupleBag(tuple(1, 2), tuple(1, 3))))
      union ! Secondary(sec)
      expectMsg(ChangeSet(positive = tupleBag(tuple(1, 4))))
    }

    "do simple bag unions 0" in {
      val prim = ChangeSet(
        positive = tupleBag(tuple(1, 2), tuple(1, 3))
      )
      val sec = ChangeSet(
        positive = tupleBag(tuple(1, 2), tuple(1, 4))
      )
      val echoActor = system.actorOf(TestActors.echoActorProps)
      val union = system.actorOf(Props(new UnionNode(echoActor ! _, all = true)))

      union ! Primary(prim)
      expectMsg(ChangeSet(positive = tupleBag(tuple(1, 2), tuple(1, 3))))
      union ! Secondary(sec)
      expectMsg(ChangeSet(positive = tupleBag(tuple(1, 2), tuple(1, 4))))
    }
  }
} 
Example 8
Source File: TerminatorTest.scala    From ingraph   with Eclipse Public License 1.0 5 votes vote down vote up
package ingraph.ire.nodes

import akka.actor.{ActorSystem, Props, actorRef2Scala}
import akka.testkit.{ImplicitSender, TestActors, TestKit}
import ingraph.ire.messages.{ChangeSet, Primary, Secondary}
import ingraph.ire.nodes.binary.JoinNode
import ingraph.ire.nodes.unary.{ProductionNode, SelectionNode}
import ingraph.ire.util.TestUtil._
import ingraph.ire.util.Utils.conversions._
import ingraph.ire.messages.Terminator
import ingraph.ire.nodes.unary.SelectionNode
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

import scala.concurrent.Await
import scala.concurrent.duration.{Duration, _}

class TerminatorTest(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
  with WordSpecLike with Matchers with BeforeAndAfterAll {
  def this() = this(ActorSystem("MySpec"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "Unary nodes" must {
    "propagate terminator messages" in {
      val echoActor = system.actorOf(TestActors.echoActorProps)
      val production = system.actorOf(Props(new ProductionNode("alpha test", 2)))
      val intermediary = system.actorOf(Props(new SelectionNode(production ! _, c => true, expectedTerminatorCount = 2))) // TODO wtf
      //      val intermediary = system.actorOf(Props(new SelectionNode(production ! _, c => true)))
      val input1 = system.actorOf(Props(new SelectionNode(production ! _, c => true)))
      input1 ! ChangeSet(positive = tupleBag(tuple(15)))
      input1 ! ChangeSet(positive = tupleBag(tuple(19)))
      val input2 = system.actorOf(Props(new SelectionNode(intermediary ! _, c => true)))
      input2 ! ChangeSet(positive = tupleBag(tuple(25)))
      input2 ! ChangeSet(positive = tupleBag(tuple(29)))
      val input3 = system.actorOf(Props(new SelectionNode(intermediary ! _, c => true)))

      val terminator = Terminator(List(
        input1 ! _, input2 ! _, input3 ! _
      ), production)
      val future = terminator.send()
      input1 ! ChangeSet(positive = tupleBag(tuple(16)))
      input1 ! ChangeSet(positive = tupleBag(tuple(17)))
      input2 ! ChangeSet(positive = tupleBag(tuple(26)))
      input2 ! ChangeSet(positive = tupleBag(tuple(27)))
      val expected = Set(tuple(15), tuple(19), tuple(25), tuple(29))
      assert(Await.result(future, Duration(1, HOURS)).toSet == expected)
    }
  }
  "Binary nodes" must {
    "propagate terminator messages" in {
      val echoActor = system.actorOf(TestActors.echoActorProps)
      val production = system.actorOf(Props(new ProductionNode("")), "Production")
      val checker = system.actorOf(Props(new SelectionNode(production ! _, c => true)), "checker")
      val intermediary = system.actorOf(Props(new JoinNode(checker ! _, 1, 1, mask(0), mask(0))), "intermediary")
      val input1 = system.actorOf(Props(new JoinNode(intermediary ! Primary(_), 1, 1, mask(0), mask(0))), "inputBeta")
      val msg15 = ChangeSet(positive = tupleBag(tuple(15)))
      input1 ! Primary(msg15)
      input1 ! Secondary(msg15)
      intermediary ! Secondary(msg15)
      val msg25 = ChangeSet(positive = tupleBag(tuple(25)))
      input1 ! Primary(msg25)
      input1 ! Secondary(msg25)
      intermediary ! Secondary(msg25)

      val terminator = Terminator(List(input1.primary, input1.secondary, intermediary.secondary), production)
      val future = terminator.send()
      input1 ! Primary(ChangeSet(positive = tupleBag(tuple(16))))
      input1 ! Secondary(ChangeSet(positive = tupleBag(tuple(16))))
      intermediary ! Secondary(ChangeSet(positive = tupleBag(tuple(16))))

      assert(Await.result(future, Duration(1, HOURS)).toSet == Set(tuple(15), tuple(25)))
      assert(Await.result(terminator.send(), Duration(1, HOURS)).toSet == Set(tuple(15), tuple(25), tuple(16)))
      (1 to 500).foreach(i => {
        input1 ! Secondary(ChangeSet(negative = tupleBag(tuple(16))))
        assert(Await.result(terminator.send(), Duration(1, HOURS)).toSet == Set(tuple(15), tuple(25)))
        input1 ! Secondary(ChangeSet(positive = tupleBag(tuple(16))))
        intermediary ! Secondary(ChangeSet(negative = tupleBag(tuple(15))))
        assert(Await.result(terminator.send(), Duration(1, HOURS)).toSet == Set(tuple(25), tuple(16)))
        intermediary ! Secondary(ChangeSet(positive = tupleBag(tuple(15))))
        assert(Await.result(terminator.send(), Duration(1, HOURS)).toSet == Set(tuple(15), tuple(25), tuple(16)))
      })
    }
  }
  "Node splitting" should {
    "work" in {

    }
  }
} 
Example 9
Source File: MapperTest.scala    From ingraph   with Eclipse Public License 1.0 5 votes vote down vote up
package ingraph.ire.nodes.unary

import akka.actor.{ActorSystem, Props, actorRef2Scala}
import akka.testkit.{ImplicitSender, TestActors, TestKit}
import ingraph.ire.messages.ChangeSet
import ingraph.ire.util.TestUtil._
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

class MapperTest(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
  with WordSpecLike with Matchers with BeforeAndAfterAll {

  def this() = this(ActorSystem("MySpec"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "MapperNode" must {
    "map values" in {
      val changeSet = ChangeSet(
        positive = tupleBag(tuple(0, "something")),
        negative = tupleBag(tuple(0, "something else"))
      )
      val echoActor = system.actorOf(TestActors.echoActorProps)
      val function = (n: Any) => n match {
        case s: String => s.length
      }
      val checker = system.actorOf(Props(new MapperNode(echoActor ! _, function, 1)))

      checker ! changeSet
      expectMsg(ChangeSet(
        positive = tupleBag(tuple(0, "something".length)),
        negative = tupleBag(tuple(0, "something else".length))
      ))
    }
  }
} 
Example 10
Source File: SortAndTopNodeTest.scala    From ingraph   with Eclipse Public License 1.0 5 votes vote down vote up
package ingraph.ire.nodes.unary

import akka.actor.{ActorSystem, Props, actorRef2Scala}
import akka.testkit.{ImplicitSender, TestActors, TestKit}
import ingraph.ire.datatypes.Tuple
import ingraph.ire.messages.ChangeSet
import ingraph.ire.util.TestUtil._
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

class SortAndTopNodeTest(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
  with WordSpecLike with Matchers with BeforeAndAfterAll {

  def this() = this(ActorSystem("MySpec"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }
  val selectionMask = Vector((v: Tuple) => v(0), (v: Tuple) => v(1))
  "Sort" should {
    "count with complex keys" in {
      val echoActor = system.actorOf(TestActors.echoActorProps)
      val counter = system.actorOf(Props(
          new SortAndTopNode(echoActor ! _,
              tupleLength = 3,
              selectionMask = selectionMask,
              skip = Some(0),
              limit = Some(2),
              ascendingOrder = Vector(true, false))
      ))

      counter ! ChangeSet(positive = tupleBag(tuple(2, 3, 4), tuple(0, 2, 3), tuple(0, 3, 3), tuple(5, 6, 7)))
      expectMsg(ChangeSet(positive = tupleBag(tuple(0, 3, 3), tuple(0, 2, 3))))

      counter ! ChangeSet(negative = tupleBag(tuple(0, 2, 3)))
      expectMsg(ChangeSet(
        positive = tupleBag(tuple(0, 3, 3), tuple(2, 3, 4)),
        negative = tupleBag(tuple(0, 3, 3), tuple(0, 2, 3))))
    }
    "have bag semantics" in {
      val echoActor = system.actorOf(TestActors.echoActorProps)
      val counter = system.actorOf(Props(new SortAndTopNode(echoActor ! _,
          tupleLength = 3,
          selectionMask = selectionMask,
          skip = Some(0),
          limit = Some(2),
          ascendingOrder = Vector(true, true))))

      counter ! ChangeSet(positive = tupleBag(tuple(0, 1, 2), tuple(0, 1, 2), tuple(0, 1, 3)))
      expectMsg(ChangeSet(positive = tupleBag(tuple(0, 1, 2), tuple(0, 1, 2))))

      counter ! ChangeSet(negative = tupleBag(tuple(0, 1, 2)))
      expectMsg(ChangeSet(
        positive = tupleBag(tuple(0, 1, 2), tuple(0, 1, 3)),
        negative = tupleBag(tuple(0, 1, 2), tuple(0, 1, 2))))

      counter ! ChangeSet(negative = tupleBag(tuple(0, 1, 2)))
      expectMsg(ChangeSet(
        positive = tupleBag(tuple(0, 1, 3)),
        negative = tupleBag(tuple(0, 1, 2), tuple(0, 1, 3))))
    }
  }
} 
Example 11
Source File: SelectionNodeTest.scala    From ingraph   with Eclipse Public License 1.0 5 votes vote down vote up
package ingraph.ire.nodes.unary

import akka.actor.{ActorSystem, Props, actorRef2Scala}
import akka.testkit.{ImplicitSender, TestActors, TestKit}
import ingraph.ire.datatypes.Tuple
import ingraph.ire.messages.ChangeSet
import ingraph.ire.util.TestUtil._
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

class SelectionNodeTest(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
  with WordSpecLike with Matchers with BeforeAndAfterAll {

  def this() = this(ActorSystem("MySpec"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "Selection" must {
    "check the condition properly" in {
      val changeSet = ChangeSet(
        positive = tupleBag(tuple(0, "something"), tuple(0, "something else"))
      )
      val echoActor = system.actorOf(TestActors.echoActorProps)
      val condition = (n: Tuple) => {
        n(1) == "something"
      }
      val checker = system.actorOf(Props(new SelectionNode(echoActor ! _, condition)))

      checker ! changeSet
      expectMsg(ChangeSet(positive = tupleBag(tuple(0, "something"))))
    }
  }
} 
Example 12
Source File: ListSelectorNodeTest.scala    From ingraph   with Eclipse Public License 1.0 5 votes vote down vote up
package ingraph.ire.nodes.unary

import akka.actor.{ActorSystem, Props, actorRef2Scala}
import akka.testkit.{ImplicitSender, TestActors, TestKit}
import ingraph.ire.messages.ChangeSet
import ingraph.ire.util.TestUtil._
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

class ListSelectorNodeTest(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
  with WordSpecLike with Matchers with BeforeAndAfterAll {

  def this() = this(ActorSystem("MySpec"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "ListSelector" must {
    "do select items in lists 0" in {
      val changeSet = ChangeSet(
        positive = tupleBag(tuple(List("a","b","c")))
      )

      val function = (n: Any) => n match {
        case s: List[Any] => s(1)
      }
      val echoActor = system.actorOf(TestActors.echoActorProps)
      val listSelector = system.actorOf(Props(new MapperNode(echoActor ! _, function, 0)))

      listSelector ! changeSet
      expectMsg(ChangeSet(positive = tupleBag(tuple("b"))))
    }
  }
} 
Example 13
Source File: UnwindNodeTest.scala    From ingraph   with Eclipse Public License 1.0 5 votes vote down vote up
package ingraph.ire.nodes.unary

import akka.actor.{ActorSystem, Props, actorRef2Scala}
import akka.testkit.{ImplicitSender, TestActors, TestKit}
import ingraph.ire.datatypes.Tuple
import ingraph.ire.messages.ChangeSet
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

class UnwindNodeTest(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
  with WordSpecLike with Matchers with BeforeAndAfterAll {

  def this() = this(ActorSystem("MySpec"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  import ingraph.ire.util.TestUtil._
  private def indexer(index: Int) = {
    (t: Tuple) => t(index).asInstanceOf[Seq[Any]]
  }
  "Unwind" must {
    "do simple unwind 0" in {
      val changeSet = ChangeSet(
        positive = tupleBag(
          tuple("x", cypherList(1, 2, 3), "y"),
          tuple("w", cypherList(), "z")
        ),
        negative = tupleBag(
          tuple("a", cypherList(1, 2), "b"),
          tuple("c", cypherList(), "d")
        )
      )
      val echoActor = system.actorOf(TestActors.echoActorProps)
      val unwind = system.actorOf(Props(new UnwindNode(echoActor ! _, indexer(1))))

      unwind ! changeSet
      expectMsg(ChangeSet(
        positive = tupleBag(
          tuple("x", cypherList(1, 2, 3), "y", 1),
          tuple("x", cypherList(1, 2, 3), "y", 2),
          tuple("x", cypherList(1, 2, 3), "y", 3)
        ),
        negative = tupleBag(
          tuple("a", cypherList(1, 2), "b", 1),
          tuple("a", cypherList(1, 2), "b", 2)
        )
      ))
    }

    "do simple unwind 1" in {
      val changeSet = ChangeSet(
        positive = tupleBag(
          tuple("x", List(1, 2, 3), "y"),
          tuple("w", List(4, 5), "z")
        )
      )
      val echoActor = system.actorOf(TestActors.echoActorProps)
      val unwind = system.actorOf(Props(new UnwindNode(echoActor ! _, indexer(1))))

      unwind ! changeSet
      expectMsg(ChangeSet(
        positive = tupleBag(
          tuple("x", cypherList(1, 2, 3), "y", 1),
          tuple("x", cypherList(1, 2, 3), "y", 2),
          tuple("x", cypherList(1, 2, 3), "y", 3),
          tuple("w", cypherList(4, 5),    "z", 4),
          tuple("w", cypherList(4, 5),    "z", 5)
        )
      ))
    }
  }
} 
Example 14
Source File: AbstractEmbeddedPersistentActorSpec.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.javadsl.persistence.testkit

import akka.actor.ActorRef
import akka.actor.Props
import akka.actor.actorRef2Scala
import akka.persistence.PersistentActor
import com.lightbend.lagom.persistence.ActorSystemSpec
import com.lightbend.lagom.serialization.Jsonable

import scala.concurrent.duration._

object AbstractEmbeddedPersistentActorSpec {
  // All commands and events extending Jsonable so that the
  // tests will use Jackson serialization instead of Java's.
  case object Get                    extends Jsonable
  final case class Cmd(data: String) extends Jsonable
  final case class Evt(data: String) extends Jsonable
  final case class State(data: Vector[String] = Vector.empty) extends Jsonable {
    def apply(evt: Evt): State = {
      copy(data :+ evt.data)
    }
  }

  def props(persistenceId: String): Props =
    Props(new Persistent(persistenceId))

  class Persistent(override val persistenceId: String) extends PersistentActor {
    var state = State()

    override def receiveRecover = {
      case evt: Evt => state = state(evt)
    }

    override def receiveCommand = {
      case Cmd(data) =>
        persist(Evt(data.toUpperCase)) { evt =>
          state = state(evt)
        }
      case Get => sender() ! state
    }
  }
}

trait AbstractEmbeddedPersistentActorSpec { spec: ActorSystemSpec =>
  import AbstractEmbeddedPersistentActorSpec._

  "A persistent actor" must {
    "store events in the embedded journal" in within(15.seconds) {
      val p = system.actorOf(props("p1"))
      println(implicitly[ActorRef])

      p ! Get
      expectMsg(State())
      p ! Cmd("a")
      p ! Cmd("b")
      p ! Cmd("c")
      p ! Get
      expectMsg(State(Vector("A", "B", "C")))

      // start another with same persistenceId should recover state
      val p2 = system.actorOf(props("p1"))
      p2 ! Get
      expectMsg(State(Vector("A", "B", "C")))
    }
  }
} 
Example 15
Source File: DuplicateEliminationNodeTest.scala    From ingraph   with Eclipse Public License 1.0 5 votes vote down vote up
package ingraph.ire.nodes.unary

import akka.actor.{ActorSystem, Props, actorRef2Scala}
import akka.testkit.{ImplicitSender, TestActors, TestKit}
import ingraph.ire.messages.ChangeSet
import ingraph.ire.util.TestUtil._
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

class DuplicateEliminationNodeTest(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
  with WordSpecLike with Matchers with BeforeAndAfterAll {

  def this() = this(ActorSystem("MySpec"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "DuplicateElimination node" must {
    "do simple duplicate elimination 0" in {
      val echoActor = system.actorOf(TestActors.echoActorProps)
      val duplicateElimination = system.actorOf(Props(new DuplicateEliminationNode(echoActor ! _)))

      duplicateElimination ! ChangeSet(
        positive = tupleBag(tuple(1, 2))
      )
      expectMsg(ChangeSet(
        positive = tupleBag(tuple(1, 2))
      ))

      duplicateElimination ! ChangeSet(
        positive = tupleBag(tuple(1, 2), tuple(3, 4))
      )
      expectMsg(ChangeSet(
        positive = tupleBag(tuple(3, 4))
      ))

      duplicateElimination ! ChangeSet(
        positive = tupleBag(tuple(5, 6)),
        negative = tupleBag(tuple(1, 2))
      )
      expectMsg(ChangeSet(
        positive = tupleBag(tuple(5, 6))
      ))

      duplicateElimination ! ChangeSet(
        positive = tupleBag(tuple(7, 8)),
        negative = tupleBag(tuple(1, 2))
      )
      expectMsg(ChangeSet(
        positive = tupleBag(tuple(7, 8)),
        negative = tupleBag(tuple(1, 2))
      ))
    }

    "do simple duplicate elimination 1" in {
      val echoActor = system.actorOf(TestActors.echoActorProps)
      val duplicateElimination = system.actorOf(Props(new DuplicateEliminationNode(echoActor ! _)))

      duplicateElimination ! ChangeSet(positive = tupleBag(tuple(1)))
      expectMsg(ChangeSet(positive = tupleBag(tuple(1))))

      duplicateElimination ! ChangeSet(positive = tupleBag(tuple(1)))
      duplicateElimination ! ChangeSet(positive = tupleBag(tuple(1)))

      duplicateElimination ! ChangeSet(negative = tupleBag(tuple(1)))
      duplicateElimination ! ChangeSet(negative = tupleBag(tuple(1)))
      duplicateElimination ! ChangeSet(negative = tupleBag(tuple(1)))
      expectMsg(ChangeSet(negative = tupleBag(tuple(1))))
    }

  }
} 
Example 16
Source File: MaxNodeTest.scala    From ingraph   with Eclipse Public License 1.0 5 votes vote down vote up
package ingraph.ire.nodes.unary

import akka.actor.{ActorSystem, Props, actorRef2Scala}
import akka.testkit.{ImplicitSender, TestActors, TestKit}
import ingraph.ire.messages.ChangeSet
import ingraph.ire.nodes.unary.aggregation.{AggregationNode, StatefulMax}
import ingraph.ire.util.TestUtil._
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

class MaxNodeTest(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
  with WordSpecLike with Matchers with BeforeAndAfterAll {

  def this() = this(ActorSystem("MySpec"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "Max" must {
    "do simple max 0" in {
      val changeSet = ChangeSet(
        positive = tupleBag(tuple("a", 1), tuple("a", 2), tuple("a", 1.1), tuple("b", 3))
      )
      val echoActor = system.actorOf(TestActors.echoActorProps)
      val max = system.actorOf(Props(new AggregationNode(
        echoActor ! _, functionMask(0), () => Vector(new StatefulMax(1)), Vector(0, 1))))

      max ! changeSet
      expectMsg(ChangeSet(
        positive = tupleBag(tuple("a", 2), tuple("b", 3))
      ))

      max ! ChangeSet(
        negative = tupleBag(tuple("a", 2))
      )
      expectMsg(ChangeSet(
        positive = tupleBag(tuple("a", 1.1)),
        negative = tupleBag(tuple("a", 2))
      ))
    }
  }
} 
Example 17
Source File: MinNodeTest.scala    From ingraph   with Eclipse Public License 1.0 5 votes vote down vote up
package ingraph.ire.nodes.unary

import akka.actor.{ActorSystem, Props, actorRef2Scala}
import akka.testkit.{ImplicitSender, TestActors, TestKit}
import ingraph.ire.messages.ChangeSet
import ingraph.ire.nodes.unary.aggregation.{AggregationNode, StatefulMin}
import ingraph.ire.util.TestUtil._
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

class MinNodeTest(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
  with WordSpecLike with Matchers with BeforeAndAfterAll {

  def this() = this(ActorSystem("MySpec"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "Min" must {
    "do simple min 0" in {
      val changeSet = ChangeSet(
        positive = tupleBag(tuple("a", 1), tuple("a", 2), tuple("a", 1.1), tuple("b", 3))
      )
      val echoActor = system.actorOf(TestActors.echoActorProps)
      val min = system.actorOf(Props(
        new AggregationNode(echoActor ! _, functionMask(0), () => Vector(new StatefulMin(1)), Vector(0, 1))))

      min ! changeSet
      expectMsg(ChangeSet(
        positive = tupleBag(tuple("a", 1), tuple("b", 3))
      ))

      min ! ChangeSet(
        negative = tupleBag(tuple("a", 1))
      )
      expectMsg(ChangeSet(
        positive = tupleBag(tuple("a", 1.1)),
        negative = tupleBag(tuple("a", 1))
      ))
    }
  }
} 
Example 18
Source File: Remoting.scala    From spark1.52   with Apache License 2.0 5 votes vote down vote up
package ch8
import org.learningconcurrency._
import ch8._

import akka.actor.Actor
import akka.actor.ActorIdentity
import akka.actor.ActorSelection.toScala
import akka.actor.Identify
import akka.actor.Props
import akka.actor.actorRef2Scala
import akka.event.Logging




object RemotingPongySystem extends App {
  val system = remotingSystem("PongyDimension", 24321)
  val pongy = system.actorOf(Props[Pongy], "pongy")
  Thread.sleep(15000)
  system.shutdown()
}


class Runner extends Actor {
  val log = Logging(context.system, this)
  val pingy = context.actorOf(Props[Pingy], "pingy")
  def receive = {
    case "start" =>
      val path = context.actorSelection("akka.tcp://[email protected]:24321/user/pongy")
      path ! Identify(0)
    case ActorIdentity(0, Some(ref)) =>
      pingy ! ref
    case ActorIdentity(0, None) =>
      log.info("Something's wrong -- no pongy anywhere!")
      context.stop(self)
    case "pong" =>
      log.info("got a pong from another dimension.")
      context.stop(self)
  }
}


object RemotingPingySystem extends App {
  val system = remotingSystem("PingyDimension", 24567)
  val runner = system.actorOf(Props[Runner], "runner")
  runner ! "start"
  Thread.sleep(5000)
  system.shutdown()
} 
Example 19
Source File: ZeroMQWordCount.scala    From iolap   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.examples.streaming

import akka.actor.ActorSystem
import akka.actor.actorRef2Scala
import akka.zeromq._
import akka.zeromq.Subscribe
import akka.util.ByteString

import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.zeromq._

import scala.language.implicitConversions
import org.apache.spark.SparkConf


// scalastyle:on
object ZeroMQWordCount {
  def main(args: Array[String]) {
    if (args.length < 2) {
      System.err.println("Usage: ZeroMQWordCount <zeroMQurl> <topic>")
      System.exit(1)
    }
    StreamingExamples.setStreamingLogLevels()
    val Seq(url, topic) = args.toSeq
    val sparkConf = new SparkConf().setAppName("ZeroMQWordCount")
    // Create the context and set the batch size
    val ssc = new StreamingContext(sparkConf, Seconds(2))

    def bytesToStringIterator(x: Seq[ByteString]): Iterator[String] = x.map(_.utf8String).iterator

    // For this stream, a zeroMQ publisher should be running.
    val lines = ZeroMQUtils.createStream(ssc, url, Subscribe(topic), bytesToStringIterator _)
    val words = lines.flatMap(_.split(" "))
    val wordCounts = words.map(x => (x, 1)).reduceByKey(_ + _)
    wordCounts.print()
    ssc.start()
    ssc.awaitTermination()
  }
} 
Example 20
Source File: PortfolioSpec.scala    From CSYE7200_Old   with MIT License 5 votes vote down vote up
package edu.neu.coe.csye7200.portfolio

import akka.actor.{ActorRef, ActorSystem, Props, actorRef2Scala}
import akka.testkit._
import com.typesafe.config.ConfigFactory
import edu.neu.coe.csye7200.HedgeFund
import edu.neu.coe.csye7200.actors._
import edu.neu.coe.csye7200.model.GoogleOptionModel
import org.scalatest.tagobjects.Slow
import org.scalatest.{BeforeAndAfterAll, Inside, Matchers, WordSpecLike}

import scala.concurrent.duration._
import scala.util.Success


class PortfolioSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
  with WordSpecLike with Matchers with Inside with BeforeAndAfterAll {

  def this() = this(ActorSystem("MockPortfolioBlackboard"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "read portfolio" taggedAs Slow in {
    val config = ConfigFactory.load
    val portfolio = HedgeFund.getPortfolio(config)
    portfolio should matchPattern { case Some(_) => }
    portfolio.get.name shouldEqual "Test Portfolio"
    println(s"portfolio: $portfolio")
  }

  "send back" taggedAs Slow in {
    val model = new GoogleOptionModel()
    val blackboard = system.actorOf(Props.create(classOf[MockPortfolioBlackboard], testActor), "blackboard")
    blackboard ! CandidateOption(model, "XX375", put = true, Map("strike" -> "45.2"), Map("underlying_id" -> "1234"))
    val confirmationMsg = expectMsgClass(3.seconds, classOf[Confirmation])
    println("confirmation msg received: " + confirmationMsg)
    inside(confirmationMsg) {
      case Confirmation(id, m, details) =>
        println(s"confirmation1 details: $details")
        id shouldEqual "XX375"
        blackboard ! KnowledgeUpdate(m, "XX", Map("id" -> "1234"))
        val confirmationMsg2 = expectMsgClass(3.seconds, classOf[Confirmation])
        println("confirmation msg2 received: " + confirmationMsg2)
        // Note that the key "id" is in the model for symbols, not options
        blackboard ! OptionQuery("id", "1234")
        val responseMsg = expectMsgClass(3.seconds, classOf[QueryResponse])
        println("msg received: " + responseMsg)
        inside(responseMsg) {
          case QueryResponse(symbol, attributes) =>
            symbol shouldEqual "XX"
            println(s"attributes: $attributes")
        }
    }
  }
}

class MockPortfolioBlackboard(testActor: ActorRef) extends Blackboard(Map(classOf[KnowledgeUpdate] -> "marketData", classOf[SymbolQuery] -> "marketData", classOf[OptionQuery] -> "marketData", classOf[CandidateOption] -> "optionAnalyzer", classOf[PortfolioUpdate] -> "updateLogger", classOf[Confirmation] -> "updateLogger"),
  Map("marketData" -> classOf[MarketData], "optionAnalyzer" -> classOf[OptionAnalyzer], "updateLogger" -> classOf[UpdateLogger])) {

  override def receive: PartialFunction[Any, Unit] = {
    case msg: Confirmation => testActor forward msg
    case msg: QueryResponse => testActor forward msg
    //      case msg: CandidateOption => testActor forward msg
    case msg => super.receive(msg)
  }
} 
Example 21
Source File: OptionAnalyzerSpec.scala    From CSYE7200_Old   with MIT License 5 votes vote down vote up
package edu.neu.coe.csye7200.actors

import akka.actor.{ActorRef, ActorSystem, Props, actorRef2Scala}
import akka.testkit._
import edu.neu.coe.csye7200.model.GoogleOptionModel
import org.scalatest.tagobjects.Slow
import org.scalatest.{BeforeAndAfterAll, Inside, Matchers, WordSpecLike}

import scala.concurrent.duration._


class OptionAnalyzerSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
  with WordSpecLike with Matchers with Inside with BeforeAndAfterAll {

  def this() = this(ActorSystem("OptionAnalyzerSpec"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "send back" taggedAs Slow in {
    val model = new GoogleOptionModel()
    val blackboard = system.actorOf(Props.create(classOf[MockAnalyzerBlackboard], testActor), "blackboard")
    blackboard ! CandidateOption(model, "XX375", put = true, Map("strike" -> "45.2"), Map("underlying_id" -> "1234", "Sharpe" -> 0.45))
    val confirmationMsg = expectMsgClass(3.seconds, classOf[Confirmation])
    println("confirmation msg received: " + confirmationMsg)
    inside(confirmationMsg) {
      case Confirmation(id, m, details) =>
        println(s"confirmation1 details: $details")
        id shouldEqual "XX375"
        blackboard ! KnowledgeUpdate(m, "XX", Map("id" -> "1234"))
        val confirmationMsg2 = expectMsgClass(3.seconds, classOf[Confirmation])
        println("confirmation msg2 received: " + confirmationMsg2)
        // Note that the key "id" is in the model for symbols, not options
        blackboard ! OptionQuery("id", "1234")
        val responseMsg = expectMsgClass(3.seconds, classOf[QueryResponse])
        println("msg received: " + responseMsg)
        inside(responseMsg) {
          case QueryResponse(symbol, attributes) =>
            symbol shouldEqual "XX"
            println(s"attributes: $attributes")
        }
    }
  }
}

class MockAnalyzerBlackboard(testActor: ActorRef) extends Blackboard(Map(classOf[KnowledgeUpdate] -> "marketData", classOf[SymbolQuery] -> "marketData", classOf[OptionQuery] -> "marketData", classOf[CandidateOption] -> "optionAnalyzer", classOf[Confirmation] -> "updateLogger"),
  Map("marketData" -> classOf[MarketData], "optionAnalyzer" -> classOf[OptionAnalyzer], "updateLogger" -> classOf[UpdateLogger])) {

  override def receive: PartialFunction[Any, Unit] = {
    case msg: Confirmation => testActor forward msg
    case msg: QueryResponse => testActor forward msg
    case msg => super.receive(msg)
  }
} 
Example 22
Source File: PortfolioSpec.scala    From CSYE7200_Old   with MIT License 5 votes vote down vote up
package edu.neu.coe.csye7200.hedge_fund.portfolio

import org.scalatest.{BeforeAndAfterAll, Inside, Matchers, WordSpecLike}
import akka.actor.{Actor, ActorRef, ActorSystem, Props}
import akka.testkit._

import scala.concurrent.duration._
import org.scalatest.Inside
import akka.actor.actorRef2Scala
import com.typesafe.config.ConfigFactory
import edu.neu.coe.csye7200.hedge_fund.HedgeFund
import edu.neu.coe.csye7200.hedge_fund.actors._
import edu.neu.coe.csye7200.hedge_fund.model.GoogleOptionModel
import org.scalatest.tagobjects.Slow


class PortfolioSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
    with WordSpecLike with Matchers with Inside with BeforeAndAfterAll {

  def this() = this(ActorSystem("MockPortfolioBlackboard"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }
  
  "read portfolio" taggedAs(Slow) in {
    val config = ConfigFactory.load
    val portfolio = HedgeFund.getPortfolio(config)
    portfolio.name shouldEqual "Test Portfolio"
    println(s"portfolio: $portfolio")
  }

  "send back" taggedAs(Slow) in {
    val model = new GoogleOptionModel()
    val blackboard = system.actorOf(Props.create(classOf[MockPortfolioBlackboard], testActor), "blackboard")
    blackboard ! CandidateOption(model, "XX375", true, Map("strike" -> "45.2"), Map("underlying_id" -> "1234"))
    val confirmationMsg = expectMsgClass(3.seconds, classOf[Confirmation])
    println("confirmation msg received: " + confirmationMsg)
    inside(confirmationMsg) {
      case Confirmation(id, model, details) =>
        println(s"confirmation1 details: $details")
        id shouldEqual "XX375"
        blackboard ! KnowledgeUpdate(model, "XX", Map("id" -> "1234"))
        val confirmationMsg2 = expectMsgClass(3.seconds, classOf[Confirmation])
        println("confirmation msg2 received: " + confirmationMsg2)
        // Note that the key "id" is in the model for symbols, not options
        blackboard ! OptionQuery("id", "1234")
        val responseMsg = expectMsgClass(3.seconds, classOf[QueryResponse])
        println("msg received: " + responseMsg)
        inside(responseMsg) {
          case QueryResponse(symbol, attributes) =>
            symbol shouldEqual "XX"
            println(s"attributes: $attributes")
        }
    }
  }
}

class MockPortfolioBlackboard(testActor: ActorRef) extends Blackboard(Map(classOf[KnowledgeUpdate] -> "marketData", classOf[SymbolQuery] -> "marketData", classOf[OptionQuery] -> "marketData", classOf[CandidateOption] -> "optionAnalyzer", classOf[PortfolioUpdate] -> "updateLogger", classOf[Confirmation] -> "updateLogger"),
  Map("marketData" -> classOf[MarketData], "optionAnalyzer" -> classOf[OptionAnalyzer], "updateLogger" -> classOf[UpdateLogger])) {

  override def receive =
    {
      case msg: Confirmation => testActor forward msg
      case msg: QueryResponse => testActor forward msg
//      case msg: CandidateOption => testActor forward msg
      case msg => super.receive(msg)
    }
} 
Example 23
Source File: OptionAnalyzerSpec.scala    From CSYE7200_Old   with MIT License 5 votes vote down vote up
package edu.neu.coe.csye7200.hedge_fund.actors

import org.scalatest.{BeforeAndAfterAll, Inside, Matchers, WordSpecLike}
import akka.actor.{Actor, ActorRef, ActorSystem, Props}
import akka.testkit._

import scala.concurrent.duration._
import org.scalatest.Inside
import akka.actor.actorRef2Scala
import edu.neu.coe.csye7200.hedge_fund.model.GoogleOptionModel
import org.scalatest.tagobjects.Slow


class OptionAnalyzerSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
    with WordSpecLike with Matchers with Inside with BeforeAndAfterAll {

  def this() = this(ActorSystem("OptionAnalyzerSpec"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "send back" taggedAs(Slow) in {
    val model = new GoogleOptionModel()
    val blackboard = system.actorOf(Props.create(classOf[MockAnalyzerBlackboard], testActor), "blackboard")
    blackboard ! CandidateOption(model, "XX375", true, Map("strike" -> "45.2"), Map("underlying_id" -> "1234", "Sharpe" -> 0.45))
    val confirmationMsg = expectMsgClass(3.seconds, classOf[Confirmation])
    println("confirmation msg received: " + confirmationMsg)
    inside(confirmationMsg) {
      case Confirmation(id, model, details) =>
        println(s"confirmation1 details: $details")
        id shouldEqual "XX375"
        blackboard ! KnowledgeUpdate(model, "XX", Map("id" -> "1234"))
        val confirmationMsg2 = expectMsgClass(3.seconds, classOf[Confirmation])
        println("confirmation msg2 received: " + confirmationMsg2)
        // Note that the key "id" is in the model for symbols, not options
        blackboard ! OptionQuery("id", "1234")
        val responseMsg = expectMsgClass(3.seconds, classOf[QueryResponse])
        println("msg received: " + responseMsg)
        inside(responseMsg) {
          case QueryResponse(symbol, attributes) =>
            symbol shouldEqual "XX"
            println(s"attributes: $attributes")
        }
    }
  }
}

class MockAnalyzerBlackboard(testActor: ActorRef) extends Blackboard(Map(classOf[KnowledgeUpdate] -> "marketData", classOf[SymbolQuery] -> "marketData", classOf[OptionQuery] -> "marketData", classOf[CandidateOption] -> "optionAnalyzer", classOf[Confirmation] -> "updateLogger"),
  Map("marketData" -> classOf[MarketData], "optionAnalyzer" -> classOf[OptionAnalyzer], "updateLogger" -> classOf[UpdateLogger])) {

  override def receive =
    {
      case msg: Confirmation => testActor forward msg
      case msg: QueryResponse => testActor forward msg
      case msg => super.receive(msg)
    }
} 
Example 24
Source File: AbstractEmbeddedPersistentActorSpec.scala    From akka-persistence-couchbase   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.scaladsl.persistence.testkit

import akka.actor.{ ActorRef, Props, actorRef2Scala }
import akka.persistence.PersistentActor
import com.lightbend.lagom.persistence.ActorSystemSpec

import scala.concurrent.duration._

object AbstractEmbeddedPersistentActorSpec {

  final case class Cmd(data: String)
  final case class Evt(data: String)
  case object Get
  final case class State(data: Vector[String] = Vector.empty) {
    def apply(evt: Evt): State = {
      copy(data :+ evt.data)
    }
  }

  def props(persistenceId: String): Props =
    Props(new Persistent(persistenceId))

  class Persistent(override val persistenceId: String) extends PersistentActor {
    var state = State()

    override def receiveRecover = {
      case evt: Evt => state = state(evt)
    }

    override def receiveCommand = {
      case Cmd(data) =>
        persist(Evt(data.toUpperCase)) { evt =>
          state = state(evt)
        }
      case Get => sender() ! state
    }
  }

}

trait AbstractEmbeddedPersistentActorSpec { spec: ActorSystemSpec =>
  import AbstractEmbeddedPersistentActorSpec._

  "A persistent actor" must {
    "store events in the embedded journal" in within(15.seconds) {
      val p = system.actorOf(props("p1"))
      println(implicitly[ActorRef])

      p ! Get
      expectMsg(State())
      p ! Cmd("a")
      p ! Cmd("b")
      p ! Cmd("c")
      p ! Get
      expectMsg(State(Vector("A", "B", "C")))

      // start another with same persistenceId should recover state
      val p2 = system.actorOf(props("p1"))
      p2 ! Get
      expectMsg(State(Vector("A", "B", "C")))
    }

  }

} 
Example 25
Source File: AbstractEmbeddedPersistentActorSpec.scala    From akka-persistence-couchbase   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.javadsl.persistence.testkit

import akka.actor.{ ActorRef, Props, actorRef2Scala }
import akka.persistence.PersistentActor
import com.lightbend.lagom.persistence.ActorSystemSpec

import scala.concurrent.duration._

object AbstractEmbeddedPersistentActorSpec {

  final case class Cmd(data: String)
  final case class Evt(data: String)
  case object Get
  final case class State(data: Vector[String] = Vector.empty) {
    def apply(evt: Evt): State = {
      copy(data :+ evt.data)
    }
  }

  def props(persistenceId: String): Props =
    Props(new Persistent(persistenceId))

  class Persistent(override val persistenceId: String) extends PersistentActor {
    var state = State()

    override def receiveRecover = {
      case evt: Evt => state = state(evt)
    }

    override def receiveCommand = {
      case Cmd(data) =>
        persist(Evt(data.toUpperCase)) { evt =>
          state = state(evt)
        }
      case Get => sender() ! state
    }
  }

}

trait AbstractEmbeddedPersistentActorSpec { spec: ActorSystemSpec =>
  import AbstractEmbeddedPersistentActorSpec._

  "A persistent actor" must {
    "store events in the embedded journal" in within(15.seconds) {
      val p = system.actorOf(props("p1"))
      println(implicitly[ActorRef])

      p ! Get
      expectMsg(State())
      p ! Cmd("a")
      p ! Cmd("b")
      p ! Cmd("c")
      p ! Get
      expectMsg(State(Vector("A", "B", "C")))

      // start another with same persistenceId should recover state
      val p2 = system.actorOf(props("p1"))
      p2 ! Get
      expectMsg(State(Vector("A", "B", "C")))
    }

  }

} 
Example 26
Source File: AbstractEmbeddedPersistentActorSpec.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.scaladsl.persistence.testkit

import akka.actor.ActorRef
import akka.actor.ActorSystem
import akka.actor.Props
import akka.actor.actorRef2Scala
import akka.persistence.PersistentActor
import akka.testkit.ImplicitSender
import akka.testkit.TestKitBase
import com.lightbend.lagom.persistence.ActorSystemSpec
import com.lightbend.lagom.persistence.PersistenceSpec

import scala.collection.immutable
import com.lightbend.lagom.scaladsl.playjson.JsonSerializerRegistry
import com.lightbend.lagom.scaladsl.playjson.JsonSerializer
import scala.concurrent.duration._

object AbstractEmbeddedPersistentActorSpec {
  final case class Cmd(data: String)
  final case class Evt(data: String)
  case object Get
  final case class State(data: Vector[String] = Vector.empty) {
    def apply(evt: Evt): State = {
      copy(data :+ evt.data)
    }
  }

  def props(persistenceId: String): Props =
    Props(new Persistent(persistenceId))

  class Persistent(override val persistenceId: String) extends PersistentActor {
    var state = State()

    override def receiveRecover = {
      case evt: Evt => state = state(evt)
    }

    override def receiveCommand = {
      case Cmd(data) =>
        persist(Evt(data.toUpperCase)) { evt =>
          state = state(evt)
        }
      case Get => sender() ! state
    }
  }

  object EmbeddedPersistentActorSerializers extends JsonSerializerRegistry {
    override def serializers: immutable.Seq[JsonSerializer[_]] = {
      import play.api.libs.json._
      import JsonSerializer.emptySingletonFormat

      Vector(
        JsonSerializer(Json.format[Cmd]),
        JsonSerializer(Json.format[Evt]),
        JsonSerializer(emptySingletonFormat(Get)),
        JsonSerializer(Json.format[State])
      )
    }
  }
}

trait AbstractEmbeddedPersistentActorSpec { spec: ActorSystemSpec =>
  import AbstractEmbeddedPersistentActorSpec._

  "A persistent actor" must {
    "store events in the embedded journal" in within(15.seconds) {
      val p = system.actorOf(props("p1"))
      println(implicitly[ActorRef])

      p ! Get
      expectMsg(State())
      p ! Cmd("a")
      p ! Cmd("b")
      p ! Cmd("c")
      p ! Get
      expectMsg(State(Vector("A", "B", "C")))

      // start another with same persistenceId should recover state
      val p2 = system.actorOf(props("p1"))
      p2 ! Get
      expectMsg(State(Vector("A", "B", "C")))
    }
  }
}