这是我的服务器:
package example
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.UnsupportedRequestContentTypeRejection
import akka.stream.ActorFlowMaterializer
import akka.util.ByteString
import scala.concurrent.ExecutionContext.Implicits.global
object Main extends App {
implicit val system = ActorSystem("Server")
implicit val materializer = ActorFlowMaterializer()
val route =
path("v1") {
post { context =>
val entity = context.request.entity
entity.contentType().toString() match {
case "application/x-protobuf" =>
entity.dataBytes.runFold(ByteString.empty) { (acc, in) => acc ++ in } map { data =>
// do something with data
} flatMap (_ => context.complete(""))
case _ =>
context.reject(UnsupportedRequestContentTypeRejection(Set(ContentTypeRange(
MediaType.custom("application/x-protobuf", MediaType.Encoding.Binary)))))
}
}
}
Http().bindAndHandle(route, "0.0.0.0", 9000)
}
现在我想用 Specs2 测试这个服务器。这是我尝试过的:
import dispatch._
import org.specs2.mutable._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent._
import scala.concurrent.duration._
class ExampleSpecs extends Specification { sequential
step(example.Main.main(null))
"Server" should {
"refuse non protobuf Content-Type" in {
val service = url("http://localhost:9000/v1")
val request = service.POST
request.setContentType("application/json", "UTF-8")
request.setBody("this is a test")
val result = Http(request)
Await.result(result, 5 seconds).getStatusCode must equalTo(415)
}
}
}
我尝试使用step
启动服务器。但是,该App
特征没有提供在测试后停止服务器的方法。我想知道这是否是测试简单服务器的正确方法。
谢谢。