akka.testkit.EventFilter Scala Examples

The following examples show how to use akka.testkit.EventFilter. 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: HelloWorldActorSpec.scala    From Scala-Reactive-Programming   with MIT License 5 votes vote down vote up
package com.packt.publishing.reactive.hello.actor

import akka.actor.{ActorSystem, Props}
import akka.testkit.{EventFilter, TestKit, TestProbe}
import com.packt.publishing.reactive.hello.actor.HelloWorldActorSpec._
import com.packt.publishing.reactive.hello.model.HelloWorld
import com.typesafe.config.ConfigFactory
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

class HelloWorldActorSpec extends TestKit(system)
           with Matchers with WordSpecLike with BeforeAndAfterAll {

  "HelloWorld Actor" should {
      "pass on a HelloWorld message" in {
        val testProbe = TestProbe()
        val helloWorldActor = system.actorOf(Props[HelloWorldActor], "HelloWorldActor")
        EventFilter.info(message = "Hello World", occurrences = 1)
          .intercept(helloWorldActor ! HelloWorld)
      }
  }

  override def afterAll: Unit = {
    shutdown(system)
  }

}

object HelloWorldActorSpec {
  val system = {
    val loggerConfig = ConfigFactory.parseString("akka.loggers = [akka.testkit.TestEventListener]")
    ActorSystem("AkkaHelloWorld", loggerConfig)
  }
} 
Example 2
Source File: BaseAkkaSpec.scala    From reactive-application-development-scala   with Apache License 2.0 5 votes vote down vote up
package com.rarebooks.library

import akka.actor.{ ActorIdentity, ActorRef, ActorSystem, Identify }
import akka.testkit.{ EventFilter, TestEvent, TestProbe }
import org.scalatest.BeforeAndAfterAll
import scala.concurrent.Await
import scala.concurrent.duration.{ DurationInt, FiniteDuration }

abstract class BaseAkkaSpec(actorSystemName: String) extends BaseSpec with BeforeAndAfterAll {

  implicit class TestProbeOps(probe: TestProbe) {
    
    def expectActor(path: String, max: FiniteDuration = 3.seconds): ActorRef = {
      probe.within(max) {
        var actor = null: ActorRef
        probe.awaitAssert {
          (probe.system actorSelection path).tell(Identify(path), probe.ref)
          probe.expectMsgPF(100 milliseconds) {
            case ActorIdentity(`path`, Some(ref)) => actor = ref
          }
        }
        actor
      }
    }
  }

  implicit val system = ActorSystem(actorSystemName)
  system.eventStream.publish(TestEvent.Mute(EventFilter.debug()))
  system.eventStream.publish(TestEvent.Mute(EventFilter.info()))
  system.eventStream.publish(TestEvent.Mute(EventFilter.warning()))
  system.eventStream.publish(TestEvent.Mute(EventFilter.error()))

  override protected def afterAll(): Unit = {
    Await.ready(system.terminate(), 20.seconds)
  }
} 
Example 3
Source File: LibrarianSpec.scala    From reactive-application-development-scala   with Apache License 2.0 5 votes vote down vote up
package com.rarebooks.library

import akka.testkit.{ EventFilter, TestProbe }
import scala.concurrent.duration.{ Duration, MILLISECONDS => Millis }

class LibrarianSpec extends BaseAkkaSpec("as-3003-librarian-spec") {

  import RareBooksProtocol._

  private val findBookDuration =
    Duration(system.settings.config.getDuration("rare-books.librarian.find-book-duration", Millis), Millis)

  private val maxComplainCount: Int = system.settings.config getInt "rare-books.librarian.max-complain-count"

  "Receiving FindBookByTitle" should {
    "When book exists, result in BookFound" in {
      val sender = TestProbe()
      implicit val _ = sender.ref
      val librarian = system.actorOf(Librarian.props(findBookDuration, maxComplainCount))
      librarian ! FindBookByTitle("The Epic of Gilgamesh")
      sender.expectMsgType[BookFound]
    }
    "When book does not exist, log BookNotFound at info" in {
      EventFilter.info(pattern = ".*BookNotFound\\(Book\\(s\\) not found based on Swiss Family Robinson.*",
        occurrences = 1) intercept {
        val librarian = system.actorOf(Librarian.props(findBookDuration, maxComplainCount))
        librarian ! FindBookByTitle("Swiss Family Robinson")
      }
    }
    "When book does not exist, return BookNotFound" in {
      val sender = TestProbe()
      implicit val _ = sender.ref
      val librarian = system.actorOf(Librarian.props(findBookDuration, maxComplainCount))
      librarian ! FindBookByTitle("Swiss Family Robinson")
      sender.expectMsgType[BookNotFound]
    }
  }

  "Receiving FindBookByTopic" should {
    "When book exists, result in BookFound" in {
      val sender = TestProbe()
      implicit val _ = sender.ref
      val librarian = system.actorOf(Librarian.props(findBookDuration, maxComplainCount))
      librarian ! FindBookByTopic(Set(Tradition))
      sender.expectMsgType[BookFound]
    }
    "When book does not exist, log BookNotFound at info" in {
      EventFilter.info(pattern = ".*BookNotFound\\(Book\\(s\\) not found based on Set\\(Unknown\\).*",
        occurrences = 1) intercept {
        val librarian = system.actorOf(Librarian.props(findBookDuration, maxComplainCount))
        librarian ! FindBookByTopic(Set(Unknown))
      }
    }
    "When book does not exist, return BookNotFound" in {
      val sender = TestProbe()
      implicit val _ = sender.ref
      val librarian = system.actorOf(Librarian.props(findBookDuration, maxComplainCount))
      librarian ! FindBookByTopic(Set(Unknown))
      sender.expectMsgType[BookNotFound]
    }
  }

  "Receiving Complain" should {
    "log Credit issued at info" in {
      EventFilter.info(pattern = ".*Credit issued to customer.*", occurrences = 1) intercept {
        val librarian = system.actorOf(Librarian.props(findBookDuration, maxComplainCount))
        librarian ! Complain()
      }
    }
    "send Credit" in {
      val sender = TestProbe()
      implicit val _ = sender.ref
      val librarian = system.actorOf(Librarian.props(findBookDuration, maxComplainCount))
      librarian ! Complain()
      sender.expectMsgType[Credit]
    }
    "result in a ComplainException if maxComplainCount reached" in {
      val librarian = system.actorOf(Librarian.props(findBookDuration, 0))
      EventFilter[Librarian.ComplainException](occurrences = 1) intercept {
        librarian ! Complain()
      }
    }
  }
} 
Example 4
Source File: RareBooksSpec.scala    From reactive-application-development-scala   with Apache License 2.0 5 votes vote down vote up
package com.rarebooks.library

import akka.actor.ActorDSL._
import akka.routing.{RoundRobinRoutingLogic, ActorRefRoutee, Router}
import akka.testkit.{ EventFilter, TestProbe }

class RareBooksSpec extends BaseAkkaSpec("as-3003-rare-books-spec") {

  import RareBooksProtocol._

  val nbrOfLibrarians = system.settings.config getInt "rare-books.nbr-of-librarians"

  "Creating RareBooks" should {
    val rareBooks = system.actorOf(RareBooks.props, "rare-books")
    "create nbrOfLibrarians" in {
      for(i <- 0 to nbrOfLibrarians - 1) {
        TestProbe().expectActor(s"/user/rare-books/librarian-$i")
      }
    }
    "when closed with no requests processed, log `0 requests processed.` at info" in {
      EventFilter.info(pattern = ".*0 requests processed.*", occurrences = 1) intercept {
        rareBooks ! RareBooks.Close
      }
    }
    "when opened, log `Time to open up!` at info" in {
      EventFilter.info(pattern = ".*Time to open up!.*", occurrences = 1) intercept {
        rareBooks ! RareBooks.Open
      }
    }
  }

