Skip to content

Commit

Permalink
generate test result json #39
Browse files Browse the repository at this point in the history
  • Loading branch information
stormcat24 committed Mar 5, 2015
1 parent 4b4b183 commit 216277d
Show file tree
Hide file tree
Showing 10 changed files with 159 additions and 954 deletions.
4 changes: 3 additions & 1 deletion aeromock-cli/Build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,6 @@ name := "aeromock-cli"

description := "Aeromock Command line interface module."

libraryDependencies ++= Seq()
libraryDependencies ++= Seq(
"net.databinder.dispatch" %% "dispatch-core" % "0.11.2"
)
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,16 @@ class ValidationJob(override val command: JobOperation)(implicit inj: Injector)
*/
override def execute(): Int = {

(project.template, project.data) match {
case (Success(Some(template)), Success(Some(data))) => // OK
var result = true

(project.template, project.data, project.naming, project.test) match {
case (Success(Some(template)), Success(Some(data)), Success(naming), Success(test)) => // OK
// templateとdataを操作してリクエストをつくる
new TemplateValidator().validate(template, data)
result &= new TemplateValidator().validate(template, data, naming, test).passed
// テンプレをループ
// 紐づくデータを探す。あればリクエスト、なければ警告
case (Success(_), Success(_)) => // nothing to do
case (_, _) => // TODO error
case (Success(_), Success(_), Success(_), Success(_)) => // nothing to do
case (_, _, _, _) => // TODO error
}

project.ajax match {
Expand All @@ -66,9 +68,7 @@ class ValidationJob(override val command: JobOperation)(implicit inj: Injector)
case (_, _) => // TODO error
}

// TODO テスト設定
// TODO useragent
0
if (result) 0 else 1
}

}
Original file line number Diff line number Diff line change
@@ -1,28 +1,136 @@
package jp.co.cyberagent.aeromock.cli.validation

import jp.co.cyberagent.aeromock.config.{Data, Template}
import java.io.{FileOutputStream, OutputStreamWriter}
import java.nio.file.{Files, Path}

import dispatch.Defaults._
import dispatch._
import jp.co.cyberagent.aeromock.config.{Data, Naming, Template, Test}
import jp.co.cyberagent.aeromock.core.http.Endpoint
import jp.co.cyberagent.aeromock.data.DataFileService
import jp.co.cyberagent.aeromock.helper._
import jp.co.cyberagent.aeromock.server.DataFile
import jp.co.cyberagent.aeromock.template.TemplateService
import scaldi.{Injector, Injectable}
import org.slf4j.LoggerFactory
import scaldi.{Injectable, Injector}

import scala.concurrent.Await
import scala.concurrent.duration.Duration
import scalaz._

/**
*
* @author stormcat24
*/
class TemplateValidator(implicit inj: Injector) extends AnyRef with Injectable {

def validate(template: Template, data: Data): Unit = {
val log = LoggerFactory.getLogger(this.getClass)

def validate(template: Template, data: Data, naming: Naming, test: Test): TestSummary = {

var numTemplate = 0
var numSuccess = 0
var numSkip = 0
var numFailed = 0

// TODO 拡張子取るためだけに取るのイケてない
val templateService = inject[Option[TemplateService]].get

template.contexts.map { context =>
val contextRoot = s"http://${context.domain}:${context.port}"
template.contexts.foreach { context =>
val requestRoot = s"http://${context.domain}:${context.port}"

// TODO 拡張子フィルタリング
context.root.filterChildren(s".${templateService.extension}$$").map { templatePath =>
println(templatePath)

val uri = templatePath.getRelativePath(template.root).withoutExtension

println(s"[Test] ${uri}")

val candidates = DataFileService.getRelatedDataFiles(Endpoint(uri.toString))

if (candidates.isEmpty) {
println(s" └ [${blue("SKIP")}] Not found data file")
numSkip += 1

} else {

val tests = candidates.zipWithIndex.map { case (dataFile, index) =>
val connector = if (index < candidates.size - 1) "" else ""
val request = createUrl(requestRoot, uri, dataFile)
val future = Http(request OK as.String)
val testResult = \/.fromTryCatchNonFatal(Await.result(future, Duration.Inf)) match {
case -\/(e) => {
val cause = e.getCause.asInstanceOf[StatusCode]
(false, cause.code)
}
case \/-(result) => (true, 200)
}

if (testResult._1) {
numSuccess += 1
} else {
numFailed += 1
}

val marker = if (testResult._1) s"[${green("SUCCESS")}]" else s"[${red("FAILED")}]"

println(s" $connector $marker data_path = ${dataFile.path}")
Map(
"request_url" -> request.toRequest.getUrl,
"data_file" -> dataFile.path.toString,
"status" -> testResult._2,
"result" -> testResult._1
)
}

val result = Map(
"template_uri" -> uri.toString,
"tests" -> tests
)
writeJson(result, test.reportRoot, uri)
}

numTemplate += 1

}
}

println( s"""
|****************************
|* Test Result Summary *
|****************************
| Total Template: ${numTemplate}
| ${green("SUCCESS")}: ${numSuccess}
| ${red("FAILED")}: ${numFailed}
| ${blue("SKIP")}: ${numSkip}
""".stripMargin)

TestSummary(numTemplate, numSuccess, numFailed, numSkip)
}

private def createUrl(urlRoot:String, requestUri: Path, dataFile: DataFile): Req = {
url(dataFile match {
case DataFile(Some(id), path, method) => s"${urlRoot}${requestUri}?_dataid=${id}"
case DataFile(None, path, method) => s"${urlRoot}${requestUri}"
}).setHeader("User-Agent", "Aeromock Test Job")
}

private def writeJson(testResult: Map[String, Any], reportRoot: Path, templateUri: Path): Unit = {

import org.json4s._
import org.json4s.native.Serialization
import org.json4s.native.Serialization.write
implicit val formats = Serialization.formats(NoTypeHints)

val templateReportRoot = reportRoot / "template"
Files.createDirectories(templateReportRoot)

val jsonString = write(testResult)
val jsonPath = templateReportRoot / templateUri + ".json"
val jsonPathDir = jsonPath.getParent
Files.createDirectories(jsonPathDir)

processResource(new OutputStreamWriter(new FileOutputStream(jsonPath.toFile), "UTF-8")) { writer =>
writer.write(jsonString)
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package jp.co.cyberagent.aeromock.cli

/**
*
* @author stormcat24
*/
package object validation {

case class TestSummary(totalTemplates: Int, numSuccess: Int, numFailed: Int, numSkip: Int) {

def passed = numFailed <= 0
}

}
Loading

0 comments on commit 216277d

Please sign in to comment.