test(creator-admin): 실제 HTTP 댓글 관리와 동시성 경계를 검증한다

This commit is contained in:
2026-11-20 14:09:41 +09:00
parent ac23b85192
commit 837823104a
2 changed files with 377 additions and 0 deletions
@@ -0,0 +1,82 @@
package kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.EnumSource
import org.springframework.http.HttpMethod
import org.springframework.http.ResponseEntity
import java.util.concurrent.Callable
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
class CreatorAdminCommentConcurrencyEndToEndTest : CreatorAdminCommentHttpTestSupport() {
@ParameterizedTest
@EnumSource(Kind::class)
@DisplayName("실제 HTTP 동시 답글 등록은 200과 409이며 활성 소유자 답글은 DB에 정확히 하나다")
fun shouldAllowExactlyOneConcurrentOwnerReply(kind: Kind) {
val path = "${rootPath(kind)}/replies"
val responses = concurrently({ request(path, HttpMethod.POST) }, { request(path, HttpMethod.POST) })
assertEquals(listOf(200, 409), responses.map { it.statusCodeValue }.sorted())
responses.forEach { json(it, it.statusCodeValue) }
val count = transactions.execute {
entityManager.createQuery(
"select count(e) from ${kind.entityName} e " +
"where e.parent.id = :rootId and e.member.id = :ownerId and e.isActive = true",
java.lang.Long::class.java
).setParameter("rootId", roots.getValue(kind)).setParameter("ownerId", owner.id).singleResult.toLong()
}
assertEquals(1L, count)
val reply = json(request(listPath(kind)))["data"]["items"].single()["creatorReply"]
assertEquals(REPLY, reply["content"].asText())
assertEquals(owner.id, reply["writer"]["memberId"].asLong())
}
@ParameterizedTest
@EnumSource(Kind::class)
@DisplayName("실제 HTTP 부모 삭제와 답글 등록이 경쟁해도 완료 순서와 무관하게 앱에 고아 답글이 노출되지 않는다")
fun shouldHideThreadAfterConcurrentParentDeleteAndReplyCreate(kind: Kind) {
val path = rootPath(kind)
assertEquals(1, json(request(listPath(kind)))["data"]["totalCount"].asInt())
val responses = concurrently({ request(path, HttpMethod.DELETE) }, { request("$path/replies", HttpMethod.POST) })
assertTrue(json(responses[0])["data"].isNull)
val create = responses[1]
assertTrue(create.statusCodeValue in setOf(200, 409), create.body)
json(create, create.statusCodeValue)
assertThreadHidden(kind)
}
private fun concurrently(
first: () -> ResponseEntity<String>,
second: () -> ResponseEntity<String>
): List<ResponseEntity<String>> {
val ready = CountDownLatch(2)
val start = CountDownLatch(1)
val executor = Executors.newFixedThreadPool(2)
val futures = listOf(first, second).map { action ->
executor.submit(
Callable {
ready.countDown()
check(start.await(5, TimeUnit.SECONDS)) { "Concurrent HTTP start was not released" }
action()
}
)
}
try {
assertTrue(ready.await(5, TimeUnit.SECONDS), "Both HTTP clients must be ready")
start.countDown()
return futures.map { it.get(20, TimeUnit.SECONDS) }
} finally {
start.countDown()
futures.forEach { it.cancel(true) }
executor.shutdownNow()
assertTrue(executor.awaitTermination(20, TimeUnit.SECONDS), "HTTP executor must terminate before fixture cleanup")
}
}
}
@@ -0,0 +1,295 @@
package kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import kr.co.vividnext.sodalive.content.AudioContent
import kr.co.vividnext.sodalive.content.comment.AudioContentComment
import kr.co.vividnext.sodalive.content.theme.AudioContentTheme
import kr.co.vividnext.sodalive.explorer.profile.CreatorCheers
import kr.co.vividnext.sodalive.explorer.profile.channelDonation.ChannelDonationMessage
import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.CreatorCommunity
import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.comment.CreatorCommunityComment
import kr.co.vividnext.sodalive.jwt.TokenProvider
import kr.co.vividnext.sodalive.member.Member
import kr.co.vividnext.sodalive.member.MemberAdapter
import kr.co.vividnext.sodalive.member.MemberRole
import kr.co.vividnext.sodalive.member.token.MemberTokenRepository
import kr.co.vividnext.sodalive.support.EmbeddedRedisInitializer
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.EnumSource
import org.junit.jupiter.params.provider.ValueSource
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.web.client.TestRestTemplate
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.http.client.SimpleClientHttpRequestFactory
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.test.context.ContextConfiguration
import org.springframework.transaction.support.TransactionTemplate
import javax.persistence.EntityManager
class CreatorAdminCommentEndToEndTest : CreatorAdminCommentHttpTestSupport() {
@Test
@DisplayName("실제 JWT HTTP는 네 관리 탭과 커뮤니티 상세의 저장 데이터를 반환한다")
fun shouldReadFourTabsAndCommunityDetailThroughRealJwtHttp() {
listOf(
Triple(listPath(Kind.CONTENT), "commentId", roots.getValue(Kind.CONTENT)),
Triple(listPath(Kind.FANTALK), "fanTalkId", roots.getValue(Kind.FANTALK)),
Triple("$BASE/community/posts", "postId", postId),
Triple("$BASE/donations", "donationId", donationId)
).forEach { (path, idField, id) ->
val data = json(request(path))["data"]
assertEquals(listOf(id), data["items"].map { it[idField].asLong() })
assertEquals(1, data["totalCount"].asInt())
}
val detail = json(request("$BASE/community/posts/$postId"))["data"]
assertEquals(postId, detail["postId"].asLong())
assertEquals("P3 community post", detail["content"].asText())
assertEquals(1, detail["commentCount"].asInt())
}
@ParameterizedTest
@ValueSource(booleans = [false, true])
@DisplayName("실제 인증 체인은 네 탭과 상세에서 토큰 없으면 401 USER JWT이면 403을 반환한다")
fun shouldRejectAnonymousAndUserJwtAtRealHttpBoundary(authenticated: Boolean) {
val token = if (authenticated) fanToken else null
val expected = if (authenticated) 403 else 401
(
Kind.values().map(::listPath) + listOf(
"$BASE/community/posts",
"$BASE/community/posts/$postId",
"$BASE/donations"
)
).forEach { json(request(it, token = token), expected) }
}
@ParameterizedTest
@EnumSource(Kind::class)
@DisplayName("실제 HTTP 답글 등록은 재조회되며 부모 삭제 후 앱에서도 답글을 직접 노출하지 않는다")
fun shouldCreateReadBackAndHideReplyAfterParentDeletion(kind: Kind) {
assertTrue(json(request("${rootPath(kind)}/replies", HttpMethod.POST))["data"].isNull)
val reply = json(request(listPath(kind)))["data"]["items"].single()["creatorReply"]
assertEquals(REPLY, reply["content"].asText())
assertEquals(owner.id, reply["writer"]["memberId"].asLong())
assertTrue(reply["replyId"].asLong() > 0)
val app = appData(kind)
when (kind) {
Kind.CONTENT, Kind.COMMUNITY -> assertEquals(REPLY, app["items"].single()["comment"].asText())
Kind.FANTALK -> assertEquals(REPLY, app["fanTalks"].single()["creatorReplies"].single()["content"].asText())
}
assertTrue(json(request(rootPath(kind), HttpMethod.DELETE))["data"].isNull)
assertThreadHidden(kind)
}
}
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = [
"cloud.aws.cloud-front.host=https://cdn.test",
"spring.cache.type=none",
"jwt.secret=dGVzdC1vbmx5LXNlY3JldC10ZXN0LW9ubHktc2VjcmV0LXRlc3Qtb25seS1zZWNyZXQtdGVzdC1vbmx5LXNlY3JldA=="
]
)
@ContextConfiguration(initializers = [EmbeddedRedisInitializer::class])
abstract class CreatorAdminCommentHttpTestSupport {
@Autowired protected lateinit var entityManager: EntityManager
@Autowired protected lateinit var transactions: TransactionTemplate
@Autowired protected lateinit var objectMapper: ObjectMapper
@Autowired protected lateinit var restTemplate: TestRestTemplate
@Autowired private lateinit var tokenProvider: TokenProvider
@Autowired private lateinit var tokenRepository: MemberTokenRepository
protected lateinit var owner: Member
protected lateinit var ownerToken: String
protected lateinit var fanToken: String
protected lateinit var roots: Map<Kind, Long>
protected var contentId: Long = 0
protected var postId: Long = 0
protected var donationId: Long = 0
private val memberIds = mutableListOf<Long>()
private var themeId: Long? = null
@BeforeEach
fun commitFixturesAndIssueStoredJwt() {
restTemplate.restTemplate.requestFactory = SimpleClientHttpRequestFactory().apply {
setConnectTimeout(5_000)
setReadTimeout(10_000)
}
val fan = requireNotNull(
transactions.execute {
entityManager.createNativeQuery(
"CREATE ALIAS IF NOT EXISTS DATE_FORMAT FOR " +
"'kr.co.vividnext.sodalive.support.H2MysqlDateFunctions.dateFormat'"
).executeUpdate()
entityManager.createNativeQuery(
"CREATE ALIAS IF NOT EXISTS CONVERT_TZ FOR " +
"'kr.co.vividnext.sodalive.support.H2MysqlDateFunctions.convertTz'"
).executeUpdate()
owner = saveMember(MemberRole.CREATOR)
val fan = saveMember(MemberRole.USER)
val theme = AudioContentTheme("P3 audio", "p3.png").also(entityManager::persist)
themeId = theme.id
val audio = AudioContent("P3 audio", "P3 detail", "ko").apply {
member = owner
this.theme = theme
duration = "01:00"
isActive = true
}.also(entityManager::persist)
contentId = requireNotNull(audio.id)
val post = CreatorCommunity("P3 community post", 0, true, false).apply { member = owner }
.also(entityManager::persist)
postId = requireNotNull(post.id)
val contentRoot = AudioContentComment("P3 content parent", "ko").apply {
member = fan
audioContent = audio
}.also(entityManager::persist)
val fanTalkRoot = CreatorCheers("P3 fan talk parent", "ko").apply {
member = fan
creator = owner
}.also(entityManager::persist)
val communityRoot = CreatorCommunityComment("P3 community parent").apply {
member = fan
creatorCommunity = post
}.also(entityManager::persist)
roots = mapOf(
Kind.CONTENT to requireNotNull(contentRoot.id),
Kind.FANTALK to requireNotNull(fanTalkRoot.id),
Kind.COMMUNITY to requireNotNull(communityRoot.id)
)
donationId = requireNotNull(
ChannelDonationMessage(100, additionalMessage = "P3 donation").apply {
member = fan
creator = owner
}.also(entityManager::persist).id
)
fan
}
)
ownerToken = issueToken(owner)
fanToken = issueToken(fan)
}
@AfterEach
fun cleanOwnedCommittedFixturesAndTokens() {
try {
transactions.executeWithoutResult {
if (memberIds.isEmpty()) return@executeWithoutResult
Kind.values().forEach { kind ->
listOf("and e.parent is not null", "").forEach { condition ->
entityManager.createQuery("delete from ${kind.entityName} e where e.member.id in :ids $condition")
.setParameter("ids", memberIds).executeUpdate()
}
}
listOf("ChannelDonationMessage", "CreatorCommunity", "AudioContent", "MemberContentPreference").forEach {
entityManager.createQuery("delete from $it e where e.member.id in :ids")
.setParameter("ids", memberIds).executeUpdate()
}
entityManager.createQuery("delete from AudioContentTheme e where e.id = :id")
.setParameter("id", themeId).executeUpdate()
entityManager.createQuery("delete from Member e where e.id in :ids")
.setParameter("ids", memberIds).executeUpdate()
}
} finally {
memberIds.forEach(tokenRepository::deleteById)
}
}
private fun saveMember(role: MemberRole): Member = Member(
password = "unused-test-password",
nickname = "p3-${role.name}",
role = role
).also {
entityManager.persist(it)
memberIds.add(requireNotNull(it.id))
}
private fun issueToken(member: Member): String {
val principal = MemberAdapter(member)
return tokenProvider.createToken(
UsernamePasswordAuthenticationToken(principal, "", principal.authorities),
requireNotNull(member.id)
)
}
protected fun request(
path: String,
method: HttpMethod = HttpMethod.GET,
token: String? = ownerToken
): ResponseEntity<String> {
val headers = HttpHeaders().apply {
token?.let(::setBearerAuth)
contentType = MediaType.APPLICATION_JSON
set(HttpHeaders.ACCEPT_LANGUAGE, "ko")
}
val body = if (method == HttpMethod.POST) """{"content":"$REPLY"}""" else null
val response = restTemplate.exchange(path, method, HttpEntity(body, headers), String::class.java)
println("HTTP P3 $method $path request=$body status=${response.statusCodeValue} response=${response.body}")
return response
}
protected fun json(response: ResponseEntity<String>, status: Int = 200): JsonNode {
assertEquals(status, response.statusCodeValue, response.body)
val json = objectMapper.readTree(requireNotNull(response.body))
assertEquals(status == 200, json["success"].asBoolean(), json.toString())
return json
}
protected fun listPath(kind: Kind): String = when (kind) {
Kind.CONTENT -> "$BASE/content/comments"
Kind.FANTALK -> "$BASE/fantalks"
Kind.COMMUNITY -> "$BASE/community/posts/$postId/comments"
}
protected fun rootPath(kind: Kind): String = when (kind) {
Kind.CONTENT -> "$BASE/content/$contentId/comments/${roots.getValue(kind)}"
Kind.FANTALK, Kind.COMMUNITY -> "${listPath(kind)}/${roots.getValue(kind)}"
}
protected fun appData(kind: Kind): JsonNode {
val path = when (kind) {
Kind.CONTENT -> "/audio-content/comment/${roots.getValue(kind)}?timezone=UTC"
Kind.FANTALK -> "/api/v2/creator-channels/${owner.id}/fan-talks"
Kind.COMMUNITY -> "/creator-community/comment/${roots.getValue(kind)}?timezone=UTC"
}
return json(request(path, token = fanToken))["data"]
}
protected fun assertThreadHidden(kind: Kind) {
val admin = json(request(listPath(kind)))["data"]
assertEquals(0, admin["totalCount"].asInt())
assertEquals(0, admin["items"].size())
val app = appData(kind)
val (count, items) = when (kind) {
Kind.CONTENT, Kind.COMMUNITY -> "totalCount" to "items"
Kind.FANTALK -> "fanTalkCount" to "fanTalks"
}
assertEquals(0, app[count].asInt())
assertEquals(0, app[items].size())
}
enum class Kind(val entityName: String) {
CONTENT("AudioContentComment"), FANTALK("CreatorCheers"), COMMUNITY("CreatorCommunityComment")
}
protected companion object {
const val BASE = "/api/v2/creator-admin/comment-management"
const val REPLY = "P3 creator reply"
}
}