akka.testkit.TestKitBase Scala Examples

The following examples show how to use akka.testkit.TestKitBase. 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: MatcherSpec.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.actors

import akka.actor.ActorSystem
import akka.testkit.TestKitBase
import com.typesafe.config.ConfigFactory
import com.wavesplatform.dex.domain.utils.ScorexLogging
import com.wavesplatform.dex.settings.loadConfig
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike
import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach, Suite}

abstract class MatcherSpec(_actorSystemName: String) extends AnyWordSpecLike with MatcherSpecLike {
  protected def actorSystemName: String = _actorSystemName
}

trait MatcherSpecLike extends TestKitBase with Matchers with BeforeAndAfterAll with BeforeAndAfterEach with ScorexLogging {
  this: Suite =>

  protected def actorSystemName: String

  implicit override lazy val system: ActorSystem = ActorSystem(
    actorSystemName,
    loadConfig(ConfigFactory.empty())
  )

  override protected def afterAll(): Unit = {
    super.afterAll()
    shutdown(system)
  }
} 
Example 2
Source File: EventLogSystemTimeSpec.scala    From eventuate   with Apache License 2.0 5 votes vote down vote up
package com.rbmhtechnology.eventuate.log

import akka.testkit.TestKitBase
import com.rbmhtechnology.eventuate.EventsourcingProtocol.Write
import com.rbmhtechnology.eventuate.EventsourcingProtocol.WriteSuccess
import com.rbmhtechnology.eventuate.EventsourcingProtocol.Written
import com.rbmhtechnology.eventuate.ReplicationProtocol.ReplicationMetadata
import com.rbmhtechnology.eventuate.ReplicationProtocol.ReplicationWrite
import com.rbmhtechnology.eventuate.DurableEvent
import com.rbmhtechnology.eventuate.VectorTime

trait EventLogSystemTimeSpec extends TestKitBase with EventLogSpecSupport {

  import EventLogSpec._

  val UndefinedTimestamp = 0L
  val SystemTimestamp = 123L

  override def currentSystemTime: Long = SystemTimestamp

  "An event log" must {
    "update an event's system timestamp" in {
      log ! Write(List(event("a").copy(systemTimestamp = 3L)), system.deadLetters, replyToProbe.ref, 0, 0)
      replyToProbe.expectMsgType[WriteSuccess].events.head.systemTimestamp should be(SystemTimestamp)
    }
    "update a replicated events system timestamp if not defined (systemTimestamp == 0L, cf. #371)" in {
      val evt = DurableEvent("a", emitterIdA, processId = logId, vectorTimestamp = VectorTime(remoteLogId -> 1L))
      val collaborator = registerCollaborator()
      log ! ReplicationWrite(List(evt), Map(remoteLogId -> ReplicationMetadata(5, VectorTime.Zero)))
      collaborator.expectMsgType[Written].event.systemTimestamp should not be UndefinedTimestamp
    }
    "not update a replicated events system timestamp if defined (systemTimestamp != 0L, cf. #371)" in {
      val evt = DurableEvent("a", emitterIdA, processId = logId, vectorTimestamp = VectorTime(remoteLogId -> 1L), systemTimestamp = SystemTimestamp)
      val collaborator = registerCollaborator()
      log ! ReplicationWrite(List(evt), Map(remoteLogId -> ReplicationMetadata(5, VectorTime.Zero)))
      collaborator.expectMsgType[Written].event.systemTimestamp should be(SystemTimestamp)
    }
  }
} 
Example 3
Source File: AkkaUnitTestLike.scala    From reactive-kinesis   with Apache License 2.0 5 votes vote down vote up
package com.weightwatchers.reactive.kinesis.common

import akka.actor.{ActorSystem, Scheduler}
import akka.stream.{ActorMaterializer, Materializer}
import akka.testkit.TestKitBase
import com.typesafe.config.{Config, ConfigFactory}
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{BeforeAndAfterAll, Suite}

import scala.concurrent.ExecutionContextExecutor


