feat(subbanner): 선택 상태와 이미지 요청 수명을 관리한다
This commit is contained in:
@@ -0,0 +1,96 @@
|
|||||||
|
package kr.co.vividnext.sodalive.v2.widget.subbanner
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import android.widget.ImageView
|
||||||
|
import androidx.recyclerview.widget.RecyclerView
|
||||||
|
import coil.dispose
|
||||||
|
import kr.co.vividnext.sodalive.R
|
||||||
|
|
||||||
|
internal class SubBannerAdapter(
|
||||||
|
private var onClickItem: ((SubBannerItem) -> Unit)? = null,
|
||||||
|
private var onBindImage: ((ImageView, SubBannerItem, Int) -> Unit)? = null
|
||||||
|
) : RecyclerView.Adapter<SubBannerAdapter.Holder>() {
|
||||||
|
private var items: List<SubBannerItem> = emptyList()
|
||||||
|
private val holders = mutableSetOf<Holder>()
|
||||||
|
private var generation = 0
|
||||||
|
|
||||||
|
override fun getItemCount(): Int = if (items.size > 1) Int.MAX_VALUE else items.size
|
||||||
|
|
||||||
|
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder = Holder(
|
||||||
|
LayoutInflater.from(parent.context).inflate(R.layout.item_sub_banner, parent, false) as ImageView
|
||||||
|
)
|
||||||
|
|
||||||
|
override fun onBindViewHolder(holder: Holder, position: Int) {
|
||||||
|
holders += holder
|
||||||
|
holder.bind(toRealIndex(position))
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onViewRecycled(holder: Holder) {
|
||||||
|
holder.clear()
|
||||||
|
holders -= holder
|
||||||
|
super.onViewRecycled(holder)
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
|
fun submitItems(items: List<SubBannerItem>) {
|
||||||
|
if (this.items == items) return
|
||||||
|
generation++
|
||||||
|
this.items = items
|
||||||
|
notifyDataSetChanged()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun toRealIndex(position: Int): Int = if (items.isEmpty()) 0 else Math.floorMod(position, items.size)
|
||||||
|
|
||||||
|
fun startPosition(realIndex: Int): Int {
|
||||||
|
if (items.size <= 1) return realIndex
|
||||||
|
val center = Int.MAX_VALUE / 2
|
||||||
|
return center - center % items.size + realIndex
|
||||||
|
}
|
||||||
|
|
||||||
|
fun refreshImages() {
|
||||||
|
holders.forEach { it.refresh() }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setOnClickItem(listener: ((SubBannerItem) -> Unit)?) {
|
||||||
|
onClickItem = listener
|
||||||
|
}
|
||||||
|
|
||||||
|
fun release() {
|
||||||
|
holders.forEach { it.clear() }
|
||||||
|
holders.clear()
|
||||||
|
onClickItem = null
|
||||||
|
onBindImage = null
|
||||||
|
}
|
||||||
|
|
||||||
|
inner class Holder(private val image: ImageView) : RecyclerView.ViewHolder(image) {
|
||||||
|
private var boundItem: SubBannerItem? = null
|
||||||
|
private var boundIndex = 0
|
||||||
|
private var boundGeneration = -1
|
||||||
|
|
||||||
|
fun bind(index: Int) {
|
||||||
|
clear()
|
||||||
|
boundIndex = index
|
||||||
|
boundItem = items[index]
|
||||||
|
boundGeneration = generation
|
||||||
|
refresh()
|
||||||
|
image.setOnClickListener {
|
||||||
|
if (boundGeneration == generation) boundItem?.let { onClickItem?.invoke(it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun refresh() {
|
||||||
|
if (boundGeneration != generation) return
|
||||||
|
boundItem?.let { onBindImage?.invoke(image, it, boundIndex) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clear() {
|
||||||
|
image.dispose()
|
||||||
|
image.setImageDrawable(null)
|
||||||
|
image.setOnClickListener(null)
|
||||||
|
boundItem = null
|
||||||
|
boundGeneration = -1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package kr.co.vividnext.sodalive.v2.widget.subbanner
|
||||||
|
|
||||||
|
internal class SubBannerState {
|
||||||
|
var items: List<SubBannerItem> = emptyList()
|
||||||
|
private set
|
||||||
|
var currentIndex: Int = 0
|
||||||
|
private set
|
||||||
|
val currentItem: SubBannerItem? get() = items.getOrNull(currentIndex)
|
||||||
|
val currentRatio: Double? get() = ratios[currentItem]
|
||||||
|
private var originalItems: List<SubBannerItem> = emptyList()
|
||||||
|
private val ratios = mutableMapOf<SubBannerItem, Double>()
|
||||||
|
private val requests = mutableMapOf<SubBannerItem, ImageKey>()
|
||||||
|
|
||||||
|
fun setItems(items: List<SubBannerItem>): Boolean {
|
||||||
|
if (originalItems == items && this.items.size == items.size) return false
|
||||||
|
originalItems = items.toList()
|
||||||
|
this.items = originalItems
|
||||||
|
currentIndex = 0
|
||||||
|
ratios.clear()
|
||||||
|
invalidateRequests()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun select(index: Int) {
|
||||||
|
currentIndex = if (items.isEmpty()) 0 else Math.floorMod(index, items.size)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun beginImageRequest(index: Int): ImageKey = ImageKey(items[index]).also { requests[it.item] = it }
|
||||||
|
|
||||||
|
fun onImageLoaded(request: ImageKey, width: Int, height: Int): Boolean {
|
||||||
|
if (requests[request.item] !== request) return false
|
||||||
|
if (width <= 0 || height <= 0) {
|
||||||
|
onImageFailed(request)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
requests.remove(request.item)
|
||||||
|
ratios[request.item] = width.toDouble() / height
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onImageFailed(request: ImageKey): Boolean {
|
||||||
|
if (requests[request.item] !== request) return false
|
||||||
|
requests.remove(request.item)
|
||||||
|
val failedIndex = items.indexOf(request.item)
|
||||||
|
items = items.filterIndexed { index, _ -> index != failedIndex }
|
||||||
|
ratios.remove(request.item)
|
||||||
|
select(if (failedIndex < currentIndex) currentIndex - 1 else currentIndex)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun invalidateRequests() {
|
||||||
|
requests.clear()
|
||||||
|
}
|
||||||
|
|
||||||
|
class ImageKey(val item: SubBannerItem)
|
||||||
|
}
|
||||||
@@ -0,0 +1,292 @@
|
|||||||
|
package kr.co.vividnext.sodalive.v2.widget.subbanner
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.drawable.Drawable
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import android.util.AttributeSet
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.widget.FrameLayout
|
||||||
|
import androidx.lifecycle.DefaultLifecycleObserver
|
||||||
|
import androidx.lifecycle.Lifecycle
|
||||||
|
import androidx.lifecycle.LifecycleOwner
|
||||||
|
import androidx.lifecycle.findViewTreeLifecycleOwner
|
||||||
|
import androidx.recyclerview.widget.LinearLayoutManager
|
||||||
|
import androidx.recyclerview.widget.PagerSnapHelper
|
||||||
|
import androidx.recyclerview.widget.RecyclerView
|
||||||
|
import coil.request.Disposable
|
||||||
|
import coil.request.ImageRequest
|
||||||
|
import coil.size.Dimension
|
||||||
|
import coil.size.Precision
|
||||||
|
import coil.size.Scale
|
||||||
|
import coil.size.Size
|
||||||
|
import kr.co.vividnext.sodalive.R
|
||||||
|
import kr.co.vividnext.sodalive.common.ImageLoaderProvider
|
||||||
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
|
class SubBannerView @JvmOverloads constructor(
|
||||||
|
context: Context,
|
||||||
|
attrs: AttributeSet? = null,
|
||||||
|
defStyleAttr: Int = 0
|
||||||
|
) : FrameLayout(context, attrs, defStyleAttr) {
|
||||||
|
private val state = SubBannerState()
|
||||||
|
private val images = mutableMapOf<SubBannerItem, Drawable>()
|
||||||
|
private val adapter = SubBannerAdapter(onBindImage = { image, item, _ -> image.setImageDrawable(images[item]) })
|
||||||
|
private val recycler: RecyclerView
|
||||||
|
private val snapHelper = PagerSnapHelper()
|
||||||
|
private val handler = Handler(Looper.getMainLooper())
|
||||||
|
private var attached = false
|
||||||
|
private var active = false
|
||||||
|
private var started = true
|
||||||
|
private var released = false
|
||||||
|
private var dragging = false
|
||||||
|
private var replacingItems = false
|
||||||
|
private var timerScheduled = false
|
||||||
|
private var lifecycleOwner: LifecycleOwner? = null
|
||||||
|
private var imageRequest: Disposable? = null
|
||||||
|
private var imageKey: SubBannerState.ImageKey? = null
|
||||||
|
private var contentWidth = 0
|
||||||
|
private var imageWidth = 0
|
||||||
|
private var displayRatio: Double? = null
|
||||||
|
private var renderedItem: SubBannerItem? = null
|
||||||
|
private var currentPosition = 0
|
||||||
|
private var animateSelection = false
|
||||||
|
private val loadImage = Runnable { loadCurrentImage() }
|
||||||
|
private val advance = Runnable {
|
||||||
|
timerScheduled = false
|
||||||
|
if (canAutoScroll()) {
|
||||||
|
state.select(state.currentIndex + 1)
|
||||||
|
currentPosition++
|
||||||
|
animateSelection = true
|
||||||
|
loadCurrentImage()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private val lifecycleObserver = object : DefaultLifecycleObserver {
|
||||||
|
override fun onStart(owner: LifecycleOwner) {
|
||||||
|
started = true
|
||||||
|
startTimer()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStop(owner: LifecycleOwner) {
|
||||||
|
started = false
|
||||||
|
stopTimer()
|
||||||
|
recycler.stopScroll()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy(owner: LifecycleOwner) = release()
|
||||||
|
}
|
||||||
|
private val scrollListener = object : RecyclerView.OnScrollListener() {
|
||||||
|
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
|
||||||
|
if (replacingItems) return
|
||||||
|
if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
|
||||||
|
dragging = true
|
||||||
|
stopTimer()
|
||||||
|
} else if (newState == RecyclerView.SCROLL_STATE_IDLE) {
|
||||||
|
dragging = false
|
||||||
|
val manager = recycler.layoutManager ?: return
|
||||||
|
val position = snapHelper.findSnapView(manager)?.let(manager::getPosition)
|
||||||
|
if (position != null && position != RecyclerView.NO_POSITION && position != currentPosition) {
|
||||||
|
stopTimer()
|
||||||
|
currentPosition = position
|
||||||
|
state.select(adapter.toRealIndex(position))
|
||||||
|
animateSelection = false
|
||||||
|
loadCurrentImage()
|
||||||
|
}
|
||||||
|
images.keys.retainAll(setOfNotNull(state.currentItem))
|
||||||
|
adapter.refreshImages()
|
||||||
|
startTimer()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
init {
|
||||||
|
LayoutInflater.from(context).inflate(R.layout.view_sub_banner, this, true)
|
||||||
|
recycler = findViewById(R.id.rv_sub_banner)
|
||||||
|
recycler.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
|
||||||
|
recycler.adapter = adapter
|
||||||
|
recycler.itemAnimator = null
|
||||||
|
visibility = GONE
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setItems(items: List<SubBannerItem>) {
|
||||||
|
if (released || !state.setItems(items)) return
|
||||||
|
replacingItems = true
|
||||||
|
stopTimer()
|
||||||
|
cancelImageRequest()
|
||||||
|
recycler.stopScroll()
|
||||||
|
dragging = false
|
||||||
|
images.clear()
|
||||||
|
renderedItem = null
|
||||||
|
displayRatio = null
|
||||||
|
animateSelection = false
|
||||||
|
adapter.submitItems(state.items)
|
||||||
|
currentPosition = adapter.startPosition(0)
|
||||||
|
visibility = if (state.items.isEmpty()) GONE else VISIBLE
|
||||||
|
requestLayout()
|
||||||
|
replacingItems = false
|
||||||
|
loadCurrentImage()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setActive(active: Boolean) {
|
||||||
|
if (released || this.active == active) return
|
||||||
|
this.active = active
|
||||||
|
if (active) {
|
||||||
|
startTimer()
|
||||||
|
} else {
|
||||||
|
stopTimer()
|
||||||
|
recycler.stopScroll()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setOnBannerClickListener(listener: ((SubBannerItem) -> Unit)?) {
|
||||||
|
if (!released) adapter.setOnClickItem(listener)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onAttachedToWindow() {
|
||||||
|
super.onAttachedToWindow()
|
||||||
|
if (released) return
|
||||||
|
attached = true
|
||||||
|
recycler.adapter = adapter
|
||||||
|
recycler.addOnScrollListener(scrollListener)
|
||||||
|
snapHelper.attachToRecyclerView(recycler)
|
||||||
|
lifecycleOwner = findViewTreeLifecycleOwner()?.also { owner ->
|
||||||
|
started = owner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)
|
||||||
|
owner.lifecycle.addObserver(lifecycleObserver)
|
||||||
|
}
|
||||||
|
loadCurrentImage()
|
||||||
|
startTimer()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDetachedFromWindow() {
|
||||||
|
detach()
|
||||||
|
super.onDetachedFromWindow()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun release() {
|
||||||
|
if (released) return
|
||||||
|
released = true
|
||||||
|
detach()
|
||||||
|
adapter.release()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun detach() {
|
||||||
|
attached = false
|
||||||
|
stopTimer()
|
||||||
|
cancelImageRequest()
|
||||||
|
handler.removeCallbacks(loadImage)
|
||||||
|
lifecycleOwner?.lifecycle?.removeObserver(lifecycleObserver)
|
||||||
|
lifecycleOwner = null
|
||||||
|
recycler.removeOnScrollListener(scrollListener)
|
||||||
|
recycler.stopScroll()
|
||||||
|
snapHelper.attachToRecyclerView(null)
|
||||||
|
recycler.adapter = null
|
||||||
|
images.clear()
|
||||||
|
renderedItem = null
|
||||||
|
dragging = false
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
|
||||||
|
val width = MeasureSpec.getSize(widthMeasureSpec)
|
||||||
|
if (contentWidth != width && width > 0) {
|
||||||
|
contentWidth = width
|
||||||
|
handler.removeCallbacks(loadImage)
|
||||||
|
handler.post(loadImage)
|
||||||
|
}
|
||||||
|
val height = displayRatio?.let { (width / it).roundToInt() } ?: 0
|
||||||
|
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun loadCurrentImage() {
|
||||||
|
if (released || !attached || contentWidth <= 0) return
|
||||||
|
val item = state.currentItem ?: return
|
||||||
|
if (imageWidth == contentWidth && images.containsKey(item)) {
|
||||||
|
showCurrentImage()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (imageKey?.item == item && imageWidth == contentWidth) return
|
||||||
|
cancelImageRequest()
|
||||||
|
if (imageWidth != contentWidth) images.clear()
|
||||||
|
imageWidth = contentWidth
|
||||||
|
val key = state.beginImageRequest(state.currentIndex)
|
||||||
|
imageKey = key
|
||||||
|
imageRequest = ImageLoaderProvider.imageLoader.enqueue(
|
||||||
|
ImageRequest.Builder(context)
|
||||||
|
.data(item.imageUrl)
|
||||||
|
.size(Size(contentWidth, Dimension.Undefined))
|
||||||
|
.scale(Scale.FIT)
|
||||||
|
.precision(Precision.INEXACT)
|
||||||
|
.listener(
|
||||||
|
onSuccess = { _, result ->
|
||||||
|
val drawable = result.drawable
|
||||||
|
if (drawable.intrinsicWidth <= 0 || drawable.intrinsicHeight <= 0) {
|
||||||
|
failImage(key)
|
||||||
|
} else if (state.onImageLoaded(key, drawable.intrinsicWidth, drawable.intrinsicHeight)) {
|
||||||
|
imageKey = null
|
||||||
|
imageRequest = null
|
||||||
|
images.keys.retainAll(setOfNotNull(renderedItem, item))
|
||||||
|
images[item] = drawable
|
||||||
|
showCurrentImage()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onError = { _, _ -> failImage(key) }
|
||||||
|
)
|
||||||
|
.build()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showCurrentImage() {
|
||||||
|
renderedItem = state.currentItem
|
||||||
|
displayRatio = state.currentRatio
|
||||||
|
visibility = VISIBLE
|
||||||
|
adapter.refreshImages()
|
||||||
|
requestLayout()
|
||||||
|
val manager = recycler.layoutManager as LinearLayoutManager
|
||||||
|
if (animateSelection) {
|
||||||
|
animateSelection = false
|
||||||
|
recycler.smoothScrollBy(contentWidth, 0, null, 350)
|
||||||
|
} else {
|
||||||
|
manager.scrollToPositionWithOffset(currentPosition, 0)
|
||||||
|
}
|
||||||
|
startTimer()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun failImage(key: SubBannerState.ImageKey) {
|
||||||
|
if (!state.onImageFailed(key)) return
|
||||||
|
imageKey = null
|
||||||
|
imageRequest = null
|
||||||
|
stopTimer()
|
||||||
|
adapter.submitItems(state.items)
|
||||||
|
currentPosition = adapter.startPosition(state.currentIndex)
|
||||||
|
animateSelection = false
|
||||||
|
if (state.items.isEmpty()) {
|
||||||
|
displayRatio = null
|
||||||
|
images.clear()
|
||||||
|
visibility = GONE
|
||||||
|
requestLayout()
|
||||||
|
} else {
|
||||||
|
handler.removeCallbacks(loadImage)
|
||||||
|
handler.post(loadImage)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun cancelImageRequest() {
|
||||||
|
state.invalidateRequests()
|
||||||
|
imageKey = null
|
||||||
|
imageRequest?.dispose()
|
||||||
|
imageRequest = null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun canAutoScroll(): Boolean = !released && attached && active && started && !dragging &&
|
||||||
|
state.items.size > 1 && images.containsKey(state.currentItem) && imageKey == null
|
||||||
|
|
||||||
|
private fun startTimer() {
|
||||||
|
if (timerScheduled || !canAutoScroll()) return
|
||||||
|
timerScheduled = true
|
||||||
|
handler.postDelayed(advance, 5_000)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun stopTimer() {
|
||||||
|
handler.removeCallbacks(advance)
|
||||||
|
timerScheduled = false
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="match_parent"
|
||||||
|
android:contentDescription="@string/screen_event_title"
|
||||||
|
android:focusable="true"
|
||||||
|
android:scaleType="fitCenter" />
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<merge xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<androidx.recyclerview.widget.RecyclerView
|
||||||
|
android:id="@+id/rv_sub_banner"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="match_parent"
|
||||||
|
android:overScrollMode="never" />
|
||||||
|
</merge>
|
||||||
+165
@@ -0,0 +1,165 @@
|
|||||||
|
package kr.co.vividnext.sodalive.v2.main.content
|
||||||
|
|
||||||
|
import android.app.Application
|
||||||
|
import android.os.Looper
|
||||||
|
import com.google.gson.Gson
|
||||||
|
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 kr.co.vividnext.sodalive.common.ApiResponse
|
||||||
|
import kr.co.vividnext.sodalive.common.SharedPreferenceManager
|
||||||
|
import kr.co.vividnext.sodalive.v2.main.content.data.AudioRecommendationsApi
|
||||||
|
import kr.co.vividnext.sodalive.v2.main.content.data.AudioRecommendationsRepository
|
||||||
|
import kr.co.vividnext.sodalive.v2.main.content.data.AudioRecommendationsResponse
|
||||||
|
import kr.co.vividnext.sodalive.v2.main.content.model.AudioRecommendationsUiState
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNotNull
|
||||||
|
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.Shadows.shadowOf
|
||||||
|
import org.robolectric.annotation.Config
|
||||||
|
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||||
|
import retrofit2.HttpException
|
||||||
|
import retrofit2.Response
|
||||||
|
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [28], application = Application::class)
|
||||||
|
class ContentMainViewModelTest {
|
||||||
|
private val api = FakeApi()
|
||||||
|
private lateinit var viewModel: ContentMainViewModel
|
||||||
|
|
||||||
|
@Before
|
||||||
|
fun setUp() {
|
||||||
|
RxJavaPlugins.setIoSchedulerHandler { Schedulers.trampoline() }
|
||||||
|
RxAndroidPlugins.setInitMainThreadSchedulerHandler { Schedulers.trampoline() }
|
||||||
|
RxAndroidPlugins.setMainThreadSchedulerHandler { Schedulers.trampoline() }
|
||||||
|
mockkObject(SharedPreferenceManager)
|
||||||
|
every { SharedPreferenceManager.token } returns ""
|
||||||
|
viewModel = ContentMainViewModel(AudioRecommendationsRepository(api))
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
fun tearDown() {
|
||||||
|
RxJavaPlugins.reset()
|
||||||
|
RxAndroidPlugins.reset()
|
||||||
|
unmockkObject(SharedPreferenceManager)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `비로그인 콘텐츠 추천은 인증 헤더를 생략한다`() {
|
||||||
|
api.responses += Single.just(ApiResponse(true, response(), null))
|
||||||
|
|
||||||
|
viewModel.loadRecommendations()
|
||||||
|
|
||||||
|
assertNull(api.headers.single())
|
||||||
|
assertEquals(AudioRecommendationsUiState.Empty, viewModel.recommendationsStateLiveData.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `서브 배너 단독 콘텐츠 추천도 Content 상태가 된다`() {
|
||||||
|
api.responses += Single.just(
|
||||||
|
ApiResponse(
|
||||||
|
true,
|
||||||
|
response(
|
||||||
|
banners = """[{"id":7,"placement":"CONTENT_RECOMMENDATION",
|
||||||
|
"imageUrl":"https://example.invalid/banner","webUrl":"https://example.invalid/page",
|
||||||
|
"androidDeepLink":null,"iosDeepLink":null}]"""
|
||||||
|
),
|
||||||
|
null
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
viewModel.loadRecommendations()
|
||||||
|
|
||||||
|
assertTrue(viewModel.recommendationsStateLiveData.value is AudioRecommendationsUiState.Content)
|
||||||
|
val state = viewModel.recommendationsStateLiveData.value as AudioRecommendationsUiState.Content
|
||||||
|
assertEquals(listOf(7L), state.subBanners.map { it.id })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `로그인 콘텐츠 추천은 기존 Bearer 헤더를 보존한다`() {
|
||||||
|
every { SharedPreferenceManager.token } returns "test-token"
|
||||||
|
api.responses += Single.just(ApiResponse(true, response(), null))
|
||||||
|
|
||||||
|
viewModel.loadRecommendations()
|
||||||
|
|
||||||
|
assertEquals(listOf("Bearer test-token"), api.headers)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `실패 envelope는 빈 성공과 다르게 Error와 일반 오류 피드백을 낸다`() {
|
||||||
|
api.responses += Single.just(ApiResponse(false, null, "denied"))
|
||||||
|
|
||||||
|
viewModel.loadRecommendations()
|
||||||
|
|
||||||
|
assertTrue(viewModel.recommendationsStateLiveData.value is AudioRecommendationsUiState.Error)
|
||||||
|
shadowOf(Looper.getMainLooper()).idle()
|
||||||
|
assertNotNull(viewModel.toastLiveData.value)
|
||||||
|
assertEquals(false, viewModel.isLoading.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `최초 HTTP 오류는 Empty 대신 Error 상태다`() {
|
||||||
|
api.responses += Single.error(HttpException(Response.error<Any>(500, "error".toResponseBody())))
|
||||||
|
|
||||||
|
viewModel.loadRecommendations()
|
||||||
|
|
||||||
|
assertTrue(viewModel.recommendationsStateLiveData.value is AudioRecommendationsUiState.Error)
|
||||||
|
shadowOf(Looper.getMainLooper()).idle()
|
||||||
|
assertNotNull(viewModel.toastLiveData.value)
|
||||||
|
assertEquals(false, viewModel.isLoading.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `refresh의 HTTP 및 envelope 오류는 표시 중인 추천과 배너를 보존한다`() {
|
||||||
|
api.responses += Single.just(
|
||||||
|
ApiResponse(
|
||||||
|
true,
|
||||||
|
response(
|
||||||
|
banners = """[{"id":9,"placement":"CONTENT_RECOMMENDATION",
|
||||||
|
"imageUrl":"https://example.invalid/image","androidDeepLink":"sodalive://event/9"}]"""
|
||||||
|
),
|
||||||
|
null
|
||||||
|
)
|
||||||
|
)
|
||||||
|
viewModel.loadRecommendations()
|
||||||
|
val previous = viewModel.recommendationsStateLiveData.value
|
||||||
|
|
||||||
|
api.responses += Single.error(HttpException(Response.error<Any>(401, "error".toResponseBody())))
|
||||||
|
viewModel.loadRecommendations()
|
||||||
|
assertEquals(previous, viewModel.recommendationsStateLiveData.value)
|
||||||
|
|
||||||
|
api.responses += Single.just(ApiResponse(false, null, "denied"))
|
||||||
|
viewModel.loadRecommendations()
|
||||||
|
assertEquals(previous, viewModel.recommendationsStateLiveData.value)
|
||||||
|
shadowOf(Looper.getMainLooper()).idle()
|
||||||
|
assertNotNull(viewModel.toastLiveData.value)
|
||||||
|
assertEquals(false, viewModel.isLoading.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun response(banners: String = "[]"): AudioRecommendationsResponse = Gson().fromJson(
|
||||||
|
"""{
|
||||||
|
"banners":[],"originalSeries":[],"latestAudios":[],"newAndHotAudios":[],"freeAudios":[],"pointAudios":[],
|
||||||
|
"mostCommentedAudios":[],"recommendedAudios":[],"subBanners":$banners}
|
||||||
|
""",
|
||||||
|
AudioRecommendationsResponse::class.java
|
||||||
|
)
|
||||||
|
|
||||||
|
private class FakeApi : AudioRecommendationsApi {
|
||||||
|
val responses = ArrayDeque<Single<ApiResponse<AudioRecommendationsResponse>>>()
|
||||||
|
val headers = mutableListOf<String?>()
|
||||||
|
override fun getRecommendations(authHeader: String?): Single<ApiResponse<AudioRecommendationsResponse>> {
|
||||||
|
headers += authHeader
|
||||||
|
return responses.removeFirst()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+163
@@ -0,0 +1,163 @@
|
|||||||
|
package kr.co.vividnext.sodalive.v2.widget.subbanner
|
||||||
|
|
||||||
|
import android.app.Application
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Color
|
||||||
|
import android.graphics.drawable.ColorDrawable
|
||||||
|
import android.widget.FrameLayout
|
||||||
|
import android.widget.ImageView
|
||||||
|
import androidx.test.core.app.ApplicationProvider
|
||||||
|
import coil.ImageLoader
|
||||||
|
import coil.load
|
||||||
|
import coil.request.Disposable
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertSame
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
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 SubBannerAdapterTest {
|
||||||
|
private val context: Context = ApplicationProvider.getApplicationContext()
|
||||||
|
private val items = listOf(item(9), item(2), item(7))
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `가상 위치는 서버 순서의 실제 항목과 동일한 클릭 payload를 전달한다`() {
|
||||||
|
var boundItem: SubBannerItem? = null
|
||||||
|
var boundImage: ImageView? = null
|
||||||
|
val clicks = mutableListOf<SubBannerItem>()
|
||||||
|
val adapter = SubBannerAdapter(
|
||||||
|
onClickItem = { clicks += it },
|
||||||
|
onBindImage = { image, item, _ ->
|
||||||
|
boundImage = image
|
||||||
|
boundItem = item
|
||||||
|
}
|
||||||
|
)
|
||||||
|
adapter.submitItems(items)
|
||||||
|
val holder = adapter.onCreateViewHolder(FrameLayout(context), 0)
|
||||||
|
|
||||||
|
adapter.onBindViewHolder(holder, adapter.startPosition(0) + 4)
|
||||||
|
holder.itemView.performClick()
|
||||||
|
|
||||||
|
assertTrue(adapter.itemCount > items.size)
|
||||||
|
assertTrue(boundImage != null)
|
||||||
|
assertSame(items[1], boundItem)
|
||||||
|
assertEquals(1, clicks.size)
|
||||||
|
assertSame(items[1], clicks.single())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `가상 목록 양쪽 수동 경계는 마지막과 첫 항목으로 이어진다`() {
|
||||||
|
val adapter = SubBannerAdapter()
|
||||||
|
adapter.submitItems(items)
|
||||||
|
|
||||||
|
assertEquals(2, adapter.toRealIndex(adapter.startPosition(0) - 1))
|
||||||
|
assertEquals(0, adapter.toRealIndex(adapter.startPosition(2) + 1))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `재바인딩한 holder 클릭은 이전 항목 대신 현재 항목을 한 번 전달한다`() {
|
||||||
|
val clicks = mutableListOf<SubBannerItem>()
|
||||||
|
val adapter = SubBannerAdapter(onClickItem = { clicks += it })
|
||||||
|
adapter.submitItems(items)
|
||||||
|
val holder = adapter.onCreateViewHolder(FrameLayout(context), 0)
|
||||||
|
adapter.onBindViewHolder(holder, 0)
|
||||||
|
|
||||||
|
adapter.onBindViewHolder(holder, 1)
|
||||||
|
holder.itemView.performClick()
|
||||||
|
|
||||||
|
assertEquals(1, clicks.size)
|
||||||
|
assertSame(items[1], clicks.single())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `목록 교체 뒤 재바인딩 전의 오래된 holder는 이전 링크를 전달하지 않는다`() {
|
||||||
|
val clicks = mutableListOf<SubBannerItem>()
|
||||||
|
val adapter = SubBannerAdapter(onClickItem = { clicks += it })
|
||||||
|
adapter.submitItems(items)
|
||||||
|
val holder = adapter.onCreateViewHolder(FrameLayout(context), 0)
|
||||||
|
adapter.onBindViewHolder(holder, 0)
|
||||||
|
|
||||||
|
adapter.submitItems(listOf(items[0].copy(webUrl = "https://example.com/replaced")))
|
||||||
|
holder.itemView.performClick()
|
||||||
|
|
||||||
|
assertTrue(clicks.isEmpty())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `빈 목록 교체와 해제 뒤에는 이전 클릭 리스너를 호출하지 않는다`() {
|
||||||
|
val clicks = mutableListOf<SubBannerItem>()
|
||||||
|
val adapter = SubBannerAdapter(onClickItem = { clicks += it })
|
||||||
|
adapter.submitItems(items)
|
||||||
|
val holder = adapter.onCreateViewHolder(FrameLayout(context), 0)
|
||||||
|
adapter.onBindViewHolder(holder, 0)
|
||||||
|
adapter.submitItems(emptyList())
|
||||||
|
holder.itemView.performClick()
|
||||||
|
assertTrue(clicks.isEmpty())
|
||||||
|
|
||||||
|
adapter.submitItems(items)
|
||||||
|
adapter.onBindViewHolder(holder, 1)
|
||||||
|
adapter.release()
|
||||||
|
holder.itemView.performClick()
|
||||||
|
|
||||||
|
assertTrue(clicks.isEmpty())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `재바인딩과 재활용은 이전 이미지 요청을 해제한다`() {
|
||||||
|
val loader = ImageLoader.Builder(context).build()
|
||||||
|
val requests = mutableListOf<Disposable>()
|
||||||
|
val adapter = SubBannerAdapter(onBindImage = { image, _, _ ->
|
||||||
|
requests += image.load(ColorDrawable(Color.GREEN), loader)
|
||||||
|
})
|
||||||
|
try {
|
||||||
|
adapter.submitItems(items)
|
||||||
|
val holder = adapter.onCreateViewHolder(FrameLayout(context), 0)
|
||||||
|
adapter.onBindViewHolder(holder, 0)
|
||||||
|
|
||||||
|
adapter.onBindViewHolder(holder, 1)
|
||||||
|
assertTrue(requests[0].isDisposed)
|
||||||
|
adapter.onViewRecycled(holder)
|
||||||
|
|
||||||
|
assertTrue(requests[1].isDisposed)
|
||||||
|
} finally {
|
||||||
|
adapter.release()
|
||||||
|
loader.shutdown()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `해제는 바인딩된 이미지 요청과 클릭 전달을 모두 중지한다`() {
|
||||||
|
val loader = ImageLoader.Builder(context).build()
|
||||||
|
var request: Disposable? = null
|
||||||
|
val clicks = mutableListOf<SubBannerItem>()
|
||||||
|
val adapter = SubBannerAdapter(
|
||||||
|
onClickItem = { clicks += it },
|
||||||
|
onBindImage = { image, _, _ -> request = image.load(ColorDrawable(Color.GREEN), loader) }
|
||||||
|
)
|
||||||
|
try {
|
||||||
|
adapter.submitItems(items)
|
||||||
|
val holder = adapter.onCreateViewHolder(FrameLayout(context), 0)
|
||||||
|
adapter.onBindViewHolder(holder, 0)
|
||||||
|
|
||||||
|
adapter.release()
|
||||||
|
holder.itemView.performClick()
|
||||||
|
|
||||||
|
assertTrue(requireNotNull(request).isDisposed)
|
||||||
|
assertTrue(clicks.isEmpty())
|
||||||
|
} finally {
|
||||||
|
adapter.release()
|
||||||
|
loader.shutdown()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun item(id: Long) = SubBannerItem(
|
||||||
|
id = id,
|
||||||
|
imageUrl = "https://example.com/banner-$id.png",
|
||||||
|
androidDeepLink = "sodalive://event/$id",
|
||||||
|
webUrl = "https://example.com/event/$id"
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
package kr.co.vividnext.sodalive.v2.widget.subbanner
|
||||||
|
|
||||||
|
import io.reactivex.rxjava3.schedulers.Schedulers
|
||||||
|
import kr.co.vividnext.sodalive.v2.main.content.data.AudioRecommendationsApi
|
||||||
|
import kr.co.vividnext.sodalive.v2.main.content.data.AudioRecommendationsRepository
|
||||||
|
import kr.co.vividnext.sodalive.v2.main.content.model.toContent
|
||||||
|
import kr.co.vividnext.sodalive.v2.main.home.data.FollowRecommendedCreatorsRequest
|
||||||
|
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.model.toContent
|
||||||
|
import okhttp3.MediaType.Companion.toMediaType
|
||||||
|
import okhttp3.OkHttpClient
|
||||||
|
import okhttp3.Protocol
|
||||||
|
import okhttp3.Request
|
||||||
|
import okhttp3.Response
|
||||||
|
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
import retrofit2.HttpException
|
||||||
|
import retrofit2.Retrofit
|
||||||
|
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
|
||||||
|
import retrofit2.converter.gson.GsonConverterFactory
|
||||||
|
|
||||||
|
class SubBannerApiTest {
|
||||||
|
@Test
|
||||||
|
fun `익명 추천은 두 기존 GET만 호출하고 인증과 query 및 body를 생략한다`() {
|
||||||
|
val fixture = Fixture()
|
||||||
|
|
||||||
|
assertTrue(fixture.home.getRecommendations("").blockingGet().success)
|
||||||
|
assertTrue(fixture.audio.getRecommendations("").blockingGet().success)
|
||||||
|
|
||||||
|
assertEquals(2, fixture.requests.size)
|
||||||
|
assertEquals(
|
||||||
|
listOf("/api/v2/home/recommendations", "/api/v2/audio/recommendations"),
|
||||||
|
fixture.requests.map { it.url.encodedPath }
|
||||||
|
)
|
||||||
|
fixture.requests.forEach {
|
||||||
|
assertEquals("GET", it.method)
|
||||||
|
assertNull(it.header("Authorization"))
|
||||||
|
assertNull(it.url.query)
|
||||||
|
assertNull(it.body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `로그인 추천의 기존 Bearer 헤더는 두 GET에서 그대로 유지된다`() {
|
||||||
|
val fixture = Fixture()
|
||||||
|
|
||||||
|
assertTrue(fixture.home.getRecommendations("Bearer test-token").blockingGet().success)
|
||||||
|
assertTrue(fixture.audio.getRecommendations("Bearer test-token").blockingGet().success)
|
||||||
|
|
||||||
|
assertEquals(2, fixture.requests.size)
|
||||||
|
assertEquals(
|
||||||
|
listOf("Bearer test-token", "Bearer test-token"),
|
||||||
|
fixture.requests.map { it.header("Authorization") }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `null 토큰도 익명 요청으로 전달한다`() {
|
||||||
|
val fixture = Fixture()
|
||||||
|
|
||||||
|
assertTrue(fixture.home.getRecommendations(null).blockingGet().success)
|
||||||
|
assertTrue(fixture.audio.getRecommendations(null).blockingGet().success)
|
||||||
|
|
||||||
|
assertEquals(2, fixture.requests.size)
|
||||||
|
assertTrue(fixture.requests.all { it.header("Authorization") == null })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `홈 follow는 기존 인증 POST와 요청 본문을 유지한다`() {
|
||||||
|
val fixture = Fixture()
|
||||||
|
|
||||||
|
assertTrue(
|
||||||
|
fixture.home.followRecommendedCreators(FollowRecommendedCreatorsRequest(listOf(7L)), "Bearer test-token")
|
||||||
|
.blockingGet().success
|
||||||
|
)
|
||||||
|
|
||||||
|
val request = fixture.requests.single()
|
||||||
|
assertEquals("POST", request.method)
|
||||||
|
assertEquals("/api/v2/home/recommendations/creators/follow", request.url.encodedPath)
|
||||||
|
assertEquals("Bearer test-token", request.header("Authorization"))
|
||||||
|
val body = okio.Buffer()
|
||||||
|
request.body!!.writeTo(body)
|
||||||
|
assertEquals("{\"creatorIds\":[7]}", body.readUtf8())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `서브 배너 단독 응답도 두 mapper에서 빈 추천으로 오인하지 않는다`() {
|
||||||
|
val fixture = Fixture(
|
||||||
|
envelope(
|
||||||
|
"""[
|
||||||
|
{"id":9007199254740993,"placement":"HOME_RECOMMENDATION","imageUrl":"https://example.invalid/home",
|
||||||
|
"webUrl":"https://example.invalid/h","androidDeepLink":null,"iosDeepLink":null},
|
||||||
|
{"id":9223372036854775807,"placement":"CONTENT_RECOMMENDATION","imageUrl":"https://example.invalid/audio",
|
||||||
|
"webUrl":null,"androidDeepLink":"sodalive://audio/7","iosDeepLink":null}
|
||||||
|
]"""
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
val home = fixture.home.getRecommendations("").blockingGet().data!!.toContent()
|
||||||
|
val audio = fixture.audio.getRecommendations("").blockingGet().data!!.toContent()
|
||||||
|
assertFalse(home.isEmpty)
|
||||||
|
assertFalse(audio.isEmpty)
|
||||||
|
assertEquals(listOf(9_007_199_254_740_993L), home.subBanners.map { it.id })
|
||||||
|
assertEquals(listOf(Long.MAX_VALUE), audio.subBanners.map { it.id })
|
||||||
|
assertEquals(2, fixture.requests.size)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `기존 응답에서 subBanners가 누락되거나 null이어도 정상 빈 상태다`() {
|
||||||
|
listOf(envelope("null"), envelope("[]").replace("\"subBanners\":[]", "\"unused\":[]")).forEach { json ->
|
||||||
|
val fixture = Fixture(json)
|
||||||
|
|
||||||
|
assertTrue(fixture.home.getRecommendations(null).blockingGet().data!!.toContent().subBanners.isEmpty())
|
||||||
|
assertTrue(fixture.audio.getRecommendations(null).blockingGet().data!!.toContent().subBanners.isEmpty())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `잘못된 서브 배너는 실제 Gson 경계에서도 기존 추천과 메인 배너를 손상시키지 않는다`() {
|
||||||
|
val fixture = Fixture(
|
||||||
|
envelope(
|
||||||
|
"""[null,false,{"id":1.2},{"id":9223372036854775808},
|
||||||
|
{"id":9,"placement":"HOME_RECOMMENDATION","imageUrl":"https://example.invalid/image","iosDeepLink":"ios://only"},
|
||||||
|
{"id":10,"placement":"CONTENT_RECOMMENDATION","imageUrl":"bad","webUrl":"https://example.invalid/page"}]
|
||||||
|
"""
|
||||||
|
).replace(
|
||||||
|
"\"banners\":[]",
|
||||||
|
""""banners":[{"imageUrl":"original-banner","eventItem":null,
|
||||||
|
"creatorId":7,"seriesId":null,"link":null}]"""
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
val home = fixture.home.getRecommendations(null).blockingGet().data!!.toContent()
|
||||||
|
val audio = fixture.audio.getRecommendations(null).blockingGet().data!!.toContent()
|
||||||
|
|
||||||
|
assertTrue(home.subBanners.isEmpty())
|
||||||
|
assertTrue(audio.subBanners.isEmpty())
|
||||||
|
assertEquals("original-banner", home.banners.items.single().imageUrl)
|
||||||
|
assertEquals("original-banner", audio.banners.items.single().imageUrl)
|
||||||
|
assertFalse(home.isEmpty)
|
||||||
|
assertFalse(audio.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `정상 빈 목록과 실패 envelope를 두 API에서 구별한다`() {
|
||||||
|
val empty = Fixture()
|
||||||
|
assertTrue(empty.home.getRecommendations("").blockingGet().data!!.toContent().isEmpty)
|
||||||
|
assertTrue(empty.audio.getRecommendations("").blockingGet().data!!.toContent().isEmpty)
|
||||||
|
val failure = Fixture("""{"success":false,"data":null,"message":"denied","errorProperty":null}""")
|
||||||
|
listOf(failure.home.getRecommendations("").blockingGet(), failure.audio.getRecommendations("").blockingGet()).forEach {
|
||||||
|
assertFalse(it.success)
|
||||||
|
assertNull(it.data)
|
||||||
|
assertEquals("denied", it.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `비JSON HTTP 오류는 빈 성공으로 바꾸지 않고 원래 상태 코드로 전달한다`() {
|
||||||
|
listOf(401, 404, 500).forEach { code ->
|
||||||
|
val fixture = Fixture("<html>server error</html>", code)
|
||||||
|
fixture.home.getRecommendations("").test().assertNoValues().assertError { it is HttpException && it.code() == code }
|
||||||
|
fixture.audio.getRecommendations("").test().assertNoValues().assertError { it is HttpException && it.code() == code }
|
||||||
|
assertEquals(2, fixture.requests.size)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private class Fixture(json: String = envelope("[]"), code: Int = 200) {
|
||||||
|
val requests = mutableListOf<Request>()
|
||||||
|
private val client = OkHttpClient.Builder().addInterceptor { chain ->
|
||||||
|
requests += chain.request()
|
||||||
|
Response.Builder().request(chain.request()).protocol(Protocol.HTTP_1_1)
|
||||||
|
.code(code).message("test response").body(json.toResponseBody("application/json".toMediaType())).build()
|
||||||
|
}.build()
|
||||||
|
private val retrofit = Retrofit.Builder().baseUrl("https://example.invalid/").client(client)
|
||||||
|
.addConverterFactory(GsonConverterFactory.create())
|
||||||
|
.addCallAdapterFactory(RxJava3CallAdapterFactory.createWithScheduler(Schedulers.trampoline())).build()
|
||||||
|
val home = HomeRecommendationRepository(retrofit.create(HomeRecommendationApi::class.java))
|
||||||
|
val audio = AudioRecommendationsRepository(retrofit.create(AudioRecommendationsApi::class.java))
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private fun envelope(subBanners: String) = """{"success":true,"message":null,"errorProperty":null,"data":{
|
||||||
|
"lives":[],"banners":[],"recentlyActiveCreators":[],"recentDebutCreators":[],"aiCharacters":[],
|
||||||
|
"genreCreators":[],"cheerCreators":[],"popularCommunityPosts":[],"originalSeries":[],"latestAudios":[],
|
||||||
|
"newAndHotAudios":[],"freeAudios":[],"pointAudios":[],"mostCommentedAudios":[],"recommendedAudios":[],
|
||||||
|
"subBanners":$subBanners}}
|
||||||
|
"""
|
||||||
|
}
|
||||||
|
}
|
||||||
+370
@@ -0,0 +1,370 @@
|
|||||||
|
package kr.co.vividnext.sodalive.v2.widget.subbanner
|
||||||
|
|
||||||
|
import android.app.Activity
|
||||||
|
import android.app.Application
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.graphics.drawable.BitmapDrawable
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import android.view.View
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import android.widget.FrameLayout
|
||||||
|
import androidx.recyclerview.widget.LinearLayoutManager
|
||||||
|
import androidx.recyclerview.widget.RecyclerView
|
||||||
|
import coil.EventListener
|
||||||
|
import coil.ImageLoader
|
||||||
|
import coil.decode.DataSource
|
||||||
|
import coil.fetch.DrawableResult
|
||||||
|
import coil.fetch.Fetcher
|
||||||
|
import coil.request.CachePolicy
|
||||||
|
import coil.request.ImageRequest
|
||||||
|
import coil.size.Dimension
|
||||||
|
import coil.size.Precision
|
||||||
|
import coil.size.Scale
|
||||||
|
import coil.size.Size
|
||||||
|
import kotlinx.coroutines.CompletableDeferred
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import kotlinx.coroutines.withTimeout
|
||||||
|
import kr.co.vividnext.sodalive.common.ImageLoaderProvider
|
||||||
|
import kr.co.vividnext.sodalive.R
|
||||||
|
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.Robolectric
|
||||||
|
import org.robolectric.RobolectricTestRunner
|
||||||
|
import org.robolectric.Shadows.shadowOf
|
||||||
|
import org.robolectric.annotation.Config
|
||||||
|
import org.robolectric.annotation.LooperMode
|
||||||
|
import java.io.IOException
|
||||||
|
import java.time.Duration
|
||||||
|
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [28], application = Application::class)
|
||||||
|
@LooperMode(LooperMode.Mode.PAUSED)
|
||||||
|
class SubBannerImageRequestTest {
|
||||||
|
private lateinit var activity: Activity
|
||||||
|
private lateinit var host: FrameLayout
|
||||||
|
private lateinit var view: SubBannerView
|
||||||
|
private lateinit var loader: ImageLoader
|
||||||
|
private var previousLoader: ImageLoader? = null
|
||||||
|
private val requests = mutableListOf<ImageRequest>()
|
||||||
|
private val cancelled = mutableListOf<ImageRequest>()
|
||||||
|
private val fetchGate = CompletableDeferred<Unit>()
|
||||||
|
private var failuresEnabled = true
|
||||||
|
|
||||||
|
@Before
|
||||||
|
fun setUp() {
|
||||||
|
activity = Robolectric.buildActivity(Activity::class.java).setup().visible().get()
|
||||||
|
loader = ImageLoader.Builder(activity)
|
||||||
|
.dispatcher(Dispatchers.Unconfined)
|
||||||
|
.memoryCachePolicy(CachePolicy.DISABLED)
|
||||||
|
.diskCachePolicy(CachePolicy.DISABLED)
|
||||||
|
.components {
|
||||||
|
add(
|
||||||
|
Fetcher.Factory<Uri> { data, _, _ ->
|
||||||
|
if (data.host != "example.com") {
|
||||||
|
null
|
||||||
|
} else {
|
||||||
|
Fetcher {
|
||||||
|
if (failuresEnabled && data.lastPathSegment?.startsWith("failure") == true) {
|
||||||
|
throw IOException("test image failure")
|
||||||
|
}
|
||||||
|
if (data.lastPathSegment == "delayed") fetchGate.await()
|
||||||
|
DrawableResult(
|
||||||
|
BitmapDrawable(
|
||||||
|
activity.resources,
|
||||||
|
if (data.lastPathSegment == "portrait") {
|
||||||
|
Bitmap.createBitmap(300, 900, Bitmap.Config.ARGB_8888)
|
||||||
|
} else {
|
||||||
|
Bitmap.createBitmap(900, 300, Bitmap.Config.ARGB_8888)
|
||||||
|
}
|
||||||
|
),
|
||||||
|
false,
|
||||||
|
DataSource.NETWORK
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
.eventListenerFactory {
|
||||||
|
object : EventListener {
|
||||||
|
override fun onStart(request: ImageRequest) {
|
||||||
|
requests += request
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCancel(request: ImageRequest) {
|
||||||
|
cancelled += request
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.build()
|
||||||
|
previousLoader = if (ImageLoaderProvider.isInitialized) ImageLoaderProvider.imageLoader else null
|
||||||
|
replaceSharedLoader(loader)
|
||||||
|
host = FrameLayout(activity)
|
||||||
|
activity.setContentView(host)
|
||||||
|
view = SubBannerView(activity)
|
||||||
|
host.addView(view, FrameLayout.LayoutParams(300, ViewGroup.LayoutParams.WRAP_CONTENT))
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
fun tearDown() {
|
||||||
|
view.release()
|
||||||
|
host.removeAllViews()
|
||||||
|
activity.finish()
|
||||||
|
loader.shutdown()
|
||||||
|
replaceSharedLoader(previousLoader)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `최초 비율 없이도 폭 제한 요청을 시작하고 성공 원본 비율을 받는다`() {
|
||||||
|
view.setItems(listOf(item("success")))
|
||||||
|
|
||||||
|
measureHost()
|
||||||
|
shadowOf(Looper.getMainLooper()).idle()
|
||||||
|
|
||||||
|
assertFalse(requests.isEmpty())
|
||||||
|
val request = requests.first()
|
||||||
|
assertEquals("https://example.com/success", request.data.toString())
|
||||||
|
assertEquals(Size(300, Dimension.Undefined), runBlocking { withTimeout(1_000) { request.sizeResolver.size() } })
|
||||||
|
assertEquals(Scale.FIT, request.scale)
|
||||||
|
assertEquals(Precision.INEXACT, request.precision)
|
||||||
|
assertNull(request.placeholder)
|
||||||
|
assertNull(request.error)
|
||||||
|
assertNull(request.fallback)
|
||||||
|
assertEquals(3.0, requireNotNull(state().currentRatio), 0.0001)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `실패 후보 제외 뒤에도 다음 목록의 성공 이미지를 받을 수 있다`() {
|
||||||
|
val failedItem = item("failure")
|
||||||
|
view.setItems(listOf(failedItem))
|
||||||
|
measureHost()
|
||||||
|
shadowOf(Looper.getMainLooper()).idle()
|
||||||
|
assertTrue(requests.isNotEmpty())
|
||||||
|
assertNull(state().currentItem)
|
||||||
|
assertNull(state().currentRatio)
|
||||||
|
|
||||||
|
view.setItems(listOf(item("success")))
|
||||||
|
measureHost()
|
||||||
|
shadowOf(Looper.getMainLooper()).idle()
|
||||||
|
|
||||||
|
assertEquals(3.0, requireNotNull(state().currentRatio), 0.0001)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `detach는 초기 비율을 기다리는 요청도 취소한다`() {
|
||||||
|
view.setItems(listOf(item("delayed")))
|
||||||
|
measureHost()
|
||||||
|
shadowOf(Looper.getMainLooper()).idle()
|
||||||
|
assertTrue(requests.isNotEmpty())
|
||||||
|
|
||||||
|
host.removeView(view)
|
||||||
|
shadowOf(Looper.getMainLooper()).idle()
|
||||||
|
|
||||||
|
assertEquals(requests.toSet(), cancelled.toSet())
|
||||||
|
assertNull(state().currentRatio)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `첫 이미지 실패는 높이를 기다리지 않고 다음 성공 이미지를 요청한다`() {
|
||||||
|
view.setItems(listOf(item("failure"), item("success").copy(id = 2L), item("third").copy(id = 3L)))
|
||||||
|
|
||||||
|
measureHost()
|
||||||
|
shadowOf(Looper.getMainLooper()).idle()
|
||||||
|
|
||||||
|
assertEquals(listOf("https://example.com/failure", "https://example.com/success"), requests.map { it.data.toString() })
|
||||||
|
assertEquals(2L, state().currentItem?.id)
|
||||||
|
assertEquals(3.0, requireNotNull(state().currentRatio), 0.0001)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `모든 이미지 실패 뒤에는 자동 전환이나 반복 요청이 없고 새 응답은 재시도한다`() {
|
||||||
|
val items = listOf(item("failure"), item("failure2").copy(id = 2L))
|
||||||
|
view.setActive(true)
|
||||||
|
view.setItems(items)
|
||||||
|
measureHost()
|
||||||
|
shadowOf(Looper.getMainLooper()).idle()
|
||||||
|
assertEquals(2, requests.size)
|
||||||
|
assertNull(state().currentItem)
|
||||||
|
|
||||||
|
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(30))
|
||||||
|
assertEquals(2, requests.size)
|
||||||
|
failuresEnabled = false
|
||||||
|
view.setItems(items.map { it.copy() })
|
||||||
|
measureHost()
|
||||||
|
shadowOf(Looper.getMainLooper()).idle()
|
||||||
|
|
||||||
|
assertEquals(1L, state().currentItem?.id)
|
||||||
|
assertEquals(3.0, requireNotNull(state().currentRatio), 0.0001)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `동일한 정상 목록을 다시 바인딩해도 이미지를 중복 요청하지 않는다`() {
|
||||||
|
val items = listOf(item("success"))
|
||||||
|
view.setItems(items)
|
||||||
|
measureHost()
|
||||||
|
shadowOf(Looper.getMainLooper()).idle()
|
||||||
|
assertEquals(1, requests.size)
|
||||||
|
|
||||||
|
view.setItems(items.map { it.copy() })
|
||||||
|
measureHost()
|
||||||
|
shadowOf(Looper.getMainLooper()).idle()
|
||||||
|
|
||||||
|
assertEquals(1, requests.size)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `실패를 건너뛴 뒤 대기 중인 다음 요청도 detach에서 취소한다`() {
|
||||||
|
view.setItems(listOf(item("failure"), item("delayed").copy(id = 2L)))
|
||||||
|
measureHost()
|
||||||
|
shadowOf(Looper.getMainLooper()).idle()
|
||||||
|
assertEquals(2, requests.size)
|
||||||
|
|
||||||
|
host.removeView(view)
|
||||||
|
shadowOf(Looper.getMainLooper()).idle()
|
||||||
|
|
||||||
|
assertEquals("https://example.com/delayed", cancelled.single().data.toString())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `자동 전환은 다음 이미지만 요청하고 현재 원본 비율로 슬라이드한다`() {
|
||||||
|
view.setItems(listOf(item("success"), item("portrait").copy(id = 2L)))
|
||||||
|
measureHost()
|
||||||
|
shadowOf(Looper.getMainLooper()).idle()
|
||||||
|
measureHost()
|
||||||
|
shadowOf(Looper.getMainLooper()).idle()
|
||||||
|
assertEquals(1, requests.size)
|
||||||
|
val recycler = view.findViewById<RecyclerView>(R.id.rv_sub_banner)
|
||||||
|
val scrollStates = mutableListOf<Int>()
|
||||||
|
recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
|
||||||
|
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
|
||||||
|
scrollStates += newState
|
||||||
|
}
|
||||||
|
})
|
||||||
|
view.setActive(true)
|
||||||
|
|
||||||
|
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(4_999))
|
||||||
|
assertEquals(1L, state().currentItem?.id)
|
||||||
|
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(1))
|
||||||
|
assertEquals(2L, state().currentItem?.id)
|
||||||
|
assertEquals(2, requests.size)
|
||||||
|
assertEquals(1.0 / 3, requireNotNull(state().currentRatio), 0.0001)
|
||||||
|
assertTrue("scrollStates=$scrollStates", RecyclerView.SCROLL_STATE_SETTLING in scrollStates)
|
||||||
|
|
||||||
|
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(400))
|
||||||
|
|
||||||
|
assertEquals(RecyclerView.SCROLL_STATE_IDLE, recycler.scrollState)
|
||||||
|
assertEquals(2L, state().currentItem?.id)
|
||||||
|
val position = (recycler.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
|
||||||
|
assertEquals(1, (recycler.adapter as SubBannerAdapter).toRealIndex(position))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `수동 스냅은 양쪽 경계에서 순환하며 실제 선택 이미지의 클릭을 전달한다`() {
|
||||||
|
val clicks = mutableListOf<SubBannerItem>()
|
||||||
|
view.setOnBannerClickListener { clicks += it }
|
||||||
|
view.setItems(listOf(item("success"), item("second").copy(id = 2L), item("third").copy(id = 3L)))
|
||||||
|
measureHost()
|
||||||
|
shadowOf(Looper.getMainLooper()).idle()
|
||||||
|
measureHost()
|
||||||
|
shadowOf(Looper.getMainLooper()).idle()
|
||||||
|
val recycler = view.findViewById<RecyclerView>(R.id.rv_sub_banner)
|
||||||
|
|
||||||
|
listOf(300 to 2L, 300 to 3L, 300 to 1L, -300 to 3L).forEach { (distance, expectedId) ->
|
||||||
|
recycler.smoothScrollBy(distance, 0, null, 350)
|
||||||
|
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(600))
|
||||||
|
measureHost()
|
||||||
|
shadowOf(Looper.getMainLooper()).idle()
|
||||||
|
assertEquals(expectedId, state().currentItem?.id)
|
||||||
|
val position = (recycler.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
|
||||||
|
requireNotNull(recycler.findViewHolderForAdapterPosition(position)).itemView.performClick()
|
||||||
|
assertEquals(expectedId, clicks.last().id)
|
||||||
|
}
|
||||||
|
assertEquals(4, clicks.size)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `전환 초반 목록 교체는 새 첫 항목의 선택 요청 표시와 클릭을 일치시킨다`() {
|
||||||
|
val clicks = mutableListOf<SubBannerItem>()
|
||||||
|
view.setOnBannerClickListener { clicks += it }
|
||||||
|
view.setItems(listOf(item("success"), item("second").copy(id = 2L), item("third").copy(id = 3L)))
|
||||||
|
measureHost()
|
||||||
|
shadowOf(Looper.getMainLooper()).idle()
|
||||||
|
measureHost()
|
||||||
|
shadowOf(Looper.getMainLooper()).idle()
|
||||||
|
val recycler = view.findViewById<RecyclerView>(R.id.rv_sub_banner)
|
||||||
|
val manager = recycler.layoutManager as LinearLayoutManager
|
||||||
|
val adapter = recycler.adapter as SubBannerAdapter
|
||||||
|
recycler.smoothScrollBy(300, 0, null, 350)
|
||||||
|
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(600))
|
||||||
|
measureHost()
|
||||||
|
shadowOf(Looper.getMainLooper()).idle()
|
||||||
|
assertEquals(2L, state().currentItem?.id)
|
||||||
|
assertEquals(RecyclerView.SCROLL_STATE_IDLE, recycler.scrollState)
|
||||||
|
val replacement = listOf(
|
||||||
|
item("replacement-first").copy(id = 4L),
|
||||||
|
item("replacement-second").copy(id = 5L),
|
||||||
|
item("replacement-third").copy(id = 6L)
|
||||||
|
)
|
||||||
|
var replaced = false
|
||||||
|
var requestCount = 0
|
||||||
|
recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
|
||||||
|
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
|
||||||
|
if (newState != RecyclerView.SCROLL_STATE_SETTLING || replaced) return
|
||||||
|
assertEquals(3L, state().currentItem?.id)
|
||||||
|
assertEquals(1, adapter.toRealIndex(manager.findFirstVisibleItemPosition()))
|
||||||
|
replaced = true
|
||||||
|
Handler(Looper.getMainLooper()).post {
|
||||||
|
assertEquals(RecyclerView.SCROLL_STATE_SETTLING, recycler.scrollState)
|
||||||
|
requestCount = requests.size
|
||||||
|
view.setItems(replacement)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
view.setActive(true)
|
||||||
|
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(5_000))
|
||||||
|
measureHost()
|
||||||
|
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(400))
|
||||||
|
|
||||||
|
assertTrue(replaced)
|
||||||
|
assertEquals(replacement.first(), state().currentItem)
|
||||||
|
assertEquals(listOf(replacement.first().imageUrl), requests.drop(requestCount).map { it.data.toString() })
|
||||||
|
val position = manager.findFirstVisibleItemPosition()
|
||||||
|
assertEquals(adapter.startPosition(0), position)
|
||||||
|
requireNotNull(recycler.findViewHolderForAdapterPosition(position)).itemView.performClick()
|
||||||
|
assertEquals(listOf(replacement.first()), clicks)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun measureHost() {
|
||||||
|
host.measure(View.MeasureSpec.makeMeasureSpec(300, View.MeasureSpec.EXACTLY), View.MeasureSpec.UNSPECIFIED)
|
||||||
|
host.layout(0, 0, host.measuredWidth, host.measuredHeight)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun state(): SubBannerState = SubBannerView::class.java.getDeclaredField("state").run {
|
||||||
|
isAccessible = true
|
||||||
|
get(view) as SubBannerState
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun replaceSharedLoader(value: ImageLoader?) {
|
||||||
|
ImageLoaderProvider::class.java.getDeclaredField("imageLoader").apply {
|
||||||
|
isAccessible = true
|
||||||
|
set(null, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun item(path: String) = SubBannerItem(
|
||||||
|
id = 1L,
|
||||||
|
imageUrl = "https://example.com/$path",
|
||||||
|
androidDeepLink = null,
|
||||||
|
webUrl = "https://example.com/event"
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
package kr.co.vividnext.sodalive.v2.widget.subbanner
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertSame
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class SubBannerStateTest {
|
||||||
|
private val items = listOf(item(9), item(2), item(7))
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `선택은 서버 순서를 유지하며 양쪽 경계에서 순환한다`() {
|
||||||
|
val state = SubBannerState()
|
||||||
|
state.setItems(items)
|
||||||
|
|
||||||
|
assertSame(items[0], state.currentItem)
|
||||||
|
state.select(1)
|
||||||
|
assertSame(items[1], state.currentItem)
|
||||||
|
state.select(2)
|
||||||
|
assertSame(items[2], state.currentItem)
|
||||||
|
state.select(3)
|
||||||
|
assertSame(items[0], state.currentItem)
|
||||||
|
state.select(-1)
|
||||||
|
assertSame(items[2], state.currentItem)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `원본 비율을 모르더라도 첫 이미지 요청 식별자를 만들 수 있다`() {
|
||||||
|
val state = SubBannerState()
|
||||||
|
state.setItems(items)
|
||||||
|
assertNull(state.currentRatio)
|
||||||
|
|
||||||
|
val request = state.beginImageRequest(0)
|
||||||
|
state.onImageLoaded(request, 1200, 400)
|
||||||
|
|
||||||
|
assertEquals(3.0, requireNotNull(state.currentRatio), 0.0001)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `새 항목 선택은 이전 이미지 비율을 물려받지 않는다`() {
|
||||||
|
val state = SubBannerState()
|
||||||
|
state.setItems(items)
|
||||||
|
state.onImageLoaded(state.beginImageRequest(0), 1200, 400)
|
||||||
|
|
||||||
|
state.select(1)
|
||||||
|
assertNull(state.currentRatio)
|
||||||
|
state.onImageLoaded(state.beginImageRequest(1), 400, 800)
|
||||||
|
|
||||||
|
assertEquals(0.5, requireNotNull(state.currentRatio), 0.0001)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `선택하지 않은 이미지의 늦은 성공은 현재 비율을 바꾸지 않는다`() {
|
||||||
|
val state = SubBannerState()
|
||||||
|
state.setItems(items)
|
||||||
|
val firstRequest = state.beginImageRequest(0)
|
||||||
|
state.select(1)
|
||||||
|
state.onImageLoaded(state.beginImageRequest(1), 900, 300)
|
||||||
|
|
||||||
|
state.onImageLoaded(firstRequest, 400, 800)
|
||||||
|
|
||||||
|
assertSame(items[1], state.currentItem)
|
||||||
|
assertEquals(3.0, requireNotNull(state.currentRatio), 0.0001)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `같은 ID의 URL이 바뀌면 이전 목록의 성공을 무시한다`() {
|
||||||
|
val state = SubBannerState()
|
||||||
|
state.setItems(items)
|
||||||
|
val staleRequest = state.beginImageRequest(0)
|
||||||
|
val replacement = items[0].copy(imageUrl = "https://example.com/replacement.png")
|
||||||
|
state.setItems(listOf(replacement))
|
||||||
|
state.onImageLoaded(state.beginImageRequest(0), 900, 300)
|
||||||
|
|
||||||
|
state.onImageLoaded(staleRequest, 400, 800)
|
||||||
|
|
||||||
|
assertSame(replacement, state.currentItem)
|
||||||
|
assertEquals(3.0, requireNotNull(state.currentRatio), 0.0001)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `목록이 바뀌었다가 원래 항목으로 돌아와도 이전 세대 성공은 무시한다`() {
|
||||||
|
val state = SubBannerState()
|
||||||
|
state.setItems(items)
|
||||||
|
val staleRequest = state.beginImageRequest(0)
|
||||||
|
state.setItems(listOf(item(5)))
|
||||||
|
state.setItems(items)
|
||||||
|
|
||||||
|
state.onImageLoaded(staleRequest, 400, 800)
|
||||||
|
|
||||||
|
assertNull(state.currentRatio)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `같은 항목을 다시 요청하면 먼저 시작한 요청의 성공은 무시한다`() {
|
||||||
|
val state = SubBannerState()
|
||||||
|
state.setItems(items)
|
||||||
|
val staleRequest = state.beginImageRequest(0)
|
||||||
|
val currentRequest = state.beginImageRequest(0)
|
||||||
|
|
||||||
|
state.onImageLoaded(currentRequest, 900, 300)
|
||||||
|
state.onImageLoaded(staleRequest, 400, 800)
|
||||||
|
|
||||||
|
assertEquals(3.0, requireNotNull(state.currentRatio), 0.0001)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `동일한 값의 목록 재설정은 선택과 비율과 진행 중 요청을 유지한다`() {
|
||||||
|
val state = SubBannerState()
|
||||||
|
assertTrue(state.setItems(items))
|
||||||
|
state.select(1)
|
||||||
|
val request = state.beginImageRequest(1)
|
||||||
|
|
||||||
|
assertFalse(state.setItems(items.map { it.copy() }))
|
||||||
|
state.onImageLoaded(request, 900, 300)
|
||||||
|
|
||||||
|
assertEquals(1, state.currentIndex)
|
||||||
|
assertEquals(3.0, requireNotNull(state.currentRatio), 0.0001)
|
||||||
|
assertFalse(state.setItems(items))
|
||||||
|
assertEquals(3.0, requireNotNull(state.currentRatio), 0.0001)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `빈 목록 교체는 현재 항목과 비율을 비우고 이전 성공을 무시한다`() {
|
||||||
|
val state = SubBannerState()
|
||||||
|
state.setItems(items)
|
||||||
|
val request = state.beginImageRequest(0)
|
||||||
|
state.onImageLoaded(request, 900, 300)
|
||||||
|
|
||||||
|
state.setItems(emptyList())
|
||||||
|
state.onImageLoaded(request, 400, 800)
|
||||||
|
|
||||||
|
assertNull(state.currentItem)
|
||||||
|
assertNull(state.currentRatio)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `현재 이미지 실패는 다음 항목으로 넘어가며 성공 순서를 유지한다`() {
|
||||||
|
val state = SubBannerState()
|
||||||
|
state.setItems(items)
|
||||||
|
val failedRequest = state.beginImageRequest(0)
|
||||||
|
state.onImageFailed(failedRequest)
|
||||||
|
assertSame(items[1], state.currentItem)
|
||||||
|
assertNull(state.currentRatio)
|
||||||
|
|
||||||
|
state.onImageLoaded(state.beginImageRequest(0), 900, 300)
|
||||||
|
state.onImageFailed(failedRequest)
|
||||||
|
|
||||||
|
assertSame(items[1], state.currentItem)
|
||||||
|
assertEquals(3.0, requireNotNull(state.currentRatio), 0.0001)
|
||||||
|
state.select(1)
|
||||||
|
assertSame(items[2], state.currentItem)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `모든 이미지가 실패하면 표시 후보와 현재 비율이 남지 않는다`() {
|
||||||
|
val state = SubBannerState()
|
||||||
|
state.setItems(items)
|
||||||
|
repeat(3) { state.onImageFailed(state.beginImageRequest(0)) }
|
||||||
|
|
||||||
|
assertTrue(state.items.isEmpty())
|
||||||
|
assertNull(state.currentItem)
|
||||||
|
assertNull(state.currentRatio)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `실패 항목이 있으면 같은 목록의 새 응답으로 재시도할 수 있다`() {
|
||||||
|
val state = SubBannerState()
|
||||||
|
state.setItems(items)
|
||||||
|
state.onImageFailed(state.beginImageRequest(0))
|
||||||
|
|
||||||
|
assertTrue(state.setItems(items.map { it.copy() }))
|
||||||
|
|
||||||
|
assertEquals(listOf(9L, 2L, 7L), state.items.map { it.id })
|
||||||
|
assertEquals(9L, state.currentItem?.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `잘못된 이미지 원본 크기는 사용할 수 있는 비율을 만들지 않는다`() {
|
||||||
|
listOf(0 to 400, 400 to 0, -1 to 400, 400 to -1).forEach { (width, height) ->
|
||||||
|
val state = SubBannerState()
|
||||||
|
state.setItems(items)
|
||||||
|
|
||||||
|
state.onImageLoaded(state.beginImageRequest(0), width, height)
|
||||||
|
|
||||||
|
assertNull(state.currentRatio)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `요청 해제 뒤 도착한 성공은 무시하고 새 요청은 받아들인다`() {
|
||||||
|
val state = SubBannerState()
|
||||||
|
state.setItems(items)
|
||||||
|
val cancelledRequest = state.beginImageRequest(0)
|
||||||
|
|
||||||
|
state.invalidateRequests()
|
||||||
|
state.onImageLoaded(cancelledRequest, 400, 800)
|
||||||
|
assertNull(state.currentRatio)
|
||||||
|
state.onImageLoaded(state.beginImageRequest(0), 900, 300)
|
||||||
|
|
||||||
|
assertEquals(3.0, requireNotNull(state.currentRatio), 0.0001)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun item(id: Long) = SubBannerItem(
|
||||||
|
id = id,
|
||||||
|
imageUrl = "https://example.com/banner-$id.png",
|
||||||
|
androidDeepLink = "sodalive://event/$id",
|
||||||
|
webUrl = "https://example.com/event/$id"
|
||||||
|
)
|
||||||
|
}
|
||||||
+275
@@ -0,0 +1,275 @@
|
|||||||
|
package kr.co.vividnext.sodalive.v2.widget.subbanner
|
||||||
|
|
||||||
|
import android.app.Application
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.graphics.drawable.BitmapDrawable
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.Looper
|
||||||
|
import android.view.View
|
||||||
|
import androidx.lifecycle.Lifecycle
|
||||||
|
import androidx.lifecycle.LifecycleOwner
|
||||||
|
import androidx.lifecycle.LifecycleRegistry
|
||||||
|
import androidx.lifecycle.setViewTreeLifecycleOwner
|
||||||
|
import androidx.recyclerview.widget.RecyclerView
|
||||||
|
import androidx.test.core.app.ApplicationProvider
|
||||||
|
import coil.ImageLoader
|
||||||
|
import coil.decode.DataSource
|
||||||
|
import coil.fetch.DrawableResult
|
||||||
|
import coil.fetch.Fetcher
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kr.co.vividnext.sodalive.R
|
||||||
|
import kr.co.vividnext.sodalive.common.ImageLoaderProvider
|
||||||
|
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.Shadows.shadowOf
|
||||||
|
import org.robolectric.annotation.Config
|
||||||
|
import org.robolectric.annotation.LooperMode
|
||||||
|
import java.time.Duration
|
||||||
|
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [28], application = Application::class)
|
||||||
|
@LooperMode(LooperMode.Mode.PAUSED)
|
||||||
|
class SubBannerViewTimerTest {
|
||||||
|
private lateinit var view: SubBannerView
|
||||||
|
private lateinit var loader: ImageLoader
|
||||||
|
private var previousLoader: ImageLoader? = null
|
||||||
|
private val items = listOf(item(9), item(2), item(7))
|
||||||
|
|
||||||
|
@Before
|
||||||
|
fun setUp() {
|
||||||
|
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||||
|
loader = ImageLoader.Builder(context)
|
||||||
|
.dispatcher(Dispatchers.Unconfined)
|
||||||
|
.components {
|
||||||
|
add(
|
||||||
|
Fetcher.Factory<Uri> { _, _, _ ->
|
||||||
|
Fetcher {
|
||||||
|
DrawableResult(
|
||||||
|
BitmapDrawable(context.resources, Bitmap.createBitmap(900, 300, Bitmap.Config.ARGB_8888)),
|
||||||
|
false,
|
||||||
|
DataSource.NETWORK
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}.build()
|
||||||
|
previousLoader = if (ImageLoaderProvider.isInitialized) ImageLoaderProvider.imageLoader else null
|
||||||
|
replaceSharedLoader(loader)
|
||||||
|
view = SubBannerView(context)
|
||||||
|
view.setItems(items)
|
||||||
|
view.setActive(true)
|
||||||
|
view.measure(View.MeasureSpec.makeMeasureSpec(300, View.MeasureSpec.EXACTLY), View.MeasureSpec.UNSPECIFIED)
|
||||||
|
view.layout(0, 0, view.measuredWidth, view.measuredHeight)
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
fun tearDown() {
|
||||||
|
view.release()
|
||||||
|
loader.shutdown()
|
||||||
|
replaceSharedLoader(previousLoader)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `attach 전에는 자동 전환하지 않는다`() {
|
||||||
|
advance(20_000)
|
||||||
|
|
||||||
|
assertEquals(0, state().currentIndex)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `4999ms에는 유지하고 5000ms마다 서버 순서대로 순환한다`() {
|
||||||
|
attach()
|
||||||
|
advance(4_999)
|
||||||
|
assertEquals(0, state().currentIndex)
|
||||||
|
advance(1)
|
||||||
|
assertEquals(1, state().currentIndex)
|
||||||
|
advance(5_000)
|
||||||
|
assertEquals(2, state().currentIndex)
|
||||||
|
advance(5_000)
|
||||||
|
assertEquals(0, state().currentIndex)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `단일 목록과 빈 목록은 이전 다중 목록 예약을 이어받지 않는다`() {
|
||||||
|
attach()
|
||||||
|
advance(2_000)
|
||||||
|
view.setItems(items.take(1))
|
||||||
|
advance(20_000)
|
||||||
|
assertEquals(0, state().currentIndex)
|
||||||
|
|
||||||
|
view.setItems(emptyList())
|
||||||
|
advance(20_000)
|
||||||
|
assertEquals(null, state().currentItem)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `동일한 목록과 반복 활성화는 선택이나 기존 타이머를 초기화하지 않는다`() {
|
||||||
|
attach()
|
||||||
|
advance(5_000)
|
||||||
|
advance(2_000)
|
||||||
|
|
||||||
|
view.setItems(items.map { it.copy() })
|
||||||
|
repeat(3) { view.setActive(true) }
|
||||||
|
assertEquals(1, state().currentIndex)
|
||||||
|
advance(2_999)
|
||||||
|
assertEquals(1, state().currentIndex)
|
||||||
|
advance(1)
|
||||||
|
|
||||||
|
assertEquals(2, state().currentIndex)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `숨긴 탭은 정지하고 다시 활성화하면 새 5초부터 시작한다`() {
|
||||||
|
attach()
|
||||||
|
advance(5_000)
|
||||||
|
view.setActive(false)
|
||||||
|
advance(20_000)
|
||||||
|
assertEquals(1, state().currentIndex)
|
||||||
|
|
||||||
|
view.setActive(true)
|
||||||
|
advance(4_999)
|
||||||
|
assertEquals(1, state().currentIndex)
|
||||||
|
advance(1)
|
||||||
|
|
||||||
|
assertEquals(2, state().currentIndex)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `숨긴 탭에 도착한 새 목록은 활성화 전까지 예약하지 않는다`() {
|
||||||
|
attach()
|
||||||
|
view.setActive(false)
|
||||||
|
view.setItems(listOf(item(5), item(4)))
|
||||||
|
advance(20_000)
|
||||||
|
assertEquals(0, state().currentIndex)
|
||||||
|
|
||||||
|
view.setActive(true)
|
||||||
|
advance(5_000)
|
||||||
|
|
||||||
|
assertEquals(1, state().currentIndex)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `lifecycle stop은 정지하고 start는 탭 활성 상태에서만 재개한다`() {
|
||||||
|
val owner = TestLifecycleOwner()
|
||||||
|
view.setViewTreeLifecycleOwner(owner)
|
||||||
|
owner.event(Lifecycle.Event.ON_START)
|
||||||
|
attach()
|
||||||
|
owner.event(Lifecycle.Event.ON_STOP)
|
||||||
|
advance(20_000)
|
||||||
|
assertEquals(0, state().currentIndex)
|
||||||
|
|
||||||
|
view.setActive(false)
|
||||||
|
owner.event(Lifecycle.Event.ON_START)
|
||||||
|
advance(20_000)
|
||||||
|
assertEquals(0, state().currentIndex)
|
||||||
|
view.setActive(true)
|
||||||
|
advance(5_000)
|
||||||
|
|
||||||
|
assertEquals(1, state().currentIndex)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `detach는 예약을 없애고 재attach는 새 5초부터 시작한다`() {
|
||||||
|
attach()
|
||||||
|
advance(2_000)
|
||||||
|
lifecycleCallback("onDetachedFromWindow")
|
||||||
|
advance(20_000)
|
||||||
|
assertEquals(0, state().currentIndex)
|
||||||
|
|
||||||
|
attach()
|
||||||
|
advance(4_999)
|
||||||
|
assertEquals(0, state().currentIndex)
|
||||||
|
advance(1)
|
||||||
|
|
||||||
|
assertEquals(1, state().currentIndex)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `수동 드래그 중에는 정지하고 스냅 완료 뒤 새 5초부터 시작한다`() {
|
||||||
|
attach()
|
||||||
|
advance(2_000)
|
||||||
|
scrollState(RecyclerView.SCROLL_STATE_DRAGGING)
|
||||||
|
view.setActive(true)
|
||||||
|
view.setItems(items.map { it.copy() })
|
||||||
|
advance(20_000)
|
||||||
|
assertEquals(0, state().currentIndex)
|
||||||
|
|
||||||
|
scrollState(RecyclerView.SCROLL_STATE_IDLE)
|
||||||
|
advance(4_999)
|
||||||
|
assertEquals(0, state().currentIndex)
|
||||||
|
advance(1)
|
||||||
|
|
||||||
|
assertEquals(1, state().currentIndex)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `release 뒤에는 활성화와 늦은 목록 전달로 예약이 되살아나지 않는다`() {
|
||||||
|
attach()
|
||||||
|
advance(5_000)
|
||||||
|
view.release()
|
||||||
|
val releasedItem = state().currentItem
|
||||||
|
|
||||||
|
view.setActive(true)
|
||||||
|
view.setItems(listOf(item(4), item(5)))
|
||||||
|
advance(20_000)
|
||||||
|
|
||||||
|
assertEquals(releasedItem, state().currentItem)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun attach() {
|
||||||
|
lifecycleCallback("onAttachedToWindow")
|
||||||
|
advance(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun replaceSharedLoader(value: ImageLoader?) {
|
||||||
|
ImageLoaderProvider::class.java.getDeclaredField("imageLoader").apply {
|
||||||
|
isAccessible = true
|
||||||
|
set(null, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun scrollState(newState: Int) {
|
||||||
|
val listener = SubBannerView::class.java.getDeclaredField("scrollListener").run {
|
||||||
|
isAccessible = true
|
||||||
|
get(view) as RecyclerView.OnScrollListener
|
||||||
|
}
|
||||||
|
listener.onScrollStateChanged(view.findViewById(R.id.rv_sub_banner), newState)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun lifecycleCallback(name: String) {
|
||||||
|
SubBannerView::class.java.getDeclaredMethod(name).apply {
|
||||||
|
isAccessible = true
|
||||||
|
invoke(view)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun state(): SubBannerState = SubBannerView::class.java.getDeclaredField("state").run {
|
||||||
|
isAccessible = true
|
||||||
|
get(view) as SubBannerState
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun advance(milliseconds: Long) {
|
||||||
|
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(milliseconds))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun item(id: Long) = SubBannerItem(
|
||||||
|
id = id,
|
||||||
|
imageUrl = "https://example.com/banner-$id.png",
|
||||||
|
androidDeepLink = "sodalive://event/$id",
|
||||||
|
webUrl = "https://example.com/event/$id"
|
||||||
|
)
|
||||||
|
|
||||||
|
private class TestLifecycleOwner : LifecycleOwner {
|
||||||
|
private val registry = LifecycleRegistry(this)
|
||||||
|
override val lifecycle: Lifecycle = registry
|
||||||
|
|
||||||
|
fun event(event: Lifecycle.Event) {
|
||||||
|
registry.handleLifecycleEvent(event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user