  "Sending FindBookByTag" should {
    val librarian = TestProbe()
    val rareBooks = actor(new RareBooks() {
      override def createLibrarian(): Router = {
        val routees: Vector[ActorRefRoutee] = Vector.fill(1) {
          val r = librarian.ref
          ActorRefRoutee(r)
        }
        Router(RoundRobinRoutingLogic(), routees)
      }
    })
    "forward to librarian" in {
      val msg = FindBookByTopic(Set(Greece))
      rareBooks ! msg
      librarian.expectMsg(msg)
    }
    "when closed with one request processed, log `1 requests processed.` at info" in {
      EventFilter.info(pattern = ".*1 requests processed.*", occurrences = 1) intercept {
        rareBooks ! RareBooks.Close
      }
    }
  }
} 
Example 5
Source File: LibrarianSpec.scala    From reactive-application-development-scala   with Apache License 2.0 5 votes vote down vote up
package com.rarebooks.library

import akka.testkit.{ EventFilter, TestProbe }
import scala.concurrent.duration.{ Duration, MILLISECONDS => Millis }

class LibrarianSpec extends BaseAkkaSpec("as-3002-librarian-spec") {

  import RareBooksProtocol._

  private val findBookDuration =
    Duration(system.settings.config.getDuration("rare-books.librarian.find-book-duration", Millis), Millis)

  "Receiving FindBookByTitle" should {
    "When book exists, result in BookFound" in {
      val sender = TestProbe()
      implicit val _ = sender.ref
      val librarian = system.actorOf(Librarian.props(findBookDuration))
      librarian ! FindBookByTitle("The Epic of Gilgamesh")
      sender.expectMsgType[BookFound]
    }
    "When book does not exist, log BookNotFound at info" in {
      EventFilter.info(pattern = ".*BookNotFound\\(Book\\(s\\) not found based on Swiss Family Robinson.*",
        occurrences = 1) intercept {
        val librarian = system.actorOf(Librarian.props(findBookDuration))
        librarian ! FindBookByTitle("Swiss Family Robinson")
      }
    }
    "When book does not exist, return BookNotFound" in {
      val sender = TestProbe()
      implicit val _ = sender.ref
      val librarian = system.actorOf(Librarian.props(findBookDuration))
      librarian ! FindBookByTitle("Swiss Family Robinson")
      sender.expectMsgType[BookNotFound]
    }
  }

  "Receiving FindBookByTopic" should {
    "When book exists, result in BookFound" in {
      val sender = TestProbe()
      implicit val _ = sender.ref
      val librarian = system.actorOf(Librarian.props(findBookDuration))
      librarian ! FindBookByTopic(Set(Tradition))
      sender.expectMsgType[BookFound]
    }
    "When book does not exist, log BookNotFound at info" in {
      EventFilter.info(pattern = ".*BookNotFound\\(Book\\(s\\) not found based on Set\\(Unknown\\).*",
        occurrences = 1) intercept {
        val librarian = system.actorOf(Librarian.props(findBookDuration))
        librarian ! FindBookByTopic(Set(Unknown))
      }
    }
    "When book does not exist, return BookNotFound" in {
      val sender = TestProbe()
      implicit val _ = sender.ref
      val librarian = system.actorOf(Librarian.props(findBookDuration))
      librarian ! FindBookByTopic(Set(Unknown))
      sender.expectMsgType[BookNotFound]
    }
  }

  "Receiving Complain" should {
    "log Credit issued at info" in {
      EventFilter.info(pattern = ".*Credit issued to customer.*", occurrences = 1) intercept {
        val librarian = system.actorOf(Librarian.props(findBookDuration))
        librarian ! Complain()
      }
    }
    "send Credit" in {
      val sender = TestProbe()
      implicit val _ = sender.ref
      val librarian = system.actorOf(Librarian.props(findBookDuration))
      librarian ! Complain()
      sender.expectMsgType[Credit]
    }
  }
} 
Example 6
Source File: RareBooksSpec.scala    From reactive-application-development-scala   with Apache License 2.0 5 votes vote down vote up
package com.rarebooks.library

import akka.actor.ActorDSL._
import akka.routing.{RoundRobinRoutingLogic, ActorRefRoutee, Router}
import akka.testkit.{ EventFilter, TestProbe }

class RareBooksSpec extends BaseAkkaSpec("as-3002-rare-books-spec") {

  import RareBooksProtocol._

  val nbrOfLibrarians = system.settings.config getInt "rare-books.nbr-of-librarians"

  "Creating RareBooks" should {
    val rareBooks = system.actorOf(RareBooks.props, "rare-books")
    "create nbrOfLibrarians" in {
      for(i <- 0 to nbrOfLibrarians - 1) {
        TestProbe().expectActor(s"/user/rare-books/librarian-$i")
      }
    }
    "when closed with no requests processed, log `0 requests processed.` at info" in {
      EventFilter.info(pattern = ".*0 requests processed.*", occurrences = 1) intercept {
        rareBooks ! RareBooks.Close
      }
    }
    "when opened, log `Time to open up!` at info" in {
      EventFilter.info(pattern = ".*Time to open up!.*", occurrences = 1) intercept {
        rareBooks ! RareBooks.Open
      }
    }
  }

  "Sending FindBookByTag" should {
    val librarian = TestProbe()
    val rareBooks = actor(new RareBooks() {
      override def createLibrarian(): Router = {
        val routees: Vector[ActorRefRoutee] = Vector.fill(1) {
          val r = librarian.ref
          ActorRefRoutee(r)
        }
        Router(RoundRobinRoutingLogic(), routees)
      }
    })
    "forward to librarian" in {
      val msg = FindBookByTopic(Set(Greece))
      rareBooks ! msg
      librarian.expectMsg(msg)
    }
    "when closed with one request processed, log `1 requests processed.` at info" in {
      EventFilter.info(pattern = ".*1 requests processed.*", occurrences = 1) intercept {
        rareBooks ! RareBooks.Close
      }
    }
  }
} 
Example 7
Source File: LibrarianSpec.scala    From reactive-application-development-scala   with Apache License 2.0 5 votes vote down vote up
package com.rarebooks.library

import akka.testkit.{ EventFilter, TestProbe }
import scala.concurrent.duration.{ Duration, MILLISECONDS => Millis }

class LibrarianSpec extends BaseAkkaSpec("as-5001-librarian-spec") {

  import LibraryProtocol._

  private val findBookDuration =
    Duration(system.settings.config.getDuration("rare-books.librarian.find-book-duration", Millis), Millis)

  private val maxComplainCount: Int = system.settings.config getInt "rare-books.librarian.max-complain-count"

  "Receiving FindBookByTitle" should {
    "When book exists, result in BookFound" in {
      val sender = TestProbe()
      implicit val _ = sender.ref
      val librarian = system.actorOf(Librarian.props(findBookDuration, maxComplainCount))
      librarian ! FindBookByTitle("The Epic of Gilgamesh")
      sender.expectMsgType[BookFound]
    }
    "When book does not exist, log BookNotFound at info" in {
      EventFilter.info(pattern = ".*BookNotFound\\(Book\\(s\\) not found based on Swiss Family Robinson.*",
        occurrences = 1) intercept {
        val librarian = system.actorOf(Librarian.props(findBookDuration, maxComplainCount))
        librarian ! FindBookByTitle("Swiss Family Robinson")
      }
    }
    "When book does not exist, return BookNotFound" in {
      val sender = TestProbe()
      implicit val _ = sender.ref
      val librarian = system.actorOf(Librarian.props(findBookDuration, maxComplainCount))
      librarian ! FindBookByTitle("Swiss Family Robinson")
      sender.expectMsgType[BookNotFound]
    }
  }

