Hey i want to build some small Funsuite test for akka actor application but after combining Testkit with FunSuiteLike i cant call th test anymore.
Somebody an idea why this is happening? is Testkit and funsuite not compatible?
import org.scalatest.{FunSuiteLike, BeforeAndAfterAll}
import akka.testkit.{ImplicitSender, TestKit, TestActorRef}
import akka.actor.{ActorSystem}
class ActorSynchroTest(_system: ActorSystem) extends TestKit(_system) with FunSuiteLike with BeforeAndAfterAll with ImplicitSender{
val actorRef = TestActorRef(new EbTreeDatabase[Int])
val actor = actorRef.underlyingActor
//override def afterAll = TestKit.shutdownActorSystem( system )
test("EbTreeDatabase InsertNewObject is invoked"){
val idList = List(1024L,1025L,1026L,1032L,1033L,1045L,1312L,1800L)
idList.
foreach(x => actorRef ! EbTreeDataObject[Int](x,x,1,None,null))
var cursor:Long = actor.uIdTree.firstKey()
var actorItems:List[Long] = List(cursor)
while(cursor!=actor.uIdTree.lastKey()){
cursor = actor.uIdTree.next(cursor)
cursor :: actorItems
}
assert(idList.diff(actorItems) == List())
}
}
The intelliJ idea test enviroment says:
One or more requested classes are not Suites: model.ActorSynchroTest
class ActorSynchroTest extends TestKit(ActorSystem("ActorSynchroTest",ConfigFactory.parseString(ActorSynchroTest.config)))
with DefaultTimeout with ImplicitSender
with FunSuiteLike with Matchers with BeforeAndAfterAll {
...
}
object ActorSynchroTest {
// Define your test specific configuration here
val config = """
akka {
loglevel = "WARNING"
}
"""
}
Different initialization of the testkit worked in the end before the standard config was used which didn't fit
Related
I have a controller that looks like:
class LoginController #Inject()(cc: ControllerComponents)
(implicit ec: ExecutionContext, assetsFinder: AssetsFinder)
I would like to write a unit test for that controller, but I need something to mock the assetsFinder dependency:
class LoginControllerSpec extends PlaySpec with Results with GuiceOneAppPerSuite {
"something to test" should {
"behave as expected" in {
val controller = new LoginController(stubControllerComponents())(???)
}
}
}
How can I mock that dependency?
You can try something like:
class LoginControllerSpec extends PlaySpec with Results with GuiceOneAppPerSuite with MockitoSugar {
"something to test" should {
"behave as expected" in {
val mockControllerComponents = mock[ControllerComponents]
implicit val mockAssetsFinder = mock[AssetsFinder]
implicit val ec = scala.concurrent.ExecutionContext.global
val controller = new LoginController(mockControllerComponents)
// asserts here
}
}
}
MockitoSugar was part of scalatest up to version 3.0.8 . If you are using a newer version, you need to import:
"org.scalatestplus" %% "mockito-3-2" % "3.1.1.0",
or any other version that works for you from scalatestplus-mockito. If you are using scalatestplus-playm please read Using MockitoSugar of scalatestplus-play deprecated.
In "Dependency Injecting Actors" it's shown how to inject a parameter into the constructor of a child actor. The parent actor uses injectedChild to be allowed to pass to the child (at child creation time) only the non-injected parameter and then let Guice inject the rest. To do this, it extends InjectedActorSupport and gets the child's factory injected in the constructor:
class MyParent #Inject() (childFactory: MyChild.Factory,
#Assisted something: Something,
#Assisted somethingElse: SomethingElse) extends Actor with InjectedActorSupport
[..]
val child: ActorRef = injectedChild(childFactory(something, somethingElse), childName)
But what about the class that starts the parent and is not an actor but a custom ApplicationLoader?
How can I start the parent actor from there? No mention of this is in the documentation.
I tried doing the same for the loader as I did for parent:
class MyLoader #Inject() (parentFactory: MyParent.Factory) extends ApplicationLoader with Actor with InjectedActorSupport {
[..]
val parent = injectedChild(parentFactory(something, somethingElse), parentName)
would this be correct? How can I test it?
class MyModule extends AbstractModule with AkkaGuiceSupport {
def configure = {
bindActor[MyParent](parentName)
bindActor[MyLoader](loaderName)
bindActorFactory[MyChild, MyChild.Factory]
bindActorFactory[MyParent, MyParent.Factory]
}
}
So:
How do I start the parent from MyLoader while letting Guice dependency-inject what's required?
How can I test MyLoader?
This has been my test so far but now I need to pass the injected thingy to MyLoader and I don't know how (note the ***???**** in place of the argument which I do not know where to find):
class MyLoaderSpec(_system: ActorSystem, implicit val ec: ExecutionContext) extends TestKit(_system) with WordSpecLike with BeforeAndAfterAll with Matchers {
val loader = new SimstimLoader(???)
override def beforeAll(): Unit = {
loader.load(ApplicationLoader.createContext(new Environment(new File("."), ApplicationLoader.getClass.getClassLoader, Mode.Test)))
}
Thanks a million in advance!
Here is how I solved this issue.
--> How to start a parent actor who needs dependency-injection.
First of all, manually starting such an actor is impossible if you, like me, need to dependency-inject an instance which you do not know how to pass and where from. The solution is to let Guice start the actor automagically. Here is how.
First, create your binder module for Guice:
class MyModule extends AbstractModule with AkkaGuiceSupport{
override def configure(): Unit = {
bindActor[Root](Root.NAME)
bind(classOf[StartupActors]).asEagerSingleton()
}
}
Then, tell Play where your binder module is located by adding the following in your conf/application.conf:
play.modules={
enabled += "my.path.to.MyModule"
}
The StartupActors is simply a class I use to log whenever the automagic start of dependency-injected actors actually takes place. I log the event so that I can be sure of when and whether it occurs:
class StartupActors #Inject() (#Named(Root.NAME) root: ActorRef) {
play.api.Logger.info(s"Initialised $root")
}
The Root actor in my case takes care of parsing a custom configuration. Since the resulting vars from the parsing is required by my parent actor and during the tests I need to mock such resulting vars, I delegate the parsing to an actor other than the parent actor, i.e., the Root actor:
object Root {
final val NAME = "THERoot"
case class ParseConfiguration()
}
class Root #Inject()(configuration: Configuration, projectDAO: ProjectDAO) extends Actor {
val resultingVar: Something = myConfigParsing()
override def preStart(): Unit = {
context.actorOf(Props(new MyParent(resultingVar: Something, somethingElse: SomethingElse, projectDAO: ProjectDAO)))
}
override def receive: Receive = {
case ParseConfiguration => sender ! myConfigParsing()
case _ => logger.error("Root actor received an unsupported message")
}
}
The ParseConfiguration message is used uniquely for testing purposes. Normally the configuration parsing occurs instead because of the initialisation of the resultingVar attribute.
This way, MyParent wont need to get anything injected. Only StartupActors and Root will get injected. MyParent will simply get projectDAO from Root and pass it on to all its children.
class MyParent(something: Something, somethingElse: SomethingElse, projectDAO: ProjectDAO) extends Actor { ... }
Finally, for completion, I'm reporting here how I wrote the tests since I had troubles finding enough information online around this as well.
import akka.actor.{ActorRef, ActorSystem, Props}
import akka.testkit.{TestKit, TestProbe}
import com.typesafe.config.ConfigFactory
import org.mockito.Mockito.mock
import org.scalatest.{BeforeAndAfterAll, WordSpecLike}
import org.specs2.matcher.MustMatchers
import play.api.Configuration
import scala.concurrent.ExecutionContext
class RootSpec(_system: ActorSystem) extends TestKit(_system)
with WordSpecLike with BeforeAndAfterAll with MustMatchers {
implicit val ec: ExecutionContext = scala.concurrent.ExecutionContext.global
val conf: com.typesafe.config.Config = ConfigFactory.load()
val configuration: Configuration = Configuration(conf)
val projectDAOMock: ProjectDAO = mock(classOf[ProjectDAO])
private var mainActor: ActorRef = _
private var something: Something = Something.empty
def this() = this(ActorSystem("MySpec"))
override def afterAll: Unit = {
system.shutdown()
}
override def beforeAll(): Unit = {
mainActor = system.actorOf(Props(new Root(configuration, projectDAOMock)), Root.NAME)
}
"RootSpec: Root Actor" should {
val probe = TestProbe()
"successfully parse the configuration file" in {
probe.send(mainActor, ParseConfiguration)
something = probe.expectMsgPF() {
case msg => msg.asInstanceOf[Something]
}
}
}
}
and then I test MyParent by conveniently providing mock objects in place of vars resulting from the configuration parsing:
import akka.actor.{ActorRef, ActorSystem, Props}
import akka.testkit.{TestKit, TestProbe}
import org.mockito.Mockito
import org.mockito.Mockito._
import org.scalatest.{BeforeAndAfterAll, WordSpecLike}
import org.specs2.matcher.MustMatchers
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{ExecutionContext, Future}
case class AnyProjectAPI(val projectAPI: ProjectAPI) extends AnyVal
class MyParentSpec(_system: ActorSystem, implicit val ec: ExecutionContext) extends TestKit(_system)
with WordSpecLike with BeforeAndAfterAll with MustMatchers {
val something = mock(classOf[Something])
val somethingElse = mock(classOf[somethingElse])
val projectDAOMock: ProjectDAO = mock(classOf[ProjectDAO])
val projectTest: ProjectAPI = new ProjectAPI(allMyRandomConstructorArguments),
val projectsList: List[ProjectAPI] = List(projectTest)
val expectedCreationId = 1
private var parent: ActorRef = _
def this() = this(ActorSystem("MySpec"), scala.concurrent.ExecutionContext.global)
override def afterAll: Unit = {
system.shutdown()
}
override def beforeAll(): Unit = {
parent = system.actorOf(Props(new MyParent(something, somethingElse, projectDAOMock)), MyParent.NAME)
}
"MyParentTesting: parent's pull request" should {
when(myProjApi.getAllProjects).thenReturn(Future {projectsList})
val anyProject: AnyProjectAPI = AnyProjectAPI(org.mockito.Matchers.any[ProjectAPI])
Mockito.when(projectDAOMock.create(org.mockito.Matchers.any[ProjectAPI]))
.thenReturn(Future {expectedCreationId}: Future[Int])
val probe = TestProbe()
val probe1 = TestProbe()
"be successfully satisfied by all children when multiple senders are waiting for an answer" in {
probe.send(parent, UpdateProjects)
probe1.send(parent, UpdateProjects)
allChildren.foreach(child =>
probe.expectMsg(expectedCreationId))
allChildren.foreach(child =>
probe1.expectMsg(expectedCreationId))
}
}
}
I'm using scalatest_2.11 version 2.2.1. I'm trying to write test that run on a SparkContext. How can I initiate a SparkContext when the tests begin, take this Sc thorugh all the tests and then stop it when they are all done?
(I know that it suppose to stop by itself, but I'sd still like to do it myself)
You can use BeforeAndAfterAll from ScalaTest. Define a base trait that starts and stops the SparkContext and use it with your other tests.
trait SparkTest extends BeforeAndAfterAll {
self: Suite =>
#transient var sc: SparkContext = _
override def beforeAll {
val conf = new SparkConf().
setMaster("local[*]").
setAppName("test")
sc = new SparkContext(conf)
super.beforeAll()
}
override def afterAll: Unit = {
try {
sc.stop()
} finally {
super.afterAll
}
}
}
// Mix-in the trait with your tests like below.
class MyTest extends FunSuite with SparkTest {
test("my test") {
// you can access "sc" here.
}
}
I want to use Akka scheduler to do some cron jobs in my Play application.
Since Play 2.4 GlobalSettings is not recommended. Anyone has some sample code on how to do that?
Even I tried the simple code from Play docs and it still not working.
class CustomApplicationLoader extends GuiceApplicationLoader() {
val logger: Logger = Logger(this.getClass)
override def builder(context: ApplicationLoader.Context): GuiceApplicationBuilder = {
logger.info("start")
val extra = Configuration("a" -> 1)
initialBuilder
.in(context.environment)
.loadConfig(extra ++ context.initialConfiguration)
.overrides(overrides(context): _*)
}
}
play.application.loader = "com.xxx.CustomApplicationLoader"
Why I can't get the logging message to print?
How I can use Akka on Application start?
This is how do it in my app:
Start of by defining a trait Scheduled.
package scheduled
import akka.actor.Cancellable
trait Scheduled {
var cancellable: Option[Cancellable] = None
val defaultInterval = 60
val secondsToWait = {
import scala.concurrent.duration._
10 seconds
}
def start()
def stop() = {
cancellable.map(_.cancel())
}
}
Then implement Scheduled with Akka magic
package scheduled
import akka.actor.ActorSystem
import play.api.{Configuration, Logger}
import com.google.inject.{Singleton, Inject}
import play.api.libs.concurrent.Execution.Implicits._
trait ScheduledWorker extends Scheduled
#Singleton
class ScheduledWorkerImpl #Inject()(
actorSystem: ActorSystem,
configuration: Configuration
) extends ScheduledWorker {
start()
lazy val intervalKey = "worker.interval"
lazy val jobEnabled = "worker.enabled"
override def start(): Unit = {
import scala.concurrent.duration._
lazy val i = configuration.getInt(intervalKey).getOrElse(defaultInterval)
lazy val isEnabled = Option(System.getProperty(jobEnabled)).getOrElse(
configuration.getString(jobEnabled).getOrElse("false")
).equals("true")
cancellable = isEnabled match {
case true =>
Some(
actorSystem.scheduler.schedule(0 seconds, i minutes) {
.. MAJOR COOL CODE!!! ;))) ...
}
)
case _ => None
}
}
}
create a module to eagerly start the scheduled stuff
package modules
import play.api.{Configuration, Environment}
import play.api.inject.Module
import scheduled.{ScheduledWorker}
class ScheduledModule extends Module {
def bindings(environment: Environment,
configuration: Configuration) = Seq(
bind[ScheduledWorker].to[ScheduledWorkerImpl].eagerly()
)
}
make sure that your config specifies ScheduledModule.
play.modules.enabled += "modules.ScheduledModule"
And voila you have a working scheduled task when your play 2.4 app starts =)
I am new to Scala Akka actor. Based on the akka tutorial example on their website,i coded a similar example with just printing messages with the time they started. But the code does not get executed in my eclipse IDE.
import akka.actor.Actor
import akka.actor.ActorRef
import scala.collection.mutable.ListBuffer
import akka.actor.Props
import akka.routing.RoundRobinRouter
import akka.actor.ActorSystem
object AkaObj extends App{
process()
sealed trait PiMessage
case class Work(value:String) extends PiMessage
case class printComp(valu:String)extends PiMessage
case object Start extends PiMessage
case class ListObj(cont:Seq[String]) extends PiMessage
class Worker extends Actor{
def receive()={
case Work(value:String)=>
println(value)
sender ! printComp(value)
}
}
class Master(listener: ActorRef) extends Actor{
val nrOfWorkers = 10
var counter = 0
var lis = ListBuffer[String]()
val workerRouter = context.actorOf(
Props[Worker].withRouter(RoundRobinRouter(nrOfWorkers)), name = "workerRouter")
def receive()={
//handle message
case Start=>workerRouter ! Work("Start now " + System.currentTimeMillis())
case printComp(value:String)=> {
counter+=1
lis.append(counter+"-"+value)
if(counter >=10)
listener ! ListObj(lis.toSeq)
// Stops this actor and all its supervised children
context.stop(self)
}
}
}
class Listener extends Actor{
def receive()={
case ListObj(cont:Seq[String])=>
println("Completed " +cont)
context.system.shutdown()
}
}
def process(){
// Create an Akka system
val system = ActorSystem("PiSystem")
// create the result listener, which will print the result and shutdown the system
val listener = system.actorOf(Props[Listener], name = "listener")
// create the master
val master = system.actorOf(Props(new Master(listener)),
name = "master")
// start the calculation
master ! Start
}
}
Issue: The error message i get is: "Error: Could not find or load main class AkaObj"
It does not even compiling i think. When i run the project,that's the message i get.
Actually, I managed to run your code just after dependencies were resolved. So the problem is in your environment configuration. I use Intellij Idea IDE.
Try this Eclipse Error: Could not find or load main class
The actual problem is the use of object AkaObj extends App. When programming scala I have noticed that using scala.App is restricted to simple programs (at least in IDEs). As soon as you start defining objects and classes inside scala.App Eclipse starts complaining about not finding the entry point of the program.
Try to fix this as follows:
import akka.actor.Actor
import akka.actor.ActorRef
import scala.collection.mutable.ListBuffer
import akka.actor.Props
import akka.routing.RoundRobinRouter
import akka.actor.ActorSystem
object AkaObj {
def main(args:Array[String]) {
process()
}
def process() {
// Create an Akka system
val system = ActorSystem("PiSystem")
// create the result listener, which will print the result and shutdown the system
val listener = system.actorOf(Props[Listener], name = "listener")
// create the master
val master = system.actorOf(Props(new Master(listener)),
name = "master")
// start the calculation
master ! Start
}
sealed trait PiMessage
case class Work(value:String) extends PiMessage
case class printComp(valu:String)extends PiMessage
case object Start extends PiMessage
case class ListObj(cont:Seq[String]) extends PiMessage
class Worker extends Actor{
def receive()={
case Work(value:String)=>
println(value)
sender ! printComp(value)
}
}
class Master(listener: ActorRef) extends Actor{
val nrOfWorkers = 10
var counter = 0
var lis = ListBuffer[String]()
val workerRouter = context.actorOf(
Props[Worker].withRouter(RoundRobinRouter(nrOfWorkers)), name = "workerRouter")
def receive()={
//handle message
case Start=>workerRouter ! Work("Start now " + System.currentTimeMillis())
case printComp(value:String)=> {
counter+=1
lis.append(counter+"-"+value)
if(counter >=10)
listener ! ListObj(lis.toSeq)
// Stops this actor and all its supervised children
context.stop(self)
}
}
}
class Listener extends Actor{
def receive()={
case ListObj(cont:Seq[String])=>
println("Completed " +cont)
context.system.shutdown()
}
}
}
Using def main(args:Array[String]) fixes the problem in most cases.