Created
September 2, 2016 12:10
-
-
Save stanislav-chetvertkov/4e32a05d37a327a8dda7fa2eff053f49 to your computer and use it in GitHub Desktop.
Akka Http Mock Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import akka.actor.ActorSystem | |
import akka.http.scaladsl.Http | |
import akka.http.scaladsl.model.{HttpRequest, HttpResponse, Uri} | |
import akka.stream.ActorMaterializer | |
import akka.stream.scaladsl.{Sink, Source} | |
import scala.concurrent.{Await, Future} | |
import scala.concurrent.duration._ | |
/** | |
* Mock Akka HTTP Server, will handle requests which is provided with handle request | |
*/ | |
object MockServer { | |
def handleRequestWithHandler(requestHandler: HttpRequest => HttpResponse, port: Int = 0) | |
(implicit system: ActorSystem, mt: ActorMaterializer): Future[Http.ServerBinding] = { | |
val serverSource: Source[Http.IncomingConnection, Future[Http.ServerBinding]] = | |
Http().bind(interface = "localhost", port = port) | |
serverSource.to(Sink.foreach { connection => | |
println("Mock Server accepted new connection from " + connection.remoteAddress) | |
connection handleWithSyncHandler requestHandler | |
}).run() | |
} | |
object withMockServer { | |
def apply(handler: HttpRequest => HttpResponse, port: Int = 2345)(block: => Unit) | |
(implicit setupDuration: FiniteDuration, system: ActorSystem): Unit = { | |
implicit val mt = ActorMaterializer() | |
val binding = Await.result(MockServer.handleRequestWithHandler(requestHandler = handler, port = port), setupDuration) | |
block | |
Await.result(binding.unbind(), setupDuration) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment