feat(mypage): 최신 공지의 상향 롤링을 연결한다

This commit is contained in:
2026-10-28 19:16:26 +09:00
parent 51a8d092a5
commit fe28b0ce59
4 changed files with 571 additions and 30 deletions
@@ -0,0 +1,424 @@
package kr.co.vividnext.sodalive.v2.mypage.notice
import android.app.Application
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.animation.Transformation
import android.widget.TextSwitcher
import android.widget.TextView
import android.widget.ViewAnimator
import androidx.core.content.IntentCompat
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.MutableLiveData
import androidx.test.core.app.ApplicationProvider
import io.reactivex.rxjava3.android.plugins.RxAndroidPlugins
import io.reactivex.rxjava3.plugins.RxJavaPlugins
import io.reactivex.rxjava3.schedulers.Schedulers
import io.reactivex.rxjava3.subjects.SingleSubject
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.common.ApiResponse
import kr.co.vividnext.sodalive.common.AppPreferencesDataStoreProvider
import kr.co.vividnext.sodalive.common.Constants
import kr.co.vividnext.sodalive.common.SharedPreferenceManager
import kr.co.vividnext.sodalive.common.SodaLiveApplicationHolder
import kr.co.vividnext.sodalive.mypage.MyPageFragment
import kr.co.vividnext.sodalive.mypage.MyPageViewModel
import kr.co.vividnext.sodalive.mypage.recent.RecentContentViewModel
import kr.co.vividnext.sodalive.settings.notice.NoticeApi
import kr.co.vividnext.sodalive.settings.notice.NoticeDetailActivity
import kr.co.vividnext.sodalive.settings.notice.NoticeItem
import kr.co.vividnext.sodalive.settings.notice.NoticeRepository
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.koin.core.context.startKoin
import org.koin.core.context.stopKoin
import org.koin.dsl.module
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.LooperMode
import org.robolectric.annotation.Implements
import org.robolectric.shadows.ShadowViewGroup
import org.robolectric.android.controller.ActivityController
import java.time.Duration
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], application = Application::class, shadows = [MyNoticeTickerTest.PlatformViewAnimatorShadow::class])
@LooperMode(LooperMode.Mode.PAUSED)
class MyNoticeTickerTest {
private val context: Context = ApplicationProvider.getApplicationContext()
private lateinit var row: View
private lateinit var titles: TextSwitcher
private lateinit var ticker: MyNoticeTicker
private val clicks = mutableListOf<NoticeItem>()
private val notices = listOf(
LatestNoticeResponse(9L, "첫 제목", "<p>첫 본문 전체 &amp;</p>", "2026-10-28"),
LatestNoticeResponse(2L, "둘째 제목", "<div>둘째 본문</div>", "2026-10-27"),
LatestNoticeResponse(7L, "셋째 제목", "<p>셋째 본문</p>", "2026-10-26")
)
@Before
fun setUp() {
row = View(context)
titles = TextSwitcher(context).apply { setFactory { TextView(context) } }
ticker = MyNoticeTicker(row, titles) { clicks += it }
}
@After
fun tearDown() {
ticker.destroy()
}
@Test
fun `빈 목록은 표시 내용과 클릭 대상을 비우고 예약하지 않는다`() {
ticker.setActive(true)
ticker.submitList(emptyList())
advance(20_000)
assertEquals("", title())
row.performClick()
assertTrue(clicks.isEmpty())
}
@Test
fun `한 개는 고정 표시하고 상세 payload 원문을 전달한다`() {
ticker.setActive(true)
ticker.submitList(notices.take(1))
assertCurrent(0)
advance(20_000)
assertCurrent(0)
assertNoAnimations()
}
@Test
fun `두 개는 4999ms에는 유지하고 5000ms마다 순환한다`() {
ticker.submitList(notices.take(2))
ticker.setActive(true)
assertCurrent(0)
advance(4_999)
assertEquals("첫 제목", title())
advance(1)
assertCurrent(1)
advance(5_000)
assertCurrent(0)
}
@Test
fun `세 개는 정렬 없이 서버 순서대로 마지막에서 처음으로 순환한다`() {
ticker.submitList(notices)
ticker.setActive(true)
assertCurrent(0)
listOf(1, 2, 0, 1).forEach {
advance(5_000)
assertCurrent(it)
}
}
@Test
fun `반복 활성화는 예약을 중복하거나 기존 5초를 연장하지 않는다`() {
ticker.submitList(notices)
ticker.setActive(true)
advance(2_000)
repeat(3) { ticker.setActive(true) }
advance(3_000)
assertCurrent(1)
advance(5_000)
assertCurrent(2)
}
@Test
fun `비활성화는 현재 항목을 유지하고 재개 시 새로운 5초를 센다`() {
ticker.submitList(notices)
ticker.setActive(true)
advance(5_000)
ticker.setActive(false)
assertNoAnimations()
advance(60_000)
assertCurrent(1)
ticker.setActive(true)
advance(4_999)
assertEquals("둘째 제목", title())
advance(1)
assertCurrent(2)
}
@Test
fun `숨김 중 도착한 목록은 첫 항목을 표시하되 복귀 전에는 예약하지 않는다`() {
ticker.setActive(true)
ticker.setActive(false)
ticker.submitList(notices)
advance(30_000)
assertCurrent(0)
ticker.setActive(true)
advance(4_999)
assertEquals("첫 제목", title())
advance(1)
assertCurrent(1)
}
@Test
fun `목록 교체는 애니메이션 없이 첫 항목으로 바꾸고 타이머를 다시 센다`() {
ticker.submitList(notices)
ticker.setActive(true)
advance(5_000)
ticker.submitList(listOf(notices[2], notices[0]))
assertCurrent(2)
assertNoAnimations()
advance(4_999)
assertEquals("셋째 제목", title())
advance(1)
assertCurrent(0)
}
@Test
fun `여러 개에서 한 개와 빈 목록으로 교체하면 이전 예약과 클릭 대상이 남지 않는다`() {
ticker.submitList(notices)
ticker.setActive(true)
advance(5_000)
ticker.submitList(listOf(notices[2]))
advance(10_000)
assertCurrent(2)
ticker.submitList(emptyList())
advance(10_000)
assertEquals("", title())
val clickCount = clicks.size
row.performClick()
assertEquals(clickCount, clicks.size)
assertNoAnimations()
ticker.submitList(notices.take(2))
advance(5_000)
assertCurrent(1)
}
@Test
fun `첫 5초 전환부터 현재 자식에 진입 애니메이션을 시작한다`() {
ticker.submitList(notices.take(2))
ticker.setActive(true)
assertEquals("첫 제목", title())
assertNoAnimations()
advance(4_999)
assertEquals("첫 제목", title())
assertNoAnimations()
Handler(Looper.getMainLooper()).postDelayed({
assertEquals("둘째 제목", title())
val animation = titles.currentView.animation
assertNotNull("첫 전환의 현재 자식에 진입 애니메이션이 있어야 한다", animation)
assertSame(titles.inAnimation, animation)
}, 1L)
advance(1)
}
@Test
fun `초기 목록은 무애니메이션이고 전환은 250ms 아래에서 위로 움직인다`() {
ticker.submitList(notices)
ticker.setActive(true)
assertEquals("첫 제목", title())
assertNoAnimations()
advance(5_000)
val incoming = titles.inAnimation
val outgoing = titles.outAnimation
assertNotNull(incoming)
assertNotNull(outgoing)
assertEquals(250L, incoming.duration)
assertEquals(250L, outgoing.duration)
incoming.initialize(100, 100, 100, 100)
outgoing.initialize(100, 100, 100, 100)
incoming.startTime = 0
outgoing.startTime = 0
val inTransform = Transformation()
val outTransform = Transformation()
incoming.getTransformation(125, inTransform)
outgoing.getTransformation(125, outTransform)
val inValues = FloatArray(9)
val outValues = FloatArray(9)
inTransform.matrix.getValues(inValues)
outTransform.matrix.getValues(outValues)
assertTrue(inValues[android.graphics.Matrix.MTRANS_Y] > 0f)
assertTrue(outValues[android.graphics.Matrix.MTRANS_Y] < 0f)
}
@Test
fun `파괴는 예약과 애니메이션과 클릭을 해제하고 늦은 응답을 무시한다`() {
ticker.submitList(notices)
ticker.setActive(true)
advance(5_000)
assertCurrent(1)
ticker.destroy()
assertNoAnimations()
assertNull(titles.inAnimation)
assertNull(titles.outAnimation)
assertFalse(row.hasOnClickListeners())
val clickCount = clicks.size
ticker.setActive(true)
ticker.submitList(listOf(notices[2]))
advance(30_000)
assertEquals("둘째 제목", title())
row.performClick()
assertEquals(clickCount, clicks.size)
ticker.destroy()
}
@Test
fun `Fragment 제목과 화살표 클릭은 매번 현재 공지의 상세 Intent를 전달한다`() = withMyPage { controller, fragment, response ->
response.onSuccess(ApiResponse(true, notices))
advance(0)
val noticeRow = fragment.binding.llLatestNotice
val switcher = fragment.binding.tsLatestNoticeTitle
listOf(0, 1, 2, 0).forEachIndexed { step, index ->
if (step > 0) advance(5_000)
assertEquals(notices[index].title, (switcher.currentView as TextView).text.toString())
listOf<View>(switcher, noticeRow.getChildAt(noticeRow.childCount - 1)).forEach { target ->
tap(noticeRow, target)
val intent = shadowOf(controller.get()).nextStartedActivity
assertNotNull(intent)
assertEquals(NoticeDetailActivity::class.java.name, intent.component?.className)
val payload = IntentCompat.getParcelableExtra(intent, Constants.EXTRA_NOTICE, NoticeItem::class.java)!!
assertEquals(notices[index].title, payload.title)
assertEquals(notices[index].content, payload.content)
assertEquals(notices[index].date, payload.date)
assertNull(shadowOf(controller.get()).nextStartedActivity)
}
}
}
@Test
fun `Fragment는 STARTED 상태의 숨김과 지연 응답 배경 복귀 및 View 파괴를 처리한다`() = withMyPage { controller, fragment, response ->
val manager = controller.get().supportFragmentManager
manager.beginTransaction().hide(fragment).commitNow()
assertTrue(fragment.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED))
response.onSuccess(ApiResponse(true, notices))
advance(20_000)
val switcher = fragment.binding.tsLatestNoticeTitle
assertEquals("첫 제목", (switcher.currentView as TextView).text.toString())
manager.beginTransaction().show(fragment).commitNow()
advance(4_000)
assertEquals("첫 제목", (switcher.currentView as TextView).text.toString())
advance(1_000)
assertEquals("둘째 제목", (switcher.currentView as TextView).text.toString())
controller.pause().stop()
advance(20_000)
assertEquals("둘째 제목", (switcher.currentView as TextView).text.toString())
controller.start().resume()
advance(4_000)
assertEquals("둘째 제목", (switcher.currentView as TextView).text.toString())
advance(1_000)
assertEquals("셋째 제목", (switcher.currentView as TextView).text.toString())
val noticeRow = fragment.binding.llLatestNotice
manager.beginTransaction().remove(fragment).commitNow()
advance(20_000)
assertEquals("셋째 제목", (switcher.currentView as TextView).text.toString())
assertFalse(noticeRow.hasOnClickListeners())
assertNull(switcher.inAnimation)
assertNull(switcher.outAnimation)
}
@Test
fun `이전 테스트의 저장된 토큰과 무관하게 공지 fixture는 비로그인으로 시작한다`() {
runBlocking {
AppPreferencesDataStoreProvider.get(context).edit {
it[stringPreferencesKey(Constants.PREF_TOKEN)] = "previous-test-token"
}
}
withMyPage { _, _, _ ->
assertEquals("", SharedPreferenceManager.token)
}
}
private fun assertCurrent(index: Int) {
val expected = notices[index]
assertEquals(expected.title, title())
row.performClick()
val payload = clicks.last()
assertEquals(expected.title, payload.title)
assertEquals(expected.content, payload.content)
assertEquals(expected.date, payload.date)
}
private fun assertNoAnimations() {
assertNull(titles.animation)
repeat(titles.childCount) { assertNull(titles.getChildAt(it).animation) }
}
private fun title() = (titles.currentView as TextView).text.toString()
private fun advance(milliseconds: Long) {
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(milliseconds))
}
private fun tap(row: ViewGroup, target: View) {
row.measure(View.MeasureSpec.makeMeasureSpec(1080, View.MeasureSpec.EXACTLY), View.MeasureSpec.UNSPECIFIED)
row.layout(0, 0, row.measuredWidth, row.measuredHeight)
val time = SystemClock.uptimeMillis()
listOf(MotionEvent.ACTION_DOWN, MotionEvent.ACTION_UP).forEach { action ->
val event = MotionEvent.obtain(time, time, action, target.x + target.width / 2f, target.y + target.height / 2f, 0)
row.dispatchTouchEvent(event)
event.recycle()
}
advance(0)
}
private fun withMyPage(
test: (
ActivityController<FragmentActivity>,
MyPageFragment,
SingleSubject<ApiResponse<List<LatestNoticeResponse>>>
) -> Unit
) {
RxJavaPlugins.setIoSchedulerHandler { Schedulers.trampoline() }
RxAndroidPlugins.setInitMainThreadSchedulerHandler { Schedulers.trampoline() }
RxAndroidPlugins.setMainThreadSchedulerHandler { Schedulers.trampoline() }
SharedPreferenceManager.resetForTest()
runBlocking {
AppPreferencesDataStoreProvider.get(context).edit {
it[stringPreferencesKey(Constants.PREF_TOKEN)] = ""
}
}
SharedPreferenceManager.init(context)
SodaLiveApplicationHolder.init(context.applicationContext as Application)
val api: NoticeApi = mock()
val response = SingleSubject.create<ApiResponse<List<LatestNoticeResponse>>>()
whenever(api.getLatestNotices()).thenReturn(response)
val viewModel = MyPageViewModel(mock(), NoticeRepository(api))
val recent: RecentContentViewModel = mock()
whenever(recent.getRecentContents(10)).thenReturn(MutableLiveData(emptyList()))
whenever(recent.recentContentsCount).thenReturn(MutableLiveData(0))
startKoin { modules(module { single { viewModel }; single { recent } }) }
val controller = Robolectric.buildActivity(FragmentActivity::class.java)
controller.get().setTheme(R.style.Theme_SodaLive)
try {
controller.setup()
val fragment = MyPageFragment()
controller.get().supportFragmentManager.beginTransaction()
.add(android.R.id.content, fragment).commitNow()
test(controller, fragment, response)
} finally {
controller.pause().stop().destroy()
stopKoin()
RxJavaPlugins.reset()
RxAndroidPlugins.reset()
SharedPreferenceManager.resetForTest()
}
}
@Implements(ViewAnimator::class)
class PlatformViewAnimatorShadow : ShadowViewGroup()
}