trait AkkaUnitTestLike extends TestKitBase with ScalaFutures with BeforeAndAfterAll {
  self: Suite =>

  implicit lazy val config: Config                = ConfigFactory.load("sample.conf")
  implicit lazy val system: ActorSystem           = ActorSystem(suiteName, config)
  implicit lazy val scheduler: Scheduler          = system.scheduler
  implicit lazy val mat: Materializer             = ActorMaterializer()
  implicit lazy val ctx: ExecutionContextExecutor = system.dispatcher

  abstract override def afterAll(): Unit = {
    super.afterAll()
    // intentionally shutdown the actor system last.
    system.terminate().futureValue
  }
} 
Example 4
Source File: AbstractEmbeddedPersistentActorSpec.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.scaladsl.persistence.testkit

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

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

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

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

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

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

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

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

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

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

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

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

      // start another with same persistenceId should recover state
      val p2 = system.actorOf(props("p1"))
      p2 ! Get
      expectMsg(State(Vector("A", "B", "C")))
    }
  }
} 
Example 5
Source File: ConsulDiscoverySpec.scala    From akka-management   with Apache License 2.0 5 votes vote down vote up
package akka.cluster.bootstrap.discovery

import java.net.InetAddress

import akka.actor.ActorSystem
import akka.discovery.ServiceDiscovery.ResolvedTarget
import akka.discovery.consul.ConsulServiceDiscovery
import akka.testkit.TestKitBase
import com.google.common.net.HostAndPort
import com.orbitz.consul.Consul
import com.orbitz.consul.model.catalog.ImmutableCatalogRegistration
import com.orbitz.consul.model.health.ImmutableService
import com.pszymczyk.consul.{ ConsulProcess, ConsulStarterBuilder }
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.{ Millis, Seconds, Span }
import org.scalatest.{ BeforeAndAfterAll, Matchers, WordSpecLike }

import scala.concurrent.duration._

class ConsulDiscoverySpec extends WordSpecLike with Matchers with BeforeAndAfterAll with TestKitBase with ScalaFutures {

  private val consul: ConsulProcess = ConsulStarterBuilder.consulStarter().withHttpPort(8500).build().start()

  "Consul Discovery" should {
    "work for defaults" in {
      val consulAgent =
        Consul.builder().withHostAndPort(HostAndPort.fromParts(consul.getAddress, consul.getHttpPort)).build()
      consulAgent
        .catalogClient()
        .register(
          ImmutableCatalogRegistration
            .builder()
            .service(
              ImmutableService
                .builder()
                .addTags(s"system:${system.name}", "akka-management-port:1234")
                .address("127.0.0.1")
                .id("test")
                .service("test")
                .port(1235)
                .build()
            )
            .node("testNode")
            .address("localhost")
            .build()
        )

      val lookupService = new ConsulServiceDiscovery(system)
      val resolved = lookupService.lookup("test", 10.seconds).futureValue
      resolved.addresses should contain(
        ResolvedTarget(
          host = "127.0.0.1",
          port = Some(1234),
          address = Some(InetAddress.getByName("127.0.0.1"))
        )
      )
    }
  }

  override def afterAll(): Unit = {
    super.afterAll()
    consul.close()
  }

  override implicit lazy val system: ActorSystem = ActorSystem("test")

  implicit override val patienceConfig: PatienceConfig =
    PatienceConfig(timeout = scaled(Span(30, Seconds)), interval = scaled(Span(50, Millis)))

} 
Example 6
Source File: ProjectionsSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.sourcing.projections

import akka.actor.ActorSystem
import akka.persistence.query.Offset
import akka.stream.scaladsl.Source
import akka.testkit.{TestKit, TestKitBase}
import cats.effect.{ContextShift, IO}
import ch.epfl.bluebrain.nexus.sourcing.projections.Fixture.memoize
import ch.epfl.bluebrain.nexus.sourcing.projections.ProjectionProgress._
import ch.epfl.bluebrain.nexus.sourcing.projections.ProjectionsSpec.SomeEvent
import io.circe.generic.auto._
import org.scalatest.concurrent.Eventually
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike
import org.scalatest.{BeforeAndAfterAll, DoNotDiscover}

import scala.concurrent.duration._

//noinspection TypeAnnotation
@DoNotDiscover
class ProjectionsSpec
    extends TestKitBase
    with AnyWordSpecLike
    with Matchers
    with TestHelpers
    with IOValues
    with Eventually
    with BeforeAndAfterAll {

  implicit override lazy val system: ActorSystem      = SystemBuilder.persistence("ProjectionsSpec")
  implicit private val contextShift: ContextShift[IO] = IO.contextShift(system.dispatcher)

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

  "A Projection" should {
    val id            = genString()
    val persistenceId = s"/some/${genString()}"
    val projections   = memoize(Projections[IO, SomeEvent]).unsafeRunSync()
    val progress      = OffsetProgress(Offset.sequence(42), 42, 42, 0)

    "store progress" in {
      projections.ioValue.recordProgress(id, progress).ioValue
    }

    "retrieve stored progress" in {
      projections.ioValue.progress(id).ioValue shouldEqual progress
    }

    "retrieve NoProgress for unknown projections" in {
      projections.ioValue.progress(genString()).ioValue shouldEqual NoProgress
    }

    val firstOffset: Offset  = Offset.sequence(42)
    val secondOffset: Offset = Offset.sequence(98)
    val firstEvent           = SomeEvent(1L, "description")
    val secondEvent          = SomeEvent(2L, "description2")

    "store an event" in {
      projections.ioValue.recordFailure(id, persistenceId, 1L, firstOffset, firstEvent).ioValue
    }

    "store another event" in {
      projections.ioValue.recordFailure(id, persistenceId, 2L, secondOffset, secondEvent).ioValue
    }

    "retrieve stored events" in {
      val expected = Seq((firstEvent, firstOffset), (secondEvent, secondOffset))
      eventually {
        logOf(projections.ioValue.failures(id)) should contain theSameElementsInOrderAs expected
      }
    }

    "retrieve empty list of events for unknown failure log" in {
      eventually {
        logOf(projections.ioValue.failures(genString())) shouldBe empty
      }
    }

  }

  private def logOf(source: Source[(SomeEvent, Offset), _]): Vector[(SomeEvent, Offset)] = {
    val f = source.runFold(Vector.empty[(SomeEvent, Offset)])(_ :+ _)
    IO.fromFuture(IO(f)).ioValue
  }

  implicit override def patienceConfig: PatienceConfig =
    PatienceConfig(30.seconds, 50.milliseconds)
}

object ProjectionsSpec {
  final case class SomeEvent(rev: Long, description: String)
} 
Example 7
Source File: JUnitCustomRouteTestKit.scala    From squbs   with Apache License 2.0 5 votes vote down vote up
package org.squbs.testkit.japi

import akka.actor.ActorSystem
import akka.http.javadsl.testkit.ActorSystemResource
import akka.stream.ActorMaterializer
import akka.testkit.TestKitBase
import com.typesafe.config.Config
import org.junit.Rule
import org.squbs.testkit.{DebugTiming, PortGetter, CustomTestKit => SCustomTestKit}
import org.squbs.unicomplex.UnicomplexBoot

import scala.collection.JavaConverters._

abstract class JUnitCustomRouteTestKit(val boot: UnicomplexBoot) extends {
  implicit override val system: ActorSystem = boot.actorSystem
} with akka.http.javadsl.testkit.JUnitRouteTest with TestKitBase
  with RouteDefinitionTest with DebugTiming with PortGetter {

  private[this] val _systemResource = new CustomTestKitActorSystemResource(boot)

  @Rule
  override protected def systemResource: ActorSystemResource = _systemResource


  def this() {
    this(SCustomTestKit.boot())
  }

  def this(config: Config) {
    this(SCustomTestKit.boot(config = Option(config)))
  }

  def this(withClassPath: Boolean) {
    this(SCustomTestKit.boot(withClassPath = Option(withClassPath)))
  }

  def this(resources: java.util.List[String], withClassPath: Boolean) {
    this(SCustomTestKit.boot(resources = Option(resources.asScala), withClassPath = Option(withClassPath)))
  }

  def this(config: Config, resources: java.util.List[String], withClassPath: Boolean) {
    this(SCustomTestKit.boot(config = Option(config), resources = Option(resources.asScala),
      withClassPath = Option(withClassPath)))
  }
}

