feat(auth): 공통 인증 흐름과 디버그 시뮬레이션을 추가한다
This commit is contained in:
@@ -0,0 +1,260 @@
|
||||
package kr.co.vividnext.sodalive.v2.auth
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.widget.Toast
|
||||
import androidx.fragment.app.Fragment
|
||||
import androidx.fragment.app.FragmentActivity
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import com.google.gson.JsonParseException
|
||||
import com.google.gson.JsonParser
|
||||
import io.reactivex.rxjava3.core.Single
|
||||
import kr.co.vividnext.sodalive.BuildConfig
|
||||
import kr.co.vividnext.sodalive.R
|
||||
import kr.co.vividnext.sodalive.common.ApiResponse
|
||||
import kr.co.vividnext.sodalive.common.LoadingDialog
|
||||
import kr.co.vividnext.sodalive.mypage.auth.Auth
|
||||
import kr.co.vividnext.sodalive.mypage.auth.AuthResponse
|
||||
import kr.co.vividnext.sodalive.splash.SplashActivity
|
||||
import kr.co.vividnext.sodalive.user.UserRepository
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.logging.HttpLoggingInterceptor
|
||||
import org.koin.android.ext.android.get
|
||||
import retrofit2.Retrofit
|
||||
import java.lang.ref.WeakReference
|
||||
|
||||
class V2AuthFlow : Fragment() {
|
||||
private lateinit var viewModel: V2AuthViewModel
|
||||
private var sheet: ContentPreferenceBottomSheet? = null
|
||||
private var loadingDialog: LoadingDialog? = null
|
||||
private var initializing = false
|
||||
private var removing = false
|
||||
private var rendering = false
|
||||
private var debugWaiting = false
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val finishDebugWait = Runnable {
|
||||
viewModel.begin(DEBUG_RECEIPT_ID, syncMemberInfo())
|
||||
debugWaiting = false
|
||||
render()
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
viewModel = ViewModelProvider(
|
||||
this,
|
||||
AuthViewModelFactory(
|
||||
requireActivity().get(),
|
||||
requireActivity().get(),
|
||||
requireActivity().get()
|
||||
)
|
||||
)[V2AuthViewModel::class.java]
|
||||
viewModel.stateLiveData.observe(this) { render() }
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
render()
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
dismissUi()
|
||||
super.onStop()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
handler.removeCallbacks(finishDebugWait)
|
||||
dismissUi()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
private fun syncMemberInfo(): Boolean = arguments?.getBoolean(SYNC_MEMBER_INFO) == true
|
||||
|
||||
private fun render() {
|
||||
val host = activity ?: return
|
||||
if (!isResumed || host.isFinishing || host.isDestroyed || removing || rendering || initializing ||
|
||||
parentFragmentManager.isStateSaved
|
||||
) {
|
||||
return
|
||||
}
|
||||
rendering = true
|
||||
try {
|
||||
if (debugWaiting) {
|
||||
showLoading()
|
||||
return
|
||||
}
|
||||
val state = requireNotNull(viewModel.stateLiveData.value)
|
||||
if (state.phase == V2AuthPhase.Completed) {
|
||||
val completed = viewModel.consumeCompletion()
|
||||
dismissUi()
|
||||
if (completed) {
|
||||
if (syncMemberInfo()) {
|
||||
parentFragmentManager.setFragmentResult(AUDIO_AUTH_COMPLETED, Bundle())
|
||||
} else {
|
||||
host.startActivity(
|
||||
Intent(host, SplashActivity::class.java).apply {
|
||||
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
}
|
||||
)
|
||||
host.finish()
|
||||
}
|
||||
}
|
||||
removeFlow()
|
||||
return
|
||||
}
|
||||
viewModel.consumeError()?.let { error ->
|
||||
val message = error.message ?: error.resId?.let(host::getString)
|
||||
if (!message.isNullOrBlank()) Toast.makeText(host, message, Toast.LENGTH_LONG).show()
|
||||
}
|
||||
when (state.phase) {
|
||||
V2AuthPhase.Choosing, V2AuthPhase.Failed -> {
|
||||
loadingDialog?.dismiss()
|
||||
loadingDialog = null
|
||||
val currentSheet = sheet ?: ContentPreferenceBottomSheet(
|
||||
host,
|
||||
onToggle = viewModel::toggleVisibility,
|
||||
onSelect = viewModel::selectContentType,
|
||||
onConfirm = {
|
||||
sheet = null
|
||||
viewModel.confirm()
|
||||
}
|
||||
).also { sheet = it }
|
||||
currentSheet.render(state.isAdultContentVisible, state.contentType, !state.selectionLocked)
|
||||
if (!currentSheet.isShowing) currentSheet.show()
|
||||
}
|
||||
V2AuthPhase.Submitting, V2AuthPhase.Syncing -> {
|
||||
sheet?.dismiss()
|
||||
sheet = null
|
||||
showLoading()
|
||||
}
|
||||
V2AuthPhase.Idle -> removeFlow()
|
||||
V2AuthPhase.Completed -> Unit
|
||||
}
|
||||
} finally {
|
||||
rendering = false
|
||||
}
|
||||
}
|
||||
|
||||
private fun dismissUi() {
|
||||
sheet?.dismiss()
|
||||
sheet = null
|
||||
loadingDialog?.dismiss()
|
||||
loadingDialog = null
|
||||
}
|
||||
|
||||
private fun showLoading() {
|
||||
if (loadingDialog == null) {
|
||||
val host = requireActivity()
|
||||
loadingDialog = LoadingDialog(host, host.layoutInflater).also {
|
||||
it.show(host.resources.displayMetrics.widthPixels)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun removeFlow() {
|
||||
if (removing || parentFragmentManager.isStateSaved) return
|
||||
removing = true
|
||||
handler.removeCallbacks(finishDebugWait)
|
||||
dismissUi()
|
||||
parentFragmentManager.beginTransaction().remove(this).commit()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val AUDIO_AUTH_COMPLETED = "kr.co.vividnext.sodalive.v2.auth.AUDIO_AUTH_COMPLETED"
|
||||
private const val TAG = "kr.co.vividnext.sodalive.v2.auth.FLOW"
|
||||
private const val SYNC_MEMBER_INFO = "syncMemberInfo"
|
||||
private const val DEBUG_RECEIPT_ID = "debug-auth-simulation"
|
||||
|
||||
fun start(activity: Activity, syncMemberInfo: Boolean = false) {
|
||||
val host = activity as? FragmentActivity ?: return
|
||||
if (host.isFinishing || host.isDestroyed) return
|
||||
val manager = host.supportFragmentManager
|
||||
if (manager.isStateSaved || manager.findFragmentByTag(TAG) != null) return
|
||||
if (V2AuthBuildBehavior.simulate) {
|
||||
val flow = V2AuthFlow().apply {
|
||||
debugWaiting = true
|
||||
arguments = Bundle().apply { putBoolean(SYNC_MEMBER_INFO, syncMemberInfo) }
|
||||
}
|
||||
manager.beginTransaction().add(flow, TAG).commitNow()
|
||||
flow.handler.postDelayed(flow.finishDebugWait, 500)
|
||||
flow.render()
|
||||
return
|
||||
}
|
||||
val hostReference = WeakReference(host)
|
||||
var callbackConsumed = false
|
||||
Auth.auth(host, host) { payload ->
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
if (callbackConsumed) return@post
|
||||
callbackConsumed = true
|
||||
val currentHost = hostReference.get() ?: return@post
|
||||
if (currentHost.isFinishing || currentHost.isDestroyed) return@post
|
||||
val currentManager = currentHost.supportFragmentManager
|
||||
if (currentManager.isStateSaved || currentManager.findFragmentByTag(TAG) != null) return@post
|
||||
val receiptId = validatedReceipt(payload)
|
||||
if (receiptId == null) {
|
||||
if (currentHost.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) {
|
||||
Toast.makeText(currentHost, R.string.common_error_unknown, Toast.LENGTH_LONG).show()
|
||||
}
|
||||
return@post
|
||||
}
|
||||
val flow = V2AuthFlow().apply {
|
||||
initializing = true
|
||||
arguments = Bundle().apply { putBoolean(SYNC_MEMBER_INFO, syncMemberInfo) }
|
||||
}
|
||||
currentManager.beginTransaction().add(flow, TAG).commitNow()
|
||||
flow.viewModel.begin(receiptId, syncMemberInfo)
|
||||
flow.initializing = false
|
||||
flow.render()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun validatedReceipt(payload: String): String? {
|
||||
val root = try {
|
||||
JsonParser.parseString(payload)
|
||||
} catch (_: JsonParseException) {
|
||||
return null
|
||||
}
|
||||
if (!root.isJsonObject) return null
|
||||
val data = root.asJsonObject.get("data") ?: return null
|
||||
if (!data.isJsonObject) return null
|
||||
val receipt = data.asJsonObject.get("receipt_id") ?: return null
|
||||
if (!receipt.isJsonPrimitive || !receipt.asJsonPrimitive.isString) return null
|
||||
return receipt.asString.takeIf { it.isNotBlank() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal object V2AuthBuildBehavior {
|
||||
val simulate: Boolean get() = BuildConfig.DEBUG
|
||||
}
|
||||
|
||||
internal object DebugV2AuthApi : V2AuthApi {
|
||||
override fun verify(request: V2AuthVerifyRequest, authHeader: String): Single<ApiResponse<AuthResponse>> =
|
||||
Single.just(ApiResponse(success = true))
|
||||
}
|
||||
|
||||
internal fun createV2AuthApi(retrofit: Retrofit, client: OkHttpClient): V2AuthApi {
|
||||
val privateClient = client.newBuilder().apply {
|
||||
interceptors().removeAll { it is HttpLoggingInterceptor }
|
||||
networkInterceptors().removeAll { it is HttpLoggingInterceptor }
|
||||
}.build()
|
||||
return retrofit.newBuilder().client(privateClient).build().create(V2AuthApi::class.java)
|
||||
}
|
||||
|
||||
private class AuthViewModelFactory(
|
||||
private val retrofit: Retrofit,
|
||||
private val client: OkHttpClient,
|
||||
private val userRepository: UserRepository
|
||||
) : ViewModelProvider.Factory {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
override fun <T : ViewModel> create(modelClass: Class<T>): T =
|
||||
V2AuthViewModel(
|
||||
if (V2AuthBuildBehavior.simulate) DebugV2AuthApi else createV2AuthApi(retrofit, client),
|
||||
userRepository
|
||||
) as T
|
||||
}
|
||||
@@ -0,0 +1,800 @@
|
||||
package kr.co.vividnext.sodalive.v2.auth
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.os.Looper
|
||||
import android.os.Parcel
|
||||
import android.view.View
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import io.mockk.every
|
||||
import io.mockk.mockk
|
||||
import io.mockk.mockkObject
|
||||
import io.mockk.unmockkObject
|
||||
import io.reactivex.rxjava3.android.plugins.RxAndroidPlugins
|
||||
import io.reactivex.rxjava3.plugins.RxJavaPlugins
|
||||
import io.reactivex.rxjava3.schedulers.Schedulers
|
||||
import io.reactivex.rxjava3.schedulers.TestScheduler
|
||||
import io.reactivex.rxjava3.subjects.SingleSubject
|
||||
import kr.co.vividnext.sodalive.BuildConfig
|
||||
import kr.co.vividnext.sodalive.R
|
||||
import kr.co.vividnext.sodalive.common.ApiResponse
|
||||
import kr.co.vividnext.sodalive.common.SharedPreferenceManager
|
||||
import kr.co.vividnext.sodalive.mypage.auth.Auth
|
||||
import kr.co.vividnext.sodalive.settings.ContentType
|
||||
import kr.co.vividnext.sodalive.settings.notification.GetMemberInfoResponse
|
||||
import kr.co.vividnext.sodalive.settings.notification.MemberRole
|
||||
import kr.co.vividnext.sodalive.splash.SplashActivity
|
||||
import kr.co.vividnext.sodalive.user.UserApi
|
||||
import kr.co.vividnext.sodalive.user.UserRepository
|
||||
import okhttp3.Interceptor
|
||||
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.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotSame
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertSame
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.koin.core.context.startKoin
|
||||
import org.koin.core.context.stopKoin
|
||||
import org.koin.dsl.module
|
||||
import org.robolectric.Robolectric
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.shadows.ShadowDialog
|
||||
import org.robolectric.shadows.ShadowToast
|
||||
import retrofit2.Retrofit
|
||||
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
|
||||
import retrofit2.converter.gson.GsonConverterFactory
|
||||
import java.time.Duration
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], application = Application::class)
|
||||
class V2AuthFlowTest {
|
||||
private val ioScheduler = TestScheduler()
|
||||
private val callbacks = mutableListOf<(String) -> Unit>()
|
||||
private val requests = mutableListOf<Request>()
|
||||
private var member = SingleSubject.create<ApiResponse<GetMemberInfoResponse>>()
|
||||
private var memberCalls = 0
|
||||
private var postSuccess = true
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
stopKoin()
|
||||
SharedPreferenceManager.resetForTest()
|
||||
SharedPreferenceManager.init(ApplicationProvider.getApplicationContext())
|
||||
SharedPreferenceManager.token = "test-token"
|
||||
RxJavaPlugins.setIoSchedulerHandler { ioScheduler }
|
||||
RxAndroidPlugins.setInitMainThreadSchedulerHandler { Schedulers.trampoline() }
|
||||
RxAndroidPlugins.setMainThreadSchedulerHandler { Schedulers.trampoline() }
|
||||
mockkObject(V2AuthBuildBehavior)
|
||||
every { V2AuthBuildBehavior.simulate } returns false
|
||||
mockkObject(Auth)
|
||||
every { Auth.auth(any(), any(), any()) } answers {
|
||||
callbacks.add(thirdArg())
|
||||
Unit
|
||||
}
|
||||
val terminal = Interceptor { chain ->
|
||||
requests.add(chain.request())
|
||||
Response.Builder().request(chain.request()).protocol(Protocol.HTTP_1_1).code(200).message("OK")
|
||||
.body("{\"success\":$postSuccess}".toResponseBody("application/json".toMediaType())).build()
|
||||
}
|
||||
val client = OkHttpClient.Builder().addInterceptor(terminal).build()
|
||||
val retrofit = Retrofit.Builder().baseUrl("https://example.test/").client(client)
|
||||
.addConverterFactory(GsonConverterFactory.create())
|
||||
.addCallAdapterFactory(RxJava3CallAdapterFactory.createSynchronous()).build()
|
||||
val userApi = mockk<UserApi>()
|
||||
every { userApi.getMemberInfo("Bearer test-token") } answers {
|
||||
io.reactivex.rxjava3.core.Single.defer {
|
||||
memberCalls += 1
|
||||
member
|
||||
}
|
||||
}
|
||||
startKoin {
|
||||
modules(
|
||||
module {
|
||||
single { client }
|
||||
single { retrofit }
|
||||
single { UserRepository(userApi) }
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
unmockkObject(V2AuthBuildBehavior)
|
||||
unmockkObject(Auth)
|
||||
stopKoin()
|
||||
RxJavaPlugins.reset()
|
||||
RxAndroidPlugins.reset()
|
||||
SharedPreferenceManager.resetForTest()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `중복 시작은 같은 인증 흐름을 유지하며 상태 저장 뒤에는 새 흐름을 열지 않는다`() {
|
||||
val controller = Robolectric.buildActivity(AuthFlowHost::class.java).setup()
|
||||
val host = controller.get()
|
||||
V2AuthFlow.start(host)
|
||||
receiveReceipt()
|
||||
val original = flow(host)
|
||||
V2AuthFlow.start(host, true)
|
||||
assertSame(original, flow(host))
|
||||
assertEquals(1, callbacks.size)
|
||||
val model = model(original)
|
||||
model.selectContentType(ContentType.FEMALE)
|
||||
V2AuthFlow.start(host)
|
||||
assertEquals(ContentType.FEMALE, model.stateLiveData.value!!.contentType)
|
||||
assertTrue(requests.isEmpty())
|
||||
model.confirm()
|
||||
V2AuthFlow.start(host)
|
||||
assertSame(original, flow(host))
|
||||
assertEquals(1, callbacks.size)
|
||||
ioScheduler.triggerActions()
|
||||
assertEquals(1, requests.size)
|
||||
controller.pause().stop().saveInstanceState(Bundle())
|
||||
V2AuthFlow.start(host)
|
||||
assertEquals(1, callbacks.size)
|
||||
controller.destroy()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `성공 callback 없는 취소 뒤에는 coordinator나 POST 없이 같은 호스트에서 재인증할 수 있다`() {
|
||||
val controller = Robolectric.buildActivity(AuthFlowHost::class.java).setup()
|
||||
val host = controller.get()
|
||||
V2AuthFlow.start(host)
|
||||
idle()
|
||||
assertTrue(host.supportFragmentManager.fragments.none { it is V2AuthFlow })
|
||||
assertTrue(requests.isEmpty())
|
||||
V2AuthFlow.start(host)
|
||||
assertEquals(2, callbacks.size)
|
||||
receiveReceipt()
|
||||
val model = model(flow(host))
|
||||
assertEquals(V2AuthPhase.Choosing, model.stateLiveData.value!!.phase)
|
||||
assertTrue(requests.isEmpty())
|
||||
ShadowDialog.getLatestDialog().findViewById<View>(R.id.btn_confirm).performClick()
|
||||
ioScheduler.triggerActions()
|
||||
idle()
|
||||
assertEquals(1, requests.size)
|
||||
assertEquals(SplashActivity::class.java.name, shadowOf(host).nextStartedActivity.component?.className)
|
||||
controller.pause().stop().destroy()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `중복 SDK 성공은 완료 전후에도 세션과 요청을 한 번만 만들고 새 인증은 별도 세션이다`() {
|
||||
val controller = Robolectric.buildActivity(AuthFlowHost::class.java).setup()
|
||||
val host = controller.get()
|
||||
V2AuthFlow.start(host, true)
|
||||
val callback = callbacks.single()
|
||||
callback("{\"data\":{\"receipt_id\":\"test-receipt\"}}")
|
||||
callback("{\"data\":{\"receipt_id\":\"duplicate-test-receipt\"}}")
|
||||
idle()
|
||||
val original = flow(host)
|
||||
val originalModel = model(original)
|
||||
originalModel.selectContentType(ContentType.FEMALE)
|
||||
callback("{\"data\":{\"receipt_id\":\"duplicate-test-receipt\"}}")
|
||||
idle()
|
||||
assertSame(original, flow(host))
|
||||
assertEquals(ContentType.FEMALE, originalModel.stateLiveData.value!!.contentType)
|
||||
assertTrue(requests.isEmpty())
|
||||
originalModel.confirm()
|
||||
originalModel.confirm()
|
||||
ioScheduler.triggerActions()
|
||||
member.onSuccess(ApiResponse(true, memberInfo()))
|
||||
idle()
|
||||
assertEquals(1, requests.size)
|
||||
assertEquals(1, host.audioResults)
|
||||
assertTrue(host.supportFragmentManager.fragments.none { it is V2AuthFlow })
|
||||
callback("{\"data\":{\"receipt_id\":\"duplicate-test-receipt\"}}")
|
||||
idle()
|
||||
assertTrue(host.supportFragmentManager.fragments.none { it is V2AuthFlow })
|
||||
assertEquals(1, requests.size)
|
||||
assertEquals(1, host.audioResults)
|
||||
V2AuthFlow.start(host, true)
|
||||
assertEquals(2, callbacks.size)
|
||||
receiveReceipt()
|
||||
assertNotSame(originalModel, model(flow(host)))
|
||||
assertEquals(ContentType.ALL, model(flow(host)).stateLiveData.value!!.contentType)
|
||||
assertEquals(1, requests.size)
|
||||
controller.pause().stop().destroy()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `상태 저장 후 도착한 SDK 성공은 coordinator를 추가하거나 요청하지 않는다`() {
|
||||
val controller = Robolectric.buildActivity(AuthFlowHost::class.java).setup()
|
||||
val host = controller.get()
|
||||
V2AuthFlow.start(host)
|
||||
val callback = callbacks.single()
|
||||
controller.pause().stop().saveInstanceState(Bundle())
|
||||
callback("{\"data\":{\"receipt_id\":\"test-receipt\"}}")
|
||||
idle()
|
||||
assertTrue(host.supportFragmentManager.fragments.none { it is V2AuthFlow })
|
||||
assertTrue(requests.isEmpty())
|
||||
controller.start().resume()
|
||||
idle()
|
||||
callback("{\"data\":{\"receipt_id\":\"test-receipt\"}}")
|
||||
idle()
|
||||
assertTrue(host.supportFragmentManager.fragments.none { it is V2AuthFlow })
|
||||
controller.pause().stop().destroy()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `정지 중 성공은 재개까지 보류하고 Splash를 한 번만 열고 완료를 소비한다`() {
|
||||
val controller = Robolectric.buildActivity(AuthFlowHost::class.java).setup()
|
||||
val host = controller.get()
|
||||
V2AuthFlow.start(host)
|
||||
receiveReceipt()
|
||||
val model = model(flow(host))
|
||||
model.selectContentType(ContentType.MALE)
|
||||
model.confirm()
|
||||
controller.pause().stop()
|
||||
ioScheduler.triggerActions()
|
||||
assertEquals(1, requests.size)
|
||||
assertTrue(model.stateLiveData.value!!.completionPending)
|
||||
assertNull(shadowOf(host).nextStartedActivity)
|
||||
controller.start().resume().visible()
|
||||
idle()
|
||||
val intent = shadowOf(host).nextStartedActivity
|
||||
assertEquals(SplashActivity::class.java.name, intent.component?.className)
|
||||
assertEquals(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK, intent.flags)
|
||||
assertTrue(host.isFinishing)
|
||||
assertFalse(model.stateLiveData.value!!.completionPending)
|
||||
assertNull(shadowOf(host).nextStartedActivity)
|
||||
assertTrue(host.supportFragmentManager.fragments.none { it is V2AuthFlow })
|
||||
assertEquals(ContentType.MALE.ordinal, SharedPreferenceManager.contentPreference)
|
||||
controller.pause().stop().destroy()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `STARTED 상태의 성공은 LiveData 관찰 중이어도 RESUMED 전에는 완료를 소비하지 않는다`() {
|
||||
val controller = Robolectric.buildActivity(AuthFlowHost::class.java).setup()
|
||||
val host = controller.get()
|
||||
V2AuthFlow.start(host, true)
|
||||
receiveReceipt()
|
||||
val model = model(flow(host))
|
||||
model.confirm()
|
||||
ioScheduler.triggerActions()
|
||||
controller.pause()
|
||||
member.onSuccess(ApiResponse(true, memberInfo()))
|
||||
assertEquals(0, host.audioResults)
|
||||
assertTrue(model.stateLiveData.value!!.completionPending)
|
||||
controller.resume()
|
||||
idle()
|
||||
assertEquals(1, host.audioResults)
|
||||
assertFalse(model.stateLiveData.value!!.completionPending)
|
||||
controller.pause().stop().destroy()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `정지 중 POST 실패는 재개에서 오류를 소비하고 같은 선택의 새 Sheet로 재제출한다`() {
|
||||
val controller = Robolectric.buildActivity(AuthFlowHost::class.java).setup()
|
||||
val host = controller.get()
|
||||
V2AuthFlow.start(host)
|
||||
receiveReceipt()
|
||||
val model = model(flow(host))
|
||||
model.selectContentType(ContentType.FEMALE)
|
||||
val firstSheet = ShadowDialog.getLatestDialog()
|
||||
firstSheet.findViewById<View>(R.id.btn_confirm).performClick()
|
||||
controller.pause().stop()
|
||||
postSuccess = false
|
||||
ioScheduler.triggerActions()
|
||||
assertTrue(model.stateLiveData.value!!.error != null)
|
||||
assertNull(ShadowToast.getTextOfLatestToast())
|
||||
assertFalse(firstSheet.isShowing)
|
||||
controller.start().resume()
|
||||
idle()
|
||||
assertNull(model.stateLiveData.value!!.error)
|
||||
assertEquals(host.getString(R.string.common_error_unknown), ShadowToast.getTextOfLatestToast())
|
||||
val retrySheet = ShadowDialog.getLatestDialog()
|
||||
assertNotSame(firstSheet, retrySheet)
|
||||
assertEquals(ContentType.FEMALE, model.stateLiveData.value!!.contentType)
|
||||
postSuccess = true
|
||||
retrySheet.findViewById<View>(R.id.btn_confirm).performClick()
|
||||
ioScheduler.triggerActions()
|
||||
idle()
|
||||
assertEquals(2, requests.size)
|
||||
assertEquals(ContentType.FEMALE.ordinal, SharedPreferenceManager.contentPreference)
|
||||
assertEquals(SplashActivity::class.java.name, shadowOf(host).nextStartedActivity.component?.className)
|
||||
controller.pause().stop().destroy()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `백그라운드 Bootpay 완료는 main에서 시작하고 제거 후 늦은 완료는 무시한다`() {
|
||||
val controller = Robolectric.buildActivity(AuthFlowHost::class.java).setup()
|
||||
val host = controller.get()
|
||||
V2AuthFlow.start(host, true)
|
||||
val callback = callbacks.single()
|
||||
Thread { callback("{\"data\":{\"receipt_id\":\"test-receipt\"}}") }.apply { start(); join() }
|
||||
assertTrue(host.supportFragmentManager.fragments.none { it is V2AuthFlow })
|
||||
idle()
|
||||
val original = flow(host)
|
||||
val model = model(original)
|
||||
assertEquals(V2AuthPhase.Choosing, model.stateLiveData.value!!.phase)
|
||||
host.supportFragmentManager.beginTransaction().remove(original).commitNow()
|
||||
callback("{\"data\":{\"receipt_id\":\"other-test-receipt\"}}")
|
||||
idle()
|
||||
assertTrue(model.compositeDisposable.isDisposed)
|
||||
assertTrue(host.supportFragmentManager.fragments.none { it is V2AuthFlow })
|
||||
assertEquals(0, host.audioResults)
|
||||
assertTrue(requests.isEmpty())
|
||||
controller.pause().stop().destroy()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `재생성한 오디오 호스트는 기존 ViewModel을 사용하고 회원 저장 뒤 결과를 한 번 받는다`() {
|
||||
val controller = Robolectric.buildActivity(AuthFlowHost::class.java).setup()
|
||||
val oldHost = controller.get()
|
||||
V2AuthFlow.start(oldHost, true)
|
||||
receiveReceipt()
|
||||
val originalModel = model(flow(oldHost))
|
||||
originalModel.confirm()
|
||||
ioScheduler.triggerActions()
|
||||
assertEquals(1, memberCalls)
|
||||
assertEquals(0, oldHost.audioResults)
|
||||
val host = controller.recreate().get()
|
||||
assertNotSame(oldHost, host)
|
||||
assertSame(originalModel, model(flow(host)))
|
||||
member.onSuccess(ApiResponse(true, memberInfo()))
|
||||
idle()
|
||||
assertEquals(0, oldHost.audioResults)
|
||||
assertEquals(1, host.audioResults)
|
||||
assertEquals(listOf(true to ContentType.FEMALE.ordinal), host.preferencesAtResult)
|
||||
assertEquals(1, callbacks.size)
|
||||
assertEquals(1, requests.size)
|
||||
assertNull(shadowOf(host).nextStartedActivity)
|
||||
assertFalse(host.isFinishing)
|
||||
controller.pause().stop().start().resume()
|
||||
idle()
|
||||
assertEquals(1, host.audioResults)
|
||||
controller.pause().stop().destroy()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `저장 후 정지 중 회원 성공도 재생성한 호스트에게만 결과를 전달한다`() {
|
||||
val controller = Robolectric.buildActivity(AuthFlowHost::class.java).setup()
|
||||
val oldHost = controller.get()
|
||||
V2AuthFlow.start(oldHost, true)
|
||||
receiveReceipt()
|
||||
val originalModel = model(flow(oldHost))
|
||||
originalModel.confirm()
|
||||
ioScheduler.triggerActions()
|
||||
controller.pause().stop().saveInstanceState(Bundle())
|
||||
member.onSuccess(ApiResponse(true, memberInfo()))
|
||||
assertEquals(0, oldHost.audioResults)
|
||||
assertTrue(originalModel.stateLiveData.value!!.completionPending)
|
||||
val host = controller.recreate().get()
|
||||
idle()
|
||||
assertEquals(0, oldHost.audioResults)
|
||||
assertEquals(1, host.audioResults)
|
||||
assertFalse(originalModel.stateLiveData.value!!.completionPending)
|
||||
assertEquals(1, requests.size)
|
||||
controller.pause().stop().destroy()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `회원 실패 뒤 새 Sheet의 완료는 선택을 유지하고 POST 없이 GET만 재시도한다`() {
|
||||
val controller = Robolectric.buildActivity(AuthFlowHost::class.java).setup()
|
||||
val host = controller.get()
|
||||
V2AuthFlow.start(host, true)
|
||||
receiveReceipt()
|
||||
val model = model(flow(host))
|
||||
model.selectContentType(ContentType.MALE)
|
||||
val firstSheet = ShadowDialog.getLatestDialog()
|
||||
firstSheet.findViewById<View>(R.id.btn_confirm).performClick()
|
||||
assertFalse(firstSheet.isShowing)
|
||||
ioScheduler.triggerActions()
|
||||
member.onSuccess(ApiResponse(false, message = "회원 조회 실패"))
|
||||
val retrySheet = ShadowDialog.getLatestDialog()
|
||||
assertNotSame(firstSheet, retrySheet)
|
||||
assertTrue(retrySheet is ContentPreferenceBottomSheet)
|
||||
assertEquals("회원 조회 실패", ShadowToast.getTextOfLatestToast())
|
||||
member = SingleSubject.create()
|
||||
retrySheet.findViewById<View>(R.id.btn_confirm).performClick()
|
||||
ioScheduler.triggerActions()
|
||||
assertEquals(1, requests.size)
|
||||
assertEquals(2, memberCalls)
|
||||
assertEquals(ContentType.MALE, model.stateLiveData.value!!.contentType)
|
||||
member.onSuccess(ApiResponse(true, memberInfo()))
|
||||
idle()
|
||||
assertEquals(1, host.audioResults)
|
||||
controller.pause().stop().destroy()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `잘못된 외부 payload는 POST나 완료 없이 안전한 오류로 종료한다`() {
|
||||
listOf(
|
||||
"not-json",
|
||||
"null",
|
||||
"[]",
|
||||
"{}",
|
||||
"{\"data\":null}",
|
||||
"{\"data\":{\"receipt_id\":17}}",
|
||||
"{\"data\":{\"receipt_id\":\" \"}}"
|
||||
).forEach { payload ->
|
||||
val controller = Robolectric.buildActivity(AuthFlowHost::class.java).setup()
|
||||
val host = controller.get()
|
||||
V2AuthFlow.start(host)
|
||||
assertTrue(host.supportFragmentManager.fragments.none { it is V2AuthFlow })
|
||||
callbacks.last().invoke(payload)
|
||||
idle()
|
||||
ioScheduler.triggerActions()
|
||||
assertTrue(requests.isEmpty())
|
||||
assertEquals(0, host.audioResults)
|
||||
assertNull(shadowOf(host).nextStartedActivity)
|
||||
assertEquals(host.getString(R.string.common_error_unknown), ShadowToast.getTextOfLatestToast())
|
||||
assertTrue(host.supportFragmentManager.fragments.none { it is V2AuthFlow })
|
||||
controller.pause().stop().destroy()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Bootpay 대기 중 재생성한 호스트와 이전 호스트의 늦은 callback은 요청이나 완료를 만들지 않는다`() {
|
||||
val controller = Robolectric.buildActivity(AuthFlowHost::class.java).setup()
|
||||
V2AuthFlow.start(controller.get(), true)
|
||||
val oldCallback = callbacks.single()
|
||||
assertTrue(controller.get().supportFragmentManager.fragments.none { it is V2AuthFlow })
|
||||
val host = controller.recreate().get()
|
||||
idle()
|
||||
oldCallback("{\"data\":{\"receipt_id\":\"test-receipt\"}}")
|
||||
idle()
|
||||
assertTrue(requests.isEmpty())
|
||||
assertEquals(0, host.audioResults)
|
||||
assertTrue(host.supportFragmentManager.fragments.none { it is V2AuthFlow })
|
||||
V2AuthFlow.start(host)
|
||||
assertEquals(2, callbacks.size)
|
||||
receiveReceipt()
|
||||
assertEquals(V2AuthPhase.Choosing, model(flow(host)).stateLiveData.value!!.phase)
|
||||
controller.pause().stop().destroy()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `파괴된 호스트의 늦은 SDK 성공은 coordinator나 요청을 만들지 않는다`() {
|
||||
val controller = Robolectric.buildActivity(AuthFlowHost::class.java).setup()
|
||||
val host = controller.get()
|
||||
V2AuthFlow.start(host)
|
||||
val callback = callbacks.single()
|
||||
controller.pause().stop().destroy()
|
||||
callback("{\"data\":{\"receipt_id\":\"test-receipt\"}}")
|
||||
idle()
|
||||
assertTrue(host.supportFragmentManager.fragments.none { it is V2AuthFlow })
|
||||
assertTrue(requests.isEmpty())
|
||||
assertEquals(0, host.audioResults)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `프로세스 복원은 영수증을 저장하지 않고 인증이나 완료를 재실행하지 않는다`() {
|
||||
val controller = Robolectric.buildActivity(AuthFlowHost::class.java).setup()
|
||||
V2AuthFlow.start(controller.get(), true)
|
||||
receiveReceipt()
|
||||
val state = Bundle()
|
||||
controller.pause().stop().saveInstanceState(state).destroy()
|
||||
val parcel = Parcel.obtain()
|
||||
try {
|
||||
parcel.writeBundle(state)
|
||||
assertFalse(String(parcel.marshall(), Charsets.UTF_16LE).contains("test-receipt"))
|
||||
} finally {
|
||||
parcel.recycle()
|
||||
}
|
||||
val restored = Robolectric.buildActivity(AuthFlowHost::class.java).create(state).start().resume().visible()
|
||||
idle()
|
||||
val host = restored.get()
|
||||
assertTrue(host.supportFragmentManager.fragments.none { it is V2AuthFlow })
|
||||
assertEquals(0, host.audioResults)
|
||||
assertEquals(1, callbacks.size)
|
||||
assertTrue(requests.isEmpty())
|
||||
restored.pause().stop().destroy()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `기본 빌드 선택은 BuildConfig DEBUG에 맞는 인증 경로를 사용한다`() {
|
||||
unmockkObject(V2AuthBuildBehavior)
|
||||
assertEquals(BuildConfig.DEBUG, V2AuthBuildBehavior.simulate)
|
||||
val controller = Robolectric.buildActivity(AuthFlowHost::class.java).setup()
|
||||
val host = controller.get()
|
||||
try {
|
||||
V2AuthFlow.start(host)
|
||||
if (BuildConfig.DEBUG) {
|
||||
assertTrue(callbacks.isEmpty())
|
||||
advance(500)
|
||||
assertEquals(V2AuthPhase.Choosing, model(flow(host)).stateLiveData.value!!.phase)
|
||||
assertTrue(requests.isEmpty())
|
||||
} else {
|
||||
assertEquals(1, callbacks.size)
|
||||
assertTrue(requests.isEmpty())
|
||||
assertTrue(host.supportFragmentManager.fragments.none { it is V2AuthFlow })
|
||||
receiveReceipt()
|
||||
val model = model(flow(host))
|
||||
assertEquals(V2AuthPhase.Choosing, model.stateLiveData.value!!.phase)
|
||||
assertTrue(requests.isEmpty())
|
||||
model.confirm()
|
||||
ioScheduler.triggerActions()
|
||||
idle()
|
||||
assertEquals(1, requests.size)
|
||||
assertEquals("POST", requests.single().method)
|
||||
assertEquals("/auth", requests.single().url.encodedPath)
|
||||
assertEquals(SplashActivity::class.java.name, shadowOf(host).nextStartedActivity.component?.className)
|
||||
assertNull(shadowOf(host).nextStartedActivity)
|
||||
assertTrue(host.isFinishing)
|
||||
}
|
||||
} finally {
|
||||
controller.pause().stop().destroy()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `디버그 중복 시작은 로딩과 단일 지연을 유지하고 정확히 500ms에 선택을 시작한다`() {
|
||||
val controller = Robolectric.buildActivity(AuthFlowHost::class.java).setup()
|
||||
val host = controller.get()
|
||||
startDebug(host)
|
||||
val original = flow(host)
|
||||
val model = model(original)
|
||||
val loading = ShadowDialog.getLatestDialog()
|
||||
assertTrue(loading.isShowing)
|
||||
assertFalse(loading is ContentPreferenceBottomSheet)
|
||||
assertEquals(V2AuthPhase.Idle, model.stateLiveData.value!!.phase)
|
||||
advance(250)
|
||||
V2AuthFlow.start(host, true)
|
||||
assertSame(original, flow(host))
|
||||
advance(249)
|
||||
assertEquals(V2AuthPhase.Idle, model.stateLiveData.value!!.phase)
|
||||
assertSame(loading, ShadowDialog.getLatestDialog())
|
||||
assertTrue(loading.isShowing)
|
||||
advance(1)
|
||||
assertEquals(V2AuthPhase.Choosing, model.stateLiveData.value!!.phase)
|
||||
assertTrue(model.stateLiveData.value!!.isAdultContentVisible)
|
||||
assertEquals(ContentType.ALL, model.stateLiveData.value!!.contentType)
|
||||
assertFalse(loading.isShowing)
|
||||
assertTrue(ShadowDialog.getLatestDialog() is ContentPreferenceBottomSheet)
|
||||
assertTrue(callbacks.isEmpty())
|
||||
assertTrue(requests.isEmpty())
|
||||
controller.pause().stop().destroy()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `디버그 일반 완료는 POST 없이 선택을 저장한 뒤 Splash를 한 번 열고 인증을 만들지 않는다`() {
|
||||
val controller = Robolectric.buildActivity(AuthFlowHost::class.java).setup()
|
||||
val host = controller.get()
|
||||
SharedPreferenceManager.isAuth = false
|
||||
SharedPreferenceManager.contentPreference = ContentType.MALE.ordinal
|
||||
startDebug(host)
|
||||
advance(500)
|
||||
val model = model(flow(host))
|
||||
ShadowDialog.getLatestDialog().findViewById<View>(R.id.radio_female).performClick()
|
||||
assertEquals(ContentType.MALE.ordinal, SharedPreferenceManager.contentPreference)
|
||||
ShadowDialog.getLatestDialog().findViewById<View>(R.id.btn_confirm).performClick()
|
||||
model.confirm()
|
||||
assertTrue(requests.isEmpty())
|
||||
assertNull(shadowOf(host).nextStartedActivity)
|
||||
ioScheduler.triggerActions()
|
||||
idle()
|
||||
assertEquals(listOf(Triple(false, true, ContentType.FEMALE.ordinal)), host.preferencesAtSplash)
|
||||
assertEquals(SplashActivity::class.java.name, shadowOf(host).nextStartedActivity.component?.className)
|
||||
assertNull(shadowOf(host).nextStartedActivity)
|
||||
assertFalse(SharedPreferenceManager.isAuth)
|
||||
assertEquals(0, memberCalls)
|
||||
assertTrue(callbacks.isEmpty())
|
||||
assertTrue(requests.isEmpty())
|
||||
assertFalse(model.stateLiveData.value!!.completionPending)
|
||||
controller.pause().stop().destroy()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `디버그 오디오는 POST 없이 실제 회원 조회를 재시도하고 서버 false와 설정 저장 뒤 한 번 완료한다`() {
|
||||
val controller = Robolectric.buildActivity(AuthFlowHost::class.java).setup()
|
||||
val host = controller.get()
|
||||
SharedPreferenceManager.isAuth = true
|
||||
SharedPreferenceManager.contentPreference = ContentType.ALL.ordinal
|
||||
startDebug(host, true)
|
||||
advance(500)
|
||||
val model = model(flow(host))
|
||||
model.selectContentType(ContentType.FEMALE)
|
||||
ShadowDialog.getLatestDialog().findViewById<View>(R.id.btn_confirm).performClick()
|
||||
ioScheduler.triggerActions()
|
||||
assertEquals(1, memberCalls)
|
||||
assertEquals(0, host.audioResults)
|
||||
assertEquals(ContentType.ALL.ordinal, SharedPreferenceManager.contentPreference)
|
||||
assertTrue(requests.isEmpty())
|
||||
member.onError(IllegalStateException("member fetch failed"))
|
||||
assertEquals(V2AuthPhase.Failed, model.stateLiveData.value!!.phase)
|
||||
assertTrue(model.stateLiveData.value!!.selectionLocked)
|
||||
assertEquals(0, host.audioResults)
|
||||
assertEquals(ContentType.ALL.ordinal, SharedPreferenceManager.contentPreference)
|
||||
member = SingleSubject.create()
|
||||
ShadowDialog.getLatestDialog().findViewById<View>(R.id.btn_confirm).performClick()
|
||||
ioScheduler.triggerActions()
|
||||
assertEquals(2, memberCalls)
|
||||
assertEquals(ContentType.FEMALE, model.stateLiveData.value!!.contentType)
|
||||
assertTrue(requests.isEmpty())
|
||||
member.onSuccess(ApiResponse(true, memberInfo(false, false, ContentType.MALE)))
|
||||
idle()
|
||||
assertEquals(1, host.audioResults)
|
||||
assertEquals(listOf(false to ContentType.MALE.ordinal), host.preferencesAtResult)
|
||||
assertFalse(SharedPreferenceManager.isAdultContentVisible)
|
||||
assertFalse(SharedPreferenceManager.isAuth)
|
||||
assertNull(shadowOf(host).nextStartedActivity)
|
||||
model.confirm()
|
||||
ioScheduler.triggerActions()
|
||||
assertEquals(2, memberCalls)
|
||||
assertEquals(1, host.audioResults)
|
||||
assertTrue(callbacks.isEmpty())
|
||||
assertTrue(requests.isEmpty())
|
||||
controller.pause().stop().destroy()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `디버그 대기 중 파괴와 명시적 제거는 지연을 취소하고 늦은 선택이나 완료를 만들지 않는다`() {
|
||||
listOf(false, true).forEach { removeOnly ->
|
||||
val controller = Robolectric.buildActivity(AuthFlowHost::class.java).setup()
|
||||
val host = controller.get()
|
||||
startDebug(host, true)
|
||||
val original = flow(host)
|
||||
val model = model(original)
|
||||
val loading = ShadowDialog.getLatestDialog()
|
||||
advance(250)
|
||||
if (removeOnly) {
|
||||
host.supportFragmentManager.beginTransaction().remove(original).commitNow()
|
||||
} else {
|
||||
controller.pause().stop().destroy()
|
||||
}
|
||||
advance(500)
|
||||
assertEquals(V2AuthPhase.Idle, model.stateLiveData.value!!.phase)
|
||||
assertTrue(model.compositeDisposable.isDisposed)
|
||||
assertFalse(loading.isShowing)
|
||||
assertSame(loading, ShadowDialog.getLatestDialog())
|
||||
assertEquals(0, host.audioResults)
|
||||
assertTrue(callbacks.isEmpty())
|
||||
assertTrue(requests.isEmpty())
|
||||
if (removeOnly) controller.pause().stop().destroy()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `디버그 정지 중 지연 완료는 Sheet 없이 보류하고 재개에서 선택을 표시한다`() {
|
||||
val controller = Robolectric.buildActivity(AuthFlowHost::class.java).setup()
|
||||
val host = controller.get()
|
||||
startDebug(host)
|
||||
val model = model(flow(host))
|
||||
val loading = ShadowDialog.getLatestDialog()
|
||||
advance(250)
|
||||
controller.pause().stop().saveInstanceState(Bundle())
|
||||
advance(250)
|
||||
assertEquals(V2AuthPhase.Choosing, model.stateLiveData.value!!.phase)
|
||||
assertFalse(loading.isShowing)
|
||||
assertSame(loading, ShadowDialog.getLatestDialog())
|
||||
assertNull(shadowOf(host).nextStartedActivity)
|
||||
assertTrue(requests.isEmpty())
|
||||
controller.start().resume().visible()
|
||||
idle()
|
||||
assertTrue(ShadowDialog.getLatestDialog() is ContentPreferenceBottomSheet)
|
||||
assertTrue(ShadowDialog.getLatestDialog().isShowing)
|
||||
assertTrue(callbacks.isEmpty())
|
||||
controller.pause().stop().destroy()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `디버그 대기 중 재생성은 흐름을 종료하고 새 시도의 500ms를 기다린다`() {
|
||||
val controller = Robolectric.buildActivity(AuthFlowHost::class.java).setup()
|
||||
startDebug(controller.get())
|
||||
advance(250)
|
||||
val host = controller.recreate().get()
|
||||
idle()
|
||||
assertTrue(host.supportFragmentManager.fragments.none { it is V2AuthFlow })
|
||||
startDebug(host)
|
||||
advance(499)
|
||||
assertEquals(V2AuthPhase.Idle, model(flow(host)).stateLiveData.value!!.phase)
|
||||
advance(1)
|
||||
assertEquals(V2AuthPhase.Choosing, model(flow(host)).stateLiveData.value!!.phase)
|
||||
assertTrue(requests.isEmpty())
|
||||
assertTrue(callbacks.isEmpty())
|
||||
controller.pause().stop().destroy()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `디버그 선택 후 재생성은 선택 ViewModel과 메모리 API를 유지한다`() {
|
||||
val controller = Robolectric.buildActivity(AuthFlowHost::class.java).setup()
|
||||
startDebug(controller.get())
|
||||
advance(500)
|
||||
val originalModel = model(flow(controller.get()))
|
||||
originalModel.toggleVisibility()
|
||||
val host = controller.recreate().get()
|
||||
idle()
|
||||
assertSame(originalModel, model(flow(host)))
|
||||
assertFalse(originalModel.stateLiveData.value!!.isAdultContentVisible)
|
||||
ShadowDialog.getLatestDialog().findViewById<View>(R.id.btn_confirm).performClick()
|
||||
ioScheduler.triggerActions()
|
||||
idle()
|
||||
assertEquals(listOf(Triple(false, false, ContentType.ALL.ordinal)), host.preferencesAtSplash)
|
||||
assertTrue(callbacks.isEmpty())
|
||||
assertTrue(requests.isEmpty())
|
||||
controller.pause().stop().destroy()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `디버그도 상태 저장 또는 파괴된 호스트에서는 대기 흐름을 만들지 않는다`() {
|
||||
every { V2AuthBuildBehavior.simulate } returns true
|
||||
val controller = Robolectric.buildActivity(AuthFlowHost::class.java).setup()
|
||||
val host = controller.get()
|
||||
controller.pause().stop().saveInstanceState(Bundle())
|
||||
V2AuthFlow.start(host)
|
||||
advance(500)
|
||||
assertTrue(host.supportFragmentManager.fragments.none { it is V2AuthFlow })
|
||||
controller.destroy()
|
||||
V2AuthFlow.start(host)
|
||||
advance(500)
|
||||
assertTrue(host.supportFragmentManager.fragments.none { it is V2AuthFlow })
|
||||
assertTrue(callbacks.isEmpty())
|
||||
assertTrue(requests.isEmpty())
|
||||
}
|
||||
|
||||
private fun startDebug(host: AuthFlowHost, syncMemberInfo: Boolean = false) {
|
||||
every { V2AuthBuildBehavior.simulate } returns true
|
||||
V2AuthFlow.start(host, syncMemberInfo)
|
||||
assertTrue(callbacks.isEmpty())
|
||||
assertEquals(1, host.supportFragmentManager.fragments.filterIsInstance<V2AuthFlow>().size)
|
||||
}
|
||||
|
||||
private fun advance(milliseconds: Long) = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(milliseconds))
|
||||
|
||||
private fun flow(host: AuthFlowHost): V2AuthFlow =
|
||||
host.supportFragmentManager.fragments.filterIsInstance<V2AuthFlow>().single()
|
||||
|
||||
private fun model(flow: V2AuthFlow): V2AuthViewModel = ViewModelProvider(flow)[V2AuthViewModel::class.java]
|
||||
|
||||
private fun receiveReceipt() {
|
||||
callbacks.last()("{\"data\":{\"receipt_id\":\"test-receipt\"}}")
|
||||
idle()
|
||||
}
|
||||
|
||||
private fun idle() = shadowOf(Looper.getMainLooper()).idle()
|
||||
|
||||
private fun memberInfo(
|
||||
isAuth: Boolean = true,
|
||||
visible: Boolean = true,
|
||||
type: ContentType = ContentType.FEMALE
|
||||
) = GetMemberInfoResponse(
|
||||
can = 0, point = 0, isAuth = isAuth, gender = "MALE", signupDate = "2026-10-12", chargeCount = 0,
|
||||
role = MemberRole.USER, messageNotice = true, followingChannelLiveNotice = true,
|
||||
followingChannelUploadContentNotice = true, auditionNotice = false, countryCode = "KR",
|
||||
isAdultContentVisible = visible, contentType = type
|
||||
)
|
||||
}
|
||||
|
||||
class AuthFlowHost : AppCompatActivity() {
|
||||
var audioResults = 0
|
||||
val preferencesAtResult = mutableListOf<Pair<Boolean, Int>>()
|
||||
val preferencesAtSplash = mutableListOf<Triple<Boolean, Boolean, Int>>()
|
||||
|
||||
override fun startActivity(intent: Intent) {
|
||||
if (intent.component?.className == SplashActivity::class.java.name) {
|
||||
preferencesAtSplash.add(
|
||||
Triple(
|
||||
SharedPreferenceManager.isAuth,
|
||||
SharedPreferenceManager.isAdultContentVisible,
|
||||
SharedPreferenceManager.contentPreference
|
||||
)
|
||||
)
|
||||
}
|
||||
super.startActivity(intent)
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
setTheme(R.style.Theme_SodaLive)
|
||||
super.onCreate(savedInstanceState)
|
||||
supportFragmentManager.setFragmentResultListener(V2AuthFlow.AUDIO_AUTH_COMPLETED, this) { _, _ ->
|
||||
audioResults += 1
|
||||
preferencesAtResult.add(SharedPreferenceManager.isAuth to SharedPreferenceManager.contentPreference)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package kr.co.vividnext.sodalive.v2.auth
|
||||
|
||||
import kr.co.vividnext.sodalive.settings.ContentType
|
||||
import okhttp3.Interceptor
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Protocol
|
||||
import okhttp3.Response
|
||||
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||
import okhttp3.logging.HttpLoggingInterceptor
|
||||
import okio.Buffer
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotSame
|
||||
import org.junit.Assert.assertSame
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import retrofit2.Retrofit
|
||||
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
|
||||
import retrofit2.converter.gson.GsonConverterFactory
|
||||
import java.lang.reflect.Proxy
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
class V2AuthNetworkPrivacyTest {
|
||||
@Test
|
||||
fun `인증 전용 복제는 양쪽 BODY 로거를 제거하고 기존 클라이언트와 인증 언어 시간제한을 보존한다`() {
|
||||
val logs = mutableListOf<String>()
|
||||
val logger = HttpLoggingInterceptor { logs.add(it) }.setLevel(HttpLoggingInterceptor.Level.BODY)
|
||||
val networkLogger = HttpLoggingInterceptor { logs.add(it) }.setLevel(HttpLoggingInterceptor.Level.BODY)
|
||||
val locale = Interceptor { chain ->
|
||||
chain.proceed(chain.request().newBuilder().header("Accept-Language", "ko").build())
|
||||
}
|
||||
var calls = 0
|
||||
val terminal = Interceptor { chain ->
|
||||
calls += 1
|
||||
val request = chain.request()
|
||||
assertEquals("Bearer test-token", request.header("Authorization"))
|
||||
assertEquals("ko", request.header("Accept-Language"))
|
||||
val body = Buffer().also { request.body!!.writeTo(it) }.readUtf8()
|
||||
assertTrue(body.contains("test-receipt"))
|
||||
assertTrue(body.contains("\"contentType\":\"FEMALE\""))
|
||||
Response.Builder().request(request).protocol(Protocol.HTTP_1_1).code(200).message("OK")
|
||||
.body("{\"success\":true}".toResponseBody("application/json".toMediaType())).build()
|
||||
}
|
||||
val client = OkHttpClient.Builder().addInterceptor(logger).addInterceptor(locale).addInterceptor(terminal)
|
||||
.addNetworkInterceptor(networkLogger).connectTimeout(27, TimeUnit.SECONDS)
|
||||
.readTimeout(31, TimeUnit.SECONDS).writeTimeout(39, TimeUnit.SECONDS).build()
|
||||
val retrofit = Retrofit.Builder().baseUrl("https://example.test/").client(client)
|
||||
.addConverterFactory(GsonConverterFactory.create())
|
||||
.addCallAdapterFactory(RxJava3CallAdapterFactory.create()).build()
|
||||
val api = createV2AuthApi(retrofit, client)
|
||||
val handler = Proxy.getInvocationHandler(api)
|
||||
val field = handler.javaClass.declaredFields.first { Retrofit::class.java.isAssignableFrom(it.type) }
|
||||
.apply { isAccessible = true }
|
||||
val privateRetrofit = field.get(handler) as Retrofit
|
||||
val privateClient = privateRetrofit.callFactory() as OkHttpClient
|
||||
assertNotSame(retrofit, privateRetrofit)
|
||||
assertNotSame(client, privateClient)
|
||||
assertFalse(privateClient.interceptors.any { it is HttpLoggingInterceptor })
|
||||
assertFalse(privateClient.networkInterceptors.any { it is HttpLoggingInterceptor })
|
||||
assertSame(locale, privateClient.interceptors.first())
|
||||
assertSame(client.authenticator, privateClient.authenticator)
|
||||
assertEquals(client.connectTimeoutMillis, privateClient.connectTimeoutMillis)
|
||||
assertEquals(client.readTimeoutMillis, privateClient.readTimeoutMillis)
|
||||
assertEquals(client.writeTimeoutMillis, privateClient.writeTimeoutMillis)
|
||||
assertSame(logger, client.interceptors.first())
|
||||
assertSame(networkLogger, client.networkInterceptors.single())
|
||||
assertEquals(HttpLoggingInterceptor.Level.BODY, logger.level)
|
||||
assertEquals(HttpLoggingInterceptor.Level.BODY, networkLogger.level)
|
||||
assertTrue(
|
||||
api.verify(V2AuthVerifyRequest("test-receipt", true, ContentType.FEMALE), "Bearer test-token")
|
||||
.blockingGet().success
|
||||
)
|
||||
assertEquals(1, calls)
|
||||
assertTrue(logs.isEmpty())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user