  "Receiving FindBookByTopic" should {
    "When book exists, result in BookFound" in {
      val sender = TestProbe()
      implicit val _ = sender.ref
      val librarian = system.actorOf(Librarian.props(findBookDuration, maxComplainCount))
      librarian ! FindBookByTopic(Set(Tradition))
      sender.expectMsgType[BookFound]
    }
    "When book does not exist, log BookNotFound at info" in {
      EventFilter.info(pattern = ".*BookNotFound\\(Book\\(s\\) not found based on Set\\(Unknown\\).*",
        occurrences = 1) intercept {
        val librarian = system.actorOf(Librarian.props(findBookDuration, maxComplainCount))
        librarian ! FindBookByTopic(Set(Unknown))
      }
    }
    "When book does not exist, return BookNotFound" in {
      val sender = TestProbe()
      implicit val _ = sender.ref
      val librarian = system.actorOf(Librarian.props(findBookDuration, maxComplainCount))
      librarian ! FindBookByTopic(Set(Unknown))
      sender.expectMsgType[BookNotFound]
    }
  }

  "Receiving Complain" should {
    "log Credit issued at info" in {
      EventFilter.info(pattern = ".*Credit issued to customer.*", occurrences = 1) intercept {
        val librarian = system.actorOf(Librarian.props(findBookDuration, maxComplainCount))
        librarian ! Complain()
      }
    }
    "send Credit" in {
      val sender = TestProbe()
      implicit val _ = sender.ref
      val librarian = system.actorOf(Librarian.props(findBookDuration, maxComplainCount))
      librarian ! Complain()
      sender.expectMsgType[Credit]
    }
    "result in a ComplainException if maxComplainCount reached" in {
      val librarian = system.actorOf(Librarian.props(findBookDuration, 0))
      EventFilter[Librarian.ComplainException](occurrences = 1) intercept {
        librarian ! Complain()
      }
    }
  }
} 
Example 8
Source File: RareBooksSpec.scala    From reactive-application-development-scala   with Apache License 2.0 5 votes vote down vote up
package com.rarebooks.library

import akka.actor.ActorDSL._
import akka.routing.{RoundRobinRoutingLogic, ActorRefRoutee, Router}
import akka.testkit.{ EventFilter, TestProbe }

class RareBooksSpec extends BaseAkkaSpec("as-5001-rare-books-spec") {

  import LibraryProtocol._

  val nbrOfLibrarians = system.settings.config getInt "rare-books.nbr-of-librarians"

  "Creating RareBooks" should {
    val rareBooks = system.actorOf(RareBooks.props, "rare-books")
    "create nbrOfLibrarians" in {
      for(i <- 0 until nbrOfLibrarians) {
        TestProbe().expectActor(s"/user/rare-books/librarian-$i")
      }
    }
    "when closed with no requests processed, log `0 requests processed.` at info" in {
      EventFilter.info(pattern = ".*0 requests processed.*", occurrences = 1) intercept {
        rareBooks ! RareBooks.Close
      }
    }
    "when opened, log `Time to open up!` at info" in {
      EventFilter.info(pattern = ".*Time to open up!.*", occurrences = 1) intercept {
        rareBooks ! RareBooks.Open
      }
    }
  }

  "Sending FindBookByTag" should {
    val librarian = TestProbe()
    val rareBooks = actor(new RareBooks() {
      override def createLibrarian(): Router = {
        val routees: Vector[ActorRefRoutee] = Vector.fill(1) {
          val r = librarian.ref
          ActorRefRoutee(r)
        }
        Router(RoundRobinRoutingLogic(), routees)
      }
    })
    "forward to librarian" in {
      val msg = FindBookByTopic(Set(Greece))
      rareBooks ! msg
      librarian.expectMsg(msg)
    }
    "when closed with one request processed, log `1 requests processed.` at info" in {
      EventFilter.info(pattern = ".*1 requests processed.*", occurrences = 1) intercept {
        rareBooks ! RareBooks.Close
      }
    }
  }

  "On failure of Librarian" should {
    system.actorOf(RareBooks.props, "rare-books-faulty-librarian")
    val customer = TestProbe()
    val librarian = TestProbe().expectActor("/user/rare-books-faulty-librarian/librarian-1")
    implicit val _ = customer.ref
    "send Credit to customer" in {
      librarian ! Complain()
      customer.expectMsgType[Credit]  // from librarian
      librarian ! Complain()
      customer.expectMsgType[Credit]  // from librarian
      librarian ! Complain()
      customer.expectMsgType[Credit]  // from rareBooks
    }
    "should restart librarian" in {
      librarian ! Complain()
      customer.expectMsgType[Credit]  // from librarian
    }
    "should log `RareBooks sent customer...` credit at info" in {
      EventFilter.info(pattern = ".*RareBooks sent customer.*", occurrences = 1) intercept {
        librarian ! Complain()
        librarian ! Complain()
      }
    }
  }
} 
Example 9
Source File: LibrarianSpec.scala    From reactive-application-development-scala   with Apache License 2.0 5 votes vote down vote up
package com.rarebooks.library

import akka.testkit.{ EventFilter, TestProbe }
import scala.concurrent.duration.{ Duration, MILLISECONDS => Millis }

class LibrarianSpec extends BaseAkkaSpec("as-3004-librarian-spec") {

  import RareBooksProtocol._

  private val findBookDuration =
    Duration(system.settings.config.getDuration("rare-books.librarian.find-book-duration", Millis), Millis)

  private val maxComplainCount: Int = system.settings.config getInt "rare-books.librarian.max-complain-count"

  "Receiving FindBookByTitle" should {
    "When book exists, result in BookFound" in {
      val sender = TestProbe()
      implicit val _ = sender.ref
      val librarian = system.actorOf(Librarian.props(findBookDuration, maxComplainCount))
      librarian ! FindBookByTitle("The Epic of Gilgamesh")
      sender.expectMsgType[BookFound]
    }
    "When book does not exist, log BookNotFound at info" in {
      EventFilter.info(pattern = ".*BookNotFound\\(Book\\(s\\) not found based on Swiss Family Robinson.*",
        occurrences = 1) intercept {
        val librarian = system.actorOf(Librarian.props(findBookDuration, maxComplainCount))
        librarian ! FindBookByTitle("Swiss Family Robinson")
      }
    }
    "When book does not exist, return BookNotFound" in {
      val sender = TestProbe()
      implicit val _ = sender.ref
      val librarian = system.actorOf(Librarian.props(findBookDuration, maxComplainCount))
      librarian ! FindBookByTitle("Swiss Family Robinson")
      sender.expectMsgType[BookNotFound]
    }
  }

  "Receiving FindBookByTopic" should {
    "When book exists, result in BookFound" in {
      val sender = TestProbe()
      implicit val _ = sender.ref
      val librarian = system.actorOf(Librarian.props(findBookDuration, maxComplainCount))
      librarian ! FindBookByTopic(Set(Tradition))
      sender.expectMsgType[BookFound]
    }
    "When book does not exist, log BookNotFound at info" in {
      EventFilter.info(pattern = ".*BookNotFound\\(Book\\(s\\) not found based on Set\\(Unknown\\).*",
        occurrences = 1) intercept {
        val librarian = system.actorOf(Librarian.props(findBookDuration, maxComplainCount))
        librarian ! FindBookByTopic(Set(Unknown))
      }
    }
    "When book does not exist, return BookNotFound" in {
      val sender = TestProbe()
      implicit val _ = sender.ref
      val librarian = system.actorOf(Librarian.props(findBookDuration, maxComplainCount))
      librarian ! FindBookByTopic(Set(Unknown))
      sender.expectMsgType[BookNotFound]
    }
  }

