akka.testkit.TestActorRef Scala Examples

The following examples show how to use akka.testkit.TestActorRef. 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: ContextsMasterSpec.scala    From mist   with Apache License 2.0 5 votes vote down vote up
package io.hydrosphere.mist.master.execution

import akka.testkit.{TestActorRef, TestProbe}
import io.hydrosphere.mist.core.CommonData.{CancelJobRequest, RunJobRequest}
import io.hydrosphere.mist.master.execution.ContextEvent.{CancelJobCommand, RunJobCommand}
import io.hydrosphere.mist.master.{ActorSpec, TestData}
import io.hydrosphere.mist.utils.akka.ActorF

class ContextsMasterSpec extends ActorSpec("contexts-master") with TestData {

  it("should spawn/ proxy to contexts") {
    val ctx = TestProbe()
    val master = TestActorRef[ContextsMaster](ContextsMaster.props(
      contextF = ActorF.static(ctx.ref)
    ))

    master ! RunJobCommand(FooContext, mkRunReq("id"))
    ctx.expectMsgType[RunJobRequest]

    master ! CancelJobCommand(FooContext.name, CancelJobRequest("id"))
    ctx.expectMsgType[CancelJobRequest]
  }
} 
Example 2
Source File: MetricsReportingManagerSpec.scala    From service-container   with Apache License 2.0 5 votes vote down vote up
package com.github.vonnagy.service.container.metrics.reporting

import akka.actor.ActorSystem
import akka.testkit.{TestActorRef, TestProbe}
import com.github.vonnagy.service.container.AkkaTestkitSpecs2Support
import com.github.vonnagy.service.container.health.{GetHealth, HealthInfo, HealthState}
import com.typesafe.config.ConfigFactory
import org.specs2.mutable.SpecificationLike


class MetricsReportingManagerSpec
    extends AkkaTestkitSpecs2Support(ActorSystem("default",
      ConfigFactory.parseString("container.metrics.reporters.Slf4j.enabled=on")))
    with SpecificationLike {

  // Run in order
  sequential

  "The MetricsReportingManager" should {

    val probe = TestProbe()
    val act = TestActorRef[MetricsReportingManager](MetricsReportingManager.props())

    "be able to load the defined reporters" in {
      act.underlyingActor.reporters.size must be equalTo (1)
    }

    "be able to report it's health" in {
      probe.send(act, GetHealth)
      probe.expectMsgClass(classOf[HealthInfo]) must beEqualTo(HealthInfo("metrics-reporting",
        HealthState.OK, "The system is currently managing 1 metrics reporters",
        Some(List("com.github.vonnagy.service.container.metrics.reporting.Slf4jReporter")), List()))
    }

    "be able to stop the running reporters" in {
      act.underlyingActor.stopReporters
      act.underlyingActor.reporters.size must be equalTo (0)
    }


  }
} 
Example 3
Source File: GracefulStopHelperSpec.scala    From squbs   with Apache License 2.0 5 votes vote down vote up
package org.squbs.lifecycle

import akka.testkit.{TestActorRef, ImplicitSender, TestKit}
import akka.actor.{PoisonPill, ActorRef, Actor, ActorSystem}
import org.scalatest.{BeforeAndAfterAll, Matchers, FlatSpecLike}
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.Future

class GracefulStopHelperSpec extends TestKit(ActorSystem("testSystem"))
  with FlatSpecLike with Matchers with ImplicitSender with BeforeAndAfterAll {

  import system.dispatcher

  "GracefulStopHelper" should "work when stop failed" in {

    val actorRef = TestActorRef(new Actor with GracefulStopHelper {
      def receive: Actor.Receive = {
        case "Stop" =>
          defaultMidActorStop(Seq(self))
          sender() ! "Done"
      }

      override def gracefulStop(target: ActorRef, timeout: FiniteDuration, stopMessage: Any = PoisonPill):
          Future[Boolean] = {
        Future {
          throw new RuntimeException("BadMan")
        }

      }
    })

    actorRef ! "Stop"
    expectMsg("Done")

  }

  "GracefulStopHelper" should "work" in {

    val actorRef = TestActorRef(new Actor with GracefulStopHelper {

      def receive: Actor.Receive = {
        case "Stop" =>
          defaultMidActorStop(Seq(self))
          sender() ! "Done"
      }

      override def gracefulStop(target: ActorRef, timeout: FiniteDuration, stopMessage: Any = PoisonPill):
          Future[Boolean] = {
        Future {
          true
        }
      }
    })

    actorRef ! "Stop"
    expectMsg("Done")
  }

} 
Example 4
Source File: TestRoute.scala    From squbs   with Apache License 2.0 5 votes vote down vote up
package org.squbs.testkit

import akka.actor.{Actor, ActorSystem}
import akka.http.scaladsl.server.directives.PathDirectives._
import akka.http.scaladsl.server.{ExceptionHandler, RejectionHandler, Route}
import akka.http.scaladsl.settings.RoutingSettings
import akka.testkit.TestActorRef
import org.squbs.unicomplex.{RouteDefinition, WithActorContext, WithWebContext}

import scala.reflect.ClassTag


  def apply[T <: RouteDefinition: ClassTag](webContext: String)(implicit system: ActorSystem): Route = {
    val clazz = implicitly[ClassTag[T]].runtimeClass
    implicit val actorContext = TestActorRef[TestRouteActor].underlyingActor.context
    val routeDef =
      WithWebContext(webContext) {
        WithActorContext {
          clazz.asSubclass(classOf[RouteDefinition]).newInstance()
        }
      }

    implicit val routingSettings = RoutingSettings(system.settings.config)
    implicit val rejectionHandler:RejectionHandler = routeDef.rejectionHandler.getOrElse(RejectionHandler.default)
    implicit val exceptionHandler:ExceptionHandler = routeDef.exceptionHandler.orNull

    if (webContext.length > 0) pathPrefix(separateOnSlashes(webContext)) { Route.seal(routeDef.route) }
    else { Route.seal(routeDef.route) }
  }

  private[testkit] class TestRouteActor extends Actor {
    def receive = {
      case _ =>
    }
  }
} 
Example 5
Source File: RouteDefinitionTest.scala    From squbs   with Apache License 2.0 5 votes vote down vote up
package org.squbs.testkit.japi

import akka.http.javadsl.model.HttpRequest
import akka.http.javadsl.server.Route
import akka.http.javadsl.testkit.{RouteTest, TestRoute, TestRouteResult}
import akka.testkit.TestActorRef
import org.squbs.testkit.TestRoute.TestRouteActor
import org.squbs.unicomplex.{AbstractRouteDefinition, BuildRoute, WithActorContext, WithWebContext}

trait RouteDefinitionTest { this: RouteTest =>
  def testRoute[T <: AbstractRouteDefinition](clazz: Class[T]): TestRoute = testRoute("", clazz)

  def testRoute[T <: AbstractRouteDefinition](webContext: String, clazz: Class[T]): TestRoute = {
    implicit val actorContext = TestActorRef[TestRouteActor].underlyingActor.context
    val routeDef =
      WithWebContext(webContext) {
        WithActorContext {
          clazz.asSubclass(classOf[AbstractRouteDefinition]).newInstance()
        }
      }

    new TestRoute {
      val underlying: Route = BuildRoute(routeDef, webContext)

      def run(request: HttpRequest): TestRouteResult = runRoute(underlying, request)

      def runWithRejections(request: HttpRequest): TestRouteResult = runRouteUnSealed(underlying, request)
    }
  }
} 
Example 6
Source File: MasterBridgeSpec.scala    From mist   with Apache License 2.0 5 votes vote down vote up
package io.hydrosphere.mist.worker

import akka.actor.ActorSystem
import akka.testkit.{TestActorRef, TestKit, TestProbe}
import io.hydrosphere.mist.core.CommonData._
import io.hydrosphere.mist.core.MockitoSugar
import io.hydrosphere.mist.utils.akka.{ActorF, ActorRegHub}
import mist.api.data.JsMap
import org.apache.spark.SparkConf
import org.scalatest.{BeforeAndAfterAll, FunSpec, FunSpecLike, Matchers}

import scala.concurrent.duration._

class MasterBridgeSpec extends TestKit(ActorSystem("WorkerBridgeSpec"))
  with FunSpecLike
  with Matchers
  with MockitoSugar
  with BeforeAndAfterAll {

  def mkInitInfo(sparkConf: Map[String, String]) =
    WorkerInitInfo(sparkConf, 1, 20 seconds, 20 seconds, "localhost:2005", "localhost:2003", "localhost:2004", 202020, "")

  it("should create named context with spark.streaming.stopSparkContextByDefault=false") {
    val sparkConf = Map(
      "spark.streaming.stopSparkContextByDefault" -> "true",
      "spark.master" -> "local[*]",
      "spark.driver.allowMultipleContexts" -> "true"
    )
    val namedContext = MistScContext("test", 1 second, new SparkConf().setAll(sparkConf))
    val propertyValue = namedContext.sc.getConf.getBoolean("spark.streaming.stopSparkContextByDefault", true)
    propertyValue shouldBe false
    namedContext.sc.stop()
  }

  it("should shutdown correctly") {
    val namedMock = mock[MistScContext]
    when(namedMock.getUIAddress()).thenReturn(Some("addr"))

    val regHub = TestProbe()
    val worker = TestProbe()

    val props = MasterBridge.props("id", regHub.ref, _ => namedMock, ActorF.static[(WorkerInitInfo, MistScContext)](worker.ref))
    val bridge = TestActorRef(props)

    regHub.expectMsgType[ActorRegHub.Register]

    val remote = TestProbe()
    remote.send(bridge, mkInitInfo(Map.empty))

    remote.expectMsgType[WorkerReady]
    remote.send(bridge, RunJobRequest("id", JobParams("path", "MyClass", JsMap.empty, action = Action.Execute)))
    worker.expectMsgType[RunJobRequest]

    remote.send(bridge, ShutdownWorker)
    remote.expectMsgType[RequestTermination.type]

    remote.send(bridge, ShutdownWorkerApp)
    remote.expectMsgType[Goodbye.type]
  }
} 
Example 7
Source File: ActorSpec.scala    From mist   with Apache License 2.0 5 votes vote down vote up
package io.hydrosphere.mist.master

import akka.actor.{ActorRef, ActorSystem}
import akka.testkit.{TestActorRef, TestKit, TestProbe}
import org.scalatest.{BeforeAndAfterAll, FunSpecLike, Matchers}

import scala.concurrent.duration.FiniteDuration

abstract class ActorSpec(name: String) extends TestKit(ActorSystem(name))
  with FunSpecLike
  with Matchers
  with BeforeAndAfterAll {

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

  def shouldTerminate(f: FiniteDuration)(ref: ActorRef): Unit = {
    val probe = TestProbe()
    probe.watch(ref)
    probe.expectTerminated(ref, f)
  }
} 
Example 8
Source File: FutureSubscribeSpec.scala    From mist   with Apache License 2.0 5 votes vote down vote up
package io.hydrosphere.mist.master.execution

import akka.actor.{Actor, ActorRef, Props}
import akka.testkit.{TestActorRef, TestProbe}
import io.hydrosphere.mist.master.ActorSpec

import scala.concurrent.{Future, Promise}

class FutureSubscribeSpec extends ActorSpec("future-subsribe-spec") {

  import FutureSubscribeSpec._

  it("should handle success") {
    val actor = TestActorRef[TestActor](Props(classOf[TestActor]))
    val probe = TestProbe()

    val p = Promise[Unit]
    probe.send(actor, TestMessage(p.future))
    p.success(())
    probe.expectMsgType[Ok.type]
  }

  it("should handle failure") {
    val actor = TestActorRef[TestActor](Props(classOf[TestActor]))
    val probe = TestProbe()

    val p = Promise[Unit]
    probe.send(actor, TestMessage(p.future))
    p.failure(new RuntimeException())
    probe.expectMsgType[Err.type]
  }

}
object FutureSubscribeSpec {

  sealed trait Rsp
  case object Ok extends Rsp
  case object Err extends Rsp
  case class TestMessage(future: Future[Unit])

  class TestActor extends Actor with FutureSubscribe {

    import context._

    override def receive: Receive = {
      case TestMessage(future) =>
        subscribe0(future)(_ => Ok, _ => Err)
        context become respond(sender())
    }

    private def respond(respond: ActorRef): Receive = {
      case x: Rsp => respond ! x
    }

  }

} 
Example 9
Source File: ExclusiveConnectorSpec.scala    From mist   with Apache License 2.0 5 votes vote down vote up
package io.hydrosphere.mist.master.execution.workers

import akka.actor.ActorRef
import akka.testkit.{TestActorRef, TestProbe}
import io.hydrosphere.mist.core.CommonData.RunJobRequest
import io.hydrosphere.mist.master.execution.workers.WorkerBridge.Event.CompleteAndShutdown
import io.hydrosphere.mist.master.execution.workers.WorkerConnector.Event.Released
import io.hydrosphere.mist.master.{ActorSpec, FilteredException, TestData}

import scala.concurrent.{Await, Future, Promise}
import scala.concurrent.duration._

class ExclusiveConnectorSpec extends ActorSpec("excl-conn") with TestData {

  it("shouldn't ignore errors") {
    val connector = TestActorRef[ExclusiveConnector](ExclusiveConnector.props(
      id = "id",
      ctx = FooContext,
      startWorker = (_, _) => Future.failed(FilteredException())
    ))

    val probe = TestProbe()
    val resolve = Promise[PerJobConnection]
    probe.send(connector, WorkerConnector.Event.AskConnection(resolve))

    intercept[Throwable] {
      Await.result(resolve.future, Duration.Inf)
    }
  }

  it("should return wrapped connections") {
    val originalRef = TestProbe()
    val original = WorkerConnection("id", originalRef.ref, workerLinkData, Promise[Unit].future)

    val connector = TestActorRef[ExclusiveConnector](ExclusiveConnector.props(
      id = "id",
      ctx = FooContext,
      startWorker = (_, _) => Future.successful(original)
    ))

    val probe = TestProbe()
    val resolve = Promise[PerJobConnection]
    probe.send(connector, WorkerConnector.Event.AskConnection(resolve))

    val connection = Await.result(resolve.future, Duration.Inf)

    connection.run(mkRunReq("id"), probe.ref)

    originalRef.expectMsgType[RunJobRequest]
    originalRef.expectMsgType[WorkerBridge.Event.CompleteAndShutdown.type]
  }

  describe("Exclusive conn wrapper") {

    it("should release connection") {

      val connRef = TestProbe()
      val termination = Promise[Unit]

      val connection = WorkerConnection(
        id = "id",
        ref = connRef.ref,
        data = workerLinkData,
        whenTerminated = termination.future
      )

      val connector = TestProbe()
      val wrapped = ExclusiveConnector.wrappedConnection(connector.ref, connection)

      wrapped.release()
      connector.expectMsgType[WorkerConnector.Event.Released]

      wrapped.run(mkRunReq("id"), ActorRef.noSender)
      connRef.expectMsgType[RunJobRequest]
      connRef.expectMsgType[CompleteAndShutdown.type]
    }
  }
} 
Example 10
Source File: StoreFlusherSpec.scala    From mist   with Apache License 2.0 5 votes vote down vote up
package io.hydrosphere.mist.master.execution.status

import java.util.concurrent.atomic.AtomicReference

import akka.testkit.TestActorRef
import io.hydrosphere.mist.master.Messages.StatusMessages._
import io.hydrosphere.mist.master.logging.JobLogger
import io.hydrosphere.mist.master.{ActorSpec, JobDetails, TestData}
import mist.api.data.JsNumber
import org.scalatest.concurrent.Eventually
import org.scalatest.time.{Seconds, Span}

import scala.concurrent.{Future, Promise}

class StoreFlusherSpec extends ActorSpec("store-flusher") with TestData with Eventually {

  it("should flush job statuses") {
    val initial1 = Promise[JobDetails]
    val initial2 = Promise[JobDetails]

    val updateResult1 = new AtomicReference[Option[JobDetails]](None)
    val updateResult2 = new AtomicReference[Option[JobDetails]](None)
    val props = StoreFlusher.props(
      get = (id: String) => id match {
        case "1" => initial1.future
        case "2" => initial2.future
      },
      update = (d: JobDetails) => {
        d.jobId match {
          case "1" => updateResult1.set(Some(d))
          case "2" => updateResult2.set(Some(d))
        }
        Future.successful(())
      },
      jobLoggerF = _ => JobLogger.NOOP
    )
    val flusher = TestActorRef(props)

    Seq("1", "2").foreach(id => {
      flusher ! ReportedEvent.plain(QueuedEvent(id))
      flusher ! ReportedEvent.plain(StartedEvent(id, System.currentTimeMillis()))
      flusher ! ReportedEvent.plain(FinishedEvent(id, System.currentTimeMillis(), JsNumber(42)))
    })
    initial1.success(mkDetails(JobDetails.Status.Initialized).copy(jobId = "1"))
    initial2.success(mkDetails(JobDetails.Status.Initialized).copy(jobId = "2"))

    def test(ref: AtomicReference[Option[JobDetails]]): Unit = {
      val value = ref.get
      value.isDefined shouldBe true

      val d = value.get
      d.status shouldBe JobDetails.Status.Finished
    }

    eventually(timeout(Span(3, Seconds))) {
      test(updateResult1)
      test(updateResult2)
    }
  }
} 
Example 11
Source File: JobStatusFlusherSpec.scala    From mist   with Apache License 2.0 5 votes vote down vote up
package io.hydrosphere.mist.master.execution.status

import java.util.concurrent.atomic.AtomicReference

import akka.actor.ActorSystem
import akka.testkit.{TestActorRef, TestKit}
import io.hydrosphere.mist.master.JobDetails.Status
import io.hydrosphere.mist.master.Messages.StatusMessages._
import io.hydrosphere.mist.master.{ActorSpec, JobDetails, TestData}
import io.hydrosphere.mist.master.logging.JobLogger
import mist.api.data._
import org.scalatest.concurrent.Eventually
import org.scalatest.{FunSpecLike, Matchers}
import org.scalatest.prop.TableDrivenPropertyChecks._
import org.scalatest.time.{Seconds, Span}

import scala.concurrent.{Future, Promise}

class JobStatusFlusherSpec extends ActorSpec("job-status-flusher") with TestData with Eventually {

  it("should flush status correctly") {
    val initial = Promise[JobDetails]

    val updateResult = new AtomicReference[Option[JobDetails]](None)
    val props = JobStatusFlusher.props(
      id = "id",
      get = (_) => initial.future,
      update = (d: JobDetails) => {updateResult.set(Some(d));Future.successful(())},
      loggerF = _ => JobLogger.NOOP
    )
    val flusher = TestActorRef(props)

    flusher ! ReportedEvent.plain(QueuedEvent("id"))
    flusher ! ReportedEvent.plain(StartedEvent("id", System.currentTimeMillis()))
    flusher ! ReportedEvent.plain(FinishedEvent("id", System.currentTimeMillis(), JsNumber(42)))

    initial.success(mkDetails(JobDetails.Status.Initialized))

    eventually(timeout(Span(3, Seconds))) {
      val value = updateResult.get
      value.isDefined shouldBe true

      val d = value.get
      d.status shouldBe JobDetails.Status.Finished
    }
  }

  describe("event conversion") {

    val baseDetails = mkDetails(JobDetails.Status.Initialized)

    val expected = Table(
      ("event", "details"),
      (QueuedEvent("id"), baseDetails.copy(status = Status.Queued)),
      (StartedEvent("id", 1), baseDetails.copy(status = Status.Started, startTime = Some(1))),
      (CancellingEvent("id", 1), baseDetails.copy(status = Status.Cancelling)),
      (CancelledEvent("id", 1), baseDetails.copy(status = Status.Canceled, endTime = Some(1))),
      (FinishedEvent("id", 1, JsMap("1" -> JsNumber(2))),
        baseDetails.copy(
          status = Status.Finished,
          endTime = Some(1),
          jobResult =
            Some(
              Right(JsMap("1" -> JsNumber(2)))
            )
        )),
      (FailedEvent("id", 1, "error"),
        baseDetails.copy(status = Status.Failed, endTime = Some(1), jobResult = Some(Left("error")))),
      (WorkerAssigned("id", "workerId"), baseDetails.copy(workerId = Some("workerId")))
    )

    it("should correct update job details") {
      forAll(expected) { (e: UpdateStatusEvent, d: JobDetails) =>
        JobStatusFlusher.applyStatusEvent(baseDetails, e) shouldBe d
      }
    }
  }
} 
Example 12
Source File: HttpMetricsSpec.scala    From service-container   with Apache License 2.0 5 votes vote down vote up
package com.github.vonnagy.service.container.http

import java.util.concurrent.TimeUnit

import akka.actor.{Actor, ActorSystem, Props}
import akka.testkit.TestActorRef
import com.github.vonnagy.service.container.AkkaTestkitSpecs2Support
import com.github.vonnagy.service.container.metrics.Metrics
import org.specs2.mutable.SpecificationLike

import scala.collection.JavaConverters._
import scala.concurrent.duration._

class HttpMetricsSpec extends AkkaTestkitSpecs2Support with SpecificationLike {

  sequential

  val svcAct = TestActorRef(new Actor {
    def receive = {
      case _ =>
    }

    val listener = context.actorOf(Props(
      new Actor {
        def receive = {
          case _ => sender ! Stats(FiniteDuration(1000, TimeUnit.MILLISECONDS), 1000, 1000, 1000, 1000, 1000, 1000, 1000)
        }

      }), "listener-0")
  }, "http")

  class MetricTest(implicit val system: ActorSystem) extends HttpMetrics {
    def httpListener = Some(system.actorSelection(svcAct.children.head.path))
  }

  val metrics = new MetricTest

  "The HttpMetrics" should {

    "provide basic stats" in {

      metrics.lastStats must be equalTo Stats(FiniteDuration(0, TimeUnit.MILLISECONDS), 0, 0, 0, 0, 0, 0, 0)
      metrics.totConn.name must be equalTo "container.http.connections.total"
      metrics.openConn.name must be equalTo "container.http.connections.open"
      metrics.maxOpenConn.name must be equalTo "container.http.connections.max-open"
      metrics.totReq.name must be equalTo "container.http.requests.total"
      metrics.openReq.name must be equalTo "container.http.requests.open"
      metrics.maxOpenReq.name must be equalTo "container.http.requests.max-open"
      metrics.uptime.name must be equalTo "container.http.uptime"
      metrics.idle.name must be equalTo "container.http.idle-timeouts"

      val metricRegistry = Metrics().metricRegistry
      metricRegistry.getGauges.asScala.foreach(_._2.getValue)
      metricRegistry.getGauges.asScala.filterKeys(g => !g.startsWith("jvm.")).size must be equalTo 8
    }

    "schedule and cancel the metrics job" in {
      metrics.metricsJob must beNone
      metrics.scheduleHttpMetrics(FiniteDuration(100, TimeUnit.MILLISECONDS))
      metrics.metricsJob must not beNone

      metrics.cancelHttpMetrics
      metrics.metricsJob must beNone
    }

    "schedule and fetch the metrics" in {
      metrics.metricsJob must beNone
      metrics.scheduleHttpMetrics(FiniteDuration(100, TimeUnit.MILLISECONDS))
      Thread.sleep(1000)

      metrics.cancelHttpMetrics
      metrics.lastStats must not be Stats(FiniteDuration(0, TimeUnit.MILLISECONDS), 0, 0, 0, 0, 0, 0, 0)

    }

  }
} 
Example 13
Source File: LogWriterSpec.scala    From mist   with Apache License 2.0 5 votes vote down vote up
package io.hydrosphere.mist.master.logging

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

