feat(main): 메인 탭 당겨서 새로고침을 추가한다

This commit is contained in:
2026-07-22 17:48:33 +09:00
parent b17e250665
commit 6755c8ae99
27 changed files with 1830 additions and 239 deletions
@@ -0,0 +1,73 @@
package kr.co.vividnext.sodalive.v2.main
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.File
class PullRefreshRequestRaceSourceTest {
@Test
fun `첫 페이지 ViewModel은 중복 loading 요청과 오래된 응답을 방어한다`() {
listOf(
"app/src/main/java/kr/co/vividnext/sodalive/v2/main/home/HomeRecommendationViewModel.kt",
"app/src/main/java/kr/co/vividnext/sodalive/v2/main/home/HomeCreatorRankingViewModel.kt",
"app/src/main/java/kr/co/vividnext/sodalive/v2/main/home/HomeFollowingViewModel.kt",
"app/src/main/java/kr/co/vividnext/sodalive/v2/main/content/ContentMainViewModel.kt"
).forEach { path ->
val source = projectFile(path).readText()
assertTrue("$path should ignore duplicate first-page loads", source.contains("if (_isLoading.value == true) return"))
assertTrue("$path should track latest first-page request", source.contains("private var requestGeneration: Int = 0"))
assertTrue("$path should create a request generation", source.contains("val generation = ++requestGeneration"))
assertTrue(
"$path should ignore stale success responses",
source.contains("if (generation != requestGeneration) return@subscribe")
)
}
}
@Test
fun `자동 로딩 중 pull refresh는 같은 key 요청만 무시하고 다른 조건 요청은 허용한다`() {
listOf(
"app/src/main/java/kr/co/vividnext/sodalive/v2/main/content/ContentRankingViewModel.kt",
"app/src/main/java/kr/co/vividnext/sodalive/v2/main/content/ContentAllTabViewModel.kt",
"app/src/main/java/kr/co/vividnext/sodalive/v2/main/chat/ChatMainViewModel.kt"
).forEach { path ->
val source = projectFile(path).readText()
assertTrue("$path should track active first-page request key", source.contains("activeFirstPageKey"))
assertTrue(
"$path should ignore only same first-page key",
source.contains("if (activeFirstPageKey == requestKey) return")
)
assertTrue("$path should clear latest first-page key", source.contains("clearActiveFirstPageKey(requestKey,"))
}
}
@Test
fun `fragment는 pull refresh 완료를 시작한 탭이나 filter에만 묶는다`() {
val home = projectFile("app/src/main/java/kr/co/vividnext/sodalive/v2/main/home/HomeMainFragment.kt").readText()
val content = projectFile("app/src/main/java/kr/co/vividnext/sodalive/v2/main/content/ContentMainFragment.kt").readText()
val chat = projectFile("app/src/main/java/kr/co/vividnext/sodalive/v2/main/chat/ChatMainFragment.kt").readText()
assertTrue(home.contains("private var refreshingHomeTabIndex: Int? = null"))
assertTrue(home.contains("refreshingHomeTabIndex = currentHomeTabIndex"))
assertTrue(home.contains("if (refreshingHomeTabIndex != tabIndex) return"))
assertTrue(home.contains("scrollHomeTabToTop(tabIndex)"))
assertTrue(content.contains("private var refreshingContentTab: Int? = null"))
assertTrue(content.contains("refreshingContentTab = currentContentTab"))
assertTrue(content.contains("if (refreshingContentTab != tab) return"))
assertTrue(content.contains("scrollContentTabToTop(tab)"))
assertTrue(chat.contains("private var refreshingChatFilter: ChatRoomFilter? = null"))
assertTrue(chat.contains("refreshingChatFilter = selectedFilter"))
assertTrue(chat.contains("val isRefreshForCurrentFilter = refreshingChatFilter == selectedFilter"))
}
private fun projectFile(relativePath: String): File {
val candidates = listOf(File(relativePath), File("../$relativePath"))
return candidates.firstOrNull { it.exists() }
?: error("Missing project file: $relativePath")
}
}
@@ -11,7 +11,6 @@ import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.RecyclerView
import androidx.test.core.app.ApplicationProvider
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.v2.widget.CapsuleTabBarView
@@ -50,41 +49,16 @@ class ChatMainFragmentLayoutTest {
val root = inflateView(R.layout.fragment_v2_main_chat) as ConstraintLayout
val titleBar = requireNotNull(root.findViewById<View>(R.id.view_chat_title_bar))
val tabBar = requireNotNull(root.findViewById<CapsuleTabBarView>(R.id.view_chat_filter_tabs))
val recyclerView = requireNotNull(root.findViewById<RecyclerView>(R.id.rv_chat_rooms))
val emptyMessage = requireNotNull(root.findViewById<TextView>(R.id.tv_chat_empty_message))
assertEquals(Color.BLACK, (root.background as ColorDrawable).color)
assertSame(root, titleBar.parent)
assertSame(root, tabBar.parent)
assertSame(root, recyclerView.parent)
assertSame(root, emptyMessage.parent)
assertEquals(View.GONE, emptyMessage.visibility)
assertFalse(root.containsClassName("com.google.android.material.bottomnavigation.BottomNavigationView"))
assertFalse(root.containsViewIdContaining("unread"))
}
@Test
fun `채팅 fragment list는 계획된 constraint를 사용한다`() {
val root = inflateView(R.layout.fragment_v2_main_chat)
val titleBar = requireNotNull(root.findViewById<View>(R.id.view_chat_title_bar))
val tabBar = requireNotNull(root.findViewById<CapsuleTabBarView>(R.id.view_chat_filter_tabs))
val recyclerView = requireNotNull(root.findViewById<RecyclerView>(R.id.rv_chat_rooms))
val emptyMessage = requireNotNull(root.findViewById<TextView>(R.id.tv_chat_empty_message))
val tabParams = tabBar.layoutParams as ConstraintLayout.LayoutParams
val listParams = recyclerView.layoutParams as ConstraintLayout.LayoutParams
val emptyParams = emptyMessage.layoutParams as ConstraintLayout.LayoutParams
assertEquals(60.dpToPx(), titleBar.layoutParams.height)
assertEquals(52.dpToPx(), tabBar.layoutParams.height)
assertEquals(R.id.view_chat_title_bar, tabParams.topToBottom)
assertEquals(R.id.view_chat_filter_tabs, listParams.topToBottom)
assertEquals(ConstraintLayout.LayoutParams.PARENT_ID, listParams.bottomToBottom)
assertEquals(R.id.view_chat_filter_tabs, emptyParams.topToBottom)
assertEquals(ConstraintLayout.LayoutParams.PARENT_ID, emptyParams.bottomToBottom)
assertEquals(false, recyclerView.clipToPadding)
assertTrue(recyclerView.paddingBottom >= 28.dpToPx())
}
@Test
fun `채팅 fragment source는 화면 초기 구성과 첫 페이지 로드를 연결한다`() {
val source = chatMainFragmentSource()
@@ -125,6 +99,26 @@ class ChatMainFragmentLayoutTest {
assertTrue(source.contains("viewModel.toastLiveData.observe(viewLifecycleOwner)"))
}
@Test
fun `chat refresh reloads first page with selected filter`() {
val source = chatMainFragmentSource()
assertTrue(source.contains("binding.swipeChatRooms.setOnRefreshListener"))
assertTrue(source.contains("binding.swipeChatRooms.setOnChildScrollUpCallback"))
assertTrue(source.contains("binding.rvChatRooms.canScrollVertically(-1)"))
assertTrue(source.contains("viewModel.loadFirstPage(selectedFilter)"))
assertTrue(source.contains("binding.swipeChatRooms.isRefreshing = false"))
}
@Test
fun `채팅 empty 상태에서 pull refresh loading은 empty message를 숨기지 않는다`() {
val source = chatMainFragmentSource()
assertTrue(source.contains("ChatRoomListUiState.Loading -> {"))
assertTrue(source.contains("if (!isChatPullRefreshing)"))
assertTrue(source.contains("binding.tvChatEmptyMessage.isVisible = false"))
}
@Test
fun `채팅 fragment source는 AI와 DM 항목을 각각 채팅방으로 이동한다`() {
val source = chatMainFragmentSource()
@@ -144,21 +138,61 @@ class ChatMainFragmentLayoutTest {
val source = chatMainFragmentSource()
assertTrue(source.contains("setOnTabSelectedListener"))
assertTrue(source.contains("rvChatRooms.scrollToPosition(0)"))
assertTrue(
source.contains(
"val shouldScrollToTop = !isRestoredPullRefreshError &&"
)
)
assertTrue(source.contains("((isChatPullRefreshing && isRefreshForCurrentFilter) || !state.isAppending)"))
assertTrue(source.contains("if (shouldScrollToTop)"))
assertTrue(source.contains("!state.isAppending"))
}
@Test
fun `채팅 pull refresh 실패로 이전 상태가 재방출되면 스크롤을 최상단으로 이동하지 않는다`() {
val source = chatMainFragmentSource()
assertTrue(source.contains("private var lastRenderedChatContentState"))
assertTrue(source.contains("private var refreshingChatFilter: ChatRoomFilter? = null"))
assertTrue(source.contains("private fun cancelChatPullRefresh()"))
assertTrue(source.contains("if (refreshingChatFilter != null && refreshingChatFilter != filter)"))
assertTrue(source.contains("binding.swipeChatRooms.isRefreshing = false"))
assertTrue(
source.contains("val isRestoredPullRefreshError = isChatPullRefreshing &&")
)
assertTrue(source.contains("isRefreshForCurrentFilter &&"))
assertTrue(source.contains("lastRenderedChatContentState === state"))
assertTrue(
source.contains(
"val shouldScrollToTop = !isRestoredPullRefreshError &&"
)
)
assertTrue(source.contains("if (shouldScrollToTop)"))
}
@Test
fun `채팅 fragment source는 탭별 empty state 문구를 표시한다`() {
val source = chatMainFragmentSource()
val filter = projectFile(
"app/src/main/java/kr/co/vividnext/sodalive/v2/main/chat/model/ChatRoomFilter.kt"
).readText()
val errorBranch = source.substringBetween(
"is ChatRoomListUiState.Error ->",
"ChatRoomListUiState.Loading ->"
)
val emptyBranch = source.substringBetween(
"ChatRoomListUiState.Empty ->",
"is ChatRoomListUiState.Error ->"
)
assertTrue(source.contains("private var selectedFilter: ChatRoomFilter = ChatRoomFilter.ALL"))
assertTrue(source.contains("private var isChatPullRefreshing = false"))
assertTrue(source.contains("isChatPullRefreshing = true"))
assertTrue(source.contains("refreshingChatFilter = selectedFilter"))
assertTrue(source.contains("binding.tvChatEmptyMessage.setText(selectedFilter.emptyMessageResId())"))
assertTrue(source.contains("ChatRoomListUiState.Empty -> bindChatRooms(emptyList(), showEmpty = true)"))
assertTrue(source.contains("is ChatRoomListUiState.Error -> bindChatRooms(emptyList(), showEmpty = false)"))
assertTrue(emptyBranch.contains("bindChatRooms(emptyList(), showEmpty = true)"))
assertTrue(errorBranch.contains("if (!isChatPullRefreshing || !isRefreshForCurrentFilter)"))
assertTrue(errorBranch.contains("bindChatRooms(emptyList(), showEmpty = false)"))
assertTrue(source.contains("binding.rvChatRooms.isVisible = !showEmpty"))
assertTrue(filter.contains("ChatRoomFilter.ALL -> R.string.screen_chat_empty_all"))
assertTrue(filter.contains("ChatRoomFilter.AI -> R.string.screen_chat_empty_ai"))
@@ -174,6 +208,14 @@ class ChatMainFragmentLayoutTest {
"app/src/main/java/kr/co/vividnext/sodalive/v2/main/chat/ChatMainFragment.kt"
).readText()
private fun String.substringBetween(startMarker: String, endMarker: String): String {
val startIndex = indexOf(startMarker)
assertTrue("Missing start marker: $startMarker", startIndex >= 0)
val endIndex = indexOf(endMarker, startIndex + startMarker.length)
assertTrue("Missing end marker: $endMarker", endIndex >= 0)
return substring(startIndex, endIndex)
}
private fun projectFile(relativePath: String): File {
val candidates = listOf(
File(relativePath),
@@ -197,9 +239,4 @@ class ChatMainFragmentLayoutTest {
if (this !is ViewGroup) return false
return (0 until childCount).any { getChildAt(it).containsClassName(className) }
}
private fun Int.dpToPx(): Int {
val context = ApplicationProvider.getApplicationContext<Context>()
return (this * context.resources.displayMetrics.density).toInt()
}
}
@@ -89,6 +89,25 @@ class ChatMainViewModelTest {
assertEquals(1, api.calls.size)
}
@Test
fun `loadFirstPage with current filter requests first page and replaces existing rooms`() {
api.enqueueSuccess(page(rooms = listOf(room(roomId = 1L)), hasMore = true, nextCursor = "next"))
viewModel.loadFirstPage(ChatRoomFilter.AI)
api.enqueueSuccess(page(rooms = listOf(room(roomId = 2L)), hasMore = false, nextCursor = null))
viewModel.loadFirstPage(ChatRoomFilter.AI)
assertEquals(
listOf(
ApiCall("Bearer test-token", "AI", null),
ApiCall("Bearer test-token", "AI", null)
),
api.calls
)
val state = viewModel.chatRoomStateLiveData.value as ChatRoomListUiState.Content
assertEquals(listOf(2L), state.items.map { it.roomId })
}
@Test
fun `첫 페이지 success와 rooms가 있으면 Content를 emit한다`() {
api.enqueueSuccess(page(rooms = listOf(room(roomId = 10L, targetName = "크리에이터"))))
@@ -128,6 +147,95 @@ class ChatMainViewModelTest {
assertFalse(state.isAppending)
}
@Test
fun `같은 filter 첫 페이지 refresh 실패 후 loadNextPage는 이전 cursor로 append한다`() {
api.enqueueSuccess(page(rooms = listOf(room(roomId = 1L)), hasMore = true, nextCursor = "next-1"))
viewModel.loadFirstPage(ChatRoomFilter.AI)
api.enqueueSuccess(ApiResponse(false, null, "refresh failed"))
viewModel.loadFirstPage(ChatRoomFilter.AI)
val restoredState = viewModel.chatRoomStateLiveData.requireValue() as ChatRoomListUiState.Content
api.enqueueSuccess(page(rooms = listOf(room(roomId = 2L)), hasMore = false, nextCursor = null))
viewModel.loadNextPage()
val appendedState = viewModel.chatRoomStateLiveData.requireValue() as ChatRoomListUiState.Content
assertEquals(listOf(1L), restoredState.items.map { it.roomId })
assertEquals(ApiCall("Bearer test-token", "AI", "next-1"), api.calls.last())
assertEquals(listOf(1L, 2L), appendedState.items.map { it.roomId })
}
@Test
fun `같은 filter 첫 페이지 요청이 진행 중이면 중복 호출을 무시한다`() {
val pending = SingleSubject.create<ApiResponse<ChatRoomListPageResponse>>()
api.enqueue(pending)
viewModel.loadFirstPage(ChatRoomFilter.ALL)
viewModel.loadFirstPage(ChatRoomFilter.ALL)
assertEquals(1, api.calls.size)
pending.onSuccess(ApiResponse(true, page(rooms = listOf(room(roomId = 1L))), null))
}
@Test
fun `다른 filter 첫 페이지 요청은 기존 요청 진행 중에도 허용한다`() {
val pendingAll = SingleSubject.create<ApiResponse<ChatRoomListPageResponse>>()
val pendingDm = SingleSubject.create<ApiResponse<ChatRoomListPageResponse>>()
api.enqueue(pendingAll)
api.enqueue(pendingDm)
viewModel.loadFirstPage(ChatRoomFilter.ALL)
viewModel.loadFirstPage(ChatRoomFilter.DM)
assertEquals(
listOf(
ApiCall("Bearer test-token", "ALL", null),
ApiCall("Bearer test-token", "DM", null)
),
api.calls
)
pendingAll.onSuccess(ApiResponse(true, page(rooms = listOf(room(roomId = 1L))), null))
pendingDm.onSuccess(ApiResponse(true, page(rooms = listOf(room(roomId = 2L))), null))
}
@Test
fun `filter를 A에서 B로 바꾼 뒤 A 응답 전 다시 A를 요청하면 최신 A 요청을 보낸다`() {
val pendingAllFirst = SingleSubject.create<ApiResponse<ChatRoomListPageResponse>>()
val pendingDm = SingleSubject.create<ApiResponse<ChatRoomListPageResponse>>()
val pendingAllLatest = SingleSubject.create<ApiResponse<ChatRoomListPageResponse>>()
api.enqueue(pendingAllFirst)
api.enqueue(pendingDm)
api.enqueue(pendingAllLatest)
viewModel.loadFirstPage(ChatRoomFilter.ALL)
viewModel.loadFirstPage(ChatRoomFilter.DM)
viewModel.loadFirstPage(ChatRoomFilter.ALL)
assertEquals(
listOf(
ApiCall("Bearer test-token", "ALL", null),
ApiCall("Bearer test-token", "DM", null),
ApiCall("Bearer test-token", "ALL", null)
),
api.calls
)
pendingAllFirst.onSuccess(ApiResponse(true, page(rooms = listOf(room(roomId = 1L))), null))
pendingDm.onSuccess(ApiResponse(true, page(rooms = listOf(room(roomId = 2L, chatType = "DM"))), null))
pendingAllLatest.onSuccess(
ApiResponse(true, page(rooms = listOf(room(roomId = 3L)), hasMore = true, nextCursor = "all-next"), null)
)
val state = viewModel.chatRoomStateLiveData.requireValue() as ChatRoomListUiState.Content
assertEquals(listOf(3L), state.items.map { it.roomId })
api.enqueueSuccess(page(rooms = listOf(room(roomId = 4L)), hasMore = false, nextCursor = null))
viewModel.loadNextPage()
assertEquals(ApiCall("Bearer test-token", "ALL", "all-next"), api.calls.last())
}
@Test
fun `hasMore가 false이면 다음 페이지 API를 호출하지 않는다`() {
api.enqueueSuccess(page(rooms = listOf(room(roomId = 1L)), hasMore = false, nextCursor = null))
@@ -517,6 +517,218 @@ class ContentAllTabViewModelTest {
verifyGetContents(page = 1)
}
@Test
fun `첫 페이지 refresh 실패 후 loadMore는 이전 page 다음을 append한다`() {
whenever(
repository.getContents(
"Bearer test-token",
MainContentAllType.AUDIO,
ContentSort.LATEST,
0,
DEFAULT_PAGE_SIZE,
null
)
)
.thenReturn(
Single.just(ApiResponse(true, response(audios = listOf(audio(1L)), hasNext = true), null)),
Single.just(ApiResponse(false, null, "refresh failed"))
)
stubGetContents(
page = 1,
response = Single.just(ApiResponse(true, response(page = 1, audios = listOf(audio(2L)), hasNext = false), null))
)
viewModel.loadContents()
viewModel.loadContents()
val restoredState = viewModel.allTabStateLiveData.requireValue() as MainContentAllTabUiState.Content
viewModel.loadMore()
val appendedState = viewModel.allTabStateLiveData.requireValue() as MainContentAllTabUiState.Content
assertEquals(0, restoredState.page)
assertTrue(restoredState.hasNext)
assertEquals(null, restoredState.paginationErrorMessage)
assertEquals(listOf(1L), restoredState.audioItems.map { it.audioContentId })
assertEquals(1, appendedState.page)
assertEquals(listOf(1L, 2L), appendedState.audioItems.map { it.audioContentId })
verifyGetContents(page = 1)
}
@Test
fun `같은 조건 첫 페이지 요청이 진행 중이면 중복 호출을 무시한다`() {
val pending = SingleSubject.create<ApiResponse<MainContentAllTabResponse>>()
stubGetContents(response = pending)
viewModel.loadContents()
viewModel.loadContents()
verifyGetContents(times = 1)
pending.onSuccess(ApiResponse(true, response(audios = listOf(audio(1L))), null))
}
@Test
fun `다른 조건 첫 페이지 요청은 기존 요청 진행 중에도 허용한다`() {
val pendingAudio = SingleSubject.create<ApiResponse<MainContentAllTabResponse>>()
val pendingFree = SingleSubject.create<ApiResponse<MainContentAllTabResponse>>()
stubGetContents(response = pendingAudio)
stubGetContents(type = MainContentAllType.FREE, response = pendingFree)
viewModel.loadContents()
viewModel.changeType(MainContentAllType.FREE)
verifyGetContents(type = MainContentAllType.AUDIO)
verifyGetContents(type = MainContentAllType.FREE)
pendingAudio.onSuccess(ApiResponse(true, response(audios = listOf(audio(1L))), null))
pendingFree.onSuccess(ApiResponse(true, response(type = MainContentAllType.FREE), null))
}
@Test
fun `오래된 첫 페이지 응답 후 같은 key를 다시 요청할 수 있다`() {
val pendingAudio = SingleSubject.create<ApiResponse<MainContentAllTabResponse>>()
val pendingFree = SingleSubject.create<ApiResponse<MainContentAllTabResponse>>()
whenever(
repository.getContents(
"Bearer test-token",
MainContentAllType.AUDIO,
ContentSort.LATEST,
0,
DEFAULT_PAGE_SIZE,
null
)
)
.thenReturn(
pendingAudio,
Single.just(ApiResponse(true, response(audios = listOf(audio(3L))), null))
)
stubGetContents(type = MainContentAllType.FREE, response = pendingFree)
viewModel.loadContents()
viewModel.changeType(MainContentAllType.FREE)
pendingAudio.onSuccess(ApiResponse(true, response(audios = listOf(audio(1L))), null))
viewModel.changeType(MainContentAllType.AUDIO)
verifyGetContents(type = MainContentAllType.AUDIO, times = 2)
pendingFree.onSuccess(ApiResponse(true, response(type = MainContentAllType.FREE), null))
}
@Test
fun `type을 A에서 B로 바꾼 뒤 A 응답 전 다시 A를 선택하면 최신 A 요청을 보낸다`() {
val pendingAudioFirst = SingleSubject.create<ApiResponse<MainContentAllTabResponse>>()
val pendingAudioLatest = SingleSubject.create<ApiResponse<MainContentAllTabResponse>>()
val pendingFree = SingleSubject.create<ApiResponse<MainContentAllTabResponse>>()
whenever(
repository.getContents(
"Bearer test-token",
MainContentAllType.AUDIO,
ContentSort.LATEST,
0,
DEFAULT_PAGE_SIZE,
null
)
)
.thenReturn(pendingAudioFirst, pendingAudioLatest)
stubGetContents(type = MainContentAllType.FREE, response = pendingFree)
viewModel.loadContents()
viewModel.changeType(MainContentAllType.FREE)
viewModel.changeType(MainContentAllType.AUDIO)
verifyGetContents(type = MainContentAllType.AUDIO, times = 2)
pendingAudioFirst.onSuccess(ApiResponse(true, response(audios = listOf(audio(1L))), null))
pendingFree.onSuccess(ApiResponse(true, response(type = MainContentAllType.FREE, audios = listOf(audio(2L))), null))
pendingAudioLatest.onSuccess(
ApiResponse(true, response(audios = listOf(audio(3L)), hasNext = true), null)
)
val state = viewModel.allTabStateLiveData.requireValue() as MainContentAllTabUiState.Content
assertEquals(MainContentAllType.AUDIO, state.selectedType)
assertEquals(listOf(3L), state.audioItems.map { it.audioContentId })
stubGetContents(
type = MainContentAllType.AUDIO,
page = 1,
response = Single.just(ApiResponse(true, response(page = 1, audios = listOf(audio(4L))), null))
)
viewModel.loadMore()
verifyGetContents(type = MainContentAllType.AUDIO, page = 1)
}
@Test
fun `첫 페이지 refresh 성공과 실패 결과를 명시적으로 emit한다`() {
whenever(
repository.getContents(
"Bearer test-token",
MainContentAllType.AUDIO,
ContentSort.LATEST,
0,
DEFAULT_PAGE_SIZE,
null
)
)
.thenReturn(
Single.just(ApiResponse(true, response(audios = listOf(audio(1L))), null)),
Single.just(ApiResponse(true, response(audios = listOf(audio(1L))), null)),
Single.just(ApiResponse(false, null, "refresh failed"))
)
viewModel.loadContents()
viewModel.loadContents()
assertEquals(ContentAllTabRefreshResult.Success, viewModel.refreshResultLiveData.requireValue())
viewModel.loadContents()
assertEquals(ContentAllTabRefreshResult.Failure, viewModel.refreshResultLiveData.requireValue())
}
@Test
fun `loadMore 진행 중 refresh 실패 후 loadMore는 다시 재시도할 수 있다`() {
val pendingLoadMore = SingleSubject.create<ApiResponse<MainContentAllTabResponse>>()
whenever(
repository.getContents(
"Bearer test-token",
MainContentAllType.AUDIO,
ContentSort.LATEST,
0,
DEFAULT_PAGE_SIZE,
null
)
)
.thenReturn(
Single.just(ApiResponse(true, response(audios = listOf(audio(1L)), hasNext = true), null)),
Single.just(ApiResponse(false, null, "refresh failed"))
)
whenever(
repository.getContents(
"Bearer test-token",
MainContentAllType.AUDIO,
ContentSort.LATEST,
1,
DEFAULT_PAGE_SIZE,
null
)
)
.thenReturn(
pendingLoadMore,
Single.just(ApiResponse(true, response(page = 1, audios = listOf(audio(2L)), hasNext = false), null))
)
viewModel.loadContents()
viewModel.loadMore()
viewModel.loadContents()
val restoredState = viewModel.allTabStateLiveData.requireValue() as MainContentAllTabUiState.Content
viewModel.loadMore()
val appendedState = viewModel.allTabStateLiveData.requireValue() as MainContentAllTabUiState.Content
assertFalse(restoredState.isLoadingMore)
assertEquals(null, restoredState.paginationErrorMessage)
assertEquals(1, appendedState.page)
assertEquals(listOf(1L, 2L), appendedState.audioItems.map { it.audioContentId })
verifyGetContents(page = 1, times = 2)
}
@Test
fun `loadMore 요청이 진행 중이면 중복 요청하지 않는다`() {
val pending = SingleSubject.create<ApiResponse<MainContentAllTabResponse>>()
@@ -71,6 +71,84 @@ class ContentMainFragmentSourceTest {
assertTrue(source.contains("screen_content_ranking_type_like_count"))
}
@Test
fun `content refresh dispatches by selected content tab`() {
val source = projectFile(
"app/src/main/java/kr/co/vividnext/sodalive/v2/main/content/ContentMainFragment.kt"
).readText()
assertTrue(source.contains("setUpRefreshLayouts()"))
assertTrue(source.contains("private fun refreshCurrentContentTab()"))
assertTrue(source.contains("CONTENT_TAB_RECOMMENDATION -> contentMainViewModel.loadRecommendations()"))
assertTrue(source.contains("CONTENT_TAB_RANKING -> refreshCurrentRankingTab()"))
assertTrue(source.contains("CONTENT_TAB_ALL -> contentAllTabViewModel.loadContents()"))
assertTrue(source.contains("contentRankingViewModel.loadRankings(type, force = true)"))
assertTrue(source.contains("binding.swipeContentRecommendation.isRefreshing = false"))
assertTrue(source.contains("binding.swipeContentRanking.isRefreshing = false"))
assertTrue(source.contains("binding.swipeContentAll.isRefreshing = false"))
}
@Test
fun `content pull refresh error preserves visible content and success scrolls current tab to top`() {
val source = projectFile(
"app/src/main/java/kr/co/vividnext/sodalive/v2/main/content/ContentMainFragment.kt"
).readText()
val updateLoadingDialog = source.substringFrom("private fun updateLoadingDialog()")
val finishPullRefresh = source.substringFrom("private fun finishContentPullRefresh")
assertTrue(source.contains("private var isContentPullRefreshing = false"))
assertTrue(source.contains("private var refreshingContentTab: Int? = null"))
assertTrue(source.contains("private var hasRenderedAllTabContent = false"))
assertTrue(source.contains("isContentPullRefreshing = true"))
assertTrue(source.contains("refreshingContentTab = currentContentTab"))
assertTrue(source.contains("private fun shouldPreserveContentOnPullRefreshError(tab: Int): Boolean"))
assertEquals(2, source.countOccurrences("if (shouldPreserveContentOnPullRefreshError(CONTENT_TAB_"))
assertTrue(
source.contains("val isAllTabPullRefresh = isContentPullRefreshing && refreshingContentTab == CONTENT_TAB_ALL")
)
assertTrue(
source.contains("state is MainContentAllTabUiState.Loading && isAllTabPullRefresh && hasRenderedAllTabContent")
)
assertTrue(
source.contains("state is MainContentAllTabUiState.Error && isAllTabPullRefresh && hasRenderedAllTabContent")
)
assertTrue(
source.contains("if (isContentPullRefreshing && refreshingContentTab == CONTENT_TAB_ALL && hasRenderedAllTabContent)")
)
assertTrue(source.contains("private fun finishContentPullRefresh(tab: Int, isRestoredPullRefreshError: Boolean = false)"))
assertTrue(source.contains("private fun cancelContentPullRefresh(tab: Int? = refreshingContentTab)"))
assertTrue(source.contains("private fun scrollContentTabToTop(tab: Int)"))
assertTrue(source.contains("CONTENT_TAB_RECOMMENDATION -> binding.nsvContentRecommendationContent.scrollTo(0, 0)"))
assertTrue(source.contains("CONTENT_TAB_RANKING -> binding.rvContentRankings.scrollToPosition(0)"))
assertTrue(source.contains("CONTENT_TAB_ALL -> binding.rvContentAllItems.scrollToPosition(0)"))
assertTrue(source.contains("val paginationErrorMessage = state.paginationErrorMessage"))
assertTrue(source.contains("if (isContentPullRefreshing && refreshingContentTab == CONTENT_TAB_ALL)"))
assertTrue(source.contains("private var lastRenderedContentRecommendationState"))
assertTrue(source.contains("private var lastRenderedContentRankingState"))
assertTrue(source.contains("refreshingContentTab == CONTENT_TAB_RECOMMENDATION"))
assertTrue(source.contains("refreshingContentTab == CONTENT_TAB_RANKING"))
assertTrue(source.contains("refreshingContentTab == CONTENT_TAB_ALL"))
assertTrue(source.contains("lastRenderedContentRecommendationState === state"))
assertTrue(source.contains("lastRenderedContentRankingState === state"))
assertFalse(source.contains("private fun MainContentAllTabUiState.Content.isSameAllTabPage("))
assertTrue(source.contains("contentAllTabViewModel.refreshResultLiveData.observe(viewLifecycleOwner)"))
assertTrue(source.contains("ContentAllTabRefreshResult.Success -> finishContentPullRefresh(CONTENT_TAB_ALL)"))
assertTrue(source.contains("ContentAllTabRefreshResult.Failure -> cancelContentPullRefresh(CONTENT_TAB_ALL)"))
assertTrue(source.contains("finishContentPullRefresh(CONTENT_TAB_RECOMMENDATION, isRestoredPullRefreshError)"))
assertTrue(source.contains("finishContentPullRefresh(CONTENT_TAB_RANKING, isRestoredPullRefreshError)"))
assertFalse(source.contains("finishContentPullRefresh(CONTENT_TAB_ALL, isRestoredPullRefreshError)"))
assertFalse(updateLoadingDialog.contains("stopContentRefreshIndicators()"))
assertTrue(
finishPullRefresh.contains(
"CONTENT_TAB_RECOMMENDATION -> binding.swipeContentRecommendation.isRefreshing = false"
)
)
assertTrue(finishPullRefresh.contains("CONTENT_TAB_RANKING -> binding.swipeContentRanking.isRefreshing = false"))
assertTrue(finishPullRefresh.contains("CONTENT_TAB_ALL -> binding.swipeContentAll.isRefreshing = false"))
assertTrue(source.contains("private fun cancelContentPullRefresh(tab: Int? = refreshingContentTab)"))
assertTrue(source.contains("CONTENT_TAB_ALL -> binding.swipeContentAll.isRefreshing = false"))
}
@Test
fun `content 전체 layout과 source는 Phase 5 요구를 포함한다`() {
val source = projectFile(
@@ -644,6 +722,8 @@ class ContentMainFragmentSourceTest {
assertTrue(message ?: "Expected source to contain: $expected", source.contains(expected))
}
private fun String.countOccurrences(needle: String): Int = split(needle).size - 1
private fun String.substringFrom(marker: String): String {
val startIndex = indexOf(marker)
assertTrue("Missing function: $marker", startIndex >= 0)
@@ -160,6 +160,132 @@ class ContentRankingViewModelTest {
assertEquals(listOf("2"), state.items.map { it.contentId })
}
@Test
fun `같은 type 첫 페이지 요청이 진행 중이면 중복 호출을 무시한다`() {
val pending = SingleSubject.create<ApiResponse<AudioRankingResponse>>()
api.enqueue(pending)
viewModel.loadRankings(AudioRankingType.WEEKLY_POPULAR, force = true)
viewModel.loadRankings(AudioRankingType.WEEKLY_POPULAR, force = true)
assertEquals(1, api.calls.size)
pending.onSuccess(ApiResponse(true, response(type = AudioRankingType.WEEKLY_POPULAR), null))
}
@Test
fun `다른 type 첫 페이지 요청은 기존 요청 진행 중에도 허용한다`() {
val pendingWeekly = SingleSubject.create<ApiResponse<AudioRankingResponse>>()
val pendingRising = SingleSubject.create<ApiResponse<AudioRankingResponse>>()
api.enqueue(pendingWeekly)
api.enqueue(pendingRising)
viewModel.loadRankings(AudioRankingType.WEEKLY_POPULAR, force = true)
viewModel.loadRankings(AudioRankingType.RISING, force = true)
assertEquals(
listOf(
ApiCall("Bearer test-token", "WEEKLY_POPULAR"),
ApiCall("Bearer test-token", "RISING")
),
api.calls
)
pendingWeekly.onSuccess(ApiResponse(true, response(type = AudioRankingType.WEEKLY_POPULAR), null))
pendingRising.onSuccess(ApiResponse(true, response(type = AudioRankingType.RISING), null))
}
@Test
fun `type을 A에서 B로 바꾼 뒤 A 응답 전 다시 A를 선택하면 최신 A 요청을 보낸다`() {
val pendingWeeklyFirst = SingleSubject.create<ApiResponse<AudioRankingResponse>>()
val pendingRising = SingleSubject.create<ApiResponse<AudioRankingResponse>>()
val pendingWeeklyLatest = SingleSubject.create<ApiResponse<AudioRankingResponse>>()
api.enqueue(pendingWeeklyFirst)
api.enqueue(pendingRising)
api.enqueue(pendingWeeklyLatest)
viewModel.loadRankings(AudioRankingType.WEEKLY_POPULAR, force = true)
viewModel.loadRankings(AudioRankingType.RISING, force = true)
viewModel.loadRankings(AudioRankingType.WEEKLY_POPULAR, force = true)
assertEquals(
listOf(
ApiCall("Bearer test-token", "WEEKLY_POPULAR"),
ApiCall("Bearer test-token", "RISING"),
ApiCall("Bearer test-token", "WEEKLY_POPULAR")
),
api.calls
)
pendingWeeklyFirst.onSuccess(
ApiResponse(true, response(type = AudioRankingType.WEEKLY_POPULAR, items = listOf(item(contentId = 1L))), null)
)
pendingRising.onSuccess(
ApiResponse(true, response(type = AudioRankingType.RISING, items = listOf(item(contentId = 2L))), null)
)
pendingWeeklyLatest.onSuccess(
ApiResponse(true, response(type = AudioRankingType.WEEKLY_POPULAR, items = listOf(item(contentId = 3L))), null)
)
val state = viewModel.rankingStateLiveData.requireValue() as AudioRankingsUiState.Content
assertEquals(AudioRankingType.WEEKLY_POPULAR, state.type)
assertEquals(listOf("3"), state.items.map { it.contentId })
}
@Test
fun `진행 중인 B 응답 전 캐시된 A를 표시하면 B key가 고착되지 않는다`() {
api.enqueueSuccess(response(type = AudioRankingType.WEEKLY_POPULAR, items = listOf(item(contentId = 1L))))
viewModel.loadRankings(AudioRankingType.WEEKLY_POPULAR)
val pendingWeeklyRefresh = SingleSubject.create<ApiResponse<AudioRankingResponse>>()
val pendingRising = SingleSubject.create<ApiResponse<AudioRankingResponse>>()
val pendingRisingLatest = SingleSubject.create<ApiResponse<AudioRankingResponse>>()
api.enqueue(pendingWeeklyRefresh)
api.enqueue(pendingRising)
api.enqueue(pendingRisingLatest)
viewModel.loadRankings(AudioRankingType.WEEKLY_POPULAR, force = true)
viewModel.loadRankings(AudioRankingType.RISING, force = true)
viewModel.loadRankings(AudioRankingType.WEEKLY_POPULAR)
pendingRising.onSuccess(
ApiResponse(true, response(type = AudioRankingType.RISING, items = listOf(item(contentId = 2L))), null)
)
viewModel.loadRankings(AudioRankingType.RISING, force = true)
assertEquals(
listOf(
ApiCall("Bearer test-token", "WEEKLY_POPULAR"),
ApiCall("Bearer test-token", "WEEKLY_POPULAR"),
ApiCall("Bearer test-token", "RISING"),
ApiCall("Bearer test-token", "RISING")
),
api.calls
)
pendingWeeklyRefresh.onSuccess(
ApiResponse(true, response(type = AudioRankingType.WEEKLY_POPULAR, items = listOf(item(contentId = 3L))), null)
)
pendingRisingLatest.onSuccess(
ApiResponse(true, response(type = AudioRankingType.RISING, items = listOf(item(contentId = 4L))), null)
)
val state = viewModel.rankingStateLiveData.requireValue() as AudioRankingsUiState.Content
assertEquals(AudioRankingType.RISING, state.type)
assertEquals(listOf("4"), state.items.map { it.contentId })
}
@Test
fun `force refresh 실패는 기존 ranking content를 유지한다`() {
api.enqueueSuccess(response(type = AudioRankingType.WEEKLY_POPULAR, items = listOf(item(contentId = 1L))))
viewModel.loadRankings(AudioRankingType.WEEKLY_POPULAR)
api.enqueueSuccess(ApiResponse(false, null, "refresh failed"))
viewModel.loadRankings(AudioRankingType.WEEKLY_POPULAR, force = true)
val state = viewModel.rankingStateLiveData.requireValue() as AudioRankingsUiState.Content
assertEquals(listOf("1"), state.items.map { it.contentId })
assertEquals(R.string.common_error_unknown, viewModel.toastLiveData.requireValue()?.resId)
}
@Test
fun `선택 type 변경 전 응답이 늦게 도착하면 화면 상태를 덮어쓰지 않는다`() {
val pendingWeekly = SingleSubject.create<ApiResponse<AudioRankingResponse>>()
@@ -44,9 +44,9 @@ class HomeFollowingFragmentSourceTest {
.substringAfter("HOME_TAB_FOLLOWING ->")
.substringBefore("}\n }")
assertTrue(branch.contains("binding.nsvHomeFollowingContent.visibility = View.VISIBLE"))
assertTrue(branch.contains("binding.nsvHomeRecommendationContent.visibility = View.GONE"))
assertTrue(branch.contains("binding.rvHomeCreatorRankings.visibility = View.GONE"))
assertTrue(branch.contains("binding.swipeHomeFollowing.visibility = View.VISIBLE"))
assertTrue(branch.contains("binding.swipeHomeRecommendation.visibility = View.GONE"))
assertTrue(branch.contains("binding.swipeHomeRanking.visibility = View.GONE"))
}
@Test
@@ -81,10 +81,14 @@ class HomeFollowingFragmentSourceTest {
val source = homeMainFragmentSource()
assertTrue(source.contains("followingStateLiveData.observe(viewLifecycleOwner)"))
assertTrue(source.contains("is HomeFollowingUiState.Content -> bindHomeFollowingContent(state)"))
assertTrue(source.contains("HomeFollowingUiState.Empty -> bindHomeFollowingEmpty(showEmptyMessage = true)"))
assertTrue(source.contains("HomeFollowingUiState.LoginRequired,"))
assertTrue(source.contains("is HomeFollowingUiState.Error -> bindHomeFollowingEmpty(showEmptyMessage = false)"))
assertTrue(source.contains("is HomeFollowingUiState.Content ->"))
assertTrue(source.contains("bindHomeFollowingContent(state)"))
assertTrue(source.contains("HomeFollowingUiState.Empty ->"))
assertTrue(source.contains("bindHomeFollowingEmpty(showEmptyMessage = true)"))
assertTrue(source.contains("HomeFollowingUiState.LoginRequired -> bindHomeFollowingEmpty(showEmptyMessage = false)"))
assertTrue(source.contains("is HomeFollowingUiState.Error ->"))
assertTrue(source.contains("if (shouldPreserveHomeContentOnPullRefreshError(HOME_TAB_FOLLOWING)) return@observe"))
assertTrue(source.contains("bindHomeFollowingEmpty(showEmptyMessage = false)"))
assertTrue(source.contains("followingCreatorAdapter.submitItems(emptyList())"))
assertTrue(source.contains("followingLiveAdapter.submitItems(emptyList())"))
assertTrue(source.contains("followingChatAdapter.submitItems(emptyList())"))
@@ -136,8 +140,10 @@ class HomeFollowingFragmentSourceTest {
assertTrue(source.contains("binding.tvHomeFollowingEmpty.visibility = View.GONE"))
assertTrue(source.contains("binding.tvHomeFollowingEmpty.visibility = if (showEmptyMessage) View.VISIBLE else View.GONE"))
assertTrue(source.contains("HomeFollowingUiState.Empty -> bindHomeFollowingEmpty(showEmptyMessage = true)"))
assertTrue(source.contains("is HomeFollowingUiState.Error -> bindHomeFollowingEmpty(showEmptyMessage = false)"))
assertTrue(source.contains("HomeFollowingUiState.Empty ->"))
assertTrue(source.contains("bindHomeFollowingEmpty(showEmptyMessage = true)"))
assertTrue(source.contains("is HomeFollowingUiState.Error ->"))
assertTrue(source.contains("bindHomeFollowingEmpty(showEmptyMessage = false)"))
}
@Test
@@ -114,6 +114,19 @@ class HomeFollowingViewModelTest {
assertEquals(R.string.common_error_unknown, viewModel.toastLiveData.requireValue()?.resId)
}
@Test
fun `refresh 실패는 기존 following content를 유지한다`() {
api.enqueueSuccess(response(followingCreators = listOf(creator())))
viewModel.loadFollowing()
api.enqueueSuccess(ApiResponse(false, null, "refresh failed"))
viewModel.loadFollowing()
val state = viewModel.followingStateLiveData.requireValue() as HomeFollowingUiState.Content
assertEquals(1L, state.followingCreators.items.single().creatorId)
assertEquals(R.string.common_error_unknown, viewModel.toastLiveData.requireValue()?.resId)
}
private fun setImmediateRxSchedulers() {
val trampoline = { _: Scheduler -> Schedulers.trampoline() }
RxJavaPlugins.setIoSchedulerHandler(trampoline)
@@ -105,7 +105,6 @@ class HomeMainFragmentLayoutTest {
assertNotNull(scrollView)
assertSame(root, titleBar.parent)
assertSame(root, tabBar.parent)
assertSame(root, scrollView.parent)
assertEquals(60.dpToPx(), titleBar.layoutParams.height)
assertEquals(52.dpToPx(), tabBar.layoutParams.height)
assertFalse(root.containsClassName("androidx.viewpager2.widget.ViewPager2"))
@@ -1202,10 +1201,10 @@ class HomeMainFragmentLayoutTest {
assertTrue(source.contains("HOME_TAB_FOLLOWING = 2"))
assertTrue(source.contains("binding.textTabBarHome.root.setOnTabSelectedListener { index ->"))
assertTrue(source.contains("showHomeTab(index)"))
assertTrue(source.contains("binding.nsvHomeRecommendationContent.visibility = View.GONE"))
assertTrue(source.contains("binding.rvHomeCreatorRankings.visibility = View.VISIBLE"))
assertTrue(source.contains("binding.nsvHomeRecommendationContent.visibility = View.VISIBLE"))
assertTrue(source.contains("binding.rvHomeCreatorRankings.visibility = View.GONE"))
assertTrue(source.contains("binding.swipeHomeRecommendation.visibility = View.GONE"))
assertTrue(source.contains("binding.swipeHomeRanking.visibility = View.VISIBLE"))
assertTrue(source.contains("binding.swipeHomeRecommendation.visibility = View.VISIBLE"))
assertTrue(source.contains("binding.swipeHomeRanking.visibility = View.GONE"))
}
@Test
@@ -1223,9 +1222,12 @@ class HomeMainFragmentLayoutTest {
val source = homeMainFragmentSource()
assertTrue(source.contains("rankingStateLiveData.observe(viewLifecycleOwner)"))
assertTrue(source.contains("is HomeCreatorRankingUiState.Content -> creatorRankingAdapter.submitItems(state.items)"))
assertTrue(source.contains("HomeCreatorRankingUiState.Empty,"))
assertTrue(source.contains("is HomeCreatorRankingUiState.Error -> creatorRankingAdapter.submitItems(emptyList())"))
assertTrue(source.contains("is HomeCreatorRankingUiState.Content ->"))
assertTrue(source.contains("creatorRankingAdapter.submitItems(state.items)"))
assertTrue(source.contains("HomeCreatorRankingUiState.Empty ->"))
assertTrue(source.contains("is HomeCreatorRankingUiState.Error ->"))
assertTrue(source.contains("if (shouldPreserveHomeContentOnPullRefreshError(HOME_TAB_RANKING)) return@observe"))
assertTrue(source.contains("creatorRankingAdapter.submitItems(emptyList())"))
assertTrue(source.contains("HomeCreatorRankingUiState.Loading -> Unit"))
}
@@ -137,11 +137,11 @@ class HomeMainFragmentLoginGuardSourceTest {
assertTrue(source.contains("private var isLiveEntryLoading = false"))
val updateSource = source.substringFrom("private fun updateLoadingDialog()")
val expectedLoadingExpression = "isRecommendationLoading || " +
"isCreatorRankingLoading || " +
"isFollowingLoading || " +
"isLiveEntryLoading"
assertTrue(updateSource.contains(expectedLoadingExpression))
assertTrue(updateSource.contains("isRecommendationLoading ||"))
assertTrue(updateSource.contains("isRecommendationFollowLoading ||"))
assertTrue(updateSource.contains("isCreatorRankingLoading ||"))
assertTrue(updateSource.contains("isFollowingLoading ||"))
assertTrue(updateSource.contains("isLiveEntryLoading"))
assertTrue(updateSource.contains("loadingDialog.show(screenWidth)"))
assertTrue(updateSource.contains("loadingDialog.dismiss()"))
@@ -1,6 +1,7 @@
package kr.co.vividnext.sodalive.v2.main.home
import android.app.Application
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
@@ -55,6 +56,71 @@ class HomeMainFragmentSourceTest {
)
}
@Test
fun `home refresh dispatches by current selected tab`() {
val source = projectFile(
"app/src/main/java/kr/co/vividnext/sodalive/v2/main/home/HomeMainFragment.kt"
).readText()
assertTrue(source.contains("setUpRefreshLayouts()"))
assertTrue(source.contains("private fun refreshCurrentHomeTab()"))
assertTrue(source.contains("HOME_TAB_RECOMMENDATION -> homeRecommendationViewModel.loadRecommendations()"))
assertTrue(source.contains("HOME_TAB_RANKING -> homeCreatorRankingViewModel.loadCreatorRankings()"))
assertTrue(source.contains("HOME_TAB_FOLLOWING -> homeFollowingViewModel.loadFollowing()"))
assertTrue(source.contains("binding.swipeHomeRecommendation.isRefreshing = false"))
assertTrue(source.contains("binding.swipeHomeRanking.isRefreshing = false"))
assertTrue(source.contains("binding.swipeHomeFollowing.isRefreshing = false"))
}
@Test
fun `home pull refresh error preserves visible content and success scrolls current tab to top`() {
val source = projectFile(
"app/src/main/java/kr/co/vividnext/sodalive/v2/main/home/HomeMainFragment.kt"
).readText()
val updateLoadingDialog = source.substringFrom("private fun updateLoadingDialog()")
val finishPullRefresh = source.substringFrom("private fun finishHomePullRefresh")
assertTrue(source.contains("private var isHomePullRefreshing = false"))
assertTrue(source.contains("private var refreshingHomeTabIndex: Int? = null"))
assertTrue(source.contains("isHomePullRefreshing = true"))
assertTrue(source.contains("refreshingHomeTabIndex = currentHomeTabIndex"))
assertTrue(source.contains("private fun shouldPreserveHomeContentOnPullRefreshError(tabIndex: Int): Boolean"))
assertEquals(3, source.countOccurrences("if (shouldPreserveHomeContentOnPullRefreshError(HOME_TAB_"))
assertTrue(
source.contains(
"private fun finishHomePullRefresh(tabIndex: Int, isRestoredPullRefreshError: Boolean = false)"
)
)
assertTrue(source.contains("private var lastRenderedHomeRecommendationState"))
assertTrue(source.contains("private var lastRenderedHomeRankingState"))
assertTrue(source.contains("private var lastRenderedHomeFollowingState"))
assertEquals(3, source.countOccurrences("refreshingHomeTabIndex == HOME_TAB_"))
assertTrue(source.contains("lastRenderedHomeRecommendationState === state"))
assertTrue(source.contains("lastRenderedHomeRankingState === state"))
assertTrue(source.contains("lastRenderedHomeFollowingState === state"))
assertTrue(source.contains("finishHomePullRefresh(HOME_TAB_RECOMMENDATION, isRestoredPullRefreshError)"))
assertTrue(source.contains("finishHomePullRefresh(HOME_TAB_RANKING, isRestoredPullRefreshError)"))
assertTrue(source.contains("finishHomePullRefresh(HOME_TAB_FOLLOWING, isRestoredPullRefreshError)"))
assertTrue(source.contains("private fun scrollHomeTabToTop(tabIndex: Int)"))
assertTrue(source.contains("HOME_TAB_RECOMMENDATION -> binding.nsvHomeRecommendationContent.scrollTo(0, 0)"))
assertTrue(source.contains("HOME_TAB_RANKING -> binding.rvHomeCreatorRankings.scrollToPosition(0)"))
assertTrue(source.contains("HOME_TAB_FOLLOWING -> binding.nsvHomeFollowingContent.scrollTo(0, 0)"))
assertFalse(updateLoadingDialog.contains("stopHomeRefreshIndicators()"))
assertTrue(finishPullRefresh.contains("HOME_TAB_RECOMMENDATION -> binding.swipeHomeRecommendation.isRefreshing = false"))
assertTrue(finishPullRefresh.contains("HOME_TAB_RANKING -> binding.swipeHomeRanking.isRefreshing = false"))
assertTrue(finishPullRefresh.contains("HOME_TAB_FOLLOWING -> binding.swipeHomeFollowing.isRefreshing = false"))
}
@Test
fun `홈 추천 follow loading은 추천 목록 loading과 분리한다`() {
val source = projectFile(
"app/src/main/java/kr/co/vividnext/sodalive/v2/main/home/HomeMainFragment.kt"
).readText()
assertTrue(source.contains("homeRecommendationViewModel.isLoading.observe(viewLifecycleOwner)"))
assertTrue(source.contains("homeRecommendationViewModel.isFollowLoading.observe(viewLifecycleOwner)"))
}
private fun String.substringFrom(marker: String): String {
val startIndex = indexOf(marker)
assertTrue("Missing function: $marker", startIndex >= 0)
@@ -64,6 +130,8 @@ class HomeMainFragmentSourceTest {
return substring(startIndex, nextFunctionIndex)
}
private fun String.countOccurrences(needle: String): Int = split(needle).size - 1
private fun projectFile(relativePath: String): File {
val candidates = listOf(File(relativePath), File("../$relativePath"))
return candidates.firstOrNull { it.exists() }
@@ -0,0 +1,206 @@
package kr.co.vividnext.sodalive.v2.main.home
import android.app.Application
import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.test.core.app.ApplicationProvider
import io.reactivex.rxjava3.android.plugins.RxAndroidPlugins
import io.reactivex.rxjava3.core.Scheduler
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.plugins.RxJavaPlugins
import io.reactivex.rxjava3.schedulers.Schedulers
import io.reactivex.rxjava3.subjects.SingleSubject
import kr.co.vividnext.sodalive.common.ApiResponse
import kr.co.vividnext.sodalive.common.SharedPreferenceManager
import kr.co.vividnext.sodalive.v2.main.home.data.FollowRecommendedCreatorsRequest
import kr.co.vividnext.sodalive.v2.main.home.data.HomeAiCharacterItem
import kr.co.vividnext.sodalive.v2.main.home.data.HomeBannerItem
import kr.co.vividnext.sodalive.v2.main.home.data.HomeLiveItem
import kr.co.vividnext.sodalive.v2.main.home.data.HomeActiveCreatorItem
import kr.co.vividnext.sodalive.v2.main.home.data.HomeCreatorItem
import kr.co.vividnext.sodalive.v2.main.home.data.HomeGenreCreatorGroupItem
import kr.co.vividnext.sodalive.v2.main.home.data.HomePopularCommunityPostItem
import kr.co.vividnext.sodalive.v2.main.home.data.HomeRecommendationApi
import kr.co.vividnext.sodalive.v2.main.home.data.HomeRecommendationRepository
import kr.co.vividnext.sodalive.v2.main.home.data.HomeRecommendationResponse
import kr.co.vividnext.sodalive.v2.main.home.model.HomeRecommendationUiState
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], application = Application::class)
class HomeRecommendationViewModelTest {
private val context: Context = ApplicationProvider.getApplicationContext()
private lateinit var api: FakeHomeRecommendationApi
private lateinit var viewModel: HomeRecommendationViewModel
@Before
fun setUp() {
setImmediateRxSchedulers()
SharedPreferenceManager.resetForTest()
SharedPreferenceManager.init(context)
SharedPreferenceManager.token = "test-token"
api = FakeHomeRecommendationApi()
viewModel = HomeRecommendationViewModel(HomeRecommendationRepository(api))
}
@After
fun tearDown() {
RxJavaPlugins.reset()
RxAndroidPlugins.reset()
SharedPreferenceManager.resetForTest()
}
@Test
fun `follow 요청 loading은 추천 목록 loading을 끄지 않는다`() {
val pendingRecommendations = SingleSubject.create<ApiResponse<HomeRecommendationResponse>>()
api.enqueueRecommendations(pendingRecommendations)
api.enqueueFollow(ApiResponse(true, Any(), null))
viewModel.loadRecommendations()
viewModel.followCreators("cheerCreators", listOf(1L))
assertEquals(true, viewModel.isLoading.requireValue())
assertEquals(false, viewModel.isFollowLoading.requireValue())
pendingRecommendations.onSuccess(ApiResponse(true, response(), null))
}
@Test
fun `추천 목록 요청 완료는 follow 요청 loading을 끄지 않는다`() {
val pendingFollow = SingleSubject.create<ApiResponse<Any>>()
api.enqueueRecommendations(ApiResponse(true, response(), null))
api.enqueueFollow(pendingFollow)
viewModel.followCreators("cheerCreators", listOf(1L))
viewModel.loadRecommendations()
assertEquals(false, viewModel.isLoading.requireValue())
assertEquals(true, viewModel.isFollowLoading.requireValue())
pendingFollow.onSuccess(ApiResponse(true, Any(), null))
}
@Test
fun `추천 refresh 중 follow가 먼저 성공해도 최종 follow 완료 상태를 유지한다`() {
val pendingRecommendations = SingleSubject.create<ApiResponse<HomeRecommendationResponse>>()
api.enqueueRecommendations(pendingRecommendations)
api.enqueueFollow(ApiResponse(true, Any(), null))
viewModel.loadRecommendations()
viewModel.followCreators("cheerCreators", listOf(1L))
pendingRecommendations.onSuccess(ApiResponse(true, response(), null))
val state = viewModel.recommendationStateLiveData.requireValue() as HomeRecommendationUiState.Content
assertEquals(true, state.cheerCreators.isFollowCompleted)
}
@Test
fun `추천 refresh가 먼저 끝난 뒤 follow가 성공해도 최종 follow 완료 상태를 유지한다`() {
val pendingFollow = SingleSubject.create<ApiResponse<Any>>()
api.enqueueRecommendations(ApiResponse(true, response(), null))
api.enqueueFollow(pendingFollow)
viewModel.loadRecommendations()
viewModel.followCreators("cheerCreators", listOf(1L))
pendingFollow.onSuccess(ApiResponse(true, Any(), null))
val state = viewModel.recommendationStateLiveData.requireValue() as HomeRecommendationUiState.Content
assertEquals(true, state.cheerCreators.isFollowCompleted)
}
@Test
fun `추천 refresh 중 follow 성공 후 refresh 실패해도 follow 완료 상태를 유지한다`() {
api.enqueueRecommendations(ApiResponse(true, response(), null))
viewModel.loadRecommendations()
val pendingRecommendations = SingleSubject.create<ApiResponse<HomeRecommendationResponse>>()
api.enqueueRecommendations(pendingRecommendations)
api.enqueueFollow(ApiResponse(true, Any(), null))
viewModel.loadRecommendations()
viewModel.followCreators("cheerCreators", listOf(1L))
pendingRecommendations.onSuccess(ApiResponse(false, null, "refresh failed"))
val state = viewModel.recommendationStateLiveData.requireValue() as HomeRecommendationUiState.Content
assertEquals(true, state.cheerCreators.isFollowCompleted)
}
@Test
fun `추천 refresh 성공 후 follow 실패해도 최신 추천 목록을 유지한다`() {
api.enqueueRecommendations(ApiResponse(true, response(creatorId = 1L), null))
viewModel.loadRecommendations()
api.enqueueRecommendations(ApiResponse(true, response(creatorId = 2L), null))
api.enqueueFollow(ApiResponse(false, null, "follow failed"))
viewModel.loadRecommendations()
viewModel.followCreators("cheerCreators", listOf(2L))
val state = viewModel.recommendationStateLiveData.requireValue() as HomeRecommendationUiState.Content
assertEquals(listOf(2L), state.cheerCreators.items.map { it.creatorId })
}
private fun response(creatorId: Long = 1L) = HomeRecommendationResponse(
lives = listOf(HomeLiveItem(1L, "크리에이터", "https://example.com/profile.png")),
banners = emptyList<HomeBannerItem>(),
recentlyActiveCreators = emptyList<HomeActiveCreatorItem>(),
recentDebutCreators = emptyList<HomeCreatorItem>(),
aiCharacters = emptyList<HomeAiCharacterItem>(),
genreCreators = emptyList<HomeGenreCreatorGroupItem>(),
cheerCreators = listOf(HomeCreatorItem(creatorId, "크리에이터", "https://example.com/profile.png")),
popularCommunityPosts = emptyList<HomePopularCommunityPostItem>()
)
private fun setImmediateRxSchedulers() {
val trampoline = { _: Scheduler -> Schedulers.trampoline() }
RxJavaPlugins.setIoSchedulerHandler(trampoline)
RxAndroidPlugins.setInitMainThreadSchedulerHandler { Schedulers.trampoline() }
RxAndroidPlugins.setMainThreadSchedulerHandler { Schedulers.trampoline() }
}
private fun <T> LiveData<T>.requireValue(): T? {
var value: T? = null
val observer = Observer<T> { value = it }
observeForever(observer)
removeObserver(observer)
return value
}
private class FakeHomeRecommendationApi : HomeRecommendationApi {
private val recommendationResponses = ArrayDeque<Single<ApiResponse<HomeRecommendationResponse>>>()
private val followResponses = ArrayDeque<Single<ApiResponse<Any>>>()
fun enqueueRecommendations(response: ApiResponse<HomeRecommendationResponse>) {
enqueueRecommendations(Single.just(response))
}
fun enqueueRecommendations(response: Single<ApiResponse<HomeRecommendationResponse>>) {
recommendationResponses.addLast(response)
}
fun enqueueFollow(response: ApiResponse<Any>) {
enqueueFollow(Single.just(response))
}
fun enqueueFollow(response: Single<ApiResponse<Any>>) {
followResponses.addLast(response)
}
override fun getRecommendations(authHeader: String): Single<ApiResponse<HomeRecommendationResponse>> {
return recommendationResponses.removeFirst()
}
override fun followRecommendedCreators(
request: FollowRecommendedCreatorsRequest,
authHeader: String
): Single<ApiResponse<Any>> {
return followResponses.removeFirst()
}
}
}