  "Receiving Complain" should {
    "log Credit issued at info" in {
      EventFilter.info(pattern = ".*Credit issued to customer.*", occurrences = 1) intercept {
        val librarian = system.actorOf(Librarian.props(findBookDuration, maxComplainCount))
        librarian ! Complain()
      }
    }
    "send Credit" in {
      val sender = TestProbe()
      implicit val _ = sender.ref
      val librarian = system.actorOf(Librarian.props(findBookDuration, maxComplainCount))
      librarian ! Complain()
      sender.expectMsgType[Credit]
    }
    "result in a ComplainException if maxComplainCount reached" in {
      val librarian = system.actorOf(Librarian.props(findBookDuration, 0))
      EventFilter[Librarian.ComplainException](occurrences = 1) intercept {
        librarian ! Complain()
      }
    }
  }
} 
Example 10
Source File: RareBooksSpec.scala    From reactive-application-development-scala   with Apache License 2.0 5 votes vote down vote up
package com.rarebooks.library

import akka.actor.ActorDSL._
import akka.routing.{RoundRobinRoutingLogic, ActorRefRoutee, Router}
import akka.testkit.{ EventFilter, TestProbe }

class RareBooksSpec extends BaseAkkaSpec("as-3004-rare-books-spec") {

  import RareBooksProtocol._

  val nbrOfLibrarians = system.settings.config getInt "rare-books.nbr-of-librarians"

  "Creating RareBooks" should {
    val rareBooks = system.actorOf(RareBooks.props, "rare-books")
    "create nbrOfLibrarians" in {
      for(i <- 0 to nbrOfLibrarians - 1) {
        TestProbe().expectActor(s"/user/rare-books/librarian-$i")
      }
    }
    "when closed with no requests processed, log `0 requests processed.` at info" in {
      EventFilter.info(pattern = ".*0 requests processed.*", occurrences = 1) intercept {
        rareBooks ! RareBooks.Close
      }
    }
    "when opened, log `Time to open up!` at info" in {
      EventFilter.info(pattern = ".*Time to open up!.*", occurrences = 1) intercept {
        rareBooks ! RareBooks.Open
      }
    }
  }

  "Sending FindBookByTag" should {
    val librarian = TestProbe()
    val rareBooks = actor(new RareBooks() {
      override def createLibrarian(): Router = {
        val routees: Vector[ActorRefRoutee] = Vector.fill(1) {
          val r = librarian.ref
          ActorRefRoutee(r)
        }
        Router(RoundRobinRoutingLogic(), routees)
      }
    })
    "forward to librarian" in {
      val msg = FindBookByTopic(Set(Greece))
      rareBooks ! msg
      librarian.expectMsg(msg)
    }
    "when closed with one request processed, log `1 requests processed.` at info" in {
      EventFilter.info(pattern = ".*1 requests processed.*", occurrences = 1) intercept {
        rareBooks ! RareBooks.Close
      }
    }
  }

  "On failure of Librarian" should {
    system.actorOf(RareBooks.props, "rare-books-faulty-librarian")
    val customer = TestProbe()
    val librarian = TestProbe().expectActor("/user/rare-books-faulty-librarian/librarian-1")
    implicit val _ = customer.ref
    "send Credit to customer" in {
      librarian ! Complain()
      customer.expectMsgType[Credit]  // from librarian
      librarian ! Complain()
      customer.expectMsgType[Credit]  // from librarian
      librarian ! Complain()
      customer.expectMsgType[Credit]  // from rareBooks
    }
    "should restart librarian" in {
      librarian ! Complain()
      customer.expectMsgType[Credit]  // from librarian
    }
    "should log `RareBooks sent customer...` credit at info" in {
      EventFilter.info(pattern = ".*RareBooks sent customer.*", occurrences = 1) intercept {
        librarian ! Complain()
        librarian ! Complain()
      }
    }
  }
} 
Example 11
Source File: LibrarianSpec.scala    From reactive-application-development-scala   with Apache License 2.0 5 votes vote down vote up
package com.rarebooks.library

import akka.testkit.{ EventFilter, TestProbe }
import scala.concurrent.duration.{ Duration, MILLISECONDS => Millis }

class LibrarianSpec extends BaseAkkaSpec("as-3001-librarian-spec") {

  import RareBooksProtocol._

  private val findBookDuration =
    Duration(system.settings.config.getDuration("rare-books.librarian.find-book-duration", Millis), Millis)

  "Receiving FindBookByTitle" should {
    "When book exists, result in BookFound" in {
      val sender = TestProbe()
      implicit val _ = sender.ref
      val librarian = system.actorOf(Librarian.props(findBookDuration))
      librarian ! FindBookByTitle("The Epic of Gilgamesh")
      sender.expectMsgType[BookFound]
    }
    "When book does not exist, log BookNotFound at info" in {
      EventFilter.info(pattern = ".*BookNotFound\\(Book\\(s\\) not found based on Swiss Family Robinson.*",
        occurrences = 1) intercept {
        val librarian = system.actorOf(Librarian.props(findBookDuration))
        librarian ! FindBookByTitle("Swiss Family Robinson")
      }
    }
    "When book does not exist, return BookNotFound" in {
      val sender = TestProbe()
      implicit val _ = sender.ref
      val librarian = system.actorOf(Librarian.props(findBookDuration))
      librarian ! FindBookByTitle("Swiss Family Robinson")
      sender.expectMsgType[BookNotFound]
    }
  }

  "Receiving FindBookByTopic" should {
    "When book exists, result in BookFound" in {
      val sender = TestProbe()
      implicit val _ = sender.ref
      val librarian = system.actorOf(Librarian.props(findBookDuration))
      librarian ! FindBookByTopic(Set(Tradition))
      sender.expectMsgType[BookFound]
    }
    "When book does not exist, log BookNotFound at info" in {
      EventFilter.info(pattern = ".*BookNotFound\\(Book\\(s\\) not found based on Set\\(Unknown\\).*",
        occurrences = 1) intercept {
        val librarian = system.actorOf(Librarian.props(findBookDuration))
        librarian ! FindBookByTopic(Set(Unknown))
      }
    }
    "When book does not exist, return BookNotFound" in {
      val sender = TestProbe()
      implicit val _ = sender.ref
      val librarian = system.actorOf(Librarian.props(findBookDuration))
      librarian ! FindBookByTopic(Set(Unknown))
      sender.expectMsgType[BookNotFound]
    }
  }

  "Receiving Complain" should {
    "log Credit issued at info" in {
      EventFilter.info(pattern = ".*Credit issued to customer.*", occurrences = 1) intercept {
        val librarian = system.actorOf(Librarian.props(findBookDuration))
        librarian ! Complain()
      }
    }
    "send Credit" in {
      val sender = TestProbe()
      implicit val _ = sender.ref
      val librarian = system.actorOf(Librarian.props(findBookDuration))
      librarian ! Complain()
      sender.expectMsgType[Credit]
    }
  }
} 
Example 12
Source File: RareBooksSpec.scala    From reactive-application-development-scala   with Apache License 2.0 5 votes vote down vote up
package com.rarebooks.library

import akka.actor.ActorDSL._
import akka.testkit.{ EventFilter, TestProbe }

class RareBooksSpec extends BaseAkkaSpec("as-3001-rare-books-spec") {

  import RareBooksProtocol._