import akka.actor.ActorSystem
import akka.pattern.ask
import akka.testkit.{TestActorRef, TestKit}
import akka.util.Timeout
import com.typesafe.config.ConfigFactory
import io.hydrosphere.mist.core.logging.LogEvent
import io.hydrosphere.mist.master.LogStoragePaths
import org.apache.commons.io.FileUtils
import org.scalatest.{BeforeAndAfterAll, FunSpecLike, Matchers}

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

class LogWriterSpec extends TestKit(ActorSystem("log-writer-test", ConfigFactory.load("master")))
  with FunSpecLike
  with Matchers
  with BeforeAndAfterAll {

  val dirName = "log_writer_test"
  val dir = Paths.get(".", "target", dirName)

  override def beforeAll(): Unit = {
    Files.createDirectories(dir)
  }

  override def afterAll(): Unit = {
    FileUtils.deleteDirectory(dir.toFile)
    TestKit.shutdownActorSystem(system)
  }

  implicit val timeout = Timeout(5 second)

  describe("writer actor") {

    it("should write to file") {
      val path = dir.resolve("test")
      val f = path.toFile
      if (f.exists()) f.delete()
      Files.createFile(path)

      val actor = TestActorRef(WriterActor.props(path))

      val event = LogEvent.mkDebug("id", "message")
      val future = actor ? WriteRequest("id", Seq(event))
      val update = Await.result(future.mapTo[LogUpdate], Duration.Inf)

      update.jobId shouldBe "id"
      update.events shouldBe Seq(event)
      update.bytesOffset shouldBe (event.mkString + "\n").getBytes.length
    }
  }

  describe("writers group") {

    it("should proxy to writer") {
      val mappings = new LogStoragePaths(dir)
      val expectedPath = mappings.pathFor("id")
      if (Files.exists(expectedPath)) Files.delete(expectedPath)

      val actor = TestActorRef(WritersGroupActor.props(mappings))

      val event = LogEvent.mkDebug("id", "message")
      val future = actor ? WriteRequest("id", Seq(event))
      val update = Await.result(future.mapTo[LogUpdate], Duration.Inf)

      val expectedSize = (event.mkString + "\n").getBytes.length

      update.jobId shouldBe "id"
      update.events shouldBe Seq(event)
      update.bytesOffset shouldBe expectedSize

      Files.readAllBytes(expectedPath).length shouldBe expectedSize
    }
  }
} 
Example 14
Source File: ThroughputMeasurementFlowTest.scala    From akka-viz   with MIT License 5 votes vote down vote up
package akkaviz.events

import akka.actor.{ActorRef, ActorSystem}
import akka.pattern
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Keep, Sink, Source}
import akka.testkit.{TestActorRef, TestKit}
import akkaviz.events.types.{BackendEvent, ReceivedWithId, ThroughputMeasurement}
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{Matchers, WordSpecLike}

import scala.concurrent.Future

class ThroughputMeasurementFlowTest extends TestKit(ActorSystem("FlowTestSystem"))
    with WordSpecLike with Matchers with ScalaFutures {

  import scala.concurrent.duration._

  implicit val materializer = ActorMaterializer()(system)

  val firstRef = TestActorRef[SomeActor](new SomeActor, "first")
  val secondRef = TestActorRef[SomeActor](new SomeActor, "second")

  override implicit val patienceConfig = PatienceConfig(timeout = 5.seconds)

  "ThroughputMeasurementFlow" should {

    "not emit any measurements if there are no Received events" in {
      val src = Source.empty[BackendEvent]
      val sink: Sink[BackendEvent, Future[List[BackendEvent]]] = Sink.fold(List.empty[BackendEvent])((list, ev) => ev :: list)

      val materialized = ThroughputMeasurementFlow(1.second).runWith(src, sink)._2

      whenReady(materialized) { r =>
        r should be('empty)
      }
    }

    "emit proper measured value for one message" in {
      val src = Source.single(ReceivedWithId(1, ActorRef.noSender, firstRef, "sup", true))
      val mat = src.via(ThroughputMeasurementFlow(1.second))
        .toMat(Sink.head[ThroughputMeasurement])(Keep.right).run()

      whenReady(mat) { measurement =>
        measurement.actorRef should equal(firstRef)
        measurement.msgsPerSecond should equal(1.0)
      }
    }

    "emit measured value for one message and 0 for actors which didn't receive anything" in {
      import system.dispatcher
      val src = Source(List(
        ReceivedWithId(1, ActorRef.noSender, firstRef, "sup", true),
        ReceivedWithId(2, ActorRef.noSender, secondRef, "sup", true)
      )).concat(Source.fromFuture(pattern.after(2.seconds, system.scheduler) {
        Future.successful(ReceivedWithId(3, ActorRef.noSender, firstRef, "sup", true))
      }))

      val mat = src.via(ThroughputMeasurementFlow(1.second))
        .toMat(Sink.fold(List.empty[ThroughputMeasurement]) { (list, ev) => ev :: list })(Keep.right).run()

      whenReady(mat) { measurements =>
        val measurementsFor = measurements.groupBy(_.actorRef)
        measurementsFor(firstRef).map(_.msgsPerSecond) should not contain 0.0
        measurementsFor(secondRef).sortBy(_.timestamp).map(_.msgsPerSecond) should contain inOrder (1.0, 0.0)
      }
    }
  }
} 
Example 15
Source File: LightSnapshotTest.scala    From akka-viz   with MIT License 5 votes vote down vote up
package akkaviz.events

import akka.actor.{ActorSystem, Actor}
import akka.testkit.{TestKit, TestActorRef}
import akkaviz.events.types._
import org.scalatest.{FunSuiteLike, Matchers}

class LightSnapshotTest() extends TestKit(ActorSystem("SnapshotTests")) with FunSuiteLike with Matchers with Helpers {

  val firstRef = TestActorRef[SomeActor](new SomeActor, "first")
  val secondRef = TestActorRef[SomeActor](new SomeActor, "second")

  test("should include actors receiving messages as live") {
    val events = Seq(
      ReceivedWithId(1, firstRef, secondRef, "sup", true),
      ReceivedWithId(2, secondRef, firstRef, "sup", true)
    )

    val snapshot = snapshotOf(events)
    snapshot.liveActors should contain allOf (firstRef.path.toString, secondRef.path.toString)
  }

  test("should contain dead actors") {
    val events = Seq(
      ReceivedWithId(1, firstRef, secondRef, "sup", true),
      ReceivedWithId(2, secondRef, firstRef, "sup", true),
      Killed(secondRef)
    )

    val snapshot = snapshotOf(events)
    snapshot.liveActors should contain(actorRefToString(firstRef))
    snapshot.liveActors should not contain actorRefToString(secondRef)
    snapshot.dead should contain(actorRefToString(secondRef))
  }

  test("should contain classes of instantiated actors") {
    val events = Seq(
      Instantiated(firstRef, firstRef.underlyingActor),
      Instantiated(secondRef, secondRef.underlyingActor)
    )
    val snapshot = snapshotOf(events)

    snapshot.classNameFor(firstRef.path.toString) should equal(Some(firstRef.underlyingActor.getClass.getName))
    snapshot.classNameFor(secondRef.path.toString) should equal(Some(secondRef.underlyingActor.getClass.getName))
  }

  test("should include recreated actor as live") {
    val events = Seq(
      Instantiated(firstRef, firstRef.underlyingActor),
      Killed(firstRef),
      Spawned(firstRef)
    )
    val snapshot = snapshotOf(events)
    snapshot.liveActors should contain(actorRefToString(firstRef))
    snapshot.dead should be('empty)
  }

  test("should ignore BackendEvents not pertaining to actor state") {
    import scala.concurrent.duration._
    val events = Seq(
      ActorSystemCreated(system),
      ReportingDisabled,
      ReportingEnabled,
      ThroughputMeasurement(firstRef, 0.0, 0xDEB1L),
      ReceiveDelaySet(2000.seconds)
    )

    snapshotOf(events) should equal(LightSnapshot())
  }

  test("should include restarted actors as live") {
    val events = Seq(
      Instantiated(firstRef, firstRef.underlyingActor),
      Killed(firstRef),
      Restarted(firstRef)
    )

    val snaphshot = snapshotOf(events)
    snaphshot.dead should be('empty)
    snaphshot.liveActors should contain(actorRefToString(firstRef))
  }

  def snapshotOf(events: Seq[BackendEvent]): LightSnapshot = {
    events.foldLeft(LightSnapshot())(_.update(_))
  }
}

class SomeActor extends Actor {
  override def receive: Receive = { case _ => () }
} 
Example 16
Source File: LogCollectorSpec.scala    From shield   with MIT License 5 votes vote down vote up
package shield.actors.listeners

import akka.actor.{ActorRef, ActorSystem}
import akka.testkit.{ImplicitSender, TestKit}
import org.scalatest.WordSpecLike
import org.specs2.matcher.MustMatchers
import shield.config.{DomainSettings, Settings}
import spray.http.HttpHeaders.RawHeader
import spray.http.HttpRequest
import spray.json.JsString

class LogCollectorSpec extends TestKit(ActorSystem("testSystem"))
// Using the ImplicitSender trait will automatically set `testActor` as the sender
with ImplicitSender
with WordSpecLike
with MustMatchers {

  import akka.testkit.TestActorRef
  val settings = Settings(system)
  val domainSettings = new DomainSettings(settings.config.getConfigList("shield.domains").get(0), system)

  val actorRef = TestActorRef(new LogCollector("1",domainSettings,Seq[ActorRef](),5))
  val actor = actorRef.underlyingActor

  "LogCollector" should {
    "Extracts headers and adds them to access logs" in {
      val request = HttpRequest().withHeaders(
        RawHeader("sample", "header"),
        RawHeader("test", "test1"),
        RawHeader("test2", "123"),
        RawHeader("test-header-3", "abc"),
        RawHeader("hh", "aaa"),
        RawHeader("hhh", "bbb")
      )

      val extractedHeaders = actor.extractHeaders(request.headers, Set("test-header-3", "hh", "sample", "DNE"))

      extractedHeaders.keys.size must be equalTo 3
      extractedHeaders.get("hh").get must be equalTo JsString("aaa")
      extractedHeaders.get("test-header-3").get must be equalTo JsString("abc")
      extractedHeaders.get("sample").get must be equalTo JsString("header")
    }
  }
} 
Example 17
Source File: StaticDomainWatcherSpec.scala    From shield   with MIT License 5 votes vote down vote up
package shield.actors.config.domain

import akka.actor.{ActorSystem, Props}
import akka.testkit.{TestActorRef, TestKit, TestProbe}
import org.scalatest.{BeforeAndAfterAll, MustMatchers, WordSpecLike}
import shield.actors.ShieldActorMsgs
import shield.config.Settings

class StaticDomainWatcherSpec extends TestKit(ActorSystem("testSystem"))
  with WordSpecLike
  with MustMatchers
  with BeforeAndAfterAll {

  val settings = Settings(system)

  "StaticDomainWatcher" should {

    "notify shield about domains found" in {
      val parent = TestProbe()
      TestActorRef(Props(new StaticDomainWatcher()), parent.ref, "static-domain-watcher")

      val msg: ShieldActorMsgs.DomainsUpdated = parent.expectMsgClass(classOf[ShieldActorMsgs.DomainsUpdated])
      msg.domains.size must equal (settings.config.getConfigList("shield.domains").size)
    }
  }

} 
Example 18
Source File: ApiKeyAuthSpec.scala    From shield   with MIT License 5 votes vote down vote up
package shield.actors.middleware

import akka.actor.ActorSystem
import akka.testkit.{ImplicitSender, TestActorRef, TestKit}
import org.scalatest.{MustMatchers, WordSpecLike}
import shield.actors.{DownstreamRequest, ForwardRequestCmd, ForwardResponseCmd, ResponseDetails}
import shield.config.Settings
import shield.proxying.FailBalancer
import shield.routing._
import spray.http.HttpHeaders.RawHeader
import spray.http._

class ApiKeyAuthSpec extends TestKit(ActorSystem("testSystem"))
  with WordSpecLike
  with MustMatchers
  with ImplicitSender {

  "ApiKeyAuthTest middleware actor" must {
    val stage = "myStage"
    val settings = Settings(system)
    val location = settings.DefaultServiceLocation
    val getEndpoint = EndpointTemplate(HttpMethods.GET, Path("/foobar"))
    val routingDestination = RoutingDestination(getEndpoint, List(), List(), FailBalancer)

    def httpRequest(headers: List[HttpHeader]): HttpRequest = HttpRequest(HttpMethods.GET, "/v4/mobile/stores", headers)

    def forwardResponseCmd(response: HttpResponse) = {
      ForwardResponseCmd(
        stage,
        ResponseDetails(
          location,
          settings.LocalServiceName,
          getEndpoint,
          None,
          response)
      )
    }

    "reply with Forbidden when created with bad parameters" in {
      val actor = TestActorRef(ApiKeyAuth.props("", Set(""), true, location))
      actor ! DownstreamRequest(stage, routingDestination, httpRequest(List()))
      expectMsg(forwardResponseCmd(HttpResponse(StatusCodes.Forbidden)))
    }

    "reply with Forbidden when given no headers" in {
      val actor = TestActorRef(ApiKeyAuth.props("pid", Set("BA914464-C559-4F81-A37E-521B830F1634"), true, location))
      actor ! DownstreamRequest(stage, routingDestination, httpRequest(List()))
      expectMsg(forwardResponseCmd(HttpResponse(StatusCodes.Forbidden)))
    }

    "reply with Unauthorized when given an incorrect header" in {
      val actor = TestActorRef(ApiKeyAuth.props("pid", Set("BA914464-C559-4F81-A37E-521B830F1634"), true, location))
      actor ! DownstreamRequest(stage, routingDestination, httpRequest(List(RawHeader("pid","asdasdada"))))
      expectMsg(forwardResponseCmd(HttpResponse(StatusCodes.Unauthorized)))
    }

    "succeed with a downstream request when given the correct header and value" in {
      val request = httpRequest(List(RawHeader("pid","BA914464-C559-4F81-A37E-521B830F1634")))
      val actor = TestActorRef(ApiKeyAuth.props("pid", Set("BA914464-C559-4F81-A37E-521B830F1634"), true, location))
      actor ! DownstreamRequest(stage, routingDestination, request)
      expectMsg(ForwardRequestCmd(stage, request, None))
    }

    "succeed with a downstream request when given a correct but capitalized header" in {
      val request = httpRequest(List(RawHeader("PID","BA914464-C559-4F81-A37E-521B830F1634")))
      val actor = TestActorRef(ApiKeyAuth.props("pid", Set("BA914464-C559-4F81-A37E-521B830F1634"), true, location))
      actor ! DownstreamRequest(stage, routingDestination, request)
      expectMsg(ForwardRequestCmd(stage, request, None))
    }

    "succeed with a downstream request when given a case-insensitive value and case sensitivity is off" in {
      val request = httpRequest(List(RawHeader("pid","ba914464-c559-4f81-a37e-521b830f1634")))
      val actor = TestActorRef(ApiKeyAuth.props("pid", Set("BA914464-C559-4F81-A37E-521B830F1634"), false, location))
      actor ! DownstreamRequest(stage, routingDestination, request)
      expectMsg(ForwardRequestCmd(stage, request, None))
    }

    "reply with Unauthorized when given a case-insensitive value and case sensitivity is on" in {
      val request = httpRequest(List(RawHeader("pid","ba914464-c559-4f81-a37e-521b830f1634")))
      val actor = TestActorRef(ApiKeyAuth.props("pid", Set("BA914464-C559-4F81-A37E-521B830F1634"), true, location))
      actor ! DownstreamRequest(stage, routingDestination, request)
      expectMsg(forwardResponseCmd(HttpResponse(StatusCodes.Unauthorized)))
    }

  }
} 
Example 19
Source File: BulkIndexerActorTest.scala    From elasticsearch-client   with Apache License 2.0 5 votes vote down vote up
package com.sumologic.elasticsearch.akkahelpers

import java.util.concurrent.TimeUnit

import akka.actor.{ActorSystem, Terminated}
import akka.testkit.{ImplicitSender, TestActorRef, TestKit}
import com.sumologic.elasticsearch.akkahelpers.BulkIndexerActor.{BulkSession, CreateRequest, DocumentIndexed, ForceFlush}
import com.sumologic.elasticsearch.restlastic.{RestlasticSearchClient, RestlasticSearchClient6}
import com.sumologic.elasticsearch.restlastic.RestlasticSearchClient.ReturnTypes.BulkItem
import com.sumologic.elasticsearch.restlastic.dsl.Dsl._
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers._
import org.mockito.Matchers._
import org.mockito.Mockito._
import org.scalatest._
import org.scalatest.concurrent.Eventually
import org.scalatest.mock.MockitoSugar
import org.scalatestplus.junit.JUnitRunner

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

@RunWith(classOf[JUnitRunner])
class BulkIndexerActorTest extends TestKit(ActorSystem("TestSystem")) with WordSpecLike with Matchers
with BeforeAndAfterAll with BeforeAndAfterEach with MockitoSugar with ImplicitSender with Eventually {

  val executionContext = scala.concurrent.ExecutionContext.Implicits.global
  var indexerActor: TestActorRef[BulkIndexerActor] = _
  var mockEs = mock[RestlasticSearchClient]
  var flushTimeoutMs = 100000L
  var maxMessages = 100000

  override def beforeEach(): Unit = {
    mockEs = mock[RestlasticSearchClient]
    when(mockEs.indexExecutionCtx).thenReturn(executionContext)
    def timeout() = Duration(flushTimeoutMs, TimeUnit.MILLISECONDS)
    def max() = maxMessages
    val config = BulkConfig(timeout, max)
    indexerActor = TestActorRef[BulkIndexerActor](BulkIndexerActor.props(mockEs, config))

  }

  override def afterAll(): Unit = {
    val terminationFuture: Future[Terminated] = system.terminate()
    Await.result(terminationFuture, 5.seconds)
  }

  "BulkIndexerActor" should {
    "flush every message when set to 1" in {
      maxMessages = 1
      when(mockEs.bulkIndex(any())).thenReturn(Future.successful(Seq(BulkItem("index","type", "_id", 201, None))))
      val sess = BulkSession.create()
      indexerActor ! CreateRequest(sess, Index("i"), Type("tpe"), Document("id", Map("k" -> "v")))
      eventually {
        mockEs.bulkIndex(any())
      }
      val msg = expectMsgType[DocumentIndexed]
      msg.sessionId should be(sess)
    }

    "not flush when set to 2" in {
      maxMessages = 2
      indexerActor ! CreateRequest(BulkSession.create(), Index("i"), Type("tpe"), Document("id", Map("k" -> "v")))
      verify(mockEs, times(0)).bulkIndex(any())
    }

    "not flush when there are no messages" in {
      indexerActor ! ForceFlush
      verify(mockEs, times(0)).bulkIndex(any())
    }
  }


} 
Example 20
Source File: PubSubRouterSpec.scala    From graphcool-framework   with Apache License 2.0 5 votes vote down vote up
package cool.graph.messagebus.pubsub.inmemory

import akka.actor.Props
import akka.testkit.{TestActorRef, TestKit, TestProbe}
import cool.graph.akkautil.SingleThreadedActorSystem
import cool.graph.messagebus.pubsub.PubSubProtocol.{Publish, Subscribe, Unsubscribe}
import cool.graph.messagebus.pubsub.PubSubRouter
import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach, Matchers, WordSpecLike}

import scala.concurrent.duration._

class PubSubRouterSpec
    extends TestKit(SingleThreadedActorSystem("pubsub-router-spec"))
    with WordSpecLike
    with Matchers
    with BeforeAndAfterAll
    with BeforeAndAfterEach {
  override def afterAll = shutdown(verifySystemShutdown = true)

  "The PubSubRouter implementation" should {
    "subscribe subscribers correctly and route messages" in {
      val routerActor = TestActorRef(Props[PubSubRouter])
      val router      = routerActor.underlyingActor.asInstanceOf[PubSubRouter]
      val probe       = TestProbe()
      val topic       = "testTopic"

      routerActor ! Subscribe(topic, probe.ref)
      router.subscribers.values.map(_.size).sum shouldEqual 1

      routerActor ! Publish(topic, "test")
      probe.expectMsg("test")
      probe.expectNoMsg(max = 1.second)

      routerActor ! Publish("testTopic2", "test2")
      probe.expectNoMsg(max = 1.second)
    }

    "unsubscribe subscribers correctly" in {
      val routerActor = TestActorRef(Props[PubSubRouter])
      val router      = routerActor.underlyingActor.asInstanceOf[PubSubRouter]
      val probe       = TestProbe()
      val topic       = "testTopic"

      routerActor ! Subscribe(topic, probe.ref)
      router.subscribers.values.map(_.size).sum shouldEqual 1

      routerActor ! Unsubscribe(topic, probe.ref)
      router.subscribers.values.map(_.size).sum shouldEqual 0

      routerActor ! Publish(topic, "test")
      probe.expectNoMsg(max = 1.second)
    }

    "handle actor terminations" in {
      val routerActor = TestActorRef(Props[PubSubRouter])
      val router      = routerActor.underlyingActor.asInstanceOf[PubSubRouter]
      val probe       = TestProbe()
      val topic       = "testTopic"

      routerActor ! Subscribe(topic, probe.ref)
      router.subscribers.values.map(_.size).sum shouldEqual 1

      system.stop(probe.ref)
      Thread.sleep(50)
      router.subscribers.values.map(_.size).sum shouldEqual 0
    }
  }
} 
Example 21
Source File: PubSubRouterAltSpec.scala    From graphcool-framework   with Apache License 2.0 5 votes vote down vote up
package cool.graph.messagebus.pubsub.inmemory

import akka.actor.Props
import akka.testkit.{TestActorRef, TestKit, TestProbe}
import cool.graph.akkautil.SingleThreadedActorSystem
import cool.graph.messagebus.pubsub.PubSubProtocol.{Publish, Subscribe, Unsubscribe}
import cool.graph.messagebus.pubsub.PubSubRouterAlt
import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach, Matchers, WordSpecLike}

import scala.concurrent.duration._

class PubSubRouterAltSpec
    extends TestKit(SingleThreadedActorSystem("pubsub-router-spec"))
    with WordSpecLike
    with Matchers
    with BeforeAndAfterAll
    with BeforeAndAfterEach {
  override def afterAll = shutdown(verifySystemShutdown = true)

  "The PubSubRouter implementation" should {
    "subscribe subscribers correctly and route messages" in {
      val routerActor = TestActorRef(Props[PubSubRouterAlt])
      val router      = routerActor.underlyingActor.asInstanceOf[PubSubRouterAlt]
      val probe       = TestProbe()
      val topic       = "testTopic"

      routerActor ! Subscribe(topic, probe.ref)
      router.router.routees.length shouldEqual 1

      routerActor ! Publish(topic, "test")
      probe.expectMsg("test")
      probe.expectNoMsg(max = 1.second)

      routerActor ! Publish("testTopic2", "test2")
      probe.expectNoMsg(max = 1.second)
    }

    "unsubscribe subscribers correctly" in {
      val routerActor = TestActorRef(Props[PubSubRouterAlt])
      val router      = routerActor.underlyingActor.asInstanceOf[PubSubRouterAlt]
      val probe       = TestProbe()
      val topic       = "testTopic"

      routerActor ! Subscribe(topic, probe.ref)
      router.router.routees.length shouldEqual 1

      routerActor ! Unsubscribe(topic, probe.ref)
      router.router.routees.length shouldEqual 0

      routerActor ! Publish(topic, "test")
      probe.expectNoMsg(max = 1.second)
    }

    "handle actor terminations" in {
      val routerActor = TestActorRef(Props[PubSubRouterAlt])
      val router      = routerActor.underlyingActor.asInstanceOf[PubSubRouterAlt]
      val probe       = TestProbe()
      val topic       = "testTopic"

      routerActor ! Subscribe(topic, probe.ref)
      router.router.routees.length shouldEqual 1

      system.stop(probe.ref)
      Thread.sleep(50)
      router.router.routees.length shouldEqual 0
    }
  }
} 
Example 22
Source File: HelloAkkaSpec.scala    From akka-nbench   with Apache License 2.0 5 votes vote down vote up
import org.scalatest.{ BeforeAndAfterAll, FlatSpecLike, Matchers }
import akka.actor.{ Actor, Props, ActorSystem }
import akka.testkit.{ ImplicitSender, TestKit, TestActorRef }
import scala.concurrent.duration._

class HelloAkkaSpec(_system: ActorSystem)
  extends TestKit(_system)
  with ImplicitSender
  with Matchers
  with FlatSpecLike
  with BeforeAndAfterAll {

  def this() = this(ActorSystem("HelloAkkaSpec"))

  override def afterAll: Unit = {
    system.shutdown()
    system.awaitTermination(10.seconds)
  }

  "An HelloAkkaActor" should "be able to set a new greeting" in {
    val greeter = TestActorRef(Props[Greeter])
    greeter ! WhoToGreet("testkit")
    greeter.underlyingActor.asInstanceOf[Greeter].greeting should be("hello, testkit")
  }

  it should "be able to get a new greeting" in {
    val greeter = system.actorOf(Props[Greeter], "greeter")
    greeter ! WhoToGreet("testkit")
    greeter ! Greet
    expectMsgType[Greeting].message.toString should be("hello, testkit")
  }
} 
Example 23
Source File: LinearRegressionActorSpec.scala    From coral   with Apache License 2.0 5 votes vote down vote up
package io.coral.actors.transform

import akka.actor.{ActorRef, ActorSystem}
import akka.testkit.{TestProbe, TestActorRef, ImplicitSender, TestKit}
import io.coral.actors.CoralActorFactory
import io.coral.api.DefaultModule
import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}
import akka.util.Timeout
import org.json4s.native.Serialization.write
import scala.concurrent.duration._

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

	implicit val timeout = Timeout(100.millis)
	implicit val injector = new DefaultModule(system.settings.config)

	override def afterAll() {
		TestKit.shutdownActorSystem(system)
	}

	def createLinearRegressionActor(intercept: Double, weights: Map[String, Double]) = {
		implicit val formats = DefaultFormats
		val str =
			s"""{ "type":"linearregression",
			   |"params": { "intercept": $intercept,
			   |"weights": ${write(weights)}
			   |}}""".stripMargin

		val createJson = parse(str).asInstanceOf[JObject]
		val props = CoralActorFactory.getProps(createJson).get
		val actorTestRef = TestActorRef[LinearRegressionActor](props)

		val probe = TestProbe()
		actorTestRef.underlyingActor.emitTargets += probe.ref
		(actorTestRef, probe)
	}

	"LinearRegressionActor" should {
		"Instantiate from companion object" in {
			val (actor, _) = createLinearRegressionActor(0, Map("salary" -> 2000))
			actor.underlyingActor.intercept should be(0)
			actor.underlyingActor.weights should be(Map("salary" -> 2000))
		}

		"process trigger data when all the features are available even with different order" in {
			val (actor, probe) = createLinearRegressionActor(0, Map("age" -> 0.2, "salary" -> 0.1))
			val message = parse( s"""{"salary": 4000, "age": 40}""").asInstanceOf[JObject]
			actor ! message

			probe.expectMsg(parse( s"""{"score": 408.0, "salary": 4000, "age": 40}"""))
		}

		"emit when score is calculated" in {
			val (actor, probe) = createLinearRegressionActor(0, Map("salary" -> 10))
			val message = parse( s"""{"salary": 2000}""").asInstanceOf[JObject]
			actor ! message

			probe.expectMsg(parse( s"""{"score": 20000.0, "salary": 2000}"""))
		}

		"not emit when keys are missing" in {
			val (actor, probe) = createLinearRegressionActor(0, Map("age" -> 0.2, "salary" -> 10))
			val message = parse( s"""{"salary": 2000}""").asInstanceOf[JObject]
			actor ! message

			probe.expectNoMsg
		}
	}
} 
Example 24
Source File: PagerDutyTest.scala    From sumobot   with Apache License 2.0 5 votes vote down vote up
package com.sumologic.sumobot.plugins.pagerduty

