207 lines
10 KiB
Kotlin
207 lines
10 KiB
Kotlin
package kr.co.vividnext.sodalive.content
|
|
|
|
import kr.co.vividnext.sodalive.admin.content.series.genre.SeriesGenre
|
|
import kr.co.vividnext.sodalive.chat.character.ChatCharacter
|
|
import kr.co.vividnext.sodalive.chat.original.OriginalWork
|
|
import kr.co.vividnext.sodalive.common.BaseEntity
|
|
import kr.co.vividnext.sodalive.configs.QueryDslConfig
|
|
import kr.co.vividnext.sodalive.content.category.Category
|
|
import kr.co.vividnext.sodalive.content.theme.AudioContentTheme
|
|
import kr.co.vividnext.sodalive.content.theme.AudioContentThemeQueryRepository
|
|
import kr.co.vividnext.sodalive.creator.admin.content.series.Series
|
|
import kr.co.vividnext.sodalive.i18n.translation.DetectedLanguage
|
|
import kr.co.vividnext.sodalive.i18n.translation.LanguageProviderId
|
|
import kr.co.vividnext.sodalive.i18n.translation.LanguageTranslationTargetType
|
|
import kr.co.vividnext.sodalive.i18n.translation.ResourceTranslationJobScheduler
|
|
import kr.co.vividnext.sodalive.i18n.translation.TranslationJob
|
|
import kr.co.vividnext.sodalive.i18n.translation.TranslationJobRepository
|
|
import kr.co.vividnext.sodalive.i18n.translation.TranslationJobScheduler
|
|
import kr.co.vividnext.sodalive.i18n.translation.TranslationJobSchedulerTestConfiguration
|
|
import kr.co.vividnext.sodalive.i18n.translation.TranslationJobStatus
|
|
import kr.co.vividnext.sodalive.i18n.translation.TranslationSourceExtractor
|
|
import kr.co.vividnext.sodalive.member.Member
|
|
import kr.co.vividnext.sodalive.member.MemberRole
|
|
import kr.co.vividnext.sodalive.v2.creator.channel.community.translation.application.CreatorCommunityTranslationService
|
|
import org.junit.jupiter.api.AfterEach
|
|
import org.junit.jupiter.api.Assertions.assertEquals
|
|
import org.junit.jupiter.api.Assertions.assertNull
|
|
import org.junit.jupiter.api.Assertions.assertThrows
|
|
import org.junit.jupiter.api.DisplayName
|
|
import org.junit.jupiter.params.ParameterizedTest
|
|
import org.junit.jupiter.params.provider.EnumSource
|
|
import org.mockito.Mockito
|
|
import org.springframework.beans.factory.annotation.Autowired
|
|
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase
|
|
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest
|
|
import org.springframework.boot.test.mock.mockito.MockBean
|
|
import org.springframework.context.annotation.Import
|
|
import org.springframework.dao.DataIntegrityViolationException
|
|
import org.springframework.jdbc.core.JdbcTemplate
|
|
import org.springframework.test.util.AopTestUtils
|
|
import org.springframework.transaction.PlatformTransactionManager
|
|
import org.springframework.transaction.annotation.Propagation
|
|
import org.springframework.transaction.annotation.Transactional
|
|
import org.springframework.transaction.support.TransactionTemplate
|
|
import javax.persistence.EntityManager
|
|
|
|
@DataJpaTest(
|
|
properties = [
|
|
"spring.cache.type=none",
|
|
"spring.datasource.url=jdbc:h2:mem:metadata-language-detect;MODE=MySQL;NON_KEYWORDS=VALUE;DB_CLOSE_ON_EXIT=FALSE"
|
|
]
|
|
)
|
|
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
|
|
@Import(
|
|
QueryDslConfig::class,
|
|
AudioContentThemeQueryRepository::class,
|
|
LanguageDetectListener::class,
|
|
kr.co.vividnext.sodalive.v2.contenttranslation.application.ContentTranslationWriteService::class,
|
|
kr.co.vividnext.sodalive.v2.contenttranslation.adapter.out.persistence.JpaContentTranslationOverrideStore::class,
|
|
kr.co.vividnext.sodalive.v2.contenttranslation.application.ContentTranslationSourceInvalidationService::class,
|
|
kr.co.vividnext.sodalive.v2.contenttranslation.application.ContentTranslationLanguageService::class,
|
|
TranslationSourceExtractor::class,
|
|
ResourceTranslationJobScheduler::class,
|
|
TranslationJobScheduler::class,
|
|
TranslationJobSchedulerTestConfiguration::class
|
|
)
|
|
@Transactional(propagation = Propagation.NOT_SUPPORTED)
|
|
class MetadataLanguageDetectTransactionTest @Autowired constructor(
|
|
private val languageDetectListener: LanguageDetectListener,
|
|
private val jobRepository: TranslationJobRepository,
|
|
private val entityManager: EntityManager,
|
|
private val jdbcTemplate: JdbcTemplate,
|
|
transactionManager: PlatformTransactionManager
|
|
) {
|
|
private val transaction = TransactionTemplate(transactionManager)
|
|
private val fixtures = mutableListOf<BaseEntity>()
|
|
|
|
@MockBean
|
|
private lateinit var detectionCache: LanguageDetectionCacheService
|
|
|
|
@MockBean
|
|
private lateinit var communityTranslationService: CreatorCommunityTranslationService
|
|
|
|
@AfterEach
|
|
fun cleanUp() {
|
|
transaction.executeWithoutResult {
|
|
jobRepository.deleteAll()
|
|
fixtures.asReversed().forEach { entity ->
|
|
entityManager.remove(entityManager.find(entity.javaClass, entity.id))
|
|
}
|
|
}
|
|
}
|
|
|
|
@ParameterizedTest
|
|
@EnumSource(MetadataTarget::class)
|
|
@DisplayName("메타데이터 감지는 언어와 전체 번역 작업을 커밋 전 같은 트랜잭션에 저장한다")
|
|
fun shouldPersistDetectedLanguageAndJobsInSameTransaction(target: MetadataTarget) {
|
|
val event = prepareDetection(target)
|
|
// 비동기 어댑터를 제외한 실제 리스너와 Spring scheduler를 하나의 DB 트랜잭션에서 실행한다.
|
|
val listener: LanguageDetectListener = AopTestUtils.getTargetObject(languageDetectListener)
|
|
|
|
val beforeCommit = transaction.execute {
|
|
listener.detectLanguage(event)
|
|
readState(target, event.id)
|
|
}!!
|
|
val afterCommit = transaction.execute { readState(target, event.id) }!!
|
|
|
|
val expectedJobs = target.fields.flatMap { (field, text) ->
|
|
listOf(Triple(field, "en", text), Triple(field, "ja", text))
|
|
}.toSet()
|
|
listOf(beforeCommit, afterCommit).forEach { (languageCode, jobs) ->
|
|
assertEquals("ko", languageCode)
|
|
assertEquals(expectedJobs.size, jobs.size)
|
|
assertEquals(expectedJobs, jobs.map { Triple(it.fieldKey, it.targetLanguage, it.sourceText) }.toSet())
|
|
assertEquals(setOf("ko"), jobs.map { it.sourceLanguage }.toSet())
|
|
assertEquals(setOf(TranslationJobStatus.PENDING), jobs.map { it.status }.toSet())
|
|
}
|
|
}
|
|
|
|
@ParameterizedTest
|
|
@EnumSource(MetadataTarget::class)
|
|
@DisplayName("번역 작업 INSERT 실패는 감지 언어와 먼저 저장한 작업을 모두 롤백한다")
|
|
fun shouldRollBackDetectedLanguageAndJobsWhenJobInsertFails(target: MetadataTarget) {
|
|
val event = prepareDetection(target)
|
|
val listener: LanguageDetectListener = AopTestUtils.getTargetObject(languageDetectListener)
|
|
// H2 전용 일시 제약으로 en INSERT 이후 ja INSERT를 실제 DB에서 실패시킨다.
|
|
jdbcTemplate.execute(
|
|
"ALTER TABLE translation_job ADD CONSTRAINT metadata_reject_ja CHECK (target_language <> 'ja')"
|
|
)
|
|
try {
|
|
assertThrows(DataIntegrityViolationException::class.java) {
|
|
transaction.executeWithoutResult { listener.detectLanguage(event) }
|
|
}
|
|
|
|
val (languageCode, jobs) = transaction.execute { readState(target, event.id) }!!
|
|
assertNull(languageCode)
|
|
assertEquals(emptyList<TranslationJob>(), jobs)
|
|
} finally {
|
|
jdbcTemplate.execute("ALTER TABLE translation_job DROP CONSTRAINT metadata_reject_ja")
|
|
}
|
|
}
|
|
|
|
private fun prepareDetection(target: MetadataTarget): LanguageDetectEvent {
|
|
val query = if (target == MetadataTarget.CONTENT) "원문 제목 원문 설명" else "원문 제목"
|
|
Mockito.`when`(detectionCache.detectWithCache(query))
|
|
.thenReturn(DetectedLanguage("ko", LanguageProviderId.PAPAGO))
|
|
val id = transaction.execute {
|
|
val owner = persist(Member(password = "password", nickname = "metadata-owner", role = MemberRole.CREATOR))
|
|
val metadata = when (target) {
|
|
MetadataTarget.CONTENT -> AudioContent("원문 제목", "원문 설명", null).apply {
|
|
member = owner
|
|
theme = persist(AudioContentTheme("theme", "theme.png"))
|
|
}
|
|
MetadataTarget.CHARACTER -> ChatCharacter(
|
|
characterUUID = "metadata-character",
|
|
name = "원문 제목",
|
|
description = "원문 설명",
|
|
systemPrompt = "system prompt"
|
|
).apply { creatorMember = owner }
|
|
MetadataTarget.SERIES -> Series("원문 제목", "원문 설명").apply {
|
|
member = owner
|
|
genre = persist(SeriesGenre("genre"))
|
|
}
|
|
MetadataTarget.ORIGINAL_WORK -> OriginalWork(
|
|
title = "원문 제목",
|
|
contentType = "소설",
|
|
category = "판타지",
|
|
description = "원문 설명"
|
|
)
|
|
MetadataTarget.CREATOR_CONTENT_CATEGORY -> Category("원문 제목").apply { member = owner }
|
|
}
|
|
requireNotNull(persist(metadata).id)
|
|
}!!
|
|
return LanguageDetectEvent(id, query, LanguageDetectTargetType.valueOf(target.name))
|
|
}
|
|
|
|
private fun <T : BaseEntity> persist(entity: T): T {
|
|
entityManager.persist(entity)
|
|
fixtures.add(entity)
|
|
return entity
|
|
}
|
|
|
|
private fun readState(target: MetadataTarget, id: Long): Pair<String?, List<TranslationJob>> {
|
|
entityManager.flush()
|
|
entityManager.clear()
|
|
val languageCode = entityManager.createQuery(
|
|
"select metadata.languageCode from ${target.entityClass.simpleName} metadata where metadata.id = :id",
|
|
String::class.java
|
|
).setParameter("id", id).singleResult
|
|
val jobs = jobRepository.findAll().filter {
|
|
it.resourceType == LanguageTranslationTargetType.valueOf(target.name) && it.resourceId == id
|
|
}
|
|
return languageCode to jobs
|
|
}
|
|
|
|
enum class MetadataTarget(val entityClass: Class<out BaseEntity>, val fields: Map<String, String>) {
|
|
CONTENT(AudioContent::class.java, mapOf("title" to "원문 제목", "detail" to "원문 설명")),
|
|
CHARACTER(ChatCharacter::class.java, mapOf("name" to "원문 제목", "description" to "원문 설명")),
|
|
SERIES(Series::class.java, mapOf("title" to "원문 제목", "introduction" to "원문 설명")),
|
|
ORIGINAL_WORK(
|
|
OriginalWork::class.java,
|
|
mapOf("title" to "원문 제목", "contentType" to "소설", "category" to "판타지", "description" to "원문 설명")
|
|
),
|
|
CREATOR_CONTENT_CATEGORY(Category::class.java, mapOf("category" to "원문 제목"))
|
|
}
|
|
}
|