  "Creating RareBooks" should {
    val rareBooks = system.actorOf(RareBooks.props, "rare-books")
    "create child actor librarian" in {
      TestProbe().expectActor("/user/rare-books/librarian")
    }
    "when closed with no requests processed, log `0 requests processed.` at info" in {
      EventFilter.info(pattern = ".*0 requests processed.*", occurrences = 1) intercept {
        rareBooks ! RareBooks.Close
      }
    }
    "when opened, log `Time to open up!` at info" in {
      EventFilter.info(pattern = ".*Time to open up!.*", occurrences = 1) intercept {
        rareBooks ! RareBooks.Open
      }
    }
  }

  "Sending FindBookByTag" should {
    val librarian = TestProbe()
    val rareBooks = actor(new RareBooks() {
      override def createLibrarian() = librarian.ref
    })
    "forward to librarian" in {
      val msg = FindBookByTopic(Set(Greece))
      rareBooks ! msg
      librarian.expectMsg(msg)
    }
    "when closed with one request processed, log `1 requests processed.` at info" in {
      EventFilter.info(pattern = ".*1 requests processed.*", occurrences = 1) intercept {
        rareBooks ! RareBooks.Close
      }
    }
  }
} 
Example 13
Source File: JsonReceiverSpec.scala    From incubator-retired-iota   with Apache License 2.0 5 votes vote down vote up
package org.apache.iota.fey

import java.nio.file.{Files, Paths}

import akka.actor.ActorRef
import akka.testkit.{EventFilter, TestProbe}
import ch.qos.logback.classic.Level
import scala.concurrent.duration.{DurationInt, FiniteDuration}

class JsonReceiverSpec extends BaseAkkaSpec with LoggingTest{


  class ReceiverTest(verifyActor: ActorRef) extends JsonReceiver{

    override def execute(): Unit = {
      verifyActor ! "EXECUTED"
      Thread.sleep(500)
    }

    override def exceptionOnRun(e: Exception): Unit = {
      verifyActor ! "INTERRUPTED"
    }

  }

  val verifyTB = TestProbe("RECEIVER-TEST")
  val receiver = new ReceiverTest(verifyTB.ref)

  "Executing validJson in JsonReceiver" should {
    "return false when json schema is not right" in {
      receiver.validJson(getJSValueFromString(Utils_JSONTest.test_json_schema_invalid)) should be(false)
    }
    "log message to Error" in {
      ("Incorrect JSON schema \n/ensembles/0 \n\tErrors: Property command missing") should beLoggedAt(Level.ERROR)
    }
    "return true when Json schema is valid" in {
      receiver.validJson(getJSValueFromString(Utils_JSONTest.create_json_test)) should be(true)
    }
  }

  "Executing checkForLocation in JsonReceiver" should {
    "log message at Debug level" in {
      receiver.checkForLocation(getJSValueFromString(Utils_JSONTest.test_json_schema_invalid))
      "Location not defined in JSON" should beLoggedAt(Level.DEBUG)
    }
    "download jar dynamically from URL" in {
      receiver.checkForLocation(getJSValueFromString(Utils_JSONTest.location_test))
      Files.exists(Paths.get(s"${CONFIG.DYNAMIC_JAR_REPO}/fey-stream.jar")) should be(true)
    }
  }

  var watchThread: Thread = _
  "Start a Thread with the JSON receiver" should {
    "Start Thread" in {
      watchThread = new Thread(receiver, "TESTING-RECEIVERS-IN-THREAD")
      watchThread.setDaemon(true)
      watchThread.start()
      TestProbe().isThreadRunning("TESTING-RECEIVERS-IN-THREAD") should be(true)
    }
    "execute execute() method inside run" in {
      verifyTB.expectMsgAllOf(600.milliseconds,"EXECUTED","EXECUTED")
    }
  }

  "Interrupting the receiver Thread" should {
    "Throw Interrupted exception" in {
      EventFilter[InterruptedException]() intercept {
        watchThread.interrupt()
        watchThread.join()
      }
    }
    "execute exceptionOnRun method" in {
      verifyTB.receiveWhile(1200.milliseconds) {
        case "EXECUTED" =>
      }
      verifyTB.expectMsg("INTERRUPTED")
    }
  }


} 
Example 14
Source File: ConsumerSpec.scala    From akka-cluster-load-balancing   with MIT License 5 votes vote down vote up
package kamkor.actor

import scala.concurrent.duration.DurationInt

import org.scalatest.{ BeforeAndAfterAll, Matchers, WordSpecLike }

import com.typesafe.config.ConfigFactory

import akka.actor.ActorSystem
import akka.testkit.{ EventFilter, ImplicitSender, TestKit }

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

  def this() = this(
    ActorSystem("ClusterSystem",
      ConfigFactory.parseString("""        
        akka.loggers = ["akka.testkit.TestEventListener"]
        akka.loglevel = "DEBUG"        
        """)))

  override def afterAll: Unit = TestKit.shutdownActorSystem(system)

  "A Customer actor that processes 1 message for 200 millis" must {
    "log endedProcessing with debug level 5 times within 1-1.3 seconds" in {
      val consumer = system.actorOf(Consumer.props(processingTimeMillis = 200))
      val data: Array[Int] = Array(0, 1, 2)

      // akka scheduling is not 100% accurate http://doc.akka.io/docs/akka/snapshot/scala/scheduler.html
      within(999.millis, 1300.millis) {
        EventFilter.debug(pattern = "endProcessing", occurrences = 5) intercept {
          for (_ <- 0 until 5) {
            consumer ! data
          }
        }
      }
    }
  }

} 
Example 15
Source File: CouchbaseReplaySpec.scala    From akka-persistence-couchbase   with Apache License 2.0 5 votes vote down vote up
package akka.persistence.couchbase

import akka.actor.PoisonPill
import akka.persistence.couchbase.scaladsl.AbstractCouchbaseSpec
import akka.testkit.EventFilter
import com.couchbase.client.java.document.JsonDocument
import com.typesafe.config.ConfigFactory

class CouchbaseReplaySpec
    extends AbstractCouchbaseSpec(
      "CouchbaseReplaySpec",
      ConfigFactory.parseString("""
 akka.loggers = [akka.testkit.TestEventListener]
  """.stripMargin)
    )
    with CouchbaseBucketSetup {
  "Replay" must {
    "fail if next document found" in new Setup {
      override def initialPersistedEvents: Int = 2
      // pid-1 and pid-2 are used as the first two document ids
      probe.watch(persistentActor)
      persistentActor ! PoisonPill
      probe.expectTerminated(persistentActor)

      couchbaseSession.insert(JsonDocument.create(s"$pid-3")).futureValue

      EventFilter[RuntimeException](
        message = "Read highest sequence nr 2 but found document with id 1-3",
        occurrences = 1
      ).intercept {
        system.actorOf(TestActor.props(pid))
      }
    }
  }
} 
Example 16
Source File: CouchbaseConfigValidatorSpec.scala    From akka-persistence-couchbase   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.persistence.couchbase

import akka.actor.ActorSystem
import akka.event.Logging
import akka.testkit.EventFilter
import com.typesafe.config.ConfigFactory
import org.scalatest.{BeforeAndAfterAll, MustMatchers, WordSpec}

import scala.concurrent.duration._
import scala.concurrent.Await

class MyException extends RuntimeException("MyException")

class CouchbaseConfigValidatorSpec extends WordSpec with MustMatchers with BeforeAndAfterAll {
  val akkaTestLogging = ConfigFactory.parseString("akka.loggers = [akka.testkit.TestEventListener]")
  implicit val system = ActorSystem("test", akkaTestLogging)
  val log = Logging(system, classOf[CouchbaseConfigValidatorSpec])

  override def afterAll =
    Await.result(system.terminate(), Duration.Inf)

