/core/src/test/scala/net/ruippeixotog/scalascraper/browser/TestServer.scala

https://github.com/ruippeixotog/scala-scraper · Scala · 58 lines · 44 code · 14 blank · 0 comment · 0 complexity · b9b2cffc7b2e39e56adac890d46c612b MD5 · raw file

  1. package net.ruippeixotog.scalascraper.browser
  2. import java.util.concurrent.atomic.AtomicInteger
  3. import scala.concurrent.duration._
  4. import scala.concurrent.{Await, ExecutionContext}
  5. import scala.io.Source
  6. import akka.actor.ActorSystem
  7. import akka.http.scaladsl.Http
  8. import akka.http.scaladsl.Http.ServerBinding
  9. import akka.http.scaladsl.model.ContentTypes._
  10. import akka.http.scaladsl.model.HttpEntity
  11. import akka.http.scaladsl.server.Directives._
  12. import akka.http.scaladsl.server.Route
  13. import akka.stream.{ActorMaterializer, Materializer}
  14. import org.specs2.mutable.Specification
  15. import org.specs2.specification.BeforeAfterAll
  16. trait TestServer extends BeforeAfterAll { this: Specification =>
  17. implicit private[this] val system: ActorSystem = ActorSystem("my-system")
  18. implicit private[this] val materializer: Materializer = ActorMaterializer()
  19. implicit private[this] val ec: ExecutionContext = system.dispatcher
  20. def testService: Route
  21. lazy val testServerPort: Int = TestServer.nextPort.getAndIncrement()
  22. private[this] var server = Option.empty[ServerBinding]
  23. def beforeAll(): Unit = {
  24. server = Some(Await.result(Http().bindAndHandle(testService, "localhost", testServerPort), 5.seconds))
  25. }
  26. def afterAll(): Unit = {
  27. server.foreach(_.unbind().onComplete(_ => system.terminate()))
  28. }
  29. def serveText(str: String): Route = {
  30. complete(HttpEntity(`text/html(UTF-8)`, s"<html><body>$str</body></html>"))
  31. }
  32. def serveHtml(html: String): Route = {
  33. complete(HttpEntity(`text/html(UTF-8)`, html))
  34. }
  35. def serveResource(name: String, charset: String = "UTF-8"): Route = {
  36. val content = Source.fromFile(getClass.getClassLoader.getResource(name).toURI, charset).mkString
  37. complete(HttpEntity(`text/html(UTF-8)`, content))
  38. }
  39. def testServerUri(path: String): String =
  40. s"http://localhost:$testServerPort/$path"
  41. }
  42. object TestServer {
  43. private val nextPort = new AtomicInteger(23464)
  44. }