Skip to content

Commit

Permalink
KTOR-4009 Add flag to respond with 500 on exceptions in tests (#3163)
Browse files Browse the repository at this point in the history
  • Loading branch information
rsinukov committed Sep 26, 2022
1 parent 6369491 commit 4ab5d7b
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 2 deletions.
Expand Up @@ -133,7 +133,7 @@ public open class TestApplicationBuilder {
developmentMode = true
val oldConfig = config
this@TestApplicationBuilder.environmentBuilder(this)
if (config == oldConfig) { // config was not set by user. load the default one
if (config == oldConfig) { // the user did not set config. load the default one
config = DefaultTestConfig()
}
parentCoroutineContext += this@TestApplicationBuilder.job
Expand Down
Expand Up @@ -19,6 +19,10 @@ import kotlinx.atomicfu.*
import kotlinx.coroutines.*
import kotlin.coroutines.*

@OptIn(InternalAPI::class)
@PublicAPICandidate("2.2.0")
internal const val CONFIG_KEY_THROW_ON_EXCEPTION = "ktor.test.throwOnException"

/**
* A test engine that provides a way to simulate application calls to the existing application module(s)
* without actual HTTP connection.
Expand Down Expand Up @@ -96,7 +100,13 @@ class TestApplicationEngine(
}

private suspend fun PipelineContext<Unit, ApplicationCall>.handleTestFailure(cause: Throwable) {
tryRespondError(defaultExceptionStatusCode(cause) ?: throw cause)
val throwOnException = environment.config
.propertyOrNull(CONFIG_KEY_THROW_ON_EXCEPTION)
?.getString()?.toBoolean() ?: true
tryRespondError(
defaultExceptionStatusCode(cause)
?: if (throwOnException) throw cause else HttpStatusCode.InternalServerError
)
}

private suspend fun PipelineContext<Unit, ApplicationCall>.tryRespondError(statusCode: HttpStatusCode) {
Expand Down
Expand Up @@ -8,8 +8,10 @@ import io.ktor.client.*
import io.ktor.client.plugins.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.server.application.*
import io.ktor.server.config.*
import io.ktor.server.plugins.*
import io.ktor.server.request.*
import io.ktor.server.response.*
Expand Down Expand Up @@ -248,4 +250,33 @@ class TestApplicationTest {
request2.await()
}
}

@Test
fun testExceptionThrowsByDefault() = testApplication {
routing {
get("/boom") {
throw IllegalStateException("error")
}
}

val error = assertFailsWith<IllegalStateException> {
client.get("/boom")
}
assertEquals("error", error.message)
}

@Test
fun testExceptionRespondsWith500IfFlagSet() = testApplication {
environment {
config = MapApplicationConfig(CONFIG_KEY_THROW_ON_EXCEPTION to "false")
}
routing {
get("/boom") {
throw IllegalStateException("error")
}
}

val response = client.get("/boom")
assertEquals(HttpStatusCode.InternalServerError, response.status)
}
}

0 comments on commit 4ab5d7b

Please sign in to comment.