  "CouchbaseConfigValidator" should {
    "detect when bucket is not set" in {
      val config = ConfigFactory.parseString("""some.config.setting = 1""".stripMargin)
      EventFilter
        .error("Configuration for [test.bucket] must be set in application.conf ", occurrences = 1)
        .intercept {
          CouchbaseConfigValidator.validateBucket("test", config, log)
        }
    }
    "detect when bucket is set to null" in {
      val config = ConfigFactory.parseString("""testpath1.bucket = null""".stripMargin)
      EventFilter
        .error("Configuration for [testpath1.bucket] must be set in application.conf ", occurrences = 1)
        .intercept {
          CouchbaseConfigValidator.validateBucket("testpath1", config, log)
        }
    }
    "pass when bucket is specified" in {
      val config = ConfigFactory.parseString("""sample.path.bucket = bucketname""".stripMargin)
      // expect only one "another error" in the log
      EventFilter.error(occurrences = 1).intercept {
        CouchbaseConfigValidator.validateBucket("sample.path", config, log)
        log.error("another error")
      }
    }
  }
} 
Example 17
Source File: Greeter01Test.scala    From 006877   with MIT License 5 votes vote down vote up
package aia.testdriven
import akka.testkit.{ CallingThreadDispatcher, EventFilter, TestKit }
import akka.actor.{ Props, ActorSystem }
import com.typesafe.config.ConfigFactory
import org.scalatest.WordSpecLike


import Greeter01Test._

class Greeter01Test extends TestKit(testSystem)
  with WordSpecLike
  with StopSystemAfterAll {

  "The Greeter" must {
    "say Hello World! when a Greeting(\"World\") is sent to it" in {
      val dispatcherId = CallingThreadDispatcher.Id
      val props = Props[Greeter].withDispatcher(dispatcherId)
      val greeter = system.actorOf(props)
      EventFilter.info(message = "Hello World!",
        occurrences = 1).intercept {
          greeter ! Greeting("World")
        }
    }
  }
}

object Greeter01Test {
  val testSystem = {
    val config = ConfigFactory.parseString(
      """
         akka.loggers = [akka.testkit.TestEventListener]
      """)
    ActorSystem("testsystem", config)
  }
} 
Example 18
Source File: PartitionCreatorActorTest.scala    From schedoscope   with Apache License 2.0 5 votes vote down vote up
package org.schedoscope.scheduler.actors

import akka.actor.{Actor, ActorRef, ActorSystem}
import akka.testkit.{EventFilter, ImplicitSender, TestActorRef, TestKit, TestProbe}
import com.typesafe.config.ConfigFactory
import org.scalatest.{BeforeAndAfterAll, FlatSpecLike, Matchers}
import org.schedoscope.Schedoscope

class PartitionCreatorActorTest extends TestKit(ActorSystem("schedoscope",
  ConfigFactory.parseString("""akka.loggers = ["akka.testkit.TestEventListener"]""")))
  with ImplicitSender
  with FlatSpecLike
  with Matchers
  with BeforeAndAfterAll {

  override def afterAll(): Unit = {
    TestKit.shutdownActorSystem(system)
  }

  val msgHub = TestProbe()
  val settings = Schedoscope.settings


  case class ToPCA(msg: String)

  class TestRouter(to: ActorRef) extends Actor {
    val pca = TestActorRef(new PartitionCreatorActor("", "", "", msgHub.ref) {
      override def getSchemaManager(jdbcUrl: String, metaStoreUri: String, serverKerberosPrincipal: String) = {
        null
      }

      override def schemaRouter = msgHub.ref
    })

    def receive = {
      case ToPCA(m) => pca forward (m)

      case "tick" => to forward "tick"
    }
  }

  it should "send tick msg upon start" in {
    TestActorRef(new TestRouter(msgHub.ref))
    msgHub.expectMsg("tick")
  }

  it should "change to active state upon receive of tick msg" in {
    val router = TestActorRef(new TestRouter(msgHub.ref))

    EventFilter.info(message = "PARTITION CREATOR ACTOR: changed to active state.", occurrences = 1) intercept {
      msgHub.send(router, ToPCA("tick"))
    }
  }

} 
Example 19
Source File: MetadataLoggerActorTest.scala    From schedoscope   with Apache License 2.0 5 votes vote down vote up
package org.schedoscope.scheduler.actors

import akka.actor.{Actor, ActorRef, ActorSystem}
import akka.testkit.{EventFilter, ImplicitSender, TestActorRef, TestKit, TestProbe}
import com.typesafe.config.ConfigFactory
import org.scalatest.{BeforeAndAfterAll, FlatSpecLike, Matchers}
import org.schedoscope.Schedoscope


class MetadataLoggerActorTest extends TestKit(ActorSystem("schedoscope",
  ConfigFactory.parseString("""akka.loggers = ["akka.testkit.TestEventListener"]""")))
  with ImplicitSender
  with FlatSpecLike
  with Matchers
  with BeforeAndAfterAll {

  override def afterAll(): Unit = {
    TestKit.shutdownActorSystem(system)
  }

  val msgHub = TestProbe()
  val settings = Schedoscope.settings


  case class toPCA(msg: String)

  class TestRouter(to: ActorRef) extends Actor {
    val pca = TestActorRef(new MetadataLoggerActor("", "", "") {
      override def getSchemaManager(jdbcUrl: String, metaStoreUri: String, serverKerberosPrincipal: String) = {
        null
      }

      override def schemaRouter = msgHub.ref
    })

    def receive = {
      case toPCA(m) => pca forward (m)

      case "tick" => to forward "tick"
    }
  }

  it should "send tick msg upon start" in {
    TestActorRef(new TestRouter(msgHub.ref))
    msgHub.expectMsg("tick")
  }

  it should "change to active state upon receive of tick msg" in {
    val router = TestActorRef(new TestRouter(msgHub.ref))

    EventFilter.info(message = "METADATA LOGGER ACTOR: changed to active state.", occurrences = 1) intercept {
      msgHub.send(router, toPCA("tick"))
    }
  }

} 
Example 20
Source File: EncryptorActorSpec.scala    From changestream   with MIT License 5 votes vote down vote up
package changestream.actors

import akka.actor.Props
import akka.testkit.EventFilter
import akka.testkit.TestActorRef
import changestream.actors.EncryptorActor._
import changestream.helpers.{Base, Config}
import com.typesafe.config.ConfigFactory
import spray.json._

class EncryptorActorSpec extends Base with Config {
  val config = ConfigFactory.
    parseString("changestream.encryptor.encrypt-fields = \"do_encrypt, do_encrypt_hash,parent.do_encrypt_hash\"").
    withFallback(testConfig).
    getConfig("changestream.encryptor")
  val encryptorActor = TestActorRef(Props(classOf[EncryptorActor], config))

  val sourceObject = JsObject(
    "no_encrypt" -> JsString("a"),
    "no_encrypt_hash" -> JsObject("aa" -> JsNumber(1), "bb" -> JsNumber(2)),
    "do_encrypt" -> JsString("b"),
    "do_encrypt_hash" -> JsObject("aa" -> JsNumber(1), "bb" -> JsNumber(2)),
    "parent" -> JsObject(
      "do_encrypt_hash" -> JsObject("aa" -> JsNumber(1), "bb" -> JsNumber(2)),
      "no_encrypt_hash" -> JsObject("cc" -> JsNumber(3), "dd" -> JsNumber(4))
    )
  )