import akka.actor.ActorSystem
import akka.testkit.{TestActorRef, TestKit}
import com.sumologic.sumobot.plugins.BotPlugin
import com.sumologic.sumobot.test.annotated.{MatchTextUtil, SumoBotSpec, SumoBotTestKit}
import org.scalatest.BeforeAndAfterAll


class PagerDutyTest
  extends SumoBotTestKit(ActorSystem("PagerDutyTest"))
  with BeforeAndAfterAll
  with MatchTextUtil {

  "PagerDuty.WhosOnCall" should {
    "match expected input" in {
      shouldMatch(PagerDuty.WhosOnCall, "who's on call?")
      shouldMatch(PagerDuty.WhosOnCall, "who's on call")
      shouldMatch(PagerDuty.WhosOnCall, "who's oncall?")
      shouldMatch(PagerDuty.WhosOnCall, "who's oncall")
      shouldMatch(PagerDuty.WhosOnCall, "whos oncall")

      "who's oncall for prod?" match {
        case PagerDuty.WhosOnCall(filter) => filter should be("prod")
        case _ => fail("Did not match filter case")
      }

      shouldNotMatch(PagerDuty.WhosOnCall, "test")
    }
  }

  "various regexes" should {

    "page on-calls" in {
      shouldMatch(PagerDuty.PageOnCalls, "page oncalls something")
      shouldMatch(PagerDuty.PageOnCalls, "page on-calls something")
      shouldMatch(PagerDuty.PageOnCalls, "page on-calls: something")
      shouldMatch(PagerDuty.PageOnCalls, "page oncalls: something")
    }
  }

  override protected def afterAll(): Unit = {
    TestKit.shutdownActorSystem(system)
  }
} 
Example 25
Source File: HttpOutcomingSenderTest.scala    From sumobot   with Apache License 2.0 5 votes vote down vote up
package com.sumologic.sumobot.http_frontend

import akka.actor.{ActorSystem, Props}
import akka.http.scaladsl.model.ws.TextMessage
import akka.testkit.{TestActorRef, TestActors, TestKit, TestProbe}
import com.sumologic.sumobot.core.HttpReceptionist
import com.sumologic.sumobot.core.model.{IncomingMessage, OutgoingMessage}
import com.sumologic.sumobot.test.SumoBotSpec
import com.sumologic.sumobot.test.annotated.SumoBotTestKit
import org.scalatest.BeforeAndAfterAll

class HttpOutcomingSenderTest
  extends SumoBotTestKit(ActorSystem("HttpOutcomingSenderTest"))
  with BeforeAndAfterAll {

  private val probe = new TestProbe(system)
  system.eventStream.subscribe(probe.ref, classOf[TextMessage.Strict])

  private val httpOutcomingSender = TestActorRef(new HttpOutcomingSender(probe.ref))

  "HttpOutcomingSender" should {
    "send TextMessage" when {
      "received OutgoingMessage" in {
        val outgoingMessage = OutgoingMessage(HttpReceptionist.DefaultSumoBotChannel, "hello!")

        system.eventStream.publish(outgoingMessage)

        val result = probe.expectMsgClass(classOf[TextMessage.Strict])
        result.getStrictText should be ("hello!")
      }
    }

    "stop publisher" when {
      "it is stopped" in {
        val dummyActor = TestActorRef(TestActors.blackholeProps)
        val testProbe = TestProbe()
        testProbe.watch(dummyActor)

        val stoppedSender = TestActorRef(new HttpOutcomingSender(dummyActor))
        system.stop(stoppedSender)

        testProbe.expectTerminated(dummyActor)
      }
    }
  }

  override def afterAll: Unit = {
    TestKit.shutdownActorSystem(system)
  }
} 
Example 26
Source File: HttpIncomingReceiverTest.scala    From sumobot   with Apache License 2.0 5 votes vote down vote up
package com.sumologic.sumobot.http_frontend

import java.time.Instant

import akka.actor.{ActorSystem, Props}
import akka.http.scaladsl.model.ws.TextMessage
import akka.stream.scaladsl.Source
import akka.testkit.{TestActorRef, TestActors, TestKit, TestProbe}
import com.sumologic.sumobot.core.HttpReceptionist
import com.sumologic.sumobot.core.model.IncomingMessage
import com.sumologic.sumobot.test.SumoBotSpec
import com.sumologic.sumobot.test.annotated.SumoBotTestKit
import org.scalatest.BeforeAndAfterAll

class HttpIncomingReceiverTest
  extends SumoBotTestKit(ActorSystem("HttpIncomingReceiverTest"))
  with BeforeAndAfterAll {

  private val probe = new TestProbe(system)
  system.eventStream.subscribe(probe.ref, classOf[IncomingMessage])

  private val dummyActor = TestActorRef(TestActors.blackholeProps)
  private val httpIncomingReceiver = TestActorRef(new HttpIncomingReceiver(dummyActor))

  "HttpIncomingReceiver" should {
    "publish IncomingMessage" when {
      "received streamed TextMessage" in {
        val msgSource = Source(List("hello"))
        val streamedMsg = TextMessage.Streamed(msgSource)

        httpIncomingReceiver ! streamedMsg
        val result = probe.expectMsgClass(classOf[IncomingMessage])
        result.canonicalText should be ("hello")
        result.addressedToUs should be (true)
        result.channel should be (HttpReceptionist.DefaultSumoBotChannel)
        result.attachments should be (Seq.empty)
        result.sentBy.plainTextReference should be (HttpReceptionist.DefaultClientUser.id)
      }

      "received strict TextMessage" in {
        val strictMsg = TextMessage.Strict("hi!")

        httpIncomingReceiver ! strictMsg

        val result = probe.expectMsgClass(classOf[IncomingMessage])
        result.canonicalText should be ("hi!")
        result.addressedToUs should be (true)
        result.channel should be (HttpReceptionist.DefaultSumoBotChannel)
        result.attachments should be (Seq.empty)
        result.sentBy.plainTextReference should be (HttpReceptionist.DefaultClientUser.id)
      }

      "properly format date" when {
        "sending IncomingMessage" in {
          val strictMsg = TextMessage.Strict("test")

          httpIncomingReceiver ! strictMsg
          val result = probe.expectMsgClass(classOf[IncomingMessage])

          val currentDate = Instant.now().getEpochSecond.toDouble
          val messageDate = result.idTimestamp.toDouble

          messageDate should be (currentDate +- 5.0)
        }
      }
    }

    "stop itself and outcoming actor" when {
      "stream ended" in {
        val outcomingActor = TestActorRef(TestActors.blackholeProps)
        val testProbeOutcoming = TestProbe()
        testProbeOutcoming.watch(outcomingActor)

        val shutdownReceiver = TestActorRef(new HttpIncomingReceiver(outcomingActor))
        val testProbeShutdown = TestProbe()
        testProbeShutdown.watch(shutdownReceiver)

        shutdownReceiver ! HttpIncomingReceiver.StreamEnded

        testProbeOutcoming.expectTerminated(outcomingActor)
        testProbeShutdown.expectTerminated(shutdownReceiver)
      }
    }
  }

  override def afterAll: Unit = {
    TestKit.shutdownActorSystem(system)
  }
} 
Example 27
Source File: CalculatorSpec.scala    From Scalaprof   with GNU General Public License v2.0 5 votes vote down vote up
package actors

import org.scalatest._
import akka.testkit.TestActorRef
import scala.concurrent.duration._
import scala.concurrent.Await
import akka.pattern.ask
import scala.util._
import scala.io.Source
import scala.concurrent._
import scala.concurrent.duration._
import com.typesafe.config.{ ConfigFactory, Config }
import akka.actor.{ Actor, ActorSystem, Props, ActorRef }
import akka.util.Timeout
import java.net.URL
import org.scalatest.concurrent._
import org.scalatest._
import org.scalatest.time._
import edu.neu.coe.scala.numerics.Rational
import models._


class CalculatorSpec extends FlatSpec with Matchers with Futures with ScalaFutures with Inside {
  implicit val system = ActorSystem("CountWords")  
  import play.api.libs.concurrent.Execution.Implicits.defaultContext
  implicit val timeout: Timeout = Timeout(10 seconds)

  "Rational Calculator" should "yield empty list for /" in {
      val lookup: String=>Option[Rational] = RationalMill.constants.get _
      val conv: String=>Try[Rational] = RationalMill.valueOf _
      val parser = new ExpressionParser[Rational](conv,lookup)
      val mill: Mill[Rational] = RationalMill()
      val props = Props(new Calculator(mill,parser))
      val taf = TestActorRef(props)
      val xsf = (taf ? View).mapTo[Seq[Rational]]
      val nf = xsf map { case xs => xs.size }
      whenReady(nf, timeout(Span(6, Seconds))) { case 0 => }
  }
  it should "yield 1 for 1" in {
      val lookup: String=>Option[Rational] = RationalMill.constants.get _
      val conv: String=>Try[Rational] = RationalMill.valueOf _
      val parser = new ExpressionParser[Rational](conv,lookup)
      val mill: Mill[Rational] = RationalMill()
      val props = Props(new Calculator(mill,parser))
      val taf = TestActorRef(props)
      val xtf = (taf ? "1").mapTo[Try[Rational]]
      whenReady(xtf, timeout(Span(6, Seconds))) { case Success(Rational(1,1)) => }
  }
  it should "yield 1 when given floating point problem" in {
      val lookup: String=>Option[Rational] = RationalMill.constants.get _
      val conv: String=>Try[Rational] = RationalMill.valueOf _
      val parser = new ExpressionParser[Rational](conv,lookup)
      val mill: Mill[Rational] = RationalMill()
      val props = Props(new Calculator(mill,parser))
      val taf = TestActorRef(props)
      val xtf = (taf ? "0.2 0.1 + 10 * 3 /").mapTo[Try[Rational]]
      whenReady(xtf, timeout(Span(6, Seconds))) { case Success(Rational(1,1)) => }
  }
  "Double Calculator" should "yield empty list for /" in {
      val lookup: String=>Option[Double] = DoubleMill.constants.get _
      val conv: String=>Try[Double] = DoubleMill.valueOf _
      val parser = new ExpressionParser[Double](conv,lookup)
      val mill: Mill[Double] = DoubleMill()
      val props = Props(new Calculator(mill,parser))
      val taf = TestActorRef(props)
      val xsf = (taf ? View).mapTo[Seq[Double]]
      val nf = xsf map { case xs => xs.size }
      whenReady(nf, timeout(Span(6, Seconds))) { case 0 => }
  }
  
  // This test suffers from a very peculiar bug which might even be a bug
  // in the Scala compiler. Kudos to you if you can fix it!!
  ignore should "yield 1 for 1" in {
      val lookup: String=>Option[Double] = DoubleMill.constants.get _
      val conv: String=>Try[Double] = DoubleMill.valueOf _
      val parser = new ExpressionParser[Double](conv,lookup)
      val mill: Mill[Double] = DoubleMill()
      val props = Props(new Calculator(mill,parser))
      val taf = TestActorRef(props)
      val xtf = (taf ? "1").mapTo[Try[Double]]
      whenReady(xtf, timeout(Span(6, Seconds))) { case Success(1.0) => }
  }
} 
Example 28
Source File: LDAPAuthenticatorSpec.scala    From coral   with Apache License 2.0 5 votes vote down vote up
package io.coral.api.security

import java.net.InetAddress
import akka.actor.Props
import akka.testkit.TestActorRef
import com.typesafe.config.ConfigFactory
import com.unboundid.ldap.listener.{InMemoryListenerConfig, InMemoryDirectoryServer, InMemoryDirectoryServerConfig}
import io.coral.TestHelper
import io.coral.actors.RootActor
import io.coral.actors.RootActor.{CreateHelperActors, CreateTestActors}
import io.coral.api.CoralConfig
import io.coral.api.security.Authenticator.Invalidate
import io.coral.cluster.ClusterMonitor

class LDAPAuthenticatorSpec
	extends AuthenticatorSpec("ldap") {
	override def createActorSystem = {
		val c = new CoralConfig(ConfigFactory.parseString(
			s"""{
			   |akka.actor.provider = "akka.actor.LocalActorRefProvider"
			   |coral {
			   |  cluster.enable = false
			   |  authentication {
			   |    mode = "ldap"
			   |    ldap {
			   |      host = "${InetAddress.getLocalHost.getHostAddress}"
			   |      port = 1234
			   |      bind-dn = "uid={user},ou=People,dc=example,dc=com"
			   |      mfa {
			   |        enabled = false
			   |      }
			   |    }
			   |  }
			   |}}""".stripMargin).withFallback(ConfigFactory.load()))
		initiateWithConfig(c)
	}

	var ldapServer: InMemoryDirectoryServer = _

	override def beforeAll() {
		startInMemoryLDAPServer()

		root = TestActorRef[RootActor](new RootActor(), "root")
		admin = system.actorSelection("/user/root/admin")

		root ! CreateHelperActors()

		cassandra = TestHelper.createCassandraActor(
			config.coral.cassandra.contactPoints.head.getHostName,
			config.coral.cassandra.port)
		TestHelper.prepareTables()
		TestHelper.clearAllTables()

		system.actorOf(Props(new ClusterMonitor(config)), "clusterMonitor")
		authenticator = system.actorSelection("/user/root/authenticator")
		permissionHandler = system.actorSelection("/user/root/authenticator/permissionHandler")

		runtimeUUID1 = TestHelper.createStandardRuntime("runtime1", user1, admin)
		runtimeUUID2 = TestHelper.createStandardRuntime("runtime2", user2, admin)
		runtimeUUID3 = TestHelper.createStandardRuntime("runtime3", user3, admin)

		userUUID1 = TestHelper.getUserUUIDFromUniqueName(authenticator, user1)
		userUUID2 = TestHelper.getUserUUIDFromUniqueName(authenticator, user2)
		userUUID3 = TestHelper.getUserUUIDFromUniqueName(authenticator, user3)

		authenticator ! Invalidate()

		Thread.sleep(500)
	}

	def startInMemoryLDAPServer() {
		val config = new InMemoryDirectoryServerConfig("dc=example,dc=com")
		config.setSchema(null)
		config.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig(
			"LDAP listener", InetAddress.getLocalHost, 1234, null))
		config.addAdditionalBindCredentials("cn=Directory Manager", "password")
		ldapServer = new InMemoryDirectoryServer(config)
		val testDataFile = getClass.getResource("testdata.ldif").getFile
		ldapServer.importFromLDIF(true, testDataFile)
		ldapServer.startListening()
	}

	override def afterAll() {
		ldapServer.shutDown(true)
	}

	"An LDAP actor" should {
		"Properly create a connection" in {
			
		}
	}
} 
Example 29
Source File: DenyAllAuthenticatorSpec.scala    From coral   with Apache License 2.0 5 votes vote down vote up
package io.coral.api.security

import akka.testkit.TestActorRef
import com.typesafe.config.ConfigFactory
import io.coral.TestHelper
import io.coral.actors.RootActor
import io.coral.api.CoralConfig
import io.coral.api.security.Authenticator.Invalidate
import spray.http.{BasicHttpCredentials, StatusCodes}

class DenyAllAuthenticatorSpec
	extends BaseAuthSpec("deny-all") {
	override def beforeAll() {
		root = TestActorRef[RootActor](new RootActor(), "root")
		admin = system.actorSelection("/user/root/admin")

		cassandra = TestHelper.createCassandraActor(
			config.coral.cassandra.contactPoints.head.getHostName,
			config.coral.cassandra.port)
		TestHelper.prepareTables()
		TestHelper.clearAllTables()

		permissionHandler = system.actorSelection("/user/root/authenticator/permissionHandler")
	}

	override def createActorSystem = {
		val c = new CoralConfig(ConfigFactory.parseString(
			s"""coral.authentication.mode = "deny-all"""".stripMargin)
			.withFallback(ConfigFactory.load()))
		initiateWithConfig(c)
	}

	"A Coral HTTP service with deny all authentication" should {
		"Deny any user" in {
			Get("/api/runtimes").withHeaders(AcceptHeader) ~>
				addCredentials(BasicHttpCredentials(user1, pass1)) ~> route ~> check {
				assert(status == StatusCodes.Unauthorized)
			}
		}
	}
} 
Example 30
Source File: StatsActorSpec.scala    From coral   with Apache License 2.0 5 votes vote down vote up
package io.coral.actors.transform

import akka.actor.ActorSystem
import akka.testkit.{ImplicitSender, TestActorRef, TestKit}
import akka.util.Timeout
import io.coral.actors.CoralActorFactory
import io.coral.api.DefaultModule
import org.json4s.JsonAST.JValue
import org.json4s.JsonDSL._
import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}
import scala.concurrent.Await
import scala.concurrent.duration._

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

	override def afterAll() {
		TestKit.shutdownActorSystem(system)
	}

	implicit val timeout = Timeout(100.millis)
	implicit val injector = new DefaultModule(system.settings.config)

	def createStatsActor: StatsActor = {
		val createJson = parse( """{ "type": "stats", "params": { "field": "val" } }""")
			.asInstanceOf[JObject]
		val props = CoralActorFactory.getProps(createJson).get
		val actorRef = TestActorRef[StatsActor](props)
		actorRef.underlyingActor
	}

	val expectedInitialState = Map(
		("count", render(0L)),
		("avg", render(JNull)),
		("sd", render(JNull)),
		("min", render(JNull)),
		("max", render(JNull))
	)

	"StatsActor" should {
		"have a field corresponding to the json definition" in {
			val actor = createStatsActor
			actor.field should be("val")
		}

		"supply it's state" in {
			val actor = createStatsActor
			actor.state should be(expectedInitialState)
		}

		"accept a value as trigger" in {
			val actor = createStatsActor
			val triggerJson = parse( """{ "bla": 1.0, "val": 2.7 }""").asInstanceOf[JObject]
			actor.trigger(triggerJson)
			actor.state should be(
				Map(
					("count", render(1L)),
					("avg", render(2.7)),
					("sd", render(0.0)),
					("min", render(2.7)),
					("max", render(2.7))
				))
		}

		"have timer reset statistics" in {
			val actor = createStatsActor
			val triggerJson = parse( """{ "val": 2.7 }""").asInstanceOf[JObject]
			actor.trigger(triggerJson)
			actor.state should be(
				Map(
					("count", render(1L)),
					("avg", render(2.7)),
					("sd", render(0.0)),
					("min", render(2.7)),
					("max", render(2.7))
				))
			val future = actor.timer
			val json = Await.result(future, timeout.duration).get
			json should be(JNothing)
			actor.state should be(expectedInitialState)
		}
	}
} 
Example 31
Source File: GroupByActorSpec.scala    From coral   with Apache License 2.0 5 votes vote down vote up
package io.coral.actors.transform

import java.util.UUID

import akka.actor.{ActorSystem, Props}
import akka.testkit.{ImplicitSender, TestActorRef, TestKit}
import akka.util.Timeout
import io.coral.actors.RuntimeActor
import io.coral.api.DefaultModule
import org.json4s.JsonDSL._
import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

import scala.concurrent.duration._
import scala.languageFeature.postfixOps

