feat(auth): 공통 인증 흐름과 디버그 시뮬레이션을 추가한다

This commit is contained in:
2026-10-13 11:30:20 +09:00
parent 31861721f4
commit 4fe75d495d
3 changed files with 1137 additions and 0 deletions
@@ -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())
}
}