feat(event): 상세 조회 상태와 재시도를 처리한다
This commit is contained in:
@@ -0,0 +1,58 @@
|
|||||||
|
package kr.co.vividnext.sodalive.v2.event
|
||||||
|
|
||||||
|
import androidx.lifecycle.LiveData
|
||||||
|
import androidx.lifecycle.MutableLiveData
|
||||||
|
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
|
||||||
|
import io.reactivex.rxjava3.schedulers.Schedulers
|
||||||
|
import kr.co.vividnext.sodalive.base.BaseViewModel
|
||||||
|
import kr.co.vividnext.sodalive.common.SharedPreferenceManager
|
||||||
|
import kr.co.vividnext.sodalive.v2.event.data.EventDetailRepository
|
||||||
|
import kr.co.vividnext.sodalive.v2.event.data.EventDetailResponse
|
||||||
|
|
||||||
|
sealed interface EventDetailUiState {
|
||||||
|
data object Loading : EventDetailUiState
|
||||||
|
data class Content(val detail: EventDetailResponse) : EventDetailUiState
|
||||||
|
data class Unavailable(val message: String?) : EventDetailUiState
|
||||||
|
data object Error : EventDetailUiState
|
||||||
|
}
|
||||||
|
|
||||||
|
class EventDetailViewModel(private val repository: EventDetailRepository) : BaseViewModel() {
|
||||||
|
private val mutableState = MutableLiveData<EventDetailUiState>()
|
||||||
|
val state: LiveData<EventDetailUiState> = mutableState
|
||||||
|
private var eventId: Long? = null
|
||||||
|
|
||||||
|
fun loadInitial(eventId: Long) {
|
||||||
|
if (this.eventId != null) return
|
||||||
|
this.eventId = eventId
|
||||||
|
if (eventId <= 0L) {
|
||||||
|
mutableState.value = EventDetailUiState.Unavailable(null)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
load(eventId)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun retry() {
|
||||||
|
val id = eventId?.takeIf { it > 0L } ?: return
|
||||||
|
if (mutableState.value == EventDetailUiState.Loading) return
|
||||||
|
load(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun load(id: Long) {
|
||||||
|
mutableState.value = EventDetailUiState.Loading
|
||||||
|
val authHeader = SharedPreferenceManager.token.takeIf { it.isNotBlank() }?.let { "Bearer $it" }
|
||||||
|
compositeDisposable.add(
|
||||||
|
repository.getEventDetail(id, authHeader)
|
||||||
|
.subscribeOn(Schedulers.io())
|
||||||
|
.observeOn(AndroidSchedulers.mainThread())
|
||||||
|
.subscribe({ response ->
|
||||||
|
val detail = response.data
|
||||||
|
mutableState.value = when {
|
||||||
|
!response.success -> EventDetailUiState.Unavailable(response.message)
|
||||||
|
detail != null && detail.id == id && detail.thumbnailImageUrl != null ->
|
||||||
|
EventDetailUiState.Content(detail)
|
||||||
|
else -> EventDetailUiState.Error
|
||||||
|
}
|
||||||
|
}, { mutableState.value = EventDetailUiState.Error })
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,274 @@
|
|||||||
|
package kr.co.vividnext.sodalive.v2.event
|
||||||
|
|
||||||
|
import android.app.Application
|
||||||
|
import androidx.lifecycle.Observer
|
||||||
|
import androidx.lifecycle.ViewModelStore
|
||||||
|
import io.mockk.every
|
||||||
|
import io.mockk.mockkObject
|
||||||
|
import io.mockk.unmockkObject
|
||||||
|
import io.reactivex.rxjava3.android.plugins.RxAndroidPlugins
|
||||||
|
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.event.data.EventDetailApi
|
||||||
|
import kr.co.vividnext.sodalive.v2.event.data.EventDetailRepository
|
||||||
|
import kr.co.vividnext.sodalive.v2.event.data.EventDetailResponse
|
||||||
|
import okhttp3.MediaType.Companion.toMediaType
|
||||||
|
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Before
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import org.robolectric.RobolectricTestRunner
|
||||||
|
import org.robolectric.annotation.Config
|
||||||
|
import retrofit2.HttpException
|
||||||
|
import retrofit2.Response
|
||||||
|
import java.io.IOException
|
||||||
|
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [28], application = Application::class)
|
||||||
|
class EventDetailViewModelTest {
|
||||||
|
private lateinit var api: DetailFakeApi
|
||||||
|
private lateinit var viewModel: EventDetailViewModel
|
||||||
|
private lateinit var store: ViewModelStore
|
||||||
|
|
||||||
|
@Before
|
||||||
|
fun setUp() {
|
||||||
|
RxJavaPlugins.setIoSchedulerHandler { Schedulers.trampoline() }
|
||||||
|
RxAndroidPlugins.setInitMainThreadSchedulerHandler { Schedulers.trampoline() }
|
||||||
|
RxAndroidPlugins.setMainThreadSchedulerHandler { Schedulers.trampoline() }
|
||||||
|
mockkObject(SharedPreferenceManager)
|
||||||
|
every { SharedPreferenceManager.token } returns "test-token"
|
||||||
|
api = DetailFakeApi()
|
||||||
|
viewModel = EventDetailViewModel(EventDetailRepository(api))
|
||||||
|
store = ViewModelStore().apply { put("event-detail", viewModel) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
fun tearDown() {
|
||||||
|
store.clear()
|
||||||
|
RxJavaPlugins.reset()
|
||||||
|
RxAndroidPlugins.reset()
|
||||||
|
unmockkObject(SharedPreferenceManager)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `최초 조회는 로딩을 거쳐 서버 상세를 표시하고 최초 중복 호출은 무시한다`() {
|
||||||
|
val pending = SingleSubject.create<ApiResponse<EventDetailResponse>>()
|
||||||
|
api.responses.add(pending)
|
||||||
|
val states = mutableListOf<EventDetailUiState>()
|
||||||
|
val observer = Observer<EventDetailUiState> { states.add(it) }
|
||||||
|
viewModel.state.observeForever(observer)
|
||||||
|
try {
|
||||||
|
viewModel.loadInitial(7L)
|
||||||
|
viewModel.loadInitial(8L)
|
||||||
|
viewModel.retry()
|
||||||
|
assertEquals(listOf(EventDetailUiState.Loading), states)
|
||||||
|
val detail = detail()
|
||||||
|
|
||||||
|
pending.onSuccess(ApiResponse(true, detail, "무시할 성공 메시지"))
|
||||||
|
viewModel.loadInitial(7L)
|
||||||
|
|
||||||
|
assertEquals(listOf(EventDetailUiState.Loading, EventDetailUiState.Content(detail)), states)
|
||||||
|
assertEquals(listOf(7L to "Bearer test-token"), api.requests)
|
||||||
|
} finally {
|
||||||
|
viewModel.state.removeObserver(observer)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `비로그인 토큰은 null 인증 헤더로 조회한다`() {
|
||||||
|
every { SharedPreferenceManager.token } returns ""
|
||||||
|
api.responses.add(Single.just(ApiResponse(true, detail(), null)))
|
||||||
|
|
||||||
|
viewModel.loadInitial(7L)
|
||||||
|
|
||||||
|
assertEquals(listOf(7L to null), api.requests)
|
||||||
|
assertEquals(EventDetailUiState.Content(detail()), viewModel.state.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `최초 조회 전 재시도는 요청하지 않는다`() {
|
||||||
|
viewModel.retry()
|
||||||
|
|
||||||
|
assertTrue(api.requests.isEmpty())
|
||||||
|
assertNull(viewModel.state.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `0과 음수 진입은 요청 없이 조회 불가이며 재시도와 재진입도 요청하지 않는다`() {
|
||||||
|
listOf(0L, -1L, Long.MIN_VALUE).forEach { id ->
|
||||||
|
val model = EventDetailViewModel(EventDetailRepository(api))
|
||||||
|
try {
|
||||||
|
model.loadInitial(id)
|
||||||
|
model.retry()
|
||||||
|
model.loadInitial(7L)
|
||||||
|
|
||||||
|
assertEquals(EventDetailUiState.Unavailable(null), model.state.value)
|
||||||
|
assertTrue(api.requests.isEmpty())
|
||||||
|
} finally {
|
||||||
|
model.compositeDisposable.dispose()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `Int 범위 초과와 Long 최댓값은 콘텐츠 검증에서도 손실 없이 보존한다`() {
|
||||||
|
listOf(3_000_000_001L, Long.MAX_VALUE).forEach { id ->
|
||||||
|
val model = EventDetailViewModel(EventDetailRepository(api))
|
||||||
|
val detail = detail().copy(id = id)
|
||||||
|
api.responses.add(Single.just(ApiResponse(true, detail, null)))
|
||||||
|
try {
|
||||||
|
model.loadInitial(id)
|
||||||
|
|
||||||
|
assertEquals(EventDetailUiState.Content(detail), model.state.value)
|
||||||
|
assertEquals(id, api.requests.last().first)
|
||||||
|
} finally {
|
||||||
|
model.compositeDisposable.dispose()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `명시적 실패는 데이터 유무와 메시지 내용에 상관없이 조회 불가다`() {
|
||||||
|
listOf<String?>(null, "잘못된 요청입니다.", "일시적인 오류", " 원문 메시지 ").forEach { message ->
|
||||||
|
listOf(null, detail()).forEach { data ->
|
||||||
|
api.responses.add(Single.just(ApiResponse(false, data, message)))
|
||||||
|
if (viewModel.state.value == null) viewModel.loadInitial(7L) else viewModel.retry()
|
||||||
|
|
||||||
|
assertEquals(EventDetailUiState.Unavailable(message), viewModel.state.value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `성공의 null 데이터는 성공 메시지와 무관하게 일반 오류다`() {
|
||||||
|
api.responses.add(Single.just(ApiResponse(true, null, "잘못된 요청입니다.")))
|
||||||
|
|
||||||
|
viewModel.loadInitial(7L)
|
||||||
|
|
||||||
|
assertEquals(EventDetailUiState.Error, viewModel.state.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `성공의 null 식별자는 일반 오류다`() = assertInvalidDetail(detail().copy(id = null))
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `성공의 0 또는 음수 식별자는 일반 오류다`() {
|
||||||
|
listOf(0L, -1L).forEach { id -> assertInvalidDetail(detail().copy(id = id)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `요청과 다른 성공 식별자는 일반 오류다`() = assertInvalidDetail(detail().copy(id = 8L))
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `성공의 null 필수 썸네일은 일반 오류다`() = assertInvalidDetail(detail().copy(thumbnailImageUrl = null))
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `빈 필수 썸네일과 null 선택 필드는 정상 콘텐츠다`() {
|
||||||
|
val detail = EventDetailResponse(7L, "", null, null, null)
|
||||||
|
api.responses.add(Single.just(ApiResponse(true, detail, null)))
|
||||||
|
|
||||||
|
viewModel.loadInitial(7L)
|
||||||
|
|
||||||
|
assertEquals(EventDetailUiState.Content(detail), viewModel.state.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `링크만 있는 상세와 미지원 scheme도 조회 성공 판정에는 영향을 주지 않는다`() {
|
||||||
|
listOf("https://example.invalid/join", "unsupported://event/7").forEach { link ->
|
||||||
|
val detail = detail().copy(detailImageUrl = null, popupImageUrl = null, link = link)
|
||||||
|
api.responses.add(Single.just(ApiResponse(true, detail, null)))
|
||||||
|
if (viewModel.state.value == null) viewModel.loadInitial(7L) else viewModel.retry()
|
||||||
|
|
||||||
|
assertEquals(EventDetailUiState.Content(detail), viewModel.state.value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `IO와 역직렬화 오류는 내부 메시지를 노출하지 않는 일반 오류다`() {
|
||||||
|
listOf(IOException("private IO detail"), IllegalStateException("private JSON detail")).forEach { error ->
|
||||||
|
api.responses.add(Single.error(error))
|
||||||
|
if (viewModel.state.value == null) viewModel.loadInitial(7L) else viewModel.retry()
|
||||||
|
|
||||||
|
assertEquals(EventDetailUiState.Error, viewModel.state.value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `비JSON HTTP 오류도 조회 불가로 분류하지 않고 일반 오류다`() {
|
||||||
|
listOf(401, 404, 500).forEach { code ->
|
||||||
|
val body = "<html>private server error</html>".toResponseBody("text/html".toMediaType())
|
||||||
|
api.responses.add(Single.error(HttpException(Response.error<Any>(code, body))))
|
||||||
|
if (viewModel.state.value == null) viewModel.loadInitial(7L) else viewModel.retry()
|
||||||
|
|
||||||
|
assertEquals(EventDetailUiState.Error, viewModel.state.value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `오류 후 재시도는 같은 ID와 최신 토큰으로 로딩을 거쳐 새 콘텐츠를 표시한다`() {
|
||||||
|
api.responses.add(Single.error(IOException("private IO detail")))
|
||||||
|
viewModel.loadInitial(7L)
|
||||||
|
assertEquals(EventDetailUiState.Error, viewModel.state.value)
|
||||||
|
every { SharedPreferenceManager.token } returns "retry-token"
|
||||||
|
val pending = SingleSubject.create<ApiResponse<EventDetailResponse>>()
|
||||||
|
api.responses.add(pending)
|
||||||
|
|
||||||
|
viewModel.retry()
|
||||||
|
viewModel.retry()
|
||||||
|
assertEquals(EventDetailUiState.Loading, viewModel.state.value)
|
||||||
|
val detail = detail().copy(detailImageUrl = " latest detail ")
|
||||||
|
pending.onSuccess(ApiResponse(true, detail, null))
|
||||||
|
|
||||||
|
assertEquals(EventDetailUiState.Content(detail), viewModel.state.value)
|
||||||
|
assertEquals(listOf(7L to "Bearer test-token", 7L to "Bearer retry-token"), api.requests)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `ViewModel 종료는 BaseViewModel 구독을 해제하고 늦은 응답을 적용하지 않는다`() {
|
||||||
|
val pending = SingleSubject.create<ApiResponse<EventDetailResponse>>()
|
||||||
|
api.responses.add(pending)
|
||||||
|
viewModel.loadInitial(7L)
|
||||||
|
assertTrue(pending.hasObservers())
|
||||||
|
|
||||||
|
store.clear()
|
||||||
|
|
||||||
|
assertTrue(viewModel.compositeDisposable.isDisposed)
|
||||||
|
assertFalse(pending.hasObservers())
|
||||||
|
pending.onSuccess(ApiResponse(true, detail(), null))
|
||||||
|
assertEquals(EventDetailUiState.Loading, viewModel.state.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun assertInvalidDetail(detail: EventDetailResponse) {
|
||||||
|
api.responses.add(Single.just(ApiResponse(true, detail, "서버 상세 오류를 노출하지 않음")))
|
||||||
|
if (viewModel.state.value == null) viewModel.loadInitial(7L) else viewModel.retry()
|
||||||
|
|
||||||
|
assertEquals(EventDetailUiState.Error, viewModel.state.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun detail() = EventDetailResponse(
|
||||||
|
id = 7L,
|
||||||
|
thumbnailImageUrl = " thumb & 원문 ",
|
||||||
|
detailImageUrl = "https://example.invalid/detail?a=1&b=2",
|
||||||
|
popupImageUrl = " popup ",
|
||||||
|
link = " sodalive://event/7 "
|
||||||
|
)
|
||||||
|
|
||||||
|
private class DetailFakeApi : EventDetailApi {
|
||||||
|
val requests = mutableListOf<Pair<Long, String?>>()
|
||||||
|
val responses = ArrayDeque<Single<ApiResponse<EventDetailResponse>>>()
|
||||||
|
|
||||||
|
override fun getEventDetail(id: Long, authHeader: String?): Single<ApiResponse<EventDetailResponse>> {
|
||||||
|
requests.add(id to authHeader)
|
||||||
|
return responses.removeFirst()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user