Skip to content

Commit

Permalink
Spec for TemplateActor
Browse files Browse the repository at this point in the history
  • Loading branch information
anistal authored and Sergio Gomez committed Oct 21, 2015
1 parent e29c9f3 commit d422cb4
Show file tree
Hide file tree
Showing 4 changed files with 189 additions and 32 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,6 @@ object FragmentActor {

case class Response(status: Try[_])


def fragmentPath(fragmentType: String): String = {
fragmentType match {
case "input" => s"${AppConstant.BaseZKPath}/fragments/input"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package com.stratio.sparkta.serving.api.actor

import java.io.{File, InputStreamReader}
import java.net.{URI, URL}

import akka.actor.Actor
import akka.event.slf4j.SLF4JLogging
Expand All @@ -28,9 +29,6 @@ import spray.httpx.Json4sJacksonSupport

import scala.util.Try

/**
* Implementation of supported CRUD operations over templates used to composite a policy.
*/
class TemplateActor extends Actor with Json4sJacksonSupport with SLF4JLogging with SparktaSerializer {

override def receive: Receive = {
Expand All @@ -41,27 +39,35 @@ class TemplateActor extends Actor with Json4sJacksonSupport with SLF4JLogging wi

def doFindByType(t: String): Unit =
sender ! ResponseTemplates(Try({
new File(this.getClass.getClassLoader.getResource(s"templates/${t}").toURI)
.listFiles
getFilesFromURI(getResource(s"templates/${t}").toURI)
.filter(file => file.getName.endsWith(".json"))
.map(file => {
log.info(s"> Retrieving template: ${file.getName}")
read[TemplateModel](new InputStreamReader(
this.getClass.getClassLoader.getResourceAsStream(s"templates/${t}/${file.getName}")))
}).toSeq
log.info(s"> Retrieving template: ${file.getName}")
read[TemplateModel](getInputStreamFromResource(s"templates/${t}/${file.getName}"))
})
}).recover {
case e: NullPointerException => Seq()
})

def doFindByTypeAndName(t: String, name: String): Unit =
sender ! ResponseTemplate(Try({
read[TemplateModel](new InputStreamReader(
this.getClass.getClassLoader.getResourceAsStream(s"templates/${t}/${name.toLowerCase}.json")))
read[TemplateModel](getInputStreamFromResource(s"templates/${t}/${name.toLowerCase}.json"))
}).recover {
case e: NullPointerException => throw new ServingApiException(ErrorModel.toString(
new ErrorModel(ErrorModel.CodeNotExistsTemplatetWithName, s"No template of type $t with name ${name}.json")
))
})

// XXX Protected methods
protected def getResource(resource: String): URL =
this.getClass.getClassLoader.getResource(resource)

protected def getInputStreamFromResource(resource: String): InputStreamReader =
new InputStreamReader(this.getClass.getClassLoader.getResourceAsStream(resource))

protected def getFilesFromURI(uri: URI): Seq[File] =
new File(uri).listFiles

}

object TemplateActor {
Expand All @@ -73,5 +79,4 @@ object TemplateActor {
case class ResponseTemplates(templates: Try[Seq[TemplateModel]])

case class ResponseTemplate(template: Try[TemplateModel])

}
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,31 @@ with MockitoSugar with SparktaSerializer {
| }
|}
""".stripMargin
val otherFragment =
"""
|{
| "id": "id2",
| "fragmentType": "input",
| "name": "inputname",
| "description": "input description",
| "shortDescription": "input description",
| "element": {
| "name": "input",
| "type": "input",
| "configuration": {
| "configKey": "configValue"
| }
| }
|}
""".stripMargin

val fragmentElementModel = read[FragmentElementModel](fragment)

val curatorFramework = mock[CuratorFramework]
val getChildrenBuilder = mock[GetChildrenBuilder]
val getDataBuilder = mock[GetDataBuilder]
val existsBuilder = mock[ExistsBuilder]
val createBuilder = mock[CreateBuilder]
val deleteBuilder = mock[DeleteBuilder]
val protectedACL = mock[ProtectACLCreateModePathAndBytesable[String]]
val setDataBuilder = mock[SetDataBuilder]
val fragmentActor = system.actorOf(Props(new FragmentActor(curatorFramework)))
Expand Down Expand Up @@ -265,11 +282,69 @@ with MockitoSugar with SparktaSerializer {
when(curatorFramework.getChildren
.forPath("/stratio/sparkta/fragments/input"))
.thenReturn(util.Arrays.asList("id"))
when(curatorFramework.getData)
.thenReturn(getDataBuilder)
when(curatorFramework.getData
.forPath("/stratio/sparkta/fragments/input/id"))
.thenReturn(otherFragment.getBytes)

fragmentActor ! FragmentActor.Update(fragmentElementModel)

expectMsgAnyClassOf(classOf[FragmentActor.Response])
}

}
"update: tries to update a fragment but it is impossible because the fragment does not exist" in new TestData {
when(curatorFramework.checkExists())
.thenReturn(existsBuilder)
when(curatorFramework.checkExists()
.forPath("/stratio/sparkta/fragments/input"))
.thenReturn(new Stat())
when(curatorFramework.getChildren)
.thenReturn(getChildrenBuilder)
when(curatorFramework.getChildren
.forPath("/stratio/sparkta/fragments/input"))
.thenReturn(util.Arrays.asList("id"))
when(curatorFramework.getData)
.thenReturn(getDataBuilder)
when(curatorFramework.getData
.forPath("/stratio/sparkta/fragments/input/id"))
.thenReturn(fragment.getBytes)

when(curatorFramework.setData)
.thenReturn(setDataBuilder)
when(curatorFramework.setData
.forPath("/stratio/sparkta/fragments/input/element"))
.thenThrow(new NoNodeException)

fragmentActor ! FragmentActor.Update(fragmentElementModel)

expectMsgAnyClassOf(classOf[FragmentActor.Response])
}

// XXX deleteByTypeAndId
"deleteByTypeAndId: deletes a fragment by its type and its id" in new TestData {
// scalastyle:off null
when(curatorFramework.delete)
.thenReturn(deleteBuilder)
when(curatorFramework.delete
.forPath("/stratio/sparkta/fragments/input/id"))
.thenReturn(null)

fragmentActor ! FragmentActor.DeleteByTypeAndId("input", "id")

expectMsg(new Response(Success(null)))
// scalastyle:on null
}

"deleteByTypeAndId: deletes a fragment but it is impossible because the fragment does not exists" in new TestData {
when(curatorFramework.delete)
.thenReturn(deleteBuilder)
when(curatorFramework.delete
.forPath("/stratio/sparkta/fragments/input/id"))
.thenThrow(new NoNodeException)

fragmentActor ! FragmentActor.DeleteByTypeAndId("input", "id")

expectMsgAnyClassOf(classOf[FragmentActor.Response])
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,36 +16,114 @@

package com.stratio.sparkta.serving.api.actor

import java.io.{File, InputStreamReader}
import java.net.{URI, URL}

import akka.actor.{ActorSystem, Props}
import akka.testkit.{DefaultTimeout, ImplicitSender, TestKit}
import com.stratio.sparkta.serving.api.actor.TemplateActor
import com.stratio.sparkta.serving.api.actor.TemplateActor.FindByType
import com.stratio.sparkta.serving.api.exception.ServingApiException
import com.stratio.sparkta.serving.core.models.{ErrorModel, SparktaSerializer, TemplateModel}
import org.apache.commons.io.IOUtils
import org.json4s.jackson.Serialization._
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

import scala.util.Success

@RunWith(classOf[JUnitRunner])
class TemplateActorSpec extends TestKit(ActorSystem("TemplateActorSpec"))
with DefaultTimeout
with ImplicitSender
with WordSpecLike
with Matchers
with BeforeAndAfterAll {
with DefaultTimeout
with ImplicitSender
with WordSpecLike
with Matchers
with BeforeAndAfterAll
with MockitoSugar with SparktaSerializer {

trait TestData {

val templateModelJson =
"""
{
| "name": "templateName",
| "modelType": "input",
| "description": {
| "short": "short"
| },
| "icon": {
| "url": "logo.png"
| },
| "properties": [
| {
| "propertyId": "templatePropertyId",
| "propertyName": "templatePropertyName",
| "propertyType": "templatePropertyType",
| "regexp": "*",
| "default": "localhost:2181",
| "required": true,
| "tooltip": ""
| }
| ]
|}
""".stripMargin

val servingApiException = new ServingApiException(
ErrorModel.toString(
new ErrorModel(ErrorModel.CodeNotExistsTemplatetWithName,
"No template of type input with name templateName.json")))

val templateModel = read[TemplateModel](templateModelJson)

val templateActor = system.actorOf(Props(new TemplateActor() {
override protected def getResource(resource: String): URL =
new File("file.json").toURI.toURL

override protected def getInputStreamFromResource(resource: String): InputStreamReader =
new InputStreamReader(IOUtils.toInputStream(templateModelJson))

override protected def getFilesFromURI(uri: URI): Seq[File] =
Seq(new File("file.json"))
}))

val wrongTemplateActor = system.actorOf(Props(new TemplateActor() {
override protected def getInputStreamFromResource(resource: String): InputStreamReader =
throw new NullPointerException("expected null pointer exception")

val templateActor = system.actorOf(Props(classOf[TemplateActor]))
override protected def getResource(resource: String): URL =
throw new NullPointerException("expected null pointer exception")
}))

override def afterAll {
shutdown()
}

override def afterAll: Unit = shutdown()

"TemplateActor" must {

// XXX findByType
"findByType: returns all templates by type" in new TestData {
templateActor ! TemplateActor.FindByType("input")

expectMsg(new TemplateActor.ResponseTemplates(Success(Seq(templateModel))))
}

"findByType: return a empty list when a null pointer exception is thrown" in new TestData {
wrongTemplateActor ! TemplateActor.FindByType("input")

expectMsg(new TemplateActor.ResponseTemplates(Success(Seq())))
}

// XXX findByTypeAndName
"findByTypeAndName: returns all templates by type and name" in new TestData {
templateActor ! TemplateActor.FindByTypeAndName("input", "templateName")

expectMsg(new TemplateActor.ResponseTemplate(Success(templateModel)))
}

"A template actor" must {
"findByTypeAndName: return a empty list when a null pointer exception is thrown" in new TestData {
wrongTemplateActor ! TemplateActor.FindByTypeAndName("input", "templateName")

"return to the sender a full list of existing templates depending ot its type" in {
//within(500 millis) {
templateActor ! FindByType("input")
//expectMsg("hello world")
//}
expectMsgAnyClassOf(classOf[TemplateActor.ResponseTemplate])
}
}
}
}

0 comments on commit d422cb4

Please sign in to comment.