class GroupByActorSpec(_system: ActorSystem)
	extends TestKit(_system)
	with ImplicitSender
	with WordSpecLike
	with Matchers
	with BeforeAndAfterAll
	with ScalaFutures {
	def this() = this(ActorSystem("GroupByActorSpec"))
	implicit val ec = scala.concurrent.ExecutionContext.Implicits.global
	implicit val injector = new DefaultModule(system.settings.config)
	val name = "runtime1"
	val userUUID1 = UUID.randomUUID()
	implicit val runtime = system.actorOf(Props(new RuntimeActor(name, userUUID1)), "coral")
	implicit val timeout = Timeout(100.millis)
	implicit val formats = org.json4s.DefaultFormats

	override def afterAll() {
		TestKit.shutdownActorSystem(system)
	}

	// here is a dependency on the stats actor
	// in the current situation (the CoralActorFactory) it seems unavoidable
	// to depend in some tests on an existing actor instead of injecting a test actor
	def statsGroupBy: GroupByActor = {
		val createJson = parse(
			"""{ "type": "stats",
			  |  "params": { "field": "amount" },
			  |  "group": { "by": "tag" }
			  | }""".stripMargin
		).asInstanceOf[JObject]
		TestActorRef[GroupByActor](GroupByActor(createJson).get).underlyingActor
	}

	"A GroupByActor" should {
		
	}
} 
Example 32
Source File: SampleActorSpec.scala    From coral   with Apache License 2.0 5 votes vote down vote up
package io.coral.actors.transform

import akka.actor.{ActorSystem, Props}
import akka.testkit.{ImplicitSender, TestActorRef, TestKit, TestProbe}
import akka.util.Timeout
import io.coral.lib.{NotSoRandom, Random}
import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

import scala.concurrent.duration._
import scala.language.postfixOps

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

	override def afterAll() {
		TestKit.shutdownActorSystem(system)
	}

	def arbitrarySampleActor(): SampleActor = {
		val json = parse(
			"""{ "type": "sample",
			  | "params": { "fraction": 0.707 } }
			""".stripMargin)
		val props = SampleActor(json).get
		TestActorRef[SampleActor](props).underlyingActor
	}

	def notSoRandomSampleActor(fraction: Double, randoms: Double*): SampleActor = {
		val json = parse(
			s"""{ "type": "sample", "params": { "fraction": ${fraction} } }
     		 """.stripMargin)
		val source = NotSoRandom(randoms: _*)
		val props = Props(classOf[SampleActor], json, Random(source))
		TestActorRef[SampleActor](props).underlyingActor
	}

	implicit val timeout = Timeout(100 millis)

	"A SampleActor" should {

		"Be instantiated with sample fraction" in {
			val json = parse("""{ "type": "sample", "params": { "fraction": 0.5 }}""".stripMargin)
			val props = SampleActor(json).get
			props.actorClass() should be(classOf[SampleActor])
			val actor = TestActorRef[SampleActor](props).underlyingActor
			actor.fraction should be(0.5)
		}

		"Not be instantiated without fraction or percentage" in {
			val json = parse("""{ "type": "sample", "params": { "bla": "blabla" }}""".stripMargin)
			SampleActor(json) should be(None)
		}

		"Be constructible with a io.coral.lib.Random for random boolean stream" in {
			val actor = notSoRandomSampleActor(fraction = 0.5, randoms = 0.1, 0.49, 0.50, 0.51, 0.8, 0.4)
			actor.next() should be(true)
			actor.next() should be(true)
			actor.next() should be(false)
			actor.next() should be(false)
			actor.next() should be(false)
			actor.next() should be(true)
		}

		"Should trigger true or false according to random binomial sequence" in {
			val actor = notSoRandomSampleActor(fraction = 0.7, randoms = 0.8, 0.6)
			val json = parse( """{ "something": "whatever" }""").asInstanceOf[JObject]

			val result1 = actor.simpleEmitTrigger(json)
			result1 should be(Some(JNothing))

			val result2 = actor.simpleEmitTrigger(json)
			result2 should be(Some(json))
		}

		"Should have trigger and emit cooperate" in {
			val actor = notSoRandomSampleActor(fraction = 0.7, randoms = 0.6, 0.8)
			val ref = actor.self
			val json = parse( """{ "something": "whatever" }""").asInstanceOf[JObject]
			val probe = TestProbe()
			actor.emitTargets += probe.ref
			ref ! json
			probe.expectMsg(json)
			ref ! json
			probe.expectNoMsg(100 millis)
		}
	}
} 
Example 33
Source File: JsonActorSpec.scala    From coral   with Apache License 2.0 5 votes vote down vote up
package io.coral.actors.transform

import akka.actor.ActorSystem
import akka.testkit.{ImplicitSender, TestActorRef, TestKit}
import akka.util.Timeout
import org.json4s.JsonAST.JValue
import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

import scala.concurrent.duration._

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

	override def afterAll() {
		TestKit.shutdownActorSystem(system)
	}

	implicit val timeout = Timeout(100.millis)
	def createJsonActor(json: JValue): JsonActor = {
		val props = JsonActor(json).get
		val actorRef = TestActorRef[JsonActor](props)
		actorRef.underlyingActor
	}

	"JsonActor" should {
		"have a standard coral props supplier" in {
			val json = parse("""{ "type": "json", "params": { "template": {} } }""")
			val props = JsonActor(json).get
			props.actorClass shouldBe classOf[JsonActor]
		}

		"read the template parameter" in {
			val template = """{ "a": "someReference" }"""
			val json = parse(s"""{ "type": "json", "params": { "template": $template } }""")
			val actor = createJsonActor(json)
			actor.template.template shouldBe parse(template)
		}

		"emit the json based on template" in {
			val templateJson =
				"""{ "a": "ALPHA",
				  |  "b": "${beta}",
				  |  "c": { "d": 123,
				  |         "e": "${epsilon}"
				  |       },
				  |  "f": 1,
				  |  "g": 1.0
				  |}""".stripMargin
			val json = parse(s"""{ "type": "json", "params": { "template": ${templateJson} } }""")
			val actor = createJsonActor(json)
			val triggerJson = parse(
				"""{ "beta": "xyz",
				  |  "epsilon": 987
				  |}""".stripMargin)
			val expectedJson = parse(
				"""{ "a": "ALPHA",
				  |  "c": { "d": 123,
				  |         "e": 987
				  |       },
				  |  "f": 1,
				  |  "b": "xyz",
				  |  "g": 1.0
				  |}""".stripMargin)
			actor.simpleEmitTrigger(triggerJson.asInstanceOf[JObject]) shouldBe Some(expectedJson)
		}
	}
} 
Example 34
Source File: ProcessActorTest.scala    From scastie   with Apache License 2.0 5 votes vote down vote up
package com.olegych.scastie.util

import java.io.File
import java.nio.file.{Files, StandardCopyOption}

import akka.actor.{Actor, ActorRef, ActorSystem}
import akka.testkit.{ImplicitSender, TestActorRef, TestKit, TestProbe}
import com.olegych.scastie.api.ProcessOutput
import com.olegych.scastie.api.ProcessOutputType._
import com.olegych.scastie.util.ProcessActor._
import org.scalatest.BeforeAndAfterAll
import org.scalatest.funsuite.AnyFunSuiteLike

import scala.concurrent.duration._

class ProcessActorTest() extends TestKit(ActorSystem("ProcessActorTest")) with ImplicitSender with AnyFunSuiteLike with BeforeAndAfterAll {

  test("do it") {
    (1 to 10).foreach { i =>
      println(s"--- Run $i ---")

      val command = new File("target", "echo.sh")
      Files.copy(getClass.getResourceAsStream("/echo.sh"), command.toPath, StandardCopyOption.REPLACE_EXISTING)
      command.setExecutable(true)

      val probe = TestProbe()

      val processActor = TestActorRef(new ProcessReceiver(command.getPath, probe.ref))

      processActor ! Input("abcd")
      processActor ! Input("1234")
      processActor ! Input("quit")

      def expected(msg0: String): Unit = {
        probe.expectMsgPF(4000.milliseconds) {
          case ProcessOutput(msg1, StdOut, _) if msg0.trim == msg1.trim => true
          case ProcessOutput(msg1, StdOut, _) =>
            println(s""""$msg1" != "$msg0"""")
            false
        }
      }

      expected("abcd")
      expected("1234")
    }
  }

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

class ProcessReceiver(command: String, probe: ActorRef) extends Actor {
  private val props =
    ProcessActor.props(command = List("bash",  "-c", command.replace("\\", "/")), killOnExit = false)
  private val process = context.actorOf(props, name = "process-receiver")

  override def receive: Receive = {
    case output: ProcessOutput => probe ! output
    case input: Input          => process ! input
  }
} 
Example 35
Source File: MinMaxActorSpec.scala    From coral   with Apache License 2.0 5 votes vote down vote up
package io.coral.actors.transform

import akka.actor.{Actor, ActorSystem, Props}
import akka.testkit.{TestProbe, ImplicitSender, TestActorRef, TestKit}
import akka.util.Timeout
import io.coral.actors.CoralActorFactory
import io.coral.api.DefaultModule
import org.json4s.JsonDSL._
import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}
import scala.concurrent.duration._

@RunWith(classOf[JUnitRunner])
class MinMaxActorSpec(_system: ActorSystem)
	extends TestKit(_system)
	with ImplicitSender
	with WordSpecLike
	with Matchers
	with BeforeAndAfterAll {
	implicit val timeout = Timeout(100.millis)
	implicit val formats = org.json4s.DefaultFormats
	implicit val injector = new DefaultModule(system.settings.config)
	def this() = this(ActorSystem("ZscoreActorSpec"))

	override def afterAll() {
		TestKit.shutdownActorSystem(system)
	}

	"A MinMaxActor" must {
		val createJson = parse(
			"""{ "type": "minmax", "params": { "field": "field1", "min": 10.0, "max": 13.5 }}"""
				.stripMargin).asInstanceOf[JObject]

		implicit val injector = new DefaultModule(system.settings.config)

		val props = CoralActorFactory.getProps(createJson).get
		val threshold = TestActorRef[MinMaxActor](props)

		// subscribe the testprobe for emitting
		val probe = TestProbe()
		threshold.underlyingActor.emitTargets += probe.ref

		"Emit the minimum when lower than the min" in {
			val json = parse( """{"field1": 7 }""").asInstanceOf[JObject]
			threshold ! json
			probe.expectMsg(parse( """{ "field1": 10.0 }"""))
		}

		"Emit the maximum when higher than the max" in {
			val json = parse( """{"field1": 15.3 }""").asInstanceOf[JObject]
			threshold ! json
			probe.expectMsg(parse( """{"field1": 13.5 }"""))
		}

		"Emit the value itself when between the min and the max" in {
			val json = parse( """{"field1": 11.7 }""").asInstanceOf[JObject]
			threshold ! json
			probe.expectMsg(parse( """{"field1": 11.7 }"""))
		}

		"Emit object unchanged when key is not present in triggering json" in {
			val json = parse( """{"otherfield": 15.3 }""").asInstanceOf[JObject]
			threshold ! json
			probe.expectMsg(parse( """{"otherfield": 15.3 }"""))
		}
	}
} 
Example 36
Source File: CoordinatorSpec.scala    From cave   with MIT License 5 votes vote down vote up
package worker

import akka.actor._
import akka.testkit.{ImplicitSender, TestActorRef, TestKit}
import com.cave.metrics.data._
import init.AwsWrapper
import init.AwsWrapper.WorkItem
import org.mockito.Matchers._
import org.mockito.Mockito._
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

import scala.collection.mutable
import scala.concurrent.{ExecutionContext, Future}
import scala.util.Success

class CoordinatorSpec extends TestKit(ActorSystem()) with WordSpecLike with Matchers with ImplicitSender with BeforeAndAfterAll with AlertJsonData with MockitoSugar {

  def fakeCoordinator(awsWrapper: AwsWrapper, mockCheckers: mutable.Map[ActorRef, WorkItem]): Props = Props(new Coordinator(awsWrapper, shouldSendHistory = false) {

    override val checkers = mockCheckers
    override def createNotifier(item: WorkItem): Unit = { }
  })

  def fakeChecker(parentCoordinator: ActorRef): Props = Props(new Actor {
    def receive = {
      case "abort" =>
        parentCoordinator ! Checker.Aborted("Boom!")
        context stop self
      case "true" =>
        parentCoordinator ! Checker.Done(Success(true))
        context stop self
      case "false" =>
        parentCoordinator ! Checker.Done(Success(false))
        context stop self
    }
  })

  val mockAwsWrapper = mock[AwsWrapper]
  val mockDataManager = mock[CacheDataManager]

  override def afterAll() = {
    system.shutdown()
  }

  "A coordinator" must {

    "return its status" in {
      when(mockAwsWrapper.receiveMessages()(any[ExecutionContext])).thenReturn(Future.successful(List.empty[WorkItem]))

      val checkers = mutable.Map.empty[ActorRef, WorkItem]
      val mockItem = mock[WorkItem]

      val coordinator = TestActorRef(fakeCoordinator(mockAwsWrapper, checkers))

      val checker1 = TestActorRef(fakeChecker(coordinator))
      val checker2 = TestActorRef(fakeChecker(coordinator))
      val checker3 = TestActorRef(fakeChecker(coordinator))
      val checker4 = TestActorRef(fakeChecker(coordinator))
      val checker5 = TestActorRef(fakeChecker(coordinator))
      val checker6 = TestActorRef(fakeChecker(coordinator))

      checkers ++= mutable.Map(checker1 -> mockItem, checker2 -> mockItem, checker3 -> mockItem,
        checker4 -> mockItem, checker5 -> mockItem, checker6 -> mockItem)

      checker1 ! "abort"
      checker2 ! "abort"
      checker3 ! "false"
      checker4 ! "false"
      checker5 ! "false"
      checker6 ! "true"

      coordinator ! Coordinator.StatusRequest

      expectMsgPF() {
        case Coordinator.StatusResponse(currentlyActive, aborted, totalProcessed, noOfAlarmsTriggered) =>
          currentlyActive should be(0)
          aborted should be(2)
          noOfAlarmsTriggered should be(1)
          totalProcessed should be(4)
        case _ => fail("Unexpected message received.")
      }

      coordinator ! PoisonPill
      watch(coordinator)
      expectTerminated(coordinator)
    }
  }
} 
Example 37
Source File: CoordinatorSpec.scala    From cave   with MIT License 5 votes vote down vote up
package actors

import akka.actor.{ActorSystem, PoisonPill, Props}
import akka.testkit.{ImplicitSender, TestActorRef, TestKit}
import com.cave.metrics.data._
import init.AwsWrapper
import init.AwsWrapper.WorkItem
import org.mockito.Mockito._
import org.mockito.Matchers._
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{BeforeAndAfterAll, WordSpecLike}
import org.specs2.matcher.ShouldMatchers

import scala.concurrent.{Future, ExecutionContext}
import scala.util.Success

class CoordinatorSpec extends TestKit(ActorSystem()) with WordSpecLike with ShouldMatchers with ImplicitSender with BeforeAndAfterAll with AlertJsonData with MockitoSugar {

  val mockAwsWrapper = mock[AwsWrapper]
  val mockDataManager = mock[CacheDataManager]

  override def afterAll() = {
    system.shutdown()
  }

  "A coordinator" must {

    "create schedulers for all enabled alerts" in {

      val SomeId = "1234"
      val AnotherId = "4321"
      val OtherId = "12345"

      val alerts = List(
        Schedule(OrgName, Some(TeamName), None, NotificationUrl, Alert(Some(SomeId), AlertDescription, AlertEnabled, AlertPeriod, AlertCondition, Some(AlertHandbookUrl), Some(AlertRouting))),
        Schedule(OrgName, Some(TeamName), None, NotificationUrl, Alert(Some(AnotherId), AlertDescription, AlertEnabled, AlertPeriod, AlertCondition, Some(AlertHandbookUrl), Some(AlertRouting))))

      val moreAlerts = List(
        Schedule(TeamName, None, None, NotificationUrl, Alert(Some(OtherId), AlertDescription, AlertEnabled, AlertPeriod, AlertCondition, Some(AlertHandbookUrl), Some(AlertRouting)))
      )

      when(mockDataManager.getEnabledAlerts()).thenReturn(Success(Map(OrgName -> alerts, TeamName -> moreAlerts)))
      when(mockAwsWrapper.receiveMessages()(any[ExecutionContext])).thenReturn(Future.successful(List.empty[WorkItem]))
      val coordinator = TestActorRef(Props(new Coordinator(mockAwsWrapper, mockDataManager) {
        override def createScheduler(schedule: Schedule) = {}
      }))

      coordinator ! Coordinator.StatusRequest

      expectMsgPF() {
        case Coordinator.StatusResponse(cache, schedules) =>
          cache.schedulesByOrganization should haveSize(2)
          val forOrgName = cache.schedulesByOrganization(OrgName)
          forOrgName should haveSize(2)
          val forTeamName = cache.schedulesByOrganization(TeamName)
          forTeamName should haveSize(1)

          schedules should haveSize(3)

        case _ => fail("Unexpected message received.")
      }


      coordinator ! PoisonPill
      watch(coordinator)
      expectTerminated(coordinator)
    }
  }
} 
Example 38
Source File: PropertiesLoaderSuite.scala    From iep-apps   with Apache License 2.0 5 votes vote down vote up
package com.netflix.iep.archaius

import akka.actor.ActorSystem
import akka.testkit.ImplicitSender
import akka.testkit.TestActorRef
import akka.testkit.TestKit
import com.amazonaws.services.dynamodbv2.model.AttributeValue
import com.amazonaws.services.dynamodbv2.model.ScanResult
import com.netflix.atlas.json.Json
import com.netflix.spectator.api.DefaultRegistry
import com.netflix.spectator.api.ManualClock
import com.typesafe.config.ConfigFactory
import org.scalatest.BeforeAndAfterAll
import org.scalatest.funsuite.AnyFunSuiteLike

class PropertiesLoaderSuite
    extends TestKit(ActorSystem())
    with ImplicitSender
    with AnyFunSuiteLike
    with BeforeAndAfterAll {

  val config = ConfigFactory.parseString("""
      |netflix.iep.archaius.table = "test"
    """.stripMargin)

  val clock = new ManualClock()
  val registry = new DefaultRegistry(clock)
  val propContext = new PropertiesContext(registry)

  val ddb = new MockDynamoDB
  val service = new DynamoService(ddb.client, config)

  val items = newItems("foo-main", Map("a"  -> "b", "1" -> "2"))
  items.addAll(newItems("bar-main", Map("c" -> "d")))
  ddb.scanResult = new ScanResult().withItems(items)

  val ref = TestActorRef(new PropertiesLoader(config, propContext, service))

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

  private def waitForUpdate(): Unit = {
    val latch = propContext.latch
    ref ! PropertiesLoader.Tick
    latch.await()
  }

  test("init") {
    waitForUpdate()
    assert(propContext.initialized)
    assert(
      propContext.getAll === List(
          PropertiesApi.Property("foo-main::a", "foo-main", "a", "b", 12345L),
          PropertiesApi.Property("foo-main::1", "foo-main", "1", "2", 12345L),
          PropertiesApi.Property("bar-main::c", "bar-main", "c", "d", 12345L)
        )
    )
  }

  test("update") {
    val items = newItems("foo-main", Map("a"  -> "b"))
    items.addAll(newItems("bar-main", Map("c" -> "d")))
    ddb.scanResult = new ScanResult().withItems(items)

    waitForUpdate()

    assert(
      propContext.getAll === List(
          PropertiesApi.Property("foo-main::a", "foo-main", "a", "b", 12345L),
          PropertiesApi.Property("bar-main::c", "bar-main", "c", "d", 12345L)
        )
    )
  }

  private def newItems(cluster: String, props: Map[String, String]): Items = {
    val items = new java.util.ArrayList[AttrMap]()
    props.foreach {
      case (k, v) =>
        val prop = PropertiesApi.Property(s"$cluster::$k", cluster, k, v, 12345L)
        val value = new AttributeValue().withS(Json.encode(prop))
        val timestamp = new AttributeValue().withS("12345")
        val m = new java.util.HashMap[String, AttributeValue]()
        m.put("data", value)
        m.put("timestamp", timestamp)
        items.add(m)
    }
    items
  }
} 
Example 39
Source File: RegisteredHealthCheckActorSpec.scala    From service-container   with Apache License 2.0 5 votes vote down vote up
package com.github.vonnagy.service.container.health

import akka.actor._
import akka.testkit.TestActorRef
import com.github.vonnagy.service.container.AkkaTestkitSpecs2Support
import org.specs2.mutable.SpecificationLike

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

class RegisteredHealthCheckActorSpec extends AkkaTestkitSpecs2Support with SpecificationLike {

  sequential

  "Health check registration" should {

    "allow for the creation of a registered health check" in {

      val r = new TestRegisteredHealthCheck()(system)
      Await.result[HealthInfo](r.getHealth, 1 second).state must be equalTo HealthState.OK
      Health(system).getChecks.length must be equalTo 1
    }

    "allow for the creation of a registered health check actor" in {

      val ext = Health(system)
      val act = TestActorRef(new Actor with RegisteredHealthCheckActor {
        def receive = {
          case GetHealth => sender ! HealthInfo("test", HealthState.OK, "details")
        }
      })

      Await.result[HealthInfo](act.underlyingActor.getHealth, 1 second).state must be equalTo HealthState.OK
      ext.getChecks.length must be equalTo 2
    }
  }
}

class TestRegisteredHealthCheck(implicit val system: ActorSystem) extends RegisteredHealthCheck {

  import system.dispatcher

  def getHealth: Future[HealthInfo] = Future {
    HealthInfo("test", HealthState.OK, "details")
  }
} 
Example 40
Source File: HttpServiceSpec.scala    From service-container   with Apache License 2.0 5 votes vote down vote up
package com.github.vonnagy.service.container.http

import akka.actor.{ActorSystem, Props}
import akka.testkit.{TestActorRef, TestProbe}
import com.github.vonnagy.service.container.{AkkaTestkitSpecs2Support, TestUtils}
import com.github.vonnagy.service.container.health.HealthState
import com.typesafe.config.ConfigFactory
import org.specs2.mutable.SpecificationLike

class HttpServiceSpec extends AkkaTestkitSpecs2Support(ActorSystem("test", {
  val http = TestUtils.temporaryServerHostnameAndPort()
  val https = TestUtils.temporaryServerHostnameAndPort()

  ConfigFactory.parseString(
    s"""
      container.http.interface="${http._2}"
      container.http.port=${http._3}
      container.https.interface="${https._2}"
      container.https.port=${https._3}
    """)})) with SpecificationLike {

  sequential
  val probe = TestProbe()
  val act = TestActorRef[HttpService](Props(new HttpService(Nil)), probe.testActor, "service")

  "The HttpService" should {

    "be able to check the services health before it is started" in {
      act.underlyingActor.getHttpHealth must not be null
      act.underlyingActor.getHttpHealth.state must be equalTo HealthState.CRITICAL
    }

    "be able to start and Http service on a specified port" in {
      act.underlyingActor.httpSettings.isEmpty must beFalse
      act.underlyingActor.httpServer.isEmpty must beTrue
      probe.send(act, HttpStart)
      val msg = probe.expectMsg(HttpStarted)
      msg must be equalTo HttpStarted

      act.underlyingActor.httpServer.size must be equalTo(2)
    }

    "be able to check the services health after it is started" in {
      act.underlyingActor.getHttpHealth must not be null
      act.underlyingActor.getHttpHealth.state must be equalTo HealthState.OK
    }

    "be able to stop the Http service" in  {
      act.underlyingActor.stopHttpServer
      val msg = probe.expectMsg(HttpStopped)
      msg must be equalTo HttpStopped
      act.underlyingActor.httpServer.isEmpty must beTrue
    }
  }

} 
Example 41
Source File: RoutedEndpointsActorSpec.scala    From service-container   with Apache License 2.0 5 votes vote down vote up
package com.github.vonnagy.service.container.http.routing

import akka.actor._
import akka.testkit.{TestActorRef, TestProbe}
import com.github.vonnagy.service.container.AkkaTestkitSpecs2Support
import org.specs2.mutable.SpecificationLike


class RoutedEndpointsActorSpec extends AkkaTestkitSpecs2Support with SpecificationLike {