  "When encrypting/decrypting data" should {
    "expect encrypt -> decrypt to result in same plaintext for a single message" in {
      encryptorActor ! Plaintext(sourceObject)
      val encryptResponse = expectMsgType[JsObject]

      encryptorActor ! Ciphertext(encryptResponse)
      val decryptResponse = expectMsgType[JsObject]

      sourceObject.compactPrint should be(decryptResponse.compactPrint)
    }

    "expect encrypt to correctly encrypt all fields in the message marked for encrypt" in {
      encryptorActor ! Plaintext(sourceObject)
      val encryptResponse = expectMsgType[JsObject]

      encryptResponse.fields("no_encrypt") should be(JsString("a"))
      encryptResponse.fields("no_encrypt_hash") should be(JsObject("aa" -> JsNumber(1), "bb" -> JsNumber(2)))
      encryptResponse.fields("do_encrypt").isInstanceOf[JsString] should be(true)
      encryptResponse.fields("do_encrypt_hash").isInstanceOf[JsString] should be(true)
      encryptResponse.fields("parent").asJsObject.fields("no_encrypt_hash") should be(JsObject("cc" -> JsNumber(3), "dd" -> JsNumber(4)))
      encryptResponse.fields("parent").asJsObject.fields("do_encrypt_hash").isInstanceOf[JsString] should be(true)
    }

    "expect encrypt to correctly decrypt all fields in the message marked for encrypt" in {
      encryptorActor ! Plaintext(sourceObject)
      val encryptResponse = expectMsgType[JsObject]

      encryptorActor ! Ciphertext(encryptResponse)
      val decryptResponse = expectMsgType[JsObject]

      decryptResponse.fields("no_encrypt") should be(JsString("a"))
      decryptResponse.fields("no_encrypt_hash") should be(JsObject("aa" -> JsNumber(1), "bb" -> JsNumber(2)))
      decryptResponse.fields("do_encrypt") should be(JsString("b"))
      decryptResponse.fields("do_encrypt_hash") should be(JsObject("aa" -> JsNumber(1), "bb" -> JsNumber(2)))
      decryptResponse.fields("parent").asJsObject.fields("do_encrypt_hash") should be(JsObject("aa" -> JsNumber(1), "bb" -> JsNumber(2)))
      decryptResponse.fields("parent").asJsObject.fields("no_encrypt_hash") should be(JsObject("cc" -> JsNumber(3), "dd" -> JsNumber(4)))
    }

    "expect decrypt of invalid ciphertext to result in an exception" in {
      EventFilter[IllegalArgumentException](occurrences = 1) intercept {
        encryptorActor ! Ciphertext(sourceObject)
      }
    }
  }
} 
Example 21
Source File: DataProducerSpec.scala    From reactive-kafka-microservice-template   with Apache License 2.0 5 votes vote down vote up
package akka.kafka

import akka.Done
import akka.actor.ActorSystem
import akka.stream.QueueOfferResult
import akka.stream.QueueOfferResult.Enqueued
import akka.stream.scaladsl.SourceQueueWithComplete
import akka.testkit.{DefaultTimeout, EventFilter, ImplicitSender, TestActorRef, TestKit, TestProbe}
import com.omearac.producers.DataProducer
import com.omearac.producers.DataProducer.PublishMessages
import com.omearac.shared.AkkaStreams
import com.omearac.shared.EventMessages.{ActivatedProducerStream, MessagesPublished}
import com.omearac.shared.KafkaMessages.ExampleAppEvent
import com.typesafe.config.ConfigFactory
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

import scala.concurrent.Future


class DataProducerSpec extends TestKit(ActorSystem("DataProducerSpec", ConfigFactory.parseString(
  """
    akka.loggers = ["akka.testkit.TestEventListener"] """)))
  with DefaultTimeout with ImplicitSender
  with WordSpecLike with Matchers with BeforeAndAfterAll
  with AkkaStreams {

  val testProducer = TestActorRef(new DataProducer)
  val producerActor = testProducer.underlyingActor

  val mockProducerStream: SourceQueueWithComplete[Any] = new SourceQueueWithComplete[Any] {
    override def complete(): Unit = println("complete")

    override def fail(ex: Throwable): Unit = println("fail")

    override def offer(elem: Any): Future[QueueOfferResult] = Future {
      Enqueued
    }

    override def watchCompletion(): Future[Done] = Future {
      Done
    }
  }

  override def afterAll: Unit = {
    shutdown()
  }

  //Create an test event listener for the local message bus
  val testEventListener = TestProbe()
  system.eventStream.subscribe(testEventListener.ref, classOf[ExampleAppEvent])


  "Sending ActivatedProducerStream to DataProducer in receive state" should {
    "save the stream ref and change state to producing " in {
      testProducer ! ActivatedProducerStream(mockProducerStream, "TestTopic")
      Thread.sleep(500)
      producerActor.producerStream should be(mockProducerStream)
      EventFilter.error(message = "DataProducer got the unknown message while producing: testMessage", occurrences = 1) intercept {
        testProducer ! "testMessage"
      }
    }
  }

  "Sending PublishMessages(number: Int) to DataProducer in publishData state" should {
    "return MessagesPublished(number: Int) and publish the local event " in {
      val producing = producerActor.publishData
      producerActor.context.become(producing)
      producerActor.producerStream = mockProducerStream
      val resultMessage = MessagesPublished(5)
      testProducer ! PublishMessages(5)
      expectMsg(resultMessage)
      testEventListener.expectMsgPF() {
        case ExampleAppEvent(_, _, m) => if (m == resultMessage.toString) () else fail()
      }
    }
  }
} 
Example 22
Source File: EventProducerSpec.scala    From reactive-kafka-microservice-template   with Apache License 2.0 5 votes vote down vote up
package akka.kafka

import java.util.Date

import akka.Done
import akka.actor.ActorSystem
import akka.serialization.Serialization
import akka.stream.QueueOfferResult
import akka.stream.QueueOfferResult.Enqueued
import akka.stream.scaladsl.SourceQueueWithComplete
import akka.testkit.{DefaultTimeout, EventFilter, ImplicitSender, TestActorRef, TestKit, TestProbe}
import com.omearac.producers.EventProducer
import com.omearac.shared.AkkaStreams
import com.omearac.shared.EventMessages.{ActivatedProducerStream, MessagesPublished}
import com.omearac.shared.KafkaMessages.ExampleAppEvent
import com.typesafe.config.ConfigFactory
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

import scala.concurrent.Future


class EventProducerSpec extends TestKit(ActorSystem("EventProducerSpec",ConfigFactory.parseString("""
    akka.loggers = ["akka.testkit.TestEventListener"] """)))
    with DefaultTimeout with ImplicitSender
    with WordSpecLike with Matchers with BeforeAndAfterAll
    with AkkaStreams {

    val testProducer = TestActorRef(new EventProducer)
    val producerActor = testProducer.underlyingActor
    val mockProducerStream: SourceQueueWithComplete[Any] = new SourceQueueWithComplete[Any] {
        override def complete(): Unit = println("complete")

        override def fail(ex: Throwable): Unit = println("fail")

        override def offer(elem: Any): Future[QueueOfferResult] = Future{Enqueued}

        override def watchCompletion(): Future[Done] = Future{Done}
    }

    override def afterAll: Unit = {
        shutdown()
    }

    //Create an test event listener for the local message bus
    val testEventListener = TestProbe()
    system.eventStream.subscribe(testEventListener.ref, classOf[ExampleAppEvent])


    "Sending ActivatedProducerStream to EventProducer in receive state" should {
        "save the stream ref and change state to producing " in {
            testProducer ! ActivatedProducerStream(mockProducerStream, "TestTopic")
            Thread.sleep(500)
            producerActor.producerStream should be(mockProducerStream)
            EventFilter.error(message = "EventProducer got the unknown message while producing: testMessage", occurrences = 1) intercept {
                testProducer ! "testMessage"
            }
        }
    }

    "Sending ExampleAppEvent to system bus while EventProducer is in publishEvent state" should {
        "offer the ExampleAppEvent to the stream " in {
            val producingState = producerActor.publishEvent
            producerActor.context.become(producingState)
            producerActor.producerStream = mockProducerStream
            val dateFormat = new java.text.SimpleDateFormat("dd:MM:yy:HH:mm:ss.SSS")
            lazy val timetag = dateFormat.format(new Date(System.currentTimeMillis()))
            val eventMsg = MessagesPublished(5)
            val testMessage = ExampleAppEvent(timetag,Serialization.serializedActorPath(self),eventMsg.toString)
            system.eventStream.publish(testMessage)
            testEventListener.expectMsgPF(){
                case ExampleAppEvent(_,_,m) => if (m == eventMsg.toString) () else fail()
            }
        }
    }
 } 
