@@ -11,8 +11,10 @@ import io.ktor.http.HttpStatusCode
1111import io.ktor.network.selector.SelectorManager
1212import io.ktor.network.sockets.InetSocketAddress
1313import io.ktor.network.sockets.aSocket
14+ import io.ktor.server.application.ApplicationStarted
1415import io.ktor.server.engine.EmbeddedServer
1516import io.ktor.utils.io.core.use
17+ import kotlinx.coroutines.CompletableDeferred
1618import kotlinx.coroutines.delay
1719import kotlinx.coroutines.runBlocking
1820import kotlinx.coroutines.withTimeout
@@ -25,22 +27,27 @@ import kotlin.time.Duration.Companion.seconds
2527 * mocking an HTTP client engine is difficult.
2628 */
2729public abstract class TestWithLocalServer {
28- protected val serverPort: Int
29- get() = runBlocking {
30- SelectorManager (this .coroutineContext).use {
31- aSocket(it)
32- .tcp()
33- .bind()
34- .use { (it.localAddress as InetSocketAddress ).port }
35- }
30+ protected val serverPort: Int = runBlocking {
31+ SelectorManager (this .coroutineContext).use {
32+ aSocket(it)
33+ .tcp()
34+ .bind()
35+ .use { (it.localAddress as InetSocketAddress ).port }
3636 }
37+ }
3738
3839 protected val testHost: String = " localhost"
3940
4041 public abstract val server: EmbeddedServer <* , * >
4142
4243 @BeforeTest
4344 public fun startServer (): Unit = runBlocking {
45+ val serverStarted = CompletableDeferred <Unit >()
46+
47+ server.monitor.subscribe(ApplicationStarted ) {
48+ serverStarted.complete(Unit )
49+ }
50+
4451 withTimeout(5 .seconds) {
4552 var attempt = 0
4653
@@ -55,7 +62,7 @@ public abstract class TestWithLocalServer {
5562 }
5663 } while (true )
5764
58- ensureServerRunning ()
65+ serverStarted.await ()
5966 }
6067 }
6168
@@ -64,21 +71,4 @@ public abstract class TestWithLocalServer {
6471 server.stop(0 , 0 )
6572 println (" test server stopped" )
6673 }
67-
68- private fun ensureServerRunning () = runBlocking {
69- val client = HttpClient ()
70- val url = " http://$testHost :$serverPort "
71- try {
72- while (true ) {
73- try {
74- val response = client.get(url)
75- if (response.status == HttpStatusCode .OK ) break
76- } catch (_: Exception ) {
77- delay(100 )
78- }
79- }
80- } finally {
81- client.close()
82- }
83- }
8474}
0 commit comments