class CustomTestKitActorSystemResource(boot: UnicomplexBoot)
    extends ActorSystemResource(boot.actorSystem.name, boot.config) {
  override protected def config: Config = boot.config
  override protected def createSystem(): ActorSystem = boot.actorSystem
  override protected def createMaterializer(system: ActorSystem): ActorMaterializer = ActorMaterializer()(system)
} 
Example 8
Source File: TestNGCustomRouteTestKit.scala    From squbs   with Apache License 2.0 5 votes vote down vote up
package org.squbs.testkit.japi

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.testkit.TestKitBase
import com.typesafe.config.Config
import org.squbs.testkit.{DebugTiming, PortGetter, CustomTestKit => SCustomTestKit}
import org.squbs.unicomplex.UnicomplexBoot

import scala.collection.JavaConverters._

abstract class TestNGCustomRouteTestKit(val boot: UnicomplexBoot) extends {
  implicit override val system: ActorSystem = boot.actorSystem
} with TestNGRouteTest with TestKitBase with DebugTiming with PortGetter {

  private[this] val _systemResource = new CustomTestKitSystemResource(boot)

  override protected def systemResource: SystemResource = _systemResource

  def this() {
    this(SCustomTestKit.boot())
  }

  def this(config: Config) {
    this(SCustomTestKit.boot(config = Option(config)))
  }

  def this(withClassPath: Boolean) {
    this(SCustomTestKit.boot(withClassPath = Option(withClassPath)))
  }

  def this(resources: java.util.List[String], withClassPath: Boolean) {
    this(SCustomTestKit.boot(resources = Option(resources.asScala), withClassPath = Option(withClassPath)))
  }

  def this(config: Config, resources: java.util.List[String], withClassPath: Boolean) {
    this(SCustomTestKit.boot(config = Option(config), resources = Option(resources.asScala),
      withClassPath = Option(withClassPath)))
  }
}

class CustomTestKitSystemResource(boot: UnicomplexBoot)
  extends SystemResource(boot.actorSystem.name, boot.config) {
    override protected def config: Config = boot.config
    override protected def createSystem(): ActorSystem = boot.actorSystem
    override protected def createMaterializer(system: ActorSystem): ActorMaterializer = ActorMaterializer()(system)
  } 
Example 9
Source File: DebugTiming.scala    From squbs   with Apache License 2.0 5 votes vote down vote up
package org.squbs.testkit

import akka.testkit.TestKitBase

import scala.concurrent.duration._

object DebugTiming {

  val debugMode = java.lang.management.ManagementFactory.getRuntimeMXBean.
    getInputArguments.toString.indexOf("jdwp") >= 0

  val debugTimeout = 10000.seconds

  if (debugMode) println(
    "\n##################\n" +
      s"IMPORTANT: Detected system running in debug mode. Test timeouts overridden to $debugTimeout.\n" +
      "##################\n\n")
}

trait DebugTiming extends TestKitBase {
  import DebugTiming._
  override def receiveOne(max: Duration): AnyRef =
    if (debugMode) super.receiveOne(debugTimeout)
    else super.receiveOne(max)
} 
Example 10
Source File: CustomRouteTestKit.scala    From squbs   with Apache License 2.0 5 votes vote down vote up
package org.squbs.testkit

import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.testkit.TestKitBase
import com.typesafe.config.Config
import org.scalatest.Suite
import org.squbs.lifecycle.GracefulStop
import org.squbs.unicomplex.{Unicomplex, UnicomplexBoot}