  import system.dispatcher

  "The RoutedEndpointsActor" should {

    "allow actor to add routes" in {
      val probe = TestProbe()

      val svc = TestActorRef(new Actor {
        def receive = {
          case _ =>
        }
      }, "service")

      svc.underlyingActor.context
        .actorOf(Props(new Actor with RoutedService {
          def receive = routeReceive
        }), "http")

      TestActorRef(new RoutedEndpointsActor {
        def receive = {
          case RouteAdded => probe.ref ! RouteAdded
        }

        override def route = {
          path("test") {
            complete("complete")
          }
        }
      })

      probe.expectMsg(RouteAdded) must beEqualTo(RouteAdded)

    }
  }
} 
Example 42
Source File: RoutedServiceSpec.scala    From service-container   with Apache License 2.0 5 votes vote down vote up
package com.github.vonnagy.service.container.http.routing

import akka.actor._
import akka.http.scaladsl.model.{HttpEntity, MediaTypes, StatusCodes}
import akka.http.scaladsl.server.{Directives, Route}
import akka.testkit.{TestActorRef, TestProbe}
import com.github.vonnagy.service.container.Specs2RouteTest
import com.github.vonnagy.service.container.http.{DefaultMarshallers, RejectionResponse}
import org.specs2.mutable.Specification

class RoutedServiceSpec extends Specification with Directives with Specs2RouteTest {

  case class TestEntity(id: Int, name: String)

  val probe = new TestProbe(system)
  val httpAct = TestActorRef(Props(new Actor with RoutedService with DefaultMarshallers {
    def receive = routeReceive
  }), "http")

  val svc = httpAct.underlyingActor.asInstanceOf[RoutedService]

  def echoComplete[T]: T => Route = { x ⇒ complete(x.toString) }

  "The RoutedService" should {

    "allow for routes to be added after the system is already loaded" in {
      // This should create the actor and register the endpoints
      val r = new RoutedEndpoints {
        def route = {
          path("test2") {
            complete("test2")
          }
        }
      }

      probe.send(httpAct, AddRoute(r))
      probe.expectMsg(RouteAdded)

      Get("/test2") ~> svc.buildRoute(svc.routes) ~> check {
        responseAs[String] must be equalTo "test2"
      }
    }

    "respond with UnprocessableEntity for requests resulting in a MalformedFormFieldRejection" in {

      implicit val unmarsh = svc.jsonUnmarshaller[TestEntity]
      implicit val rejMarsh = svc.jsonUnmarshaller[RejectionResponse]

      val postRoute = new RoutedEndpoints {
        def route = {
          post {
            path("test4") {
              entity(as[TestEntity]) {
                echoComplete
              }
            }
          }
        }
      }

      probe.send(httpAct, AddRoute(postRoute))
      probe.expectMsg(RouteAdded)

      import svc.defaultJsonFormats
      val ent = TestEntity(100, "product")

      Post("/test4", HttpEntity(MediaTypes.`application/json`, svc.serialization.write(ent))) ~>
        handleRejections(svc.rejectionHandler)(svc.buildRoute(svc.routes)) ~> check {
        status === StatusCodes.UnprocessableEntity
        mediaType === MediaTypes.`application/json`
        responseAs[RejectionResponse] must not beNull
      }
    }

    "respond with RejectionResponse for requests that error out" in {

      implicit val rejMarsh = svc.jsonUnmarshaller[RejectionResponse]

      val postRoute = new RoutedEndpoints {
        def route = {
          get {
            path("test5") { ctx => throw new Exception("test") }
          }
        }
      }

      probe.send(httpAct, AddRoute(postRoute))
      probe.expectMsg(RouteAdded)

      Get("/test5") ~>
        Route.seal(svc.buildRoute(svc.routes))(svc.routeSettings,
          exceptionHandler = svc.exceptionHandler,
          rejectionHandler = svc.rejectionHandler) ~> check {

        mediaType === MediaTypes.`application/json`
        responseAs[RejectionResponse] must not beNull
      }
    }
  }

} 
Example 43
Source File: SSLProviderSpec.scala    From service-container   with Apache License 2.0 5 votes vote down vote up
package com.github.vonnagy.service.container.http.security

import akka.actor.Actor
import akka.http.scaladsl.{HttpConnectionContext, HttpsConnectionContext}
import akka.testkit.TestActorRef
import com.github.vonnagy.service.container.AkkaTestkitSpecs2Support
import org.specs2.mutable.SpecificationLike

class SSLProviderSpec extends AkkaTestkitSpecs2Support with SpecificationLike {

  val act = TestActorRef(new SSLActor)

  class SSLActor extends Actor with SSLProvider {
    def receive = {
      case _ =>
    }
  }

  "SSLProviderSpec" should {

    "allow for getting an SSL context" in {
      val ctx = act.underlyingActor.getContext(true)
      ctx.isInstanceOf[HttpsConnectionContext] must beTrue
    }

    "allow for getting an non-SSL context" in {
      val ctx = act.underlyingActor.getContext(false)
      ctx.isInstanceOf[HttpConnectionContext] must beTrue
    }

  }
} 
Example 44
Source File: ReplicaRemoteWriterTest.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.replica.write

import java.util.UUID

import akka.actor.{Actor, ActorSystem}
import akka.testkit.{TestActorRef, TestKit}
import justin.db.Data
import justin.db.actors.StorageNodeActorRef
import justin.db.actors.protocol.{StorageNodeFailedWrite, StorageNodeSuccessfulWrite, StorageNodeWriteDataLocal}
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{FlatSpecLike, Matchers}

import scala.concurrent.duration._

class ReplicaRemoteWriterTest extends TestKit(ActorSystem("test-system"))
  with FlatSpecLike
  with Matchers
  with ScalaFutures {

  behavior of "Replica Remote Writer"

  override implicit def patienceConfig: PatienceConfig = PatienceConfig(10.seconds, 50.millis)

  it should "get info back that one of the saving is successful and second one has failed" in {
    // given
    val service = new ReplicaRemoteWriter()(system.dispatcher)
    val data = Data(id = UUID.randomUUID(), value = "exemplary-value")
    val storageSuccessfulActorRef = testActorRef(msgBack = StorageNodeSuccessfulWrite(data.id))
    val storageFailedActorRef     = testActorRef(msgBack = StorageNodeFailedWrite(data.id))
    val storageNodeRefs           = List(storageSuccessfulActorRef, storageFailedActorRef).map(StorageNodeActorRef)

    // when
    val writingResult = service.apply(storageNodeRefs, data)

    // then
    whenReady(writingResult) { _ shouldBe List(StorageNodeSuccessfulWrite(data.id), StorageNodeFailedWrite(data.id)) }
  }

  it should "recover failed behavior of actor" in {
    // given
    val service = new ReplicaRemoteWriter()(system.dispatcher)
    val data = Data(id = UUID.randomUUID(), value = "exemplary-value")
    val storageActorRef = testActorRef(new Exception)
    val storageNodeRefs = List(StorageNodeActorRef(storageActorRef))

    // when
    val writingResult = service.apply(storageNodeRefs, data)

    // then
    whenReady(writingResult) { _ shouldBe List(StorageNodeFailedWrite(data.id)) }
  }

  private def testActorRef(msgBack: => Any) = {
    TestActorRef(new Actor {
      override def receive: Receive = {
        case StorageNodeWriteDataLocal(id) => sender() ! msgBack
      }
    })
  }
} 
Example 45
Source File: BenchBase.scala    From changestream   with MIT License 5 votes vote down vote up
package changestream.helpers

import akka.actor.{ActorRefFactory, ActorSystem, Props}
import akka.testkit.{TestActorRef, TestProbe}
import com.github.mauricio.async.db.Configuration
import com.github.mauricio.async.db.mysql.MySQLConnection
import com.typesafe.config.ConfigFactory
import org.scalameter.api._
import org.scalameter.picklers.Implicits._

import scala.concurrent.duration._
import scala.language.postfixOps
import scala.concurrent.Await

class BenchBase extends Bench[Double] {
  lazy val executor = LocalExecutor(
    new Executor.Warmer.Default,
    Aggregator.min[Double],
    measurer)
  lazy val measurer = new Measurer.Default
  lazy val reporter = new LoggingReporter[Double]
  lazy val persistor = Persistor.None

  implicit val system = ActorSystem("changestream", ConfigFactory.load("test.conf"))
  implicit val ec = system.dispatcher
  val probe = TestProbe()
  val maker = (_: ActorRefFactory) => probe.ref

  val testConfig = ConfigFactory.load("test.conf")

  def getProbedActorOf[K](klass: Predef.Class[K], configPath: String = "changestream") =
    TestActorRef(Props(klass, maker, testConfig.getConfig(configPath)))

  protected val config = testConfig.getConfig("changestream.mysql")
  protected val mysqlConfig = new Configuration(
    config.getString("user"),
    config.getString("host"),
    config.getInt("port"),
    Some(config.getString("password"))
  )

  protected val connectionTimeout = config.getLong("timeout")
  protected val connection = new MySQLConnection(mysqlConfig)
  Await.result(connection.connect, connectionTimeout milliseconds)
  val result = connection.sendQuery("drop database if exists changestream_test")
    .flatMap(_ => connection.sendQuery("create database changestream_test"))
    .flatMap(_ => connection.sendQuery(s"""
                                          | CREATE TABLE changestream_test.users (
                                          |   `id` int(11) NOT NULL AUTO_INCREMENT,
                                          |   `username` varchar(32) DEFAULT NULL,
                                          |   `password` varchar(32) DEFAULT NULL,
                                          |   `login_count` int(11) NOT NULL DEFAULT '0',
                                          |   `bio` text DEFAULT NULL,
                                          |   PRIMARY KEY (`id`)
                                          | ) ENGINE=InnoDB
        """.stripMargin))
  Await.result(result, (connectionTimeout * 3) milliseconds)
} 
Example 46
Source File: ProducerStreamManagerSpec.scala    From reactive-kafka-microservice-template   with Apache License 2.0 5 votes vote down vote up
package akka.kafka

import akka.actor.ActorSystem
import akka.stream.scaladsl.SourceQueueWithComplete
import akka.testkit.{DefaultTimeout, ImplicitSender, TestActorRef, TestKit, TestProbe}
import com.omearac.producers.ProducerStreamManager
import com.omearac.producers.ProducerStreamManager.InitializeProducerStream
import com.omearac.shared.AkkaStreams
import com.omearac.shared.EventMessages.ActivatedProducerStream
import com.omearac.shared.KafkaMessages.{ExampleAppEvent, KafkaMessage}
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}


class ProducerStreamManagerSpec extends TestKit(ActorSystem("ProducerStreamManagerSpec"))
  with DefaultTimeout with ImplicitSender
  with WordSpecLike with Matchers with BeforeAndAfterAll
  with AkkaStreams {

  val testProducerStreamManager = TestActorRef(new ProducerStreamManager)
  val producerStreamManagerActor = testProducerStreamManager.underlyingActor

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

  override def afterAll: Unit = {
    shutdown()
  }


  "Sending InitializeProducerStream(self, KafkaMessage) to ProducerStreamManager" should {
    "initialize the stream for that particular message type, return ActivatedProducerStream(streaRef, \"TempChannel1\") and produce local event " in {
      testProducerStreamManager ! InitializeProducerStream(self, KafkaMessage)
      Thread.sleep(500)
      var streamRef: SourceQueueWithComplete[Any] = null
      expectMsgPF() {
        case ActivatedProducerStream(sr, kt) => if (kt == "TempChannel1") {
          streamRef = sr; ()
        } else fail()
      }

      Thread.sleep(500)
      val resultMessage = ActivatedProducerStream(streamRef, "TempChannel1")
      testEventListener.expectMsgPF() {
        case ExampleAppEvent(_, _, m) => if (m == resultMessage.toString) () else fail()
      }
    }
  }

  "Sending InitializeProducerStream(self, ExampleAppEvent) to ProducerStreamManager" should {
    "initialize the stream for that particular message type, return ActivatedProducerStream(streaRef, \"TempChannel2\") and produce local event " in {
      testProducerStreamManager ! InitializeProducerStream(self, ExampleAppEvent)
      Thread.sleep(500)
      var streamRef: SourceQueueWithComplete[Any] = null
      expectMsgPF() {
        case ActivatedProducerStream(sr, kt) => if (kt == "TempChannel2") {
          streamRef = sr; ()
        } else fail()
      }

      Thread.sleep(500)
      val resultMessage = ActivatedProducerStream(streamRef, "TempChannel2")
      testEventListener.expectMsgPF() {
        case ExampleAppEvent(_, _, m) => if (m == resultMessage.toString) () else fail()
      }
    }
  }
} 
Example 47
Source File: DataConsumerSpec.scala    From reactive-kafka-microservice-template   with Apache License 2.0 5 votes vote down vote up
package akka.kafka

import akka.actor.{Actor, ActorSystem, Props}
import akka.testkit.{DefaultTimeout, ImplicitSender, TestActorRef, TestKit}
import com.omearac.consumers.ConsumerStreamManager.{InitializeConsumerStream, TerminateConsumerStream}
import com.omearac.consumers.DataConsumer
import com.omearac.consumers.DataConsumer.{ConsumerActorReply, ManuallyInitializeStream, ManuallyTerminateStream}
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

import scala.collection.mutable.ArrayBuffer


class DataConsumerSpec extends TestKit(ActorSystem("DataConsumerSpec"))
  with DefaultTimeout with ImplicitSender
  with WordSpecLike with Matchers with BeforeAndAfterAll {

  //Creating the Actors
  val testConsumer = TestActorRef(new DataConsumer)
  val mockStreamAndManager = system.actorOf(Props(new MockStreamAndManager), "mockStreamAndManager")

  override def afterAll: Unit = {
    shutdown()
  }

  class MockStreamAndManager extends Actor {
    val receive: Receive = {
      case InitializeConsumerStream(_, _) => testConsumer ! "STREAM_INIT"
      case TerminateConsumerStream(_) => testConsumer ! "STREAM_DONE"
    }
  }


  "Sending ManuallyTerminateStream to DataConsumer in receive state" should {
    "return a Stream Already Stopped reply " in {
      testConsumer ! ManuallyTerminateStream
      expectMsg(ConsumerActorReply("Data Consumer Stream Already Stopped"))
    }
  }

  "Sending ManuallyInitializeStream to DataConsumer in receive state" should {
    "forward the message to the ConsumerStreamManager and change state to consuming" in {
      testConsumer.underlyingActor.consumerStreamManager = mockStreamAndManager
      testConsumer ! ManuallyInitializeStream
      expectMsg(ConsumerActorReply("Data Consumer Stream Started"))
      //Now check for state change
      Thread.sleep(750)
      testConsumer ! ManuallyInitializeStream
      expectMsg(ConsumerActorReply("Data Consumer Already Started"))
    }
  }

  "Sending STREAM_DONE to DataConsumer while in consuming state" should {
    "change state to idle state" in {
      val consuming = testConsumer.underlyingActor.consumingData
      testConsumer.underlyingActor.context.become(consuming)
      testConsumer ! "STREAM_DONE"
      //Now check for state change
      Thread.sleep(750)
      testConsumer ! ManuallyTerminateStream
      expectMsg(ConsumerActorReply("Data Consumer Stream Already Stopped"))
    }
  }
  "Sending ManuallyTerminateStream to DataConsumer while in consuming state" should {
    "forward the message to the ConsumerStreamManager and then upon reply, change state to idle" in {
      val consuming = testConsumer.underlyingActor.consumingData
      testConsumer.underlyingActor.context.become(consuming)
      testConsumer ! ManuallyTerminateStream
      expectMsg(ConsumerActorReply("Data Consumer Stream Stopped"))
      //Now check for state change
      Thread.sleep(750)
      testConsumer ! ManuallyTerminateStream
      expectMsg(ConsumerActorReply("Data Consumer Stream Already Stopped"))
    }
  }

  "Sending ConsumerMessageBatch message" should {
    "reply OK" in {
      val msgBatch: ArrayBuffer[String] = ArrayBuffer("test1")
      val consuming = testConsumer.underlyingActor.consumingData
      testConsumer.underlyingActor.context.become(consuming)
      testConsumer.underlyingActor.consumerStreamManager = mockStreamAndManager
      testConsumer ! msgBatch
      expectMsg("OK")
    }
  }
} 
Example 48
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 49
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 50
Source File: EventConsumerSpec.scala    From reactive-kafka-microservice-template   with Apache License 2.0 5 votes vote down vote up
package akka.kafka

import akka.actor.{Actor, ActorSystem, Props}
import akka.testkit.{DefaultTimeout, ImplicitSender, TestActorRef, TestKit}
import com.omearac.consumers.ConsumerStreamManager.{InitializeConsumerStream, TerminateConsumerStream}
import com.omearac.consumers.DataConsumer.{ConsumerActorReply, ManuallyInitializeStream, ManuallyTerminateStream}
import com.omearac.consumers.EventConsumer
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

import scala.collection.mutable.ArrayBuffer


class EventConsumerSpec extends TestKit(ActorSystem("EventConsumerSpec"))
  with DefaultTimeout with ImplicitSender
  with WordSpecLike with Matchers with BeforeAndAfterAll {

  //Creating the Actors
  val testConsumer = TestActorRef(new EventConsumer)
  val mockStreamAndManager = system.actorOf(Props(new MockStreamAndManager), "mockStreamAndManager")

  override def afterAll: Unit = {
    shutdown()
  }

  class MockStreamAndManager extends Actor {
    val receive: Receive = {
      case InitializeConsumerStream(_, _) => testConsumer ! "STREAM_INIT"
      case TerminateConsumerStream(_) => testConsumer ! "STREAM_DONE"
    }
  }


  "Sending ManuallyTerminateStream to EventConsumer in receive state" should {
    "return a Stream Already Stopped reply " in {
      testConsumer ! ManuallyTerminateStream
      expectMsg(ConsumerActorReply("Event Consumer Stream Already Stopped"))
    }
  }

  "Sending ManuallyInitializeStream to EventConsumer in receive state" should {
    "forward the message to the ConsumerStreamManager and change state to consuming" in {
      testConsumer.underlyingActor.consumerStreamManager = mockStreamAndManager
      testConsumer ! ManuallyInitializeStream
      expectMsg(ConsumerActorReply("Event Consumer Stream Started"))
      //Now check for state change
      Thread.sleep(750)
      testConsumer ! ManuallyInitializeStream
      expectMsg(ConsumerActorReply("Event Consumer Already Started"))
    }
  }

  "Sending STREAM_DONE to EventConsumer while in consuming state" should {
    "change state to idle state" in {
      val consuming = testConsumer.underlyingActor.consumingEvents
      testConsumer.underlyingActor.context.become(consuming)
      testConsumer ! "STREAM_DONE"
      //Now check for state change
      Thread.sleep(750)
      testConsumer ! ManuallyTerminateStream
      expectMsg(ConsumerActorReply("Event Consumer Stream Already Stopped"))
    }
  }
  "Sending ManuallyTerminateStream to EventConsumer while in consuming state" should {
    "forward the message to the ConsumerStreamManager and then upon reply, change state to idle" in {
      val consuming = testConsumer.underlyingActor.consumingEvents
      testConsumer.underlyingActor.context.become(consuming)
      testConsumer ! ManuallyTerminateStream
      expectMsg(ConsumerActorReply("Event Consumer Stream Stopped"))
      //Now check for state change
      Thread.sleep(750)
      testConsumer ! ManuallyTerminateStream
      expectMsg(ConsumerActorReply("Event Consumer Stream Already Stopped"))
    }
  }

  "Sending ConsumerMessageBatch message" should {
    "reply OK" in {
      val msgBatch: ArrayBuffer[String] = ArrayBuffer("test1")
      val consuming = testConsumer.underlyingActor.consumingEvents
      testConsumer.underlyingActor.context.become(consuming)
      testConsumer.underlyingActor.consumerStreamManager = mockStreamAndManager
      testConsumer ! msgBatch
      expectMsg("OK")
    }
  }
} 
Example 51
Source File: HTTPInterfaceSpec.scala    From reactive-kafka-microservice-template   with Apache License 2.0 5 votes vote down vote up
package akka

import akka.event.Logging
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.stream.QueueOfferResult
import akka.stream.QueueOfferResult.Enqueued
import akka.stream.scaladsl.SourceQueueWithComplete
import akka.testkit.{TestActorRef, TestProbe}
import com.omearac.consumers.{DataConsumer, EventConsumer}
import com.omearac.http.routes.{ConsumerCommands, ProducerCommands}
import com.omearac.producers.DataProducer
import org.scalatest.{Matchers, WordSpec}

import scala.concurrent.Future


class HTTPInterfaceSpec extends WordSpec
    with Matchers with ScalatestRouteTest
    with ConsumerCommands with ProducerCommands {

    val log = Logging(system, this.getClass.getName)

    //Mocks for DataConsumer Tests
    val dataConsumer = TestActorRef(new DataConsumer)
    val manager = TestProbe()
    dataConsumer.underlyingActor.consumerStreamManager = manager.ref

    //Mocks for EventConsumer Tests
    val eventConsumer = TestActorRef(new EventConsumer)
    eventConsumer.underlyingActor.consumerStreamManager = manager.ref

    //Mocks for DataProducer Tests
    val dataProducer = TestActorRef(new DataProducer)
    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}
    }


    "The HTTP interface to control the DataConsumerStream" should {
        "return a Already Stopped message for GET requests to /data_consumer/stop" in {
            Get("/data_consumer/stop") ~> dataConsumerHttpCommands ~> check {
                responseAs[String] shouldEqual "Data Consumer Stream Already Stopped"
            }
        }

        "return a Stream Started response for GET requests to /data_consumer/start" in {
            Get("/data_consumer/start") ~> dataConsumerHttpCommands ~> check {
                responseAs[String] shouldEqual "Data Consumer Stream Started"
            }
        }
    }

    "The HTTP interface to control the EventConsumerStream" should {
        "return a Already Stopped message for GET requests to /event_consumer/stop" in {
            Get("/event_consumer/stop") ~> eventConsumerHttpCommands ~> check {
                responseAs[String] shouldEqual "Event Consumer Stream Already Stopped"
            }
        }

        "return a Stream Started response for GET requests to /data_consumer/start" in {
            Get("/event_consumer/start") ~> eventConsumerHttpCommands ~> check {
                responseAs[String] shouldEqual "Event Consumer Stream Started"
            }
        }
    }

    "The HTTP interface to tell the DataProducer Actor to publish messages to Kafka" should {
        "return a Messages Produced message for GET requests to /data_producer/produce/10" in {
            dataProducer.underlyingActor.producerStream = mockProducerStream
            val producing = dataProducer.underlyingActor.publishData
            dataProducer.underlyingActor.context.become(producing)

            Get("/data_producer/produce/10") ~> producerHttpCommands ~> check {
                responseAs[String] shouldEqual "10 messages Produced as Ordered, Boss!"
            }
        }
    }
} 
Example 52
Source File: LeaderFollowerActorSpec.scala    From reactive-consul   with MIT License 5 votes vote down vote up
package stormlantern.consul.client.election

import java.util
import java.util.UUID

import akka.actor.ActorSystem
import akka.testkit.{ TestActorRef, ImplicitSender, TestKit }
import org.scalamock.scalatest.MockFactory
import org.scalatest.{ BeforeAndAfterAll, Matchers, FlatSpecLike }
import stormlantern.consul.client.dao.{ BinaryData, KeyData, AcquireSession, ConsulHttpClient }
import stormlantern.consul.client.election.LeaderFollowerActor.Participate

