SimpleNotes/api/test/integration/routing/UserControllerKtTest.kt

107 lines
3.2 KiB
Kotlin

package integration.routing
import be.vandewalleh.auth.SimpleJWT
import be.vandewalleh.entities.User
import be.vandewalleh.mainModule
import be.vandewalleh.module
import be.vandewalleh.services.UserService
import io.ktor.http.*
import io.ktor.server.testing.*
import io.mockk.coEvery
import io.mockk.mockk
import org.amshove.kluent.*
import org.junit.jupiter.api.*
import org.kodein.di.Kodein
import org.kodein.di.generic.bind
import org.kodein.di.generic.instance
import utils.*
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class UserControllerKtTest {
private val userService = mockk<UserService>()
init {
// new user
coEvery { userService.exists("new") } returns false
coEvery { userService.create("new", any()) } returns User {
this.username = "new"
}
// existing user
coEvery { userService.exists("existing") } returns true
coEvery { userService.create("existing", any()) } returns null
coEvery { userService.delete(1) } returns true andThen false
// modified user
coEvery { userService.exists("modified") } returns true
coEvery { userService.exists(and(not("modified"), not("existing"))) } returns false
coEvery { userService.exists(1) } returns true
coEvery { userService.create("modified", any()) } returns null
}
private val kodein = Kodein {
import(mainModule, allowOverride = true)
bind<UserService>(overrides = true) with instance(userService)
}
private val testEngine = TestApplicationEngine().apply {
start()
application.module(kodein)
}
@Nested
inner class CreateUser {
@Test
fun `create a new user`() {
val res = testEngine.post("/user") {
json {
it["username"] = "new"
it["password"] = "test123abc"
}
}
res.status() `should be equal to` HttpStatusCode.Created
res.content `should strictly be equal to json` """{username:"new"}"""
}
@Test
fun `create an existing user`() {
val res = testEngine.post("/user") {
json {
it["username"] = "existing"
it["password"] = "test123abc"
}
}
res.status() `should be equal to` HttpStatusCode.Conflict
res.content `should be equal to json` """{msg:"Conflict"}"""
}
}
@Nested
inner class DeleteUser {
@Test
fun `delete an existing user`() {
val authJwt by kodein.instance<SimpleJWT>("auth")
val token = authJwt.sign(1)
val res = testEngine.delete("/user") {
addHeader(HttpHeaders.Authorization, "Bearer $token")
}
res.status() `should be equal to` HttpStatusCode.OK
res.content `should be equal to json` """{msg:"OK"}"""
// try again
val res2 = testEngine.delete("/user") {
setToken(token)
}
res2.status() `should be equal to` HttpStatusCode.NotFound
res2.content `should be equal to json` """{msg:"Not Found"}"""
}
}
}