Skip to content

Commit

Permalink
test: unit test for authService.login
Browse files Browse the repository at this point in the history
  • Loading branch information
ShiinaKin committed Sep 14, 2024
1 parent 1ddea5b commit c3575e2
Show file tree
Hide file tree
Showing 3 changed files with 119 additions and 17 deletions.
112 changes: 112 additions & 0 deletions app/src/test/kotlin/io/sakurasou/service/auth/AuthServiceTest.kt
Original file line number Diff line number Diff line change
@@ -1,8 +1,120 @@
package io.sakurasou.service.auth

import at.favre.lib.crypto.bcrypt.BCrypt
import io.mockk.*
import io.sakurasou.controller.request.UserLoginRequest
import io.sakurasou.exception.UnauthorizedAccessException
import io.sakurasou.exception.UserNotFoundException
import io.sakurasou.model.DatabaseSingleton
import io.sakurasou.model.dao.relation.RelationDao
import io.sakurasou.model.dao.user.UserDao
import io.sakurasou.model.entity.User
import io.sakurasou.util.JwtUtils
import kotlinx.coroutines.runBlocking
import kotlinx.datetime.Clock
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith

/**
* @author Shiina Kin
* 2024/9/13 21:47
*/
class AuthServiceTest {
private lateinit var userDao: UserDao
private lateinit var relationDao: RelationDao
private lateinit var authService: AuthService

private val username = "testUser"
private val password = "testPassword"
private val email = "[email protected]"

@BeforeTest
fun setUp() {
mockkObject(DatabaseSingleton)
mockkObject(JwtUtils)
mockkStatic(BCrypt::class)
userDao = mockk()
relationDao = mockk()
authService = AuthServiceImpl(userDao, relationDao)
}

@Test
fun `login should throw UserNotFoundException for non-existent user`() = runBlocking {
val userLoginRequest = UserLoginRequest(username, password)

coEvery { DatabaseSingleton.dbQuery<User>(any()) } coAnswers {
this.arg<suspend () -> User>(0).invoke()
}
coEvery { userDao.findUserByName(username) } returns null

assertFailsWith<UserNotFoundException> {
authService.login(userLoginRequest)
}
coVerify(exactly = 1) { userDao.findUserByName(username) }
}

@Test
fun `login should throw UnauthorizedAccessException for incorrect password`() = runBlocking {
val userLoginRequest = UserLoginRequest(username, password)

val instant = Clock.System.now()
val now = instant.toLocalDateTime(TimeZone.currentSystemDefault())
val hashedPassword = BCrypt.withDefaults().hashToString(12, "correctPassword".toCharArray())
val user = User(
id = 1,
groupId = 2,
name = username,
password = hashedPassword,
email = email,
createTime = now,
updateTime = now
)

coEvery { DatabaseSingleton.dbQuery<User>(any()) } coAnswers {
this.arg<suspend () -> User>(0).invoke()
}
coEvery { userDao.findUserByName(username) } returns user

assertFailsWith<UnauthorizedAccessException> {
authService.login(userLoginRequest)
}
coVerify { userDao.findUserByName(username) }
}

@Test
fun `login should return a JWT token`() = runBlocking {
val userLoginRequest = UserLoginRequest(username, password)

val instant = Clock.System.now()
val now = instant.toLocalDateTime(TimeZone.currentSystemDefault())
val hashedPassword = BCrypt.withDefaults().hashToString(12, password.toCharArray())
val user = User(
id = 1,
groupId = 2,
name = username,
password = hashedPassword,
email = email,
createTime = now,
updateTime = now
)
val roles = listOf("user")
val justAJwtToken = "mockJwtToken"

coEvery { DatabaseSingleton.dbQuery<User>(any()) } coAnswers {
this.arg<suspend () -> User>(0).invoke()
}
coEvery { DatabaseSingleton.dbQuery<List<String>>(any()) } coAnswers {
this.arg<suspend () -> List<String>>(0).invoke()
}
coEvery { userDao.findUserByName(username) } returns user
coEvery { relationDao.listRoleByGroupId(user.groupId) } returns roles
every { JwtUtils.generateJwtToken(user, roles) } returns justAJwtToken

val token = authService.login(userLoginRequest)
assertEquals(justAJwtToken, token)
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package io.sakurasou.service.common

import at.favre.lib.crypto.bcrypt.BCrypt
import io.ktor.server.testing.*
import io.mockk.*
import io.sakurasou.controller.request.SiteInitRequest
import io.sakurasou.exception.SiteRepeatedInitializationException
Expand All @@ -12,11 +11,12 @@ import io.sakurasou.model.setting.SiteSetting
import io.sakurasou.model.setting.SystemStatus
import io.sakurasou.service.album.AlbumService
import io.sakurasou.service.setting.SettingService
import kotlinx.coroutines.runBlocking
import kotlinx.datetime.Clock
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime
import kotlin.test.Test
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertFailsWith

/**
Expand Down Expand Up @@ -44,8 +44,7 @@ class CommonServiceTest {
}

@Test
fun `initSite should throw SiteRepeatedInitializationException if already initialized`() = testApplication {
// Arrange
fun `initSite should throw SiteRepeatedInitializationException if already initialized`(): Unit = runBlocking {
val siteInitRequest = SiteInitRequest(
username = "testUser",
password = "testPassword",
Expand All @@ -56,15 +55,13 @@ class CommonServiceTest {
)
coEvery { settingService.getSystemStatus() } returns SystemStatus(isInit = true)

// Act & Assert
assertFailsWith<SiteRepeatedInitializationException> {
commonService.initSite(siteInitRequest)
}
}

@Test
fun `initSite should initialize site correctly`() = testApplication {
// Arrange
fun `initSite should initialize site correctly`() = runBlocking {
val siteInitRequest = SiteInitRequest(
username = "testUser",
password = "testPassword",
Expand Down Expand Up @@ -109,10 +106,8 @@ class CommonServiceTest {
coEvery { settingService.updateSiteSetting(siteSettingConfig) } just Runs
coEvery { settingService.updateSystemStatus(systemStatus) } just Runs

// Act
commonService.initSite(siteInitRequest)

// Assert
coVerify(exactly = 1) { DatabaseSingleton.dbQuery<Unit>(any()) }
coVerify(exactly = 1) { userDao.saveUser(userInsertDTO) }
coVerify(exactly = 1) { albumService.initAlbumForUser(1) }
Expand Down
11 changes: 3 additions & 8 deletions app/src/test/kotlin/io/sakurasou/service/user/UserServiceTest.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package io.sakurasou.service.user

import at.favre.lib.crypto.bcrypt.BCrypt
import io.ktor.server.testing.*
import io.mockk.*
import io.sakurasou.controller.request.UserInsertRequest
import io.sakurasou.exception.SignupNotAllowedException
Expand All @@ -11,6 +10,7 @@ import io.sakurasou.model.dto.UserInsertDTO
import io.sakurasou.model.setting.SystemSetting
import io.sakurasou.service.album.AlbumService
import io.sakurasou.service.setting.SettingService
import kotlinx.coroutines.runBlocking
import kotlinx.datetime.Clock
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime
Expand Down Expand Up @@ -43,8 +43,7 @@ class UserServiceTest {
}

@Test
fun `signup should throw SignupNotAllowedException if system not allowed signup`() = testApplication {
// Arrange
fun `signup should throw SignupNotAllowedException if system not allowed signup`(): Unit = runBlocking {
val userInsertRequest = UserInsertRequest(
username = "testUser",
password = "testPassword",
Expand All @@ -57,15 +56,13 @@ class UserServiceTest {

coEvery { settingService.getSystemSetting() } returns systemSetting

// Act & Assert
assertFailsWith<SignupNotAllowedException> {
userService.saveUser(userInsertRequest)
}
}

@Test
fun `test saveUser`() = testApplication {
// Arrange
fun `signup should be successful`() = runBlocking {
val userInsertRequest = UserInsertRequest(
username = "testUser",
password = "testPassword",
Expand Down Expand Up @@ -96,10 +93,8 @@ class UserServiceTest {
coEvery { userDao.saveUser(userInsertDTO) } returns 1
coEvery { albumService.initAlbumForUser(1L) } just Runs

// Act
userService.saveUser(userInsertRequest)

// Assert
coVerify(exactly = 1) { DatabaseSingleton.dbQuery<Unit>(any()) }
coVerify(exactly = 1) { userDao.saveUser(userInsertDTO) }
coVerify(exactly = 1) { albumService.initAlbumForUser(1L) }
Expand Down

0 comments on commit c3575e2

Please sign in to comment.