import scala.concurrent.Future

class LeaderFollowerActorSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender with FlatSpecLike
    with Matchers with BeforeAndAfterAll with MockFactory {

  def this() = this(ActorSystem("LeaderFollowerActorSpec"))

  override def afterAll() {
    TestKit.shutdownActorSystem(system)
  }

  trait TestScope {
    val sessionId: UUID = UUID.fromString("9A3BB9C-E2E7-43DF-BFD5-845417146552")
    val key = "path/to/our/key"
    val host = "myhost.mynetwork.net"
    val port = 1337
    val consulHttpClient: ConsulHttpClient = mock[ConsulHttpClient]
    val leaderInfoBytes: Array[Byte] = s"""{"host":"$host","port":$port}""".getBytes("UTF-8")
  }

  "The LeaderFollowerActor" should "participate in an election, win, watch for changes and participate again when session is lost" in new TestScope {
    val sut = TestActorRef(LeaderFollowerActor.props(consulHttpClient, sessionId, key, host, port))
    (consulHttpClient.putKeyValuePair _).expects(where { (k, lib, op) ⇒
      k == key && util.Arrays.equals(lib, leaderInfoBytes) && op.contains(AcquireSession(sessionId))
    }).returns(Future.successful(true))
    (consulHttpClient.getKeyValuePair _).expects(key, Some(0L), Some("1s"), false, false).returns {
      Future.successful(Seq(KeyData(key, 1, 1, 1, 0, BinaryData(leaderInfoBytes), Some(sessionId))))
    }
    (consulHttpClient.getKeyValuePair _).expects(key, Some(1L), Some("1s"), false, false).returns {
      Future.successful(Seq(KeyData(key, 1, 2, 1, 0, BinaryData(leaderInfoBytes), None)))
    }
    (consulHttpClient.putKeyValuePair _).expects(where { (k, lib, op) ⇒
      k == key && util.Arrays.equals(lib, leaderInfoBytes) && op.contains(AcquireSession(sessionId))
    }).onCall { p ⇒
      sut.stop()
      Future.successful(false)
    }
    sut ! Participate
  }

  it should "participate in an election, lose, watch for changes and participate again when session is lost" in new TestScope {
    val otherSessionId: UUID = UUID.fromString("9A3BB9C-E2E7-43DF-BFD5-845417146553")
    val sut = TestActorRef(LeaderFollowerActor.props(consulHttpClient, sessionId, key, host, port))
    (consulHttpClient.putKeyValuePair _).expects(where { (k, lib, op) ⇒
      k == key && util.Arrays.equals(lib, leaderInfoBytes) && op.contains(AcquireSession(sessionId))
    }).returns(Future.successful(false))
    (consulHttpClient.getKeyValuePair _).expects(key, Some(0L), Some("1s"), false, false).returns {
      Future.successful(Seq(KeyData(key, 1, 1, 1, 0, BinaryData(leaderInfoBytes), Some(otherSessionId))))
    }
    (consulHttpClient.getKeyValuePair _).expects(key, Some(1L), Some("1s"), false, false).returns {
      Future.successful(Seq(KeyData(key, 1, 2, 1, 0, BinaryData(leaderInfoBytes), None)))
    }
    (consulHttpClient.putKeyValuePair _).expects(where { (k, lib, op) ⇒
      k == key && util.Arrays.equals(lib, leaderInfoBytes) && op.contains(AcquireSession(sessionId))
    }).onCall { p ⇒
      sut.stop()
      Future.successful(true)
    }
    sut ! Participate
  }
} 
Example 53
Source File: ServiceAvailabilityActorSpec.scala    From reactive-consul   with MIT License 5 votes vote down vote up
package stormlantern.consul.client.discovery

import akka.actor.ActorSystem
import akka.testkit.{ ImplicitSender, TestActorRef, TestKit }
import org.scalamock.scalatest.MockFactory
import org.scalatest.{ BeforeAndAfterAll, FlatSpecLike, Matchers }
import stormlantern.consul.client.dao.{ ConsulHttpClient, IndexedServiceInstances }
import stormlantern.consul.client.discovery.ServiceAvailabilityActor.Start
import stormlantern.consul.client.helpers.ModelHelpers
import stormlantern.consul.client.util.Logging

import scala.concurrent.Future
import scala.concurrent.duration._

class ServiceAvailabilityActorSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender with FlatSpecLike
    with Matchers with BeforeAndAfterAll with MockFactory with Logging {

  def this() = this(ActorSystem("ServiceAvailabilityActorSpec"))

  override def afterAll() {
    TestKit.shutdownActorSystem(system)
  }

  "The ServiceAvailabilityActor" should "receive one service update when there are no changes" in {
    val httpClient: ConsulHttpClient = mock[ConsulHttpClient]
    val sut = TestActorRef(ServiceAvailabilityActor.props(httpClient, ServiceDefinition("bogus123", "bogus"), self))
    (httpClient.getService _).expects("bogus", None, Some(0L), Some("1s"), None).returns(Future.successful(IndexedServiceInstances(1, Set.empty)))
    (httpClient.getService _).expects("bogus", None, Some(1L), Some("1s"), None).onCall { p ⇒
      sut.stop()
      Future.successful(IndexedServiceInstances(1, Set.empty))
    }
    sut ! Start
    expectMsg(1.second, ServiceAvailabilityActor.ServiceAvailabilityUpdate("bogus123"))
    expectMsg(1.second, ServiceAvailabilityActor.Started)
    expectNoMsg(1.second)
  }

  it should "receive two service updates when there is a change" in {
    val httpClient: ConsulHttpClient = mock[ConsulHttpClient]
    lazy val sut = TestActorRef(ServiceAvailabilityActor.props(httpClient, ServiceDefinition("bogus123", "bogus"), self))
    val service = ModelHelpers.createService("bogus123", "bogus")
    (httpClient.getService _).expects("bogus", None, Some(0L), Some("1s"), None).returns(Future.successful(IndexedServiceInstances(1, Set.empty)))
    (httpClient.getService _).expects("bogus", None, Some(1L), Some("1s"), None).returns(Future.successful(IndexedServiceInstances(2, Set(service))))
    (httpClient.getService _).expects("bogus", None, Some(2L), Some("1s"), None).onCall { p ⇒
      sut.stop()
      Future.successful(IndexedServiceInstances(2, Set(service)))
    }
    sut ! Start
    expectMsg(1.second, ServiceAvailabilityActor.ServiceAvailabilityUpdate("bogus123"))
    expectMsg(1.second, ServiceAvailabilityActor.Started)
    expectMsg(1.second, ServiceAvailabilityActor.ServiceAvailabilityUpdate("bogus123", Set(service), Set.empty))
    expectNoMsg(1.second)
  }

  it should "receive one service update when there are two with different tags" in {
    val httpClient: ConsulHttpClient = mock[ConsulHttpClient]
    lazy val sut = TestActorRef(ServiceAvailabilityActor.props(httpClient, ServiceDefinition("bogus123", "bogus", Set("one", "two")), self))
    val nonMatchingservice = ModelHelpers.createService("bogus123", "bogus", tags = Set("one"))
    val matchingService = nonMatchingservice.copy(serviceTags = Set("one", "two"))
    (httpClient.getService _).expects("bogus", Some("one"), Some(0L), Some("1s"), None).returns(Future.successful(IndexedServiceInstances(1, Set.empty)))
    (httpClient.getService _).expects("bogus", Some("one"), Some(1L), Some("1s"), None).returns(Future.successful(IndexedServiceInstances(2, Set(nonMatchingservice, matchingService))))
    (httpClient.getService _).expects("bogus", Some("one"), Some(2L), Some("1s"), None).onCall { p ⇒
      sut.stop()
      Future.successful(IndexedServiceInstances(2, Set(nonMatchingservice, matchingService)))
    }
    sut ! Start
    expectMsg(1.second, ServiceAvailabilityActor.ServiceAvailabilityUpdate("bogus123"))
    expectMsg(1.second, ServiceAvailabilityActor.Started)
    expectMsg(1.second, ServiceAvailabilityActor.ServiceAvailabilityUpdate("bogus123", Set(matchingService), Set.empty))
    expectNoMsg(1.second)
  }
} 
Example 54
Source File: ReplicaRemoteReaderTest.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.replica.read

import java.util.UUID

import akka.actor.{Actor, ActorSystem}
import akka.testkit.{TestActorRef, TestKit}
import justin.db.Data
import justin.db.actors.StorageNodeActorRef
import justin.db.actors.protocol._
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{FlatSpecLike, Matchers}

import scala.concurrent.duration._

class ReplicaRemoteReaderTest extends TestKit(ActorSystem("test-system"))
  with FlatSpecLike
  with Matchers
  with ScalaFutures {

  behavior of "Replica Remote Reader"

  override implicit def patienceConfig: PatienceConfig = PatienceConfig(10.seconds, 50.millis)

  it should "get info back that one of the value could be found and second one is obsolete" in {
    // given
    val service = new ReplicaRemoteReader()(system.dispatcher)
    val id = UUID.randomUUID()
    val foundData = Data(id, "value")
    val notFoundId = UUID.randomUUID()
    val storageNotFoundActorRef = testActorRef(msgBack = StorageNodeNotFoundRead(notFoundId))
    val storageFoundActorRef    = testActorRef(msgBack = StorageNodeFoundRead(foundData))
    val storageNodeRefs         = List(storageNotFoundActorRef, storageFoundActorRef).map(StorageNodeActorRef)

    // when
    val readingResult = service.apply(storageNodeRefs, id)

    // then
    whenReady(readingResult) { _ shouldBe List(StorageNodeNotFoundRead(notFoundId), StorageNodeFoundRead(foundData)) }
  }

  it should "recover failed behavior of actor" in {
    // given
    val service = new ReplicaRemoteReader()(system.dispatcher)
    val id = UUID.randomUUID()
    val storageActorRef = testActorRef(new Exception)
    val storageNodeRefs = List(StorageNodeActorRef(storageActorRef))

    // when
    val readingResult = service.apply(storageNodeRefs, id)

    // then
    whenReady(readingResult) { _ shouldBe List(StorageNodeFailedRead(id)) }
  }

  private def testActorRef(msgBack: => Any) = {
    TestActorRef(new Actor {
      override def receive: Receive = {
        case StorageNodeLocalRead(id) => sender() ! msgBack
      }
    })
  }
} 
Example 55
Source File: StdoutActorSpec.scala    From changestream   with MIT License 5 votes vote down vote up
package changestream.actors

import akka.actor.{ActorRefFactory, Props}
import akka.testkit.{TestActorRef, TestProbe}
import changestream.actors.PositionSaver.EmitterResult
import changestream.helpers.{Config, Emitter}

import scala.concurrent.duration._
import scala.language.postfixOps

class StdoutActorSpec extends Emitter with Config {
  val probe = TestProbe()
  val maker = (_: ActorRefFactory) => probe.ref
  val actorRef = TestActorRef(Props(classOf[StdoutActor], maker, awsConfig))

  "When StdoutActor receives a single valid message" should {
    "Print to stdout and forward result" in {
      actorRef ! message

      val result = probe.expectMsgType[EmitterResult](5000 milliseconds)
      result.position should be(message.nextPosition)
    }
  }
} 
Example 56
Source File: StorageNodeActorTest.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.actors

import akka.actor.ActorSystem
import akka.testkit.{ImplicitSender, TestActorRef, TestKit}
import com.typesafe.config.ConfigFactory
import justin.db.actors.protocol.RegisterNode
import justin.db.cluster.datacenter.Datacenter
import justin.db.consistenthashing.{NodeId, Ring}
import justin.db.replica.N
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{BeforeAndAfterAll, FlatSpecLike, Matchers}

class StorageNodeActorTest extends TestKit(StorageNodeActorTest.actorSystem)
  with FlatSpecLike
  with ImplicitSender
  with Matchers
  with ScalaFutures
  with BeforeAndAfterAll {

  behavior of "Storage Node Actor"

  it should "send msg back with targeted NodeId when registration of other node has correctly happened" in {
    // given
    val nodeId = NodeId(1)
    val testActor = TestActorRef(new TestActor(nodeId, Ring.apply(3, 1)))

    // when
    testActor ! RegisterNode(NodeId(2))

    // then
    expectMsg(RegisterNode(nodeId))
  }

  it should "has defined role \"storagenode\"" in {
    StorageNodeActor.role shouldBe "storagenode"
  }

  it should "compose its name based on datacenter it belongs to and given id" in {
    StorageNodeActor.name(NodeId(0), Datacenter("dc1"))   shouldBe "dc1-id-0"
    StorageNodeActor.name(NodeId(10), Datacenter("dc2"))  shouldBe "dc2-id-10"
    StorageNodeActor.name(NodeId(20), Datacenter("dc1"))  shouldBe "dc1-id-20"
    StorageNodeActor.name(NodeId(999), Datacenter("dc1")) shouldBe "dc1-id-999"
  }

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

  class TestActor(nodeId: NodeId, ring: Ring) extends StorageNodeActor(nodeId, Datacenter("default"), null, ring, N(1))
}

object StorageNodeActorTest {
  def actorSystem: ActorSystem = {
    val config = ConfigFactory.parseString(
      """
        |akka.loglevel = off
        |akka.actor.provider = cluster
        |akka.cluster.auto-join = off
        |akka.cluster.metrics.enabled = off
      """.stripMargin).withFallback(ConfigFactory.load())

    ActorSystem("test-system", config)
  }
} 
Example 57
Source File: ActorConfigSupportSpec.scala    From hydra   with Apache License 2.0 5 votes vote down vote up
package hydra.common.config

import akka.actor.ActorSystem
import akka.testkit.{TestActorRef, TestKit}
import hydra.common.testing.DummyActor
import org.scalatest.matchers.should.Matchers
import org.scalatest.funspec.AnyFunSpecLike
import org.scalatest.BeforeAndAfterAll


class ActorConfigSupportSpec
    extends TestKit(ActorSystem("test"))
    with Matchers
    with AnyFunSpecLike
    with BeforeAndAfterAll
    with ConfigSupport {

  val dummy = TestActorRef[DummyActor]

  override def afterAll = TestKit.shutdownActorSystem(system)

  describe("When mixing the trait in an actor") {
    it("has the correct actor name") {
      dummy.underlyingActor.thisActorName shouldBe "dummy_actor"
    }

    it("has the correct actor config") {
      dummy.underlyingActor.actorConfig shouldBe rootConfig.getConfig(
        "hydraTest.actors.dummy_actor"
      )
    }

  }
} 
Example 58
Source File: LoggingAdapterSpec.scala    From hydra   with Apache License 2.0 5 votes vote down vote up
package hydra.common.logging

import akka.actor.{Actor, ActorSystem}
import akka.testkit.{TestActorRef, TestKit, TestProbe}
import org.scalatest.matchers.should.Matchers
import org.scalatest.funspec.AnyFunSpecLike
import org.scalatest.BeforeAndAfterAll


class LoggingAdapterSpec
    extends TestKit(ActorSystem("test"))
    with Matchers
    with AnyFunSpecLike
    with BeforeAndAfterAll {

  override def afterAll = TestKit.shutdownActorSystem(system)

  describe("The logging adapter") {

    it("allows an actor to use the logger") {

      val act = TestActorRef(new Actor with ActorLoggingAdapter {
        override def receive = {
          case _ => log.info("got it"); sender ! "got it"
        }
      }, "logger-test")

      act.underlyingActor.log.getName shouldBe "akka.testkit.TestActorRef"

      // Send a message and make sure we get a response back
      val probe = TestProbe()
      probe.send(act, "test")
      probe.expectMsgType[String] shouldBe "got it"
    }
  }
} 
Example 59
Source File: IngestorsEndpointSpec.scala    From hydra   with Apache License 2.0 5 votes vote down vote up
package hydra.ingest.http

import akka.actor.Actor
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.testkit.{TestActorRef, TestKit, TestProbe}
import hydra.common.util.ActorUtils
import hydra.ingest.IngestorInfo
import hydra.ingest.services.IngestorRegistry.{FindAll, FindByName, LookupResult}
import org.joda.time.DateTime
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

import scala.concurrent.duration._


class IngestorsEndpointSpec
    extends Matchers
    with AnyWordSpecLike
    with ScalatestRouteTest
    with HydraIngestJsonSupport {

  val ingestorsRoute = new IngestorRegistryEndpoint().route

  override def afterAll = {
    super.afterAll()
    TestKit.shutdownActorSystem(
      system,
      verifySystemShutdown = true,
      duration = 10 seconds
    )
  }

  val probe = TestProbe()

  val ingestorInfo = IngestorInfo(
    ActorUtils.actorName(probe.ref),
    "test",
    probe.ref.path,
    DateTime.now
  )

  val registry = TestActorRef(
    new Actor {

      override def receive = {
        case FindByName("tester") => sender ! LookupResult(Seq(ingestorInfo))
        case FindAll              => sender ! LookupResult(Seq(ingestorInfo))
      }
    },
    "ingestor_registry"
  ).underlyingActor

  "The ingestors endpoint" should {

    "returns all ingestors" in {
      Get("/ingestors") ~> ingestorsRoute ~> check {
        val r = responseAs[Seq[IngestorInfo]]
        r.size shouldBe 1
        r(0).path shouldBe ingestorInfo.path
        r(0).group shouldBe ingestorInfo.group
        r(0).path shouldBe ingestorInfo.path
        r(0).registeredAt shouldBe ingestorInfo.registeredAt.withMillisOfSecond(
          0
        )
      }
    }
  }
} 
Example 60
Source File: ServiceSpec.scala    From wookiee   with Apache License 2.0 5 votes vote down vote up
package com.webtrends.harness

import akka.actor.ActorSystem
import akka.testkit.{TestActorRef, TestKit, TestProbe}
import com.webtrends.harness.health.{ComponentState, HealthComponent}
import com.webtrends.harness.service.messages._
import com.webtrends.harness.service.meta.ServiceMetaDetails
import org.specs2.mutable.SpecificationLike

case class TestClass(val name: String, val value: Int)


class ServiceSpec extends TestKit(ActorSystem("harness")) with SpecificationLike {

  val act = TestActorRef(new TestService)
  //val httpAct = TestActorRef(new TestHttpService)

  "services " should {

    " be able to be loaded and pinged" in {
      val probe = TestProbe()
      probe.send(act, Ping)
      Pong must beEqualTo(probe.expectMsg(Pong))
    }

    " be able to be loaded and sent a ready message" in {
      val probe = TestProbe()
      probe.send(act, Ready)
      Ready must beEqualTo(probe.expectMsg(Ready))
    }

    " be able to be loaded and checked" in {
      val probe = TestProbe()
      probe.send(act, CheckHealth)
      val comp = HealthComponent("testservice", ComponentState.NORMAL, "test")
      comp.addComponent(HealthComponent("childcomponent", ComponentState.DEGRADED, "test"))

      comp must beEqualTo(probe.expectMsg(comp))
    }

    //todo only HttpService should be able to do this
    
  }

  step {
    TestKit.shutdownActorSystem(system)
  }
} 
Example 61
Source File: MemoryPoolTests.scala    From EncryCore   with GNU General Public License v3.0 5 votes vote down vote up
package encry.view.mempool

import akka.actor.ActorSystem
import akka.testkit.{ TestActorRef, TestProbe }
import com.typesafe.scalalogging.StrictLogging
import encry.modifiers.InstanceFactory
import encry.settings.{ EncryAppSettings, TestNetSettings }
import encry.utils.NetworkTimeProvider
import encry.view.mempool.MemoryPool.{ NewTransaction, TransactionsForMiner }
import org.scalatest.{ BeforeAndAfterAll, Matchers, OneInstancePerTest, WordSpecLike }

import scala.concurrent.duration._

class MemoryPoolTests
    extends WordSpecLike
    with Matchers
    with InstanceFactory
    with BeforeAndAfterAll
    with OneInstancePerTest
    with TestNetSettings
    with StrictLogging {

  implicit val system: ActorSystem = ActorSystem()

  override def afterAll(): Unit = system.terminate()

  val timeProvider: NetworkTimeProvider = new NetworkTimeProvider(testNetSettings.ntp)

  "MemoryPool" should {
    "add new unique transactions" in {
      val mempool                = MemoryPoolStorage.empty(testNetSettings, timeProvider)
      val transactions           = genValidPaymentTxs(10)
      val (newMempool, validTxs) = mempool.validateTransactions(transactions)
      newMempool.size shouldBe 10
      validTxs.map(_.encodedId).forall(transactions.map(_.encodedId).contains) shouldBe true
    }
    "reject not unique transactions" in {
      val mempool                          = MemoryPoolStorage.empty(testNetSettings, timeProvider)
      val transactions                     = genValidPaymentTxs(10)
      val (newMempool, validTxs)           = mempool.validateTransactions(transactions)
      val (newMempoolAgain, validTxsAgain) = newMempool.validateTransactions(validTxs)
      newMempoolAgain.size shouldBe 10
      validTxsAgain.size shouldBe 0
    }
    "mempoolMaxCapacity works correct" in {
      val mempool                = MemoryPoolStorage.empty(testNetSettings, timeProvider)
      val transactions           = genValidPaymentTxs(11)
      val (newMempool, validTxs) = mempool.validateTransactions(transactions)
      newMempool.size shouldBe 10
      validTxs.size shouldBe 10
    }
    "getTransactionsForMiner works fine" in {
      val mempool         = MemoryPoolStorage.empty(testNetSettings, timeProvider)
      val transactions    = (0 until 10).map(k => coinbaseAt(k))
      val (newMempool, _) = mempool.validateTransactions(transactions)
      val (uPool, txs)    = newMempool.getTransactionsForMiner
      uPool.size shouldBe 0
      txs.map(_.encodedId).forall(transactions.map(_.encodedId).contains) shouldBe true
      transactions.map(_.encodedId).forall(txs.map(_.encodedId).contains) shouldBe true
    }
  }
  "Mempool actor" should {
    "send transactions to miner" in {
      val miner1 = TestProbe()
      val mempool1: TestActorRef[MemoryPool] =
        TestActorRef[MemoryPool](MemoryPool.props(testNetSettings, timeProvider, miner1.ref, Some(TestProbe().ref)))
      val transactions1 = (0 until 4).map { k =>
        val a = coinbaseAt(k)
        a
      }
      transactions1.foreach(mempool1 ! NewTransaction(_))
      mempool1.underlyingActor.memoryPool.size shouldBe 4
      logger.info(s"generated: ${transactions1.map(_.encodedId)}")
      miner1.expectMsg(20.seconds, TransactionsForMiner(transactions1))
    }
  }
} 
Example 62
Source File: DMUtils.scala    From EncryCore   with GNU General Public License v3.0 5 votes vote down vote up
package encry.network.DeliveryManagerTests

import java.net.InetSocketAddress
import akka.actor.ActorSystem
import akka.testkit.{TestActorRef, TestProbe}
import encry.local.miner.Miner.{DisableMining, StartMining}
import encry.modifiers.InstanceFactory
import encry.network.DeliveryManager
import encry.network.DeliveryManager.FullBlockChainIsSynced
import encry.network.NodeViewSynchronizer.ReceivableMessages.UpdatedHistory
import encry.network.PeerConnectionHandler.{ConnectedPeer, Incoming}
import encry.settings.EncryAppSettings
import encry.view.history.History
import org.encryfoundation.common.modifiers.history.Block
import org.encryfoundation.common.network.BasicMessagesRepo.Handshake
import org.encryfoundation.common.utils.TaggedTypes.ModifierId
import scala.collection.mutable
import scala.collection.mutable.WrappedArray