Example 23
Source File: BaseAkkaSpec.scala    From incubator-retired-iota   with Apache License 2.0 5 votes vote down vote up
package org.apache.iota.fey

import java.nio.file.Paths

import akka.actor.{ActorIdentity, ActorRef, ActorSystem, Identify, Props}
import akka.testkit.{EventFilter, TestEvent, TestProbe}
import com.typesafe.config.ConfigFactory
import org.scalatest.BeforeAndAfterAll
import play.api.libs.json._

import scala.concurrent.duration.{DurationInt, FiniteDuration}
import scala.concurrent.Await

class BaseAkkaSpec extends BaseSpec with BeforeAndAfterAll with LoggingTest{

  //Load default configuration for Fey when running tests
  resetCapturedLogs()
  CONFIG.loadUserConfiguration(Paths.get(TestSetup.configTest.toURI()).toFile().getAbsolutePath)
  TestSetup.setup()

  val systemName = "FEY-TEST"
  implicit val system = ActorSystem(systemName, ConfigFactory.parseString("""akka.loggers = ["akka.testkit.TestEventListener"]"""))
  system.eventStream.publish(TestEvent.Mute(EventFilter.debug()))
  system.eventStream.publish(TestEvent.Mute(EventFilter.info()))
  system.eventStream.publish(TestEvent.Mute(EventFilter.warning()))
  system.eventStream.publish(TestEvent.Mute(EventFilter.error()))

  val globalIdentifierName = "GLOBAL-IDENTIFIER"
  val globalIdentifierRef = system.actorOf(Props[IdentifyFeyActors],globalIdentifierName)

  override protected def afterAll(): Unit = {
    //Force reload of GenericActor's jar
    Utils.loadedJars.remove("fey-test-actor.jar")
    Monitor.events.removeAllNodes()
    Await.ready(system.terminate(), 20.seconds)
  }

  implicit class TestProbeOps(probe: TestProbe) {

    def expectActor(path: String, max: FiniteDuration = 3.seconds): ActorRef = {
      probe.within(max) {
        var actor = null: ActorRef
        probe.awaitAssert {
          (probe.system actorSelection path).tell(Identify(path), probe.ref)
          probe.expectMsgPF(100 milliseconds) {
            case ActorIdentity(`path`, Some(ref)) => actor = ref
          }
        }
        actor
      }
    }

    def expectActorInSystem(path: String, lookInSystem: ActorSystem, max: FiniteDuration = 3.seconds): ActorRef = {
      probe.within(max) {
        var actor = null: ActorRef
        probe.awaitAssert {
          (lookInSystem actorSelection path).tell(Identify(path), probe.ref)
          probe.expectMsgPF(100 milliseconds) {
            case ActorIdentity(`path`, Some(ref)) => actor = ref
          }
        }
        actor
      }
    }

    def verifyActorTermination(actor: ActorRef)(implicit system: ActorSystem): Unit = {
      val watcher = TestProbe()
      watcher.watch(actor)
      watcher.expectTerminated(actor)
    }

    def notExpectActor(path: String, max: FiniteDuration = 3.seconds): Unit = {
      probe.within(max) {
        probe.awaitAssert {
          (probe.system actorSelection path).tell(Identify(path), probe.ref)
          probe.expectMsgPF(100 milliseconds) {
            case ActorIdentity(`path`, None) =>
          }
        }
      }
    }

    def isThreadRunning(threadName: String): Boolean = {
      Thread.getAllStackTraces.keySet().toArray
        .map(_.asInstanceOf[Thread])
        .find(_.getName == threadName) match {
        case Some(thread) =>
          if(thread.isAlive) true else false
        case None => false
      }
    }
  }

  //Utils Functions
  def getJSValueFromString(json: String): JsValue = {
    Json.parse(json)
  }

} 
Example 24
Source File: WatchServiceReceiverSpec.scala    From incubator-retired-iota   with Apache License 2.0 5 votes vote down vote up
package org.apache.iota.fey

import java.nio.file.{Files, Paths}
import java.nio.charset.StandardCharsets

import akka.testkit.{EventFilter, TestProbe}

import scala.concurrent.duration.{DurationInt, FiniteDuration}
import java.io.File

import ch.qos.logback.classic.Level

class WatchServiceReceiverSpec extends BaseAkkaSpec{

  val watcherTB = TestProbe("WATCH-SERVICE")
  var watchFileTask:WatchServiceReceiver = _
  val watchTestDir = s"${CONFIG.JSON_REPOSITORY}/watchtest"

  "Creating WatchServiceReceiver" should {
    "process initial files in the JSON repository" in {
      CONFIG.JSON_EXTENSION = "json.not"
      watchFileTask = new WatchServiceReceiver(watcherTB.ref)
      watcherTB.expectMsgAllClassOf(classOf[JsonReceiverActor.JSON_RECEIVED])
      CONFIG.JSON_EXTENSION = "json.test"
    }
  }

  var watchThread: Thread = _
  "Start a Thread with WatchServiceReceiver" should {
    "Start Thread" in {
      watchThread = new Thread(watchFileTask, "TESTING-WATCHER-IN-THREAD")
      watchThread.setDaemon(true)
      watchThread.start()
      TestProbe().isThreadRunning("TESTING-WATCHER-IN-THREAD") should be(true)
    }
  }

  "Start watching directory" should {
    "Starting receiving CREATED event" taggedAs(SlowTest) in {
      watchFileTask.watch(Paths.get(watchTestDir))
      Files.write(Paths.get(s"$watchTestDir/watched.json.test"), Utils_JSONTest.create_json_test.getBytes(StandardCharsets.UTF_8))
      watcherTB.expectMsgAllClassOf(20.seconds, classOf[JsonReceiverActor.JSON_RECEIVED])
    }
    "Starting receiving UPDATE event" taggedAs(SlowTest) in {
      Files.write(Paths.get(s"$watchTestDir/watched-update.json.test"), Utils_JSONTest.delete_json_test.getBytes(StandardCharsets.UTF_8))
      Thread.sleep(200)
      Files.write(Paths.get(s"$watchTestDir/watched-update.json.test"), Utils_JSONTest.create_json_test.getBytes(StandardCharsets.UTF_8))
      watcherTB.expectMsgAllClassOf(20.seconds, classOf[JsonReceiverActor.JSON_RECEIVED])
    }
  }

  "processJson" should {
    "log to warn level when json has invalid schema" in {
      Files.write(Paths.get(s"$watchTestDir/watched-invalid.json.test"), Utils_JSONTest.test_json_schema_invalid.getBytes(StandardCharsets.UTF_8))
      watchFileTask.processJson(s"$watchTestDir/watched-invalid.json.test",new File(s"$watchTestDir/watched-invalid.json.test"))
      s"File $watchTestDir/watched-invalid.json.test not processed. Incorrect JSON schema" should beLoggedAt(Level.WARN)
    }
  }

  "interrupt watchservice" should{
    "interrupt thread" in {
      watchThread.interrupt()
    }
  }

}