/integration-tests/src/test/scala/play/AkkaServerProvider.scala

https://github.com/playframework/play-ws · Scala · 54 lines · 31 code · 11 blank · 12 comment · 0 complexity · 93d08a5f1b95123cc4038b07ff53c32d MD5 · raw file

  1. /*
  2. * Copyright (C) Lightbend Inc. <https://www.lightbend.com>
  3. */
  4. package play
  5. import akka.actor.ActorSystem
  6. import akka.http.scaladsl.Http
  7. import akka.http.scaladsl.server.Route
  8. import org.specs2.concurrent.ExecutionEnv
  9. import org.specs2.specification.BeforeAfterAll
  10. import scala.concurrent.duration._
  11. import scala.concurrent.Await
  12. import scala.concurrent.Future
  13. import akka.stream.Materializer
  14. trait AkkaServerProvider extends BeforeAfterAll {
  15. /**
  16. * @return Routes to be used by the test.
  17. */
  18. def routes: Route
  19. /**
  20. * The execution context environment.
  21. */
  22. def executionEnv: ExecutionEnv
  23. var testServerPort: Int = _
  24. val defaultTimeout: FiniteDuration = 5.seconds
  25. // Create Akka system for thread and streaming management
  26. implicit val system = ActorSystem()
  27. implicit val materializer = Materializer.matFromSystem
  28. lazy val futureServer: Future[Http.ServerBinding] = {
  29. // Using 0 (zero) means that a random free port will be used.
  30. // So our tests can run in parallel and won't mess with each other.
  31. Http().bindAndHandle(routes, "localhost", 0)
  32. }
  33. override def beforeAll(): Unit = {
  34. val portFuture = futureServer.map(_.localAddress.getPort)(executionEnv.executionContext)
  35. portFuture.foreach(port => testServerPort = port)(executionEnv.executionContext)
  36. Await.ready(portFuture, defaultTimeout)
  37. }
  38. override def afterAll(): Unit = {
  39. futureServer.foreach(_.unbind())(executionEnv.executionContext)
  40. val terminate = system.terminate()
  41. Await.ready(terminate, defaultTimeout)
  42. }
  43. }