object DMUtils extends InstanceFactory {

  def initialiseDeliveryManager(isBlockChainSynced: Boolean,
                                isMining: Boolean,
                                settings: EncryAppSettings)
                               (implicit actorSystem: ActorSystem): (TestActorRef[DeliveryManager], History) = {
    val history: History = generateDummyHistory(settings)
    val deliveryManager: TestActorRef[DeliveryManager] =
      TestActorRef[DeliveryManager](DeliveryManager
        .props(None, TestProbe().ref, TestProbe().ref, TestProbe().ref, TestProbe().ref, TestProbe().ref, settings))
    deliveryManager ! UpdatedHistory(history)
    if (isMining) deliveryManager ! StartMining
    else deliveryManager ! DisableMining
    if (isBlockChainSynced) deliveryManager ! FullBlockChainIsSynced
    (deliveryManager, history)
  }

  def generateBlocks(qty: Int, history: History): (History, List[Block]) =
    (0 until qty).foldLeft(history, List.empty[Block]) {
      case ((prevHistory, blocks), _) =>
        val block: Block = generateNextBlock(prevHistory)
        prevHistory.append(block.header)
        prevHistory.append(block.payload)
        val a = prevHistory.reportModifierIsValid(block)
        (a, blocks :+ block)
    }

  def toKey(id: ModifierId): WrappedArray.ofByte = new mutable.WrappedArray.ofByte(id)

  def createPeer(port: Int,
                 host: String,
                 settings: EncryAppSettings)(implicit system: ActorSystem): (InetSocketAddress, ConnectedPeer) = {
    val address = new InetSocketAddress(host, port)
    val peer: ConnectedPeer = ConnectedPeer(address, TestProbe().ref, Incoming,
      Handshake(protocolToBytes(settings.network.appVersion), host, Some(address), System.currentTimeMillis()))
    (address, peer)
  }
} 
Example 63
Source File: BlackListTests.scala    From EncryCore   with GNU General Public License v3.0 5 votes vote down vote up
package encry.network

import java.net.{InetAddress, InetSocketAddress}

import akka.actor.ActorSystem
import akka.testkit.{TestActorRef, TestProbe}
import encry.modifiers.InstanceFactory
import encry.network.BlackList.BanReason._
import encry.network.PeerConnectionHandler.{ConnectedPeer, Outgoing}
import encry.network.PeerConnectionHandler.ReceivableMessages.CloseConnection
import encry.network.PeersKeeper.BanPeer
import encry.settings.TestNetSettings
import org.encryfoundation.common.network.BasicMessagesRepo.Handshake
import org.scalatest.{BeforeAndAfterAll, Matchers, OneInstancePerTest, WordSpecLike}
import scala.concurrent.duration._

class BlackListTests extends WordSpecLike
  with Matchers
  with BeforeAndAfterAll
  with InstanceFactory
  with OneInstancePerTest
  with TestNetSettings {

  implicit val system: ActorSystem = ActorSystem()

  override def afterAll(): Unit = system.terminate()

  val knowPeersSettings = testNetSettings.copy(
    network = settings.network.copy(
      knownPeers = List(new InetSocketAddress("172.16.11.11", 9001)),
      connectOnlyWithKnownPeers = Some(true)
    ),
    blackList = settings.blackList.copy(
      banTime = 2 seconds,
      cleanupTime = 3 seconds
    ))

  
  "Peers keeper" should {
    "handle ban peer message correctly" in {
      val peersKeeper: TestActorRef[PeersKeeper] = TestActorRef[PeersKeeper](PeersKeeper.props(knowPeersSettings, TestProbe().ref, TestProbe().ref))
      val address: InetSocketAddress = new InetSocketAddress("0.0.0.0", 9000)
      val peerHandler: TestProbe = TestProbe()
      val connectedPeer: ConnectedPeer = ConnectedPeer(
        address,
        peerHandler.ref,
        Outgoing,
        Handshake(protocolToBytes(knowPeersSettings.network.appVersion), "test node", Some(address), System.currentTimeMillis())
      )
      peersKeeper ! BanPeer(connectedPeer, SpamSender)
      peerHandler.expectMsg(CloseConnection)
      peersKeeper.underlyingActor.blackList.contains(address.getAddress) shouldBe true
    }
    "cleanup black list by scheduler correctly" in {
      val peersKeeper: TestActorRef[PeersKeeper] = TestActorRef[PeersKeeper](PeersKeeper.props(knowPeersSettings, TestProbe().ref, TestProbe().ref))
      val address: InetSocketAddress = new InetSocketAddress("0.0.0.0", 9000)
      val peerHandler: TestProbe = TestProbe()
      val connectedPeer: ConnectedPeer = ConnectedPeer(
        address,
        peerHandler.ref,
        Outgoing,
        Handshake(protocolToBytes(knowPeersSettings.network.appVersion), "test node", Some(address), System.currentTimeMillis())
      )
      peersKeeper ! BanPeer(connectedPeer, SentPeersMessageWithoutRequest)
      Thread.sleep(6000)
      peersKeeper.underlyingActor.blackList.contains(address.getAddress) shouldBe false
    }
    "don't remove peer from black list before ban time expired" in {
      val peersKeeper: TestActorRef[PeersKeeper] = TestActorRef[PeersKeeper](PeersKeeper.props(knowPeersSettings, TestProbe().ref, TestProbe().ref))
      val address: InetSocketAddress = new InetSocketAddress("0.0.0.0", 9000)
      val peerHandler: TestProbe = TestProbe()
      val connectedPeer: ConnectedPeer = ConnectedPeer(
        address,
        peerHandler.ref,
        Outgoing,
        Handshake(protocolToBytes(knowPeersSettings.network.appVersion), "test node", Some(address), System.currentTimeMillis())
      )
      Thread.sleep(4000)
      peersKeeper ! BanPeer(connectedPeer, CorruptedSerializedBytes)
      Thread.sleep(2000)
      peersKeeper.underlyingActor.blackList.contains(address.getAddress) shouldBe true
    }
  }
} 
Example 64
Source File: AkkaQuickstartSpec.scala    From didactic-computing-machine   with GNU Affero General Public License v3.0 5 votes vote down vote up
//#full-example
package com.lightbend.akka.sample

import org.scalatest.{ BeforeAndAfterAll, FlatSpecLike, Matchers }
import akka.actor.{ Actor, Props, ActorSystem }
import akka.testkit.{ ImplicitSender, TestKit, TestActorRef, TestProbe }
import scala.concurrent.duration._
import Greeter._
import Printer._

//#test-classes
class AkkaQuickstartSpec(_system: ActorSystem)
  extends TestKit(_system)
  with Matchers
  with FlatSpecLike
  with BeforeAndAfterAll {
  //#test-classes

  def this() = this(ActorSystem("AkkaQuickstartSpec"))

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

  //#first-test
  //#specification-example
  "A Greeter Actor" should "pass on a greeting message when instructed to" in {
    //#specification-example
    val testProbe = TestProbe()
    val helloGreetingMessage = "hello"
    val helloGreeter = system.actorOf(Greeter.props(helloGreetingMessage, testProbe.ref))
    val greetPerson = "Akka"
    helloGreeter ! WhoToGreet(greetPerson)
    helloGreeter ! Greet
    testProbe.expectMsg(500 millis, Greeting(s"$helloGreetingMessage, $greetPerson"))
  }
  //#first-test
}
//#full-example 
Example 65
Source File: DistServiceAppMasterSpec.scala    From incubator-retired-gearpump   with Apache License 2.0 5 votes vote down vote up
package org.apache.gearpump.experiments.distributeservice

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

import akka.actor.ActorSystem
import akka.testkit.{TestActorRef, TestProbe}
import org.scalatest.{BeforeAndAfter, Matchers, WordSpec}

import org.apache.gearpump.cluster.AppMasterToMaster.{GetAllWorkers, RegisterAppMaster, RequestResource}
import org.apache.gearpump.cluster.AppMasterToWorker.LaunchExecutor
import org.apache.gearpump.cluster.MasterToAppMaster.{AppMasterRegistered, ResourceAllocated, WorkerList}
import org.apache.gearpump.cluster.appmaster.AppMasterRuntimeEnvironment
import org.apache.gearpump.cluster.scheduler.{Relaxation, Resource, ResourceAllocation, ResourceRequest}
import org.apache.gearpump.cluster.worker.WorkerId
import org.apache.gearpump.cluster.{AppDescription, AppMasterContext, TestUtil, UserConfig}
import org.apache.gearpump.experiments.distributeservice.DistServiceAppMaster.{FileContainer, GetFileContainer}
import org.apache.gearpump.util.ActorSystemBooter.RegisterActorSystem
import org.apache.gearpump.util.ActorUtil

class DistServiceAppMasterSpec extends WordSpec with Matchers with BeforeAndAfter {
  implicit val system = ActorSystem("AppMasterSpec", TestUtil.DEFAULT_CONFIG)
  val mockMaster = TestProbe()(system)
  val mockWorker1 = TestProbe()(system)
  val client = TestProbe()(system)
  val masterProxy = mockMaster.ref
  val appId = 0
  val userName = "test"
  val masterExecutorId = 0
  val workerList = List(WorkerId(1, 0L), WorkerId(2, 0L), WorkerId(3, 0L))
  val resource = Resource(1)
  val appJar = None
  val appDescription = AppDescription("app0", classOf[DistServiceAppMaster].getName,
    UserConfig.empty)

  "DistService AppMaster" should {
    "responsable for service distributing" in {
      val appMasterContext = AppMasterContext(appId, userName, resource, null, appJar, masterProxy)
      TestActorRef[DistServiceAppMaster](
        AppMasterRuntimeEnvironment.props(List(masterProxy.path), appDescription,
          appMasterContext))
      val registerAppMaster = mockMaster.receiveOne(15.seconds)
      assert(registerAppMaster.isInstanceOf[RegisterAppMaster])

      val appMaster = registerAppMaster.asInstanceOf[RegisterAppMaster].appMaster
      mockMaster.reply(AppMasterRegistered(appId))
      // The DistributedShell AppMaster will ask for worker list
      mockMaster.expectMsg(GetAllWorkers)
      mockMaster.reply(WorkerList(workerList))
      // After worker list is ready, DistributedShell AppMaster will request resouce on each worker
      workerList.foreach { workerId =>
        mockMaster.expectMsg(RequestResource(appId, ResourceRequest(Resource(1), workerId,
          relaxation = Relaxation.SPECIFICWORKER)))
      }
      mockMaster.reply(ResourceAllocated(Array(ResourceAllocation(resource, mockWorker1.ref,
        WorkerId(1, 0L)))))
      mockWorker1.expectMsgClass(classOf[LaunchExecutor])
      mockWorker1.reply(RegisterActorSystem(ActorUtil.getSystemAddress(system).toString))

      appMaster.tell(GetFileContainer, client.ref)
      client.expectMsgClass(15.seconds, classOf[FileContainer])
    }
  }

  after {
    system.terminate()
    Await.result(system.whenTerminated, Duration.Inf)
  }
} 
Example 66
Source File: SwitchboardSpec.scala    From eclair   with Apache License 2.0 5 votes vote down vote up
package fr.acinq.eclair.io

import akka.actor.ActorRef
import akka.testkit.{TestActorRef, TestProbe}
import fr.acinq.bitcoin.ByteVector64
import fr.acinq.bitcoin.Crypto.PublicKey
import fr.acinq.eclair.TestConstants._
import fr.acinq.eclair.blockchain.TestWallet
import fr.acinq.eclair.wire._
import fr.acinq.eclair.{Features, NodeParams, TestKitBaseClass}
import org.scalatest.funsuite.AnyFunSuiteLike
import scodec.bits._

class SwitchboardSpec extends TestKitBaseClass with AnyFunSuiteLike {

  class TestSwitchboard(nodeParams: NodeParams, remoteNodeId: PublicKey, remotePeer: TestProbe) extends Switchboard(nodeParams, TestProbe().ref, TestProbe().ref, new TestWallet()) {
    override def createPeer(remoteNodeId2: PublicKey): ActorRef = {
      assert(remoteNodeId === remoteNodeId2)
      remotePeer.ref
    }
  }

  test("on initialization create peers") {
    val nodeParams = Alice.nodeParams
    val peer = TestProbe()
    val remoteNodeId = ChannelCodecsSpec.normal.commitments.remoteParams.nodeId
    // If we have a channel with that remote peer, we will automatically reconnect.
    nodeParams.db.channels.addOrUpdateChannel(ChannelCodecsSpec.normal)

    val _ = TestActorRef(new TestSwitchboard(nodeParams, remoteNodeId, peer))
    peer.expectMsg(Peer.Init(Set(ChannelCodecsSpec.normal)))
  }

  test("when connecting to a new peer forward Peer.Connect to it") {
    val nodeParams = Alice.nodeParams
    val (probe, peer) = (TestProbe(), TestProbe())
    val remoteNodeId = PublicKey(hex"03864ef025fde8fb587d989186ce6a4a186895ee44a926bfc370e2c366597a3f8f")
    val remoteNodeAddress = NodeAddress.fromParts("127.0.0.1", 9735).get
    nodeParams.db.network.addNode(NodeAnnouncement(ByteVector64.Zeroes, Features.empty, 0, remoteNodeId, Color(0, 0, 0), "alias", remoteNodeAddress :: Nil))

    val switchboard = TestActorRef(new TestSwitchboard(nodeParams, remoteNodeId, peer))
    probe.send(switchboard, Peer.Connect(remoteNodeId, None))
    peer.expectMsg(Peer.Init(Set.empty))
    peer.expectMsg(Peer.Connect(remoteNodeId, None))
  }

} 
Example 67
Source File: WorkerWatcherSuite.scala    From SparkCore   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.deploy.worker

import akka.actor.{ActorSystem, AddressFromURIString, Props}
import akka.testkit.TestActorRef
import akka.remote.DisassociatedEvent
import org.scalatest.FunSuite

class WorkerWatcherSuite extends FunSuite {
  test("WorkerWatcher shuts down on valid disassociation") {
    val actorSystem = ActorSystem("test")
    val targetWorkerUrl = "akka://1.2.3.4/user/Worker"
    val targetWorkerAddress = AddressFromURIString(targetWorkerUrl)
    val actorRef = TestActorRef[WorkerWatcher](Props(classOf[WorkerWatcher], targetWorkerUrl))(actorSystem)
    val workerWatcher = actorRef.underlyingActor
    workerWatcher.setTesting(testing = true)
    actorRef.underlyingActor.receive(new DisassociatedEvent(null, targetWorkerAddress, false))
    assert(actorRef.underlyingActor.isShutDown)
  }

  test("WorkerWatcher stays alive on invalid disassociation") {
    val actorSystem = ActorSystem("test")
    val targetWorkerUrl = "akka://1.2.3.4/user/Worker"
    val otherAkkaURL = "akka://4.3.2.1/user/OtherActor"
    val otherAkkaAddress = AddressFromURIString(otherAkkaURL)
    val actorRef = TestActorRef[WorkerWatcher](Props(classOf[WorkerWatcher], targetWorkerUrl))(actorSystem)
    val workerWatcher = actorRef.underlyingActor
    workerWatcher.setTesting(testing = true)
    actorRef.underlyingActor.receive(new DisassociatedEvent(null, otherAkkaAddress, false))
    assert(!actorRef.underlyingActor.isShutDown)
  }
} 
Example 68
Source File: BlockActorTest.scala    From bitcoin-s-spv-node   with MIT License 5 votes vote down vote up
package org.bitcoins.spvnode.networking

import akka.actor.ActorSystem
import akka.testkit.{ImplicitSender, TestActorRef, TestKit, TestProbe}
import org.bitcoins.core.crypto.DoubleSha256Digest
import org.bitcoins.core.protocol.blockchain.BlockHeader
import org.bitcoins.core.util.{BitcoinSLogger, BitcoinSUtil}
import org.bitcoins.spvnode.messages.BlockMessage
import org.scalatest.{BeforeAndAfter, BeforeAndAfterAll, FlatSpecLike, MustMatchers}

import scala.concurrent.duration.DurationInt


class BlockActorTest extends TestKit(ActorSystem("BlockActorTest")) with FlatSpecLike
  with MustMatchers with ImplicitSender
  with BeforeAndAfter with BeforeAndAfterAll with BitcoinSLogger  {

  def blockActor = TestActorRef(BlockActor.props,self)
  val blockHash = DoubleSha256Digest(BitcoinSUtil.flipEndianness("00000000b873e79784647a6c82962c70d228557d24a747ea4d1b8bbe878e1206"))

  "BlockActor" must "be able to send a GetBlocksMessage then receive that block back" in {
    blockActor ! blockHash
    val blockMsg = expectMsgType[BlockMessage](10.seconds)
    blockMsg.block.blockHeader.hash must be (blockHash)

  }


  it must "be able to request a block from it's block header" in {
    val blockHeader = BlockHeader("0100000043497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000bac8b0fa927c0ac8234287e33c5f74d38d354820e24756ad709d7038fc5f31f020e7494dffff001d03e4b672")
    blockActor ! blockHeader
    val blockMsg = expectMsgType[BlockMessage](10.seconds)
    blockMsg.block.blockHeader.hash must be (blockHash)
  }


  override def afterAll = {
    TestKit.shutdownActorSystem(system)
  }
} 
Example 69
Source File: ClientTest.scala    From bitcoin-s-spv-node   with MIT License 5 votes vote down vote up
package org.bitcoins.spvnode.networking

import java.net.{InetSocketAddress, ServerSocket}

import akka.actor.ActorSystem
import akka.io.{Inet, Tcp}
import akka.testkit.{ImplicitSender, TestActorRef, TestKit, TestProbe}
import org.bitcoins.core.config.TestNet3
import org.bitcoins.core.util.{BitcoinSLogger, BitcoinSUtil}
import org.bitcoins.spvnode.messages.control.VersionMessage
import org.bitcoins.spvnode.messages.{NetworkPayload, VersionMessage}
import org.bitcoins.spvnode.util.BitcoinSpvNodeUtil
import org.scalatest.{BeforeAndAfter, BeforeAndAfterAll, FlatSpecLike, MustMatchers}

import scala.concurrent.duration._
import scala.util.Try

class ClientTest extends TestKit(ActorSystem("ClientTest")) with FlatSpecLike
  with MustMatchers with ImplicitSender
  with BeforeAndAfter with BeforeAndAfterAll with BitcoinSLogger {

  "Client" must "connect to a node on the bitcoin network, " +
    "send a version message to a peer on the network and receive a version message back, then close that connection" in {
    val probe = TestProbe()

    val client = TestActorRef(Client.props,probe.ref)

    val remote = new InetSocketAddress(TestNet3.dnsSeeds(0), TestNet3.port)
    val randomPort = 23521
    //random port
    client ! Tcp.Connect(remote, Some(new InetSocketAddress(randomPort)))

    //val bound : Tcp.Bound = probe.expectMsgType[Tcp.Bound]
    val conn : Tcp.Connected = probe.expectMsgType[Tcp.Connected]

    //make sure the socket is currently bound
    Try(new ServerSocket(randomPort)).isSuccess must be (false)
    client ! Tcp.Abort
    val confirmedClosed = probe.expectMsg(Tcp.Aborted)

    //make sure the port is now available
    val boundSocket = Try(new ServerSocket(randomPort))
    boundSocket.isSuccess must be (true)

    boundSocket.get.close()

  }

  it must "bind connect to two nodes on one port" in {
    //NOTE if this test case fails it is more than likely because one of the two dns seeds
    //below is offline
    val remote1 = new InetSocketAddress(TestNet3.dnsSeeds(0), TestNet3.port)
    val remote2 = new InetSocketAddress(TestNet3.dnsSeeds(2), TestNet3.port)

    val probe1 = TestProbe()
    val probe2 = TestProbe()


    val client1 = TestActorRef(Client.props, probe1.ref)
    val client2 = TestActorRef(Client.props, probe2.ref)

    val local1 = new InetSocketAddress(TestNet3.port)
    val options = List(Inet.SO.ReuseAddress(true))
    client1 ! Tcp.Connect(remote1,Some(local1),options)


    probe1.expectMsgType[Tcp.Connected]
    client1 ! Tcp.Abort

    val local2 = new InetSocketAddress(TestNet3.port)
    client2 ! Tcp.Connect(remote2,Some(local2),options)
    probe2.expectMsgType[Tcp.Connected](5.seconds)
    client2 ! Tcp.Abort
  }

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


} 
Example 70
Source File: SilentActorNextTest.scala    From 006877   with MIT License 5 votes vote down vote up
package aia.testdriven

import org.scalatest.WordSpecLike
import org.scalatest.MustMatchers
import akka.testkit.{ TestActorRef, TestKit }
import akka.actor._

package silentactor02 {

class SilentActorTest extends TestKit(ActorSystem("testsystem"))
    with WordSpecLike
    with MustMatchers
    with StopSystemAfterAll {

    "A Silent Actor" must {

      "change internal state when it receives a message, single" in {
        import SilentActor._

        val silentActor = TestActorRef[SilentActor]
        silentActor ! SilentMessage("whisper")
        silentActor.underlyingActor.state must (contain("whisper"))
      }

    }
  }


  object SilentActor {
    case class SilentMessage(data: String)
    case class GetState(receiver: ActorRef)
  }

  class SilentActor extends Actor {
    import SilentActor._
    var internalState = Vector[String]()

    def receive = {
      case SilentMessage(data) =>
        internalState = internalState :+ data
    }

    def state = internalState
  }
}

package silentactor03 {

  class SilentActorTest extends TestKit(ActorSystem("testsystem"))
    with WordSpecLike
    with MustMatchers
    with StopSystemAfterAll {

    "A Silent Actor" must {

      "change internal state when it receives a message, multi" in {
        import SilentActor._

        val silentActor = system.actorOf(Props[SilentActor], "s3")
        silentActor ! SilentMessage("whisper1")
        silentActor ! SilentMessage("whisper2")
        silentActor ! GetState(testActor)
        expectMsg(Vector("whisper1", "whisper2"))
      }

    }

  }



  object SilentActor {
    case class SilentMessage(data: String)
    case class GetState(receiver: ActorRef)
  }

  class SilentActor extends Actor {
    import SilentActor._
    var internalState = Vector[String]()

    def receive = {
      case SilentMessage(data) =>
        internalState = internalState :+ data
      case GetState(receiver) => receiver ! internalState
    }
  }

} 
Example 71
Source File: HelloWorldTest.scala    From 006877   with MIT License 5 votes vote down vote up
package aia.deploy

import org.scalatest.{BeforeAndAfterAll, WordSpecLike}
import org.scalatest.MustMatchers
import akka.testkit.{TestActorRef, ImplicitSender, TestKit}
import akka.actor.ActorSystem

class HelloWorldTest extends TestKit(ActorSystem("HelloWorldTest"))
    with ImplicitSender
    with WordSpecLike
    with MustMatchers
    with BeforeAndAfterAll {

  val actor = TestActorRef[HelloWorld]

  override def afterAll(): Unit = {
    system.terminate()
  }
  "HelloWorld" must {
    "reply when sending a string" in {
      actor ! "everybody"
      expectMsg("Hello everybody")
    }
  }
} 
Example 72
Source File: TimeOutSchedulerSpec.scala    From incubator-retired-gearpump   with Apache License 2.0 5 votes vote down vote up
package org.apache.gearpump.util

import scala.concurrent.duration._

import akka.actor._
import akka.testkit.{ImplicitSender, TestActorRef, TestKit, TestProbe}
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}
import org.slf4j.Logger

