/mist/master/src/test/scala/io/hydrosphere/mist/master/TestUtils.scala

https://github.com/Hydrospheredata/mist · Scala · 96 lines · 75 code · 21 blank · 0 comment · 0 complexity · 16dcbe9fd27599f532dd923f0dce9f32 MD5 · raw file

  1. package io.hydrosphere.mist.master
  2. import akka.http.scaladsl.model.{HttpRequest, HttpResponse}
  3. import akka.stream.scaladsl.Flow
  4. import com.typesafe.config.ConfigFactory
  5. import scala.concurrent.duration.{Duration, FiniteDuration}
  6. import scala.concurrent.{Await, Future, Promise}
  7. trait TestUtils {
  8. implicit class AwaitSyntax[A](f: => Future[A]) {
  9. def await: A = Await.result(f, Duration.Inf)
  10. def await(d: FiniteDuration): A = Await.result(f, d)
  11. }
  12. }
  13. object TestUtils extends TestUtils {
  14. val cfgStr =
  15. """
  16. |context-defaults {
  17. | downtime = Inf
  18. | streaming-duration = 1 seconds
  19. | max-parallel-jobs = 20
  20. | precreated = false
  21. | spark-conf = { }
  22. | worker-mode = "shared"
  23. | run-options = "--opt"
  24. | max-conn-failures = 5
  25. |}
  26. |
  27. |context {
  28. |
  29. | foo {
  30. | spark-conf {
  31. | spark.master = "local[2]"
  32. | }
  33. | }
  34. |}
  35. """.stripMargin
  36. val contextSettings = {
  37. val cfg = ConfigFactory.parseString(cfgStr)
  38. ContextsSettings(cfg)
  39. }
  40. val FooContext = contextSettings.contexts.get("foo").get
  41. object MockHttpServer {
  42. import akka.actor.ActorSystem
  43. import akka.http.scaladsl.Http
  44. import akka.stream.ActorMaterializer
  45. import akka.util.Timeout
  46. import scala.concurrent.duration._
  47. def onServer[A](
  48. routes: Flow[HttpRequest, HttpResponse, _],
  49. f: (Http.ServerBinding) => A): Future[A] = {
  50. implicit val system = ActorSystem("mock-http-cli")
  51. implicit val materializer = ActorMaterializer()
  52. implicit val executionContext = system.dispatcher
  53. implicit val timeout = Timeout(1.seconds)
  54. val binding = Http().bindAndHandle(routes, "localhost", 0)
  55. val close = Promise[Http.ServerBinding]
  56. close.future
  57. .flatMap(binding => binding.unbind())
  58. .onComplete(_ => {
  59. materializer.shutdown()
  60. Await.result(system.terminate(), Duration.Inf)
  61. })
  62. val result = binding.flatMap(binding => {
  63. try {
  64. Future.successful(f(binding))
  65. } catch {
  66. case e: Throwable =>
  67. Future.failed(e)
  68. } finally {
  69. close.success(binding)
  70. }
  71. })
  72. result
  73. }
  74. }
  75. }