Test Akka-HTTP server using Specs2

940 views Asked by At

Here is my server:

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)
}

Now I wanna test this server with Specs2. Here is what I tried:

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)
    }
  }

}

I tried to use step to start the server. However, the App trait provides no ways to stop the server after the test. I wonder if this is the proper way to test the simple server.

Thanks.

0

There are 0 answers