import org.apache.gearpump.cluster.TestUtil

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

  def this() = this(ActorSystem("WorkerSpec", TestUtil.DEFAULT_CONFIG))
  val mockActor = TestProbe()

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "The TimeOutScheduler" should {
    "handle the time out event" in {
      val testActorRef = TestActorRef(Props(classOf[TestActor], mockActor.ref))
      val testActor = testActorRef.underlyingActor.asInstanceOf[TestActor]
      testActor.sendMsgToIgnore()
      mockActor.expectMsg(30.seconds, MessageTimeOut)
    }
  }
}

case object Echo
case object MessageTimeOut

class TestActor(mock: ActorRef) extends Actor with TimeOutScheduler {
  private val LOG: Logger = LogUtil.getLogger(getClass)

  val target = context.actorOf(Props(classOf[EchoActor]))

  override def receive: Receive = {
    case _ =>
  }

  def sendMsgToIgnore(): Unit = {
    sendMsgWithTimeOutCallBack(target, Echo, 2000, sendMsgTimeOut())
  }

  private def sendMsgTimeOut(): Unit = {
    mock ! MessageTimeOut
  }
}

class EchoActor extends Actor {
  override def receive: Receive = {
    case _ =>
  }
} 
Example 73
Source File: MiniCluster.scala    From incubator-retired-gearpump   with Apache License 2.0 5 votes vote down vote up
package org.apache.gearpump.cluster

import akka.actor.{Actor, ActorRef, ActorSystem, Props}
import akka.pattern.ask
import akka.testkit.TestActorRef
import com.typesafe.config.ConfigValueFactory
import org.apache.gearpump.cluster.AppMasterToMaster.GetAllWorkers
import org.apache.gearpump.cluster.MasterToAppMaster.WorkerList
import org.apache.gearpump.cluster.master.Master
import org.apache.gearpump.cluster.worker.Worker
import org.apache.gearpump.util.Constants

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

class MiniCluster {
  private val mockMasterIP = "127.0.0.1"

  implicit val system = ActorSystem("system", TestUtil.MASTER_CONFIG.
    withValue(Constants.NETTY_TCP_HOSTNAME, ConfigValueFactory.fromAnyRef(mockMasterIP)))

  val (mockMaster, worker) = {
    val master = system.actorOf(Props(classOf[Master]), "master")
    val worker = system.actorOf(Props(classOf[Worker], master), "worker")

    // Wait until worker register itself to master
    waitUtilWorkerIsRegistered(master)
    (master, worker)
  }

  def launchActor(props: Props): TestActorRef[Actor] = {
    TestActorRef(props)
  }

  private def waitUtilWorkerIsRegistered(master: ActorRef): Unit = {
    while (!isWorkerRegistered(master)) {}
  }

  private def isWorkerRegistered(master: ActorRef): Boolean = {
    import scala.concurrent.duration._
    implicit val dispatcher = system.dispatcher

    implicit val futureTimeout = Constants.FUTURE_TIMEOUT

    val workerListFuture = (master ? GetAllWorkers).asInstanceOf[Future[WorkerList]]

    // Waits until the worker is registered.
    val workers = Await.result[WorkerList](workerListFuture, 15.seconds)
    workers.workers.size > 0
  }

  def shutDown(): Unit = {
    system.terminate()
    Await.result(system.whenTerminated, Duration.Inf)
  }
} 
Example 74
Source File: MockUtil.scala    From incubator-retired-gearpump   with Apache License 2.0 5 votes vote down vote up
package org.apache.gearpump.streaming

import akka.actor.{Actor, ActorSystem}
import akka.testkit.TestActorRef
import org.apache.gearpump.cluster.TestUtil
import org.apache.gearpump.streaming.task.{TaskContext, TaskId}
import org.mockito.{ArgumentMatcher, Matchers, Mockito}

object MockUtil {

  lazy val system: ActorSystem = ActorSystem("mockUtil", TestUtil.DEFAULT_CONFIG)

  def mockTaskContext: TaskContext = {
    val context = Mockito.mock(classOf[TaskContext])
    Mockito.when(context.self).thenReturn(Mockito.mock(classOf[TestActorRef[Actor]]))
    Mockito.when(context.system).thenReturn(system)
    Mockito.when(context.parallelism).thenReturn(1)
    Mockito.when(context.taskId).thenReturn(TaskId(0, 0))
    context
  }

  def argMatch[T](func: T => Boolean): T = {
    Matchers.argThat(new ArgumentMatcher[T] {
      override def matches(param: Any): Boolean = {
        val mesage = param.asInstanceOf[T]
        func(mesage)
      }
    })
  }
} 
Example 75
Source File: StreamingTestUtil.scala    From incubator-retired-gearpump   with Apache License 2.0 5 votes vote down vote up
package org.apache.gearpump.streaming

import akka.actor._
import akka.testkit.TestActorRef
import org.apache.gearpump.cluster.AppMasterToMaster.RegisterAppMaster
import org.apache.gearpump.cluster.scheduler.Resource
import org.apache.gearpump.cluster.{AppDescription, AppMasterContext, MiniCluster, UserConfig}
import org.apache.gearpump.streaming.appmaster.AppMaster
import org.apache.gearpump.util.Graph

object StreamingTestUtil {
  private var executorId = 0
  val testUserName = "testuser"

  def startAppMaster(miniCluster: MiniCluster, appId: Int): TestActorRef[AppMaster] = {

    implicit val actorSystem = miniCluster.system
    val masterConf = AppMasterContext(appId, testUserName, Resource(1), null,
      None, miniCluster.mockMaster)

    val app = StreamApplication("test", Graph.empty, UserConfig.empty)
    val appDescription = AppDescription(app.name, app.appMaster.getName, app.userConfig)
    val props = Props(new AppMaster(masterConf, appDescription))
    val appMaster = miniCluster.launchActor(props).asInstanceOf[TestActorRef[AppMaster]]
    val registerAppMaster = RegisterAppMaster(appId, ActorRef.noSender, null)
    miniCluster.mockMaster.tell(registerAppMaster, appMaster)

    appMaster
  }
} 
Example 76
Source File: FastSyncStateStorageActorSpec.scala    From mantis   with Apache License 2.0 5 votes vote down vote up
package io.iohk.ethereum.blockchain.sync

import akka.actor.ActorSystem
import akka.pattern._
import akka.testkit.TestActorRef
import akka.util.ByteString
import io.iohk.ethereum.NormalPatience
import io.iohk.ethereum.blockchain.sync.FastSync.SyncState
import io.iohk.ethereum.blockchain.sync.FastSyncStateStorageActor.GetStorage
import io.iohk.ethereum.db.dataSource.EphemDataSource
import io.iohk.ethereum.db.storage.FastSyncStateStorage
import io.iohk.ethereum.domain.BlockHeader
import org.scalatest.concurrent.Eventually
import org.scalatest.{AsyncFlatSpec, Matchers}

class FastSyncStateStorageActorSpec extends AsyncFlatSpec with Matchers with Eventually with NormalPatience {

  "FastSyncStateActor" should "eventually persist a newest state of a fast sync" in {

    val dataSource = EphemDataSource()
    implicit val system = ActorSystem("FastSyncStateActorSpec_System")
    val syncStateActor = TestActorRef(new FastSyncStateStorageActor)
    val maxN = 10

    val targetBlockHeader = BlockHeader(ByteString(""), ByteString(""), ByteString(""), ByteString(""), ByteString(""),
      ByteString(""), ByteString(""), 0, 0, 0, 0, 0, ByteString(""), ByteString(""), ByteString(""))
    syncStateActor ! new FastSyncStateStorage(dataSource)
    (0 to maxN).foreach(n => syncStateActor ! SyncState(targetBlockHeader).copy(downloadedNodesCount = n))

    eventually {
      (syncStateActor ? GetStorage).mapTo[Option[SyncState]].map { syncState =>
        val expected = SyncState(targetBlockHeader).copy(downloadedNodesCount = maxN)
        syncState shouldEqual Some(expected)
      }
    }

  }

} 
Example 77
Source File: DistShellAppMasterSpec.scala    From incubator-retired-gearpump   with Apache License 2.0 5 votes vote down vote up
package org.apache.gearpump.examples.distributedshell

import scala.concurrent.Await
import scala.concurrent.duration.Duration

import akka.actor.ActorSystem
import akka.testkit.{TestActorRef, TestProbe}
import org.scalatest.{BeforeAndAfter, Matchers, WordSpec}

import org.apache.gearpump.cluster.AppMasterToMaster.{GetAllWorkers, RegisterAppMaster, RequestResource}
import org.apache.gearpump.cluster.AppMasterToWorker.LaunchExecutor
import org.apache.gearpump.cluster.MasterToAppMaster.{AppMasterRegistered, ResourceAllocated, WorkerList}
import org.apache.gearpump.cluster._
import org.apache.gearpump.cluster.appmaster.{AppMasterRuntimeEnvironment, ApplicationRuntimeInfo}
import org.apache.gearpump.cluster.scheduler.{Relaxation, Resource, ResourceAllocation, ResourceRequest}
import org.apache.gearpump.cluster.worker.WorkerId
import org.apache.gearpump.util.ActorSystemBooter.RegisterActorSystem
import org.apache.gearpump.util.ActorUtil

class DistShellAppMasterSpec extends WordSpec with Matchers with BeforeAndAfter {
  implicit val system = ActorSystem("AppMasterSpec", TestUtil.DEFAULT_CONFIG)
  val mockMaster = TestProbe()(system)
  val mockWorker1 = TestProbe()(system)
  val masterProxy = mockMaster.ref
  val appId = 0
  val userName = "test"
  val masterExecutorId = 0
  val workerList = List(WorkerId(1, 0L), WorkerId(2, 0L), WorkerId(3, 0L))
  val resource = Resource(1)
  val appJar = None
  val appDescription = AppDescription("app0", classOf[DistShellAppMaster].getName, UserConfig.empty)

  "DistributedShell AppMaster" should {
    "launch one ShellTask on each worker" in {
      val appMasterInfo = ApplicationRuntimeInfo(appId, appName = appId.toString)
      val appMasterContext = AppMasterContext(appId, userName, resource, null, appJar, masterProxy)
      TestActorRef[DistShellAppMaster](
        AppMasterRuntimeEnvironment.props(List(masterProxy.path), appDescription,
          appMasterContext))
      mockMaster.expectMsgType[RegisterAppMaster]
      mockMaster.reply(AppMasterRegistered(appId))
      // The DistributedShell AppMaster asks for worker list from Master.
      mockMaster.expectMsg(GetAllWorkers)
      mockMaster.reply(WorkerList(workerList))
      // After worker list is ready, DistributedShell AppMaster requests resource on each worker
      workerList.foreach { workerId =>
        mockMaster.expectMsg(RequestResource(appId, ResourceRequest(Resource(1), workerId,
          relaxation = Relaxation.SPECIFICWORKER)))
      }
      mockMaster.reply(ResourceAllocated(
        Array(ResourceAllocation(resource, mockWorker1.ref, WorkerId(1, 0L)))))
      mockWorker1.expectMsgClass(classOf[LaunchExecutor])
      mockWorker1.reply(RegisterActorSystem(ActorUtil.getSystemAddress(system).toString))
    }
  }

  after {
    system.terminate()
    Await.result(system.whenTerminated, Duration.Inf)
  }
} 
Example 78
Source File: ViewSchedulingListenerActorSpec.scala    From schedoscope   with Apache License 2.0 5 votes vote down vote up
package org.schedoscope.scheduler.actors

import akka.actor.ActorSystem
import akka.testkit.{ImplicitSender, TestActorRef, TestKit, TestProbe}
import org.joda.time.LocalDateTime
import org.scalatest.{BeforeAndAfterAll, FlatSpecLike, Matchers}
import org.schedoscope.dsl.Parameter._
import org.schedoscope.scheduler.listeners.{RetryableViewSchedulingListenerException, ViewSchedulingListenerException}
import org.schedoscope.scheduler.messages.{RegisterFailedListener, ViewSchedulingMonitoringEvent}
import org.schedoscope.scheduler.states._
import test.views.Brand

import scala.concurrent.duration._

class ViewSchedulingListenerActorSpec extends TestKit(ActorSystem("schedoscope"))
  with ImplicitSender
  with FlatSpecLike
  with Matchers
  with BeforeAndAfterAll {

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

  val TIMEOUT = 5 seconds

  "A viewSchedulingListenerActor" should "execute listener handler methods" in {
    val viewSchedulingListenerManagerActor = TestProbe()
    val handlerClassName = "org.schedoscope.test.TestViewListener"
    val viewSchedulingListenerActor = TestActorRef(ViewSchedulingListenerActor.props(
      handlerClassName, viewSchedulingListenerManagerActor.ref))

    val view = Brand(p("ec01"))
    val prevState1 = CreatedByViewManager(view)

    // confirm listener method is being executed correctly
    intercept[RetryableViewSchedulingListenerException] {
      viewSchedulingListenerActor.receive(
        ViewSchedulingMonitoringEvent(prevState1, prevState1, Set(Transform(view)), new LocalDateTime()))
    }
    // since at it, confirm that listener actor handles retryable exceptions
    // and tries to cache in viewSchedulingListenerManagerActor as receiver of
    // latest events
    viewSchedulingListenerManagerActor.expectMsg(RegisterFailedListener(handlerClassName))

    val newState1 = Failed(view)
    // confirm listener method is being executed correctly
    intercept[ViewSchedulingListenerException] {
      viewSchedulingListenerActor.receive(
        ViewSchedulingMonitoringEvent(prevState1, newState1, Set(Transform(view)), new LocalDateTime()))
    }
    // Confirm that listener actor does not register for receiving latest events!
    viewSchedulingListenerManagerActor.expectNoMsg(TIMEOUT)
  }


} 
Example 79
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 80
Source File: SchemaManagerRouterTest.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, Props}
import akka.testkit.{TestActorRef, TestKit, TestProbe}
import org.scalatest.{BeforeAndAfterAll, FlatSpecLike, Matchers}
import org.schedoscope.conf.SchedoscopeSettings
import org.schedoscope.{Settings, TestUtils}

import scala.concurrent.duration._

class SchemaManagerRouterTest extends TestKit(ActorSystem("schedoscope"))
  with FlatSpecLike
  with Matchers
  with BeforeAndAfterAll {

  override def afterAll() {
    TestKit.shutdownActorSystem(system)
  }

  // common vars
  val settings: SchedoscopeSettings = Settings()


  class ForwardChildActor(to: ActorRef) extends Actor {
    def receive = {
      case x => to.forward(x)
    }
  }

  trait SchemaManagerRouterTest {

    val partitionCreatorRouterActor = TestProbe()
    val metadataLoggerActorTest = TestProbe()

    def getSchemaManager(s: SchedoscopeSettings): ActorRef = {

      TestActorRef(new SchemaManagerRouter(s) {
        override def preStart {
          context.actorOf(Props(new ForwardChildActor(partitionCreatorRouterActor.ref)),
            "partition-creator")
          context.actorOf(Props(new ForwardChildActor(metadataLoggerActorTest.ref)),
            "metadata-logger")
        }
      })
    }
  }

  it should "set an exponential backoff time for restarting drivers" in
    new SchemaManagerRouterTest {

      val newSettings = TestUtils.createSettings(
        "schedoscope.metastore.actor-backoff-slot-time=10",
        "schedoscope.metastore.actor-backoff-minimum-delay=0")


      var schemaManagerRouter: ActorRef = getSchemaManager(newSettings)

      partitionCreatorRouterActor.send(schemaManagerRouter, "tick")
      partitionCreatorRouterActor.expectMsg("tick")
      partitionCreatorRouterActor.send(schemaManagerRouter, "tick")
      partitionCreatorRouterActor.expectMsg("tick")

      metadataLoggerActorTest.send(schemaManagerRouter, "tick")
      metadataLoggerActorTest.expectMsg("tick")
      metadataLoggerActorTest.send(schemaManagerRouter, "tick")
      metadataLoggerActorTest.expectMsg("tick")

    }

  it should "set an exponential backoff time too big for the test to get it" in
    new SchemaManagerRouterTest {

      val newSettings = TestUtils.createSettings(
        "schedoscope.metastore.actor-backoff-slot-time=10000",
        "schedoscope.metastore.actor-backoff-minimum-delay=10000")


      var schemaManagerRouter: ActorRef = getSchemaManager(newSettings)

      partitionCreatorRouterActor.send(schemaManagerRouter, "tick")
      partitionCreatorRouterActor.expectMsg("tick")
      partitionCreatorRouterActor.send(schemaManagerRouter, "tick")
      partitionCreatorRouterActor.expectNoMsg(3 seconds)

      metadataLoggerActorTest.send(schemaManagerRouter, "tick")
      metadataLoggerActorTest.expectMsg("tick")
      metadataLoggerActorTest.send(schemaManagerRouter, "tick")
      metadataLoggerActorTest.expectNoMsg(3 seconds)

    }

} 
Example 81
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 82
Source File: S3ActorSpec.scala    From changestream   with MIT License 5 votes vote down vote up
package changestream.actors

import akka.actor.{ActorRefFactory, Props}
import akka.testkit.{TestActorRef, TestProbe}
import changestream.actors.PositionSaver.EmitterResult
import changestream.helpers.{Config, Emitter}

import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory

import scala.language.postfixOps

class S3ActorSpec extends Emitter with Config {
  val probe = TestProbe()
  val maker = (_: ActorRefFactory) => probe.ref
  val s3Config = ConfigFactory.
    parseString("aws.s3.batch-size = 2, aws.s3.flush-timeout = 1000").
    withFallback(awsConfig)
  val actorRef = TestActorRef(Props(classOf[S3Actor], maker, s3Config))

  "When S3Actor receives a single valid message" should {
    "Add the message to S3 in a batch of one" in {
      actorRef ! message

      val result = probe.expectMsgType[EmitterResult](5000 milliseconds)
      result.position should be(message.nextPosition)
      result.meta.get.asInstanceOf[String] should endWith ("-1.json")
    }
  }

  "When S3Actor receives multiple valid messages in quick succession" should {
    "Add the messages to S3 in a batch of many" in {
      actorRef ! message
      actorRef ! message.copy(nextPosition = "FOOBAZ")

      val result = probe.expectMsgType[EmitterResult](5000 milliseconds)
      result.position should be("FOOBAZ")
      result.meta.get.asInstanceOf[String] should endWith ("-2.json")
    }
  }

  "When S3Actor receives multiple valid messages in slow succession" should {
    "Add the messages to the S3 queue in multiple batches of one message" in {
      actorRef ! message
      Thread.sleep(2000)
      actorRef ! message.copy(nextPosition = "FOOBAZ")

      val result1 = probe.expectMsgType[EmitterResult](5000 milliseconds)
      val result2 = probe.expectMsgType[EmitterResult](5000 milliseconds)
      result1.position should be(message.nextPosition)
      result1.meta.get.asInstanceOf[String] should endWith ("-1.json")
      result2.position should be("FOOBAZ")
      result2.meta.get.asInstanceOf[String] should endWith ("-1.json")
    }
  }

  "When S3Actor receives multiple valid messages that exceed the flush size" should {
    "Add the messages to the S3 queue in multiple batches" in {
      actorRef ! message
      actorRef ! message.copy(nextPosition = "FOOBAZ")
      actorRef ! message.copy(nextPosition = "BIPBOP")

      val result1 = probe.expectMsgType[EmitterResult](5000 milliseconds)
      val result2 = probe.expectMsgType[EmitterResult](5000 milliseconds)
      result1.position should be("FOOBAZ")
      result1.meta.get.asInstanceOf[String] should endWith ("-2.json")
      result2.position should be("BIPBOP")
      result2.meta.get.asInstanceOf[String] should endWith ("-1.json")
    }
  }
} 
Example 83
Source File: SnsActorSpec.scala    From changestream   with MIT License 5 votes vote down vote up
package changestream.actors

import akka.actor.{ActorRefFactory, Props}
import akka.testkit.{TestActorRef, TestProbe}
import changestream.actors.PositionSaver.EmitterResult
import changestream.helpers.{Config, Emitter}
import com.typesafe.config.ConfigFactory

import scala.concurrent.duration._
import scala.language.postfixOps

class SnsActorSpec extends Emitter with Config {
  val probe = TestProbe()
  val maker = (_: ActorRefFactory) => probe.ref

  val actorRef = TestActorRef(Props(classOf[SnsActor], maker, awsConfig))

  val configWithInterpolation = ConfigFactory.
    parseString("aws.sns.topic = \"__integration_tests-{database}-{tableName}\"").
    withFallback(awsConfig)
  val snsWithInterpolation = TestActorRef(Props(classOf[SnsActor], maker, configWithInterpolation))


  "When SnsActor receives a single valid message" should {
    "Immediately publish the message to SNS" in {
      actorRef ! message

      val result = probe.expectMsgType[EmitterResult](5000 milliseconds)
      result.position should be(message.nextPosition)
    }
  }

  "When SnsActor receives a message" should {
    "Should correctly publish the message when the topic contains interpolated database and/or tableName" in {
      snsWithInterpolation ! message

      val result = probe.expectMsgType[EmitterResult](5000 milliseconds)
      result.position should be(message.nextPosition)
    }
  }
} 
Example 84
Source File: SqsActorSpec.scala    From changestream   with MIT License 5 votes vote down vote up
package changestream.actors

import akka.actor.{ActorRefFactory, Props}
import akka.testkit.{TestActorRef, TestProbe}
import changestream.actors.PositionSaver.EmitterResult
import changestream.actors.SqsActor.BatchResult
import changestream.helpers.{Config, Emitter}

import scala.concurrent.duration._
import scala.language.postfixOps

class SqsActorSpec extends Emitter with Config {
  val probe = TestProbe()
  val maker = (_: ActorRefFactory) => probe.ref
  val actorRef = TestActorRef(Props(classOf[SqsActor], maker, awsConfig))

  "When SqsActor receives a single valid message" should {
    "Add the message to the SQS queue in a batch of one" in {
      actorRef ! message

      val result = probe.expectMsgType[EmitterResult](5000 milliseconds)
      result.position should be(message.nextPosition)
      result.meta.get shouldBe a[BatchResult]
      result.meta.get.asInstanceOf[BatchResult].failed shouldBe empty
      result.meta.get.asInstanceOf[BatchResult].queued should have length 1
    }
  }

  "When SqsActor receives multiple valid messages in quick succession" should {
    "Add the messages to the SQS queue in a batch of multiple" in {
      actorRef ! message
      actorRef ! message.copy(nextPosition = "FOOBAZ")

      val result = probe.expectMsgType[EmitterResult](5000 milliseconds)
      result.position should be("FOOBAZ")
      result.meta.get shouldBe a[BatchResult]
      result.meta.get.asInstanceOf[BatchResult].failed shouldBe empty
      result.meta.get.asInstanceOf[BatchResult].queued should have length 2
    }
  }

  "When SqsActor receives multiple valid messages in slow succession" should {
    "Add the messages to the SQS queue in multiple batches of one message" in {
      actorRef ! message
      Thread.sleep(500)
      actorRef ! message.copy(nextPosition = "FOOBAZ")

      val result1 = probe.expectMsgType[EmitterResult](5000 milliseconds)
      val result2 = probe.expectMsgType[EmitterResult](5000 milliseconds)

      result1.position should be(message.nextPosition)
      result1.meta.get shouldBe a[BatchResult]
      result1.meta.get.asInstanceOf[BatchResult].failed shouldBe empty
      result1.meta.get.asInstanceOf[BatchResult].queued should have length 1

      result2.position should be("FOOBAZ")
      result2.meta.get shouldBe a[BatchResult]
      result2.meta.get.asInstanceOf[BatchResult].failed shouldBe empty
      result2.meta.get.asInstanceOf[BatchResult].queued should have length 1
    }
  }
} 
Example 85
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)
      }
    }
  }
}