abstract class CustomRouteTestKit(val boot: UnicomplexBoot) extends {
  implicit override val system = boot.actorSystem
} with TestKitBase with Suite with ScalatestRouteTest with DebugTiming with PortGetter {

  def this() {
    this(CustomTestKit.boot())
  }

  def this(actorSystemName: String) {
    this(CustomTestKit.boot(Option(actorSystemName)))
  }

  def this(config: Config) {
    this(CustomTestKit.boot(config = Option(config)))
  }

  def this(resources: Seq[String], withClassPath: Boolean) {
    this(CustomTestKit.boot(resources = Option(resources), withClassPath = Option(withClassPath)))
  }

  def this(actorSystemName: String, resources: Seq[String], withClassPath: Boolean) {
    this(CustomTestKit.boot(Option(actorSystemName), resources = Option(resources), withClassPath = Option(withClassPath)))
  }

  def this(config: Config, resources: Seq[String], withClassPath: Boolean) {
    this(CustomTestKit.boot(config = Option(config), resources = Option(resources), withClassPath = Option(withClassPath)))
  }

  override protected def beforeAll(): Unit = {
    CustomTestKit.checkInit(system)
  }

  override protected def afterAll(): Unit = {
    Unicomplex(system).uniActor ! GracefulStop
  }
} 
Example 11
Source File: ControllerSpec.scala    From akka-ddd-cqrs-es-example   with MIT License 5 votes vote down vote up
package com.github.j5ik2o.bank.adaptor.util

import akka.http.scaladsl.model.{ HttpEntity, MediaTypes }
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.testkit.TestKitBase
import akka.util.ByteString
import com.github.j5ik2o.scalatestplus.db.{ MySQLdConfig, UserWithPassword }
import com.wix.mysql.distribution.Version.v5_6_21
import io.circe.Encoder
import io.circe.syntax._
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.prop.PropertyChecks
import org.scalatest.time.{ Millis, Seconds, Span }
import org.scalatest.{ BeforeAndAfterAll, FreeSpecLike, Matchers }

import scala.concurrent.duration._

object ControllerSpec {

  implicit class JsonOps[A](val self: A) extends AnyVal {
    def toEntity(implicit enc: Encoder[A]): HttpEntity.Strict =
      HttpEntity(MediaTypes.`application/json`, ByteString(self.asJson.noSpaces))
  }

}

abstract class ControllerSpec
    extends FreeSpecLike
    with PropertyChecks
    with Matchers
    with BeforeAndAfterAll
    with ScalaFutures
    with FlywayWithMySQLSpecSupport
    with ScalatestRouteTest
    with TestKitBase {
  override implicit val patienceConfig: PatienceConfig =
    PatienceConfig(timeout = Span(10, Seconds), interval = Span(200, Millis))

  override def afterAll: Unit = cleanUp()

  override protected lazy val mySQLdConfig: MySQLdConfig = MySQLdConfig(
    version = v5_6_21,
    port = Some(12345),
    userWithPassword = Some(UserWithPassword("bank", "passwd")),
    timeout = Some((30 seconds) * sys.env.getOrElse("SBT_TEST_TIME_FACTOR", "1").toDouble)
  )

} 
Example 12
Source File: ExecutorServiceBase.scala    From sparkplug   with MIT License 5 votes vote down vote up
package springnz.sparkplug

import akka.actor._
import akka.testkit.TestKitBase
import springnz.sparkplug.core.{ Configurer, LocalConfigurer }
import springnz.sparkplug.executor.ExecutorService
import springnz.sparkplug.executor.MessageTypes._

import scala.concurrent.Promise

trait ExecutorServiceBase { self: TestKitBase ⇒

  class ExecutorServiceFixture(probe: ActorRef, clientName: String, brokerName: String) {

    val readyPromise = Promise[Unit]

    val executorService = new ExecutorService("TestService", brokerName) {
      // Run it locally in Spark
      override val configurer: Configurer = new LocalConfigurer("TestService", None)
    }

    val clientActor = system.actorOf(Props(new Actor {
      override def receive = {
        case ServerReady ⇒
          probe forward ServerReady
          sender ! ClientReady
          readyPromise.success(())
      }
    }), clientName)

    executorService.start(system, s"/user/$clientName")
  }

}