Skip to content
Merged
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
package com.afternote.afternote_fe

import android.app.Instrumentation
import androidx.compose.ui.semantics.SemanticsProperties
import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.SemanticsMatcher
import androidx.compose.ui.test.assertIsSelected
import androidx.compose.ui.test.hasText
import androidx.compose.ui.test.junit4.createEmptyComposeRule
import androidx.compose.ui.test.waitUntilAtLeastOneExists
import androidx.lifecycle.ViewModelProvider
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
Expand All @@ -10,6 +17,8 @@ import com.afternote.afternote_fe.notification.NotificationEntrySource
import com.afternote.afternote_fe.test.backgroundActivityStartOptions
import com.afternote.core.common.notification.NotificationDestination
import com.afternote.core.common.notification.NotificationPendingIntentFactory
import com.afternote.core.domain.repository.auth.AuthRepository
import com.afternote.core.domain.testing.FakeAuthRepository
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import org.junit.After
Expand All @@ -19,13 +28,22 @@ import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import javax.inject.Inject
import com.afternote.core.ui.R as CoreUiR

@HiltAndroidTest
@RunWith(AndroidJUnit4::class)
@OptIn(ExperimentalTestApi::class)
class NotificationColdStartAndroidTest {
@get:Rule
@Inject
lateinit var authRepository: AuthRepository

@get:Rule(order = 0)
val hiltRule = HiltAndroidRule(this)

@get:Rule(order = 1)
val composeRule = createEmptyComposeRule()

private val instrumentation: Instrumentation
get() = InstrumentationRegistry.getInstrumentation()

Expand All @@ -48,29 +66,11 @@ class NotificationColdStartAndroidTest {

@Test
fun coldPendingIntentLaunch_enqueuesInitialNotificationEntry() {
val context = ApplicationProvider.getApplicationContext<android.content.Context>()
val source = NotificationEntrySource.FCM
val occurrenceId = "cold-start-1"
// 폴백(HOME)이 아닌 목적지를 실어 cold start 경로에서 extra 가 살아남는지 본다.
val destination = NotificationDestination.TIME_LETTER
activityMonitor = instrumentation.addMonitor(MainActivity::class.java.name, null, false)

val pendingIntent =
NotificationPendingIntentFactory.create(
context = context,
source = source.contractValue,
occurrenceId = occurrenceId,
destination = destination,
)

assertNotNull(pendingIntent)
pendingIntent?.send(context, 0, null, null, null, null, backgroundActivityStartOptions())
launchedActivity =
activityMonitor?.let { monitor ->
instrumentation.waitForMonitorWithTimeout(monitor, ACTIVITY_START_TIMEOUT_MILLIS)
} as? MainActivity
assertNotNull(launchedActivity)
instrumentation.waitForIdleSync()
launchNotification(source, occurrenceId, destination)

var pendingEntry: NotificationEntryRequest? = null
instrumentation.runOnMainSync {
Expand All @@ -91,6 +91,45 @@ class NotificationColdStartAndroidTest {
)
}

@Test
fun coldPendingIntentLaunchWhileLoggedIn_opensDestination() {
(authRepository as FakeAuthRepository).loggedIn = true
launchNotification(NotificationEntrySource.FCM, "cold-start-signed-in", NotificationDestination.TIME_LETTER)

val context = ApplicationProvider.getApplicationContext<android.content.Context>()
val destinationTab =
hasText(context.getString(CoreUiR.string.core_ui_nav_item_timeletter)) and
SemanticsMatcher.expectValue(SemanticsProperties.Selected, true)
composeRule.waitUntilAtLeastOneExists(destinationTab, timeoutMillis = ACTIVITY_START_TIMEOUT_MILLIS)
composeRule.onNode(destinationTab).assertIsSelected()
}

private fun launchNotification(
source: NotificationEntrySource,
occurrenceId: String,
destination: NotificationDestination,
) {
val context = ApplicationProvider.getApplicationContext<android.content.Context>()
activityMonitor = instrumentation.addMonitor(MainActivity::class.java.name, null, false)

val pendingIntent =
NotificationPendingIntentFactory.create(
context = context,
source = source.contractValue,
occurrenceId = occurrenceId,
destination = destination,
)

assertNotNull(pendingIntent)
pendingIntent?.send(context, 0, null, null, null, null, backgroundActivityStartOptions())
launchedActivity =
activityMonitor?.let { monitor ->
instrumentation.waitForMonitorWithTimeout(monitor, ACTIVITY_START_TIMEOUT_MILLIS)
} as? MainActivity
assertNotNull(launchedActivity)
instrumentation.waitForIdleSync()
}

private companion object {
const val ACTIVITY_START_TIMEOUT_MILLIS = 10_000L
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,20 +109,18 @@ class NotificationNavigationAndroidTest {
composeRule
.onNodeWithText(context.getString(OnboardingR.string.onboarding_welcome_start))
.assertIsDisplayed()
deliverWarmNotification(NotificationEntrySource.FCM, "logged-out-1", NotificationDestination.HOME)
deliverWarmNotification(NotificationEntrySource.FCM, "logged-out-1", NotificationDestination.TIME_LETTER)

awaitNotificationIntent(NotificationEntrySource.FCM, "logged-out-1", NotificationDestination.HOME)
awaitNotificationIntent(NotificationEntrySource.FCM, "logged-out-1", NotificationDestination.TIME_LETTER)
assertSame(activityUnderTest, resumedMainActivity())
composeRule
.onNodeWithText(context.getString(OnboardingR.string.onboarding_welcome_start))
.assertIsDisplayed()

fakeAuth.loggedIn = true

val greeting = context.getString(HomeR.string.home_tab_greeting, "테스트 사용자")
composeRule.waitUntilAtLeastOneExists(hasText(greeting), timeoutMillis = 10_000)
composeRule.onNodeWithText(greeting).assertIsDisplayed()
composeRule.onNode(selectedBottomBarMatcher(CoreUiR.string.core_ui_nav_item_home)).assertIsSelected()
// 로그인이 확정되면 큐에 남아 있던 알림이 그제서야 목적지로 이어진다.
awaitSelectedBottomBarTab(CoreUiR.string.core_ui_nav_item_timeletter)
}

@Test
Expand All @@ -136,12 +134,17 @@ class NotificationNavigationAndroidTest {

awaitNotificationIntent(NotificationEntrySource.FCM, "logged-in-1", NotificationDestination.HOME)
assertSame(activityUnderTest, resumedMainActivity())
// 목적지 이동 결선은 #1795 가 Nav3 루트에 붙인다 — 지금은 보던 탭에 머문다.
awaitSelectedBottomBarTab(CoreUiR.string.core_ui_nav_item_home)

// 같은 알림을 다시 받아도 두 번 처리하지 않는다 — 탭을 옮겨 둔 뒤 재전달해도 그대로다.
openTimeLetterTab()
deliverWarmNotification(NotificationEntrySource.FCM, "logged-in-1", NotificationDestination.HOME)
composeRule.waitForIdle()
awaitSelectedBottomBarTab(CoreUiR.string.core_ui_nav_item_timeletter)
}

@Test
fun backgroundNotification_resumesSameActivityAndKeepsCurrentScreen() {
fun backgroundNotification_resumesSameActivityAndNavigatesToDestination() {
fakeAuth.loggedIn = true

val greeting = context.getString(HomeR.string.home_tab_greeting, "테스트 사용자")
Expand All @@ -162,8 +165,7 @@ class NotificationNavigationAndroidTest {
NotificationDestination.AFTERNOTE,
)
assertSame(activityUnderTest, resumedMainActivity())
// 목적지 이동 결선은 #1795 가 붙인다 — 지금은 보던 홈 탭에 머문다.
awaitSelectedBottomBarTab(CoreUiR.string.core_ui_nav_item_home)
awaitSelectedBottomBarTab(CoreUiR.string.core_ui_nav_item_note)
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,12 @@ import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
Expand Down Expand Up @@ -69,8 +72,14 @@ fun AppNavigation(
) {
val context = LocalContext.current
val activity = remember(context) { context.findActivity() }
val rememberedMindRecordController = rememberNavController()
val rememberedTimeLetterController = rememberNavController()
// 탭 NavHost 의 컨트롤러는 셸이 들고 있지만, NavHost 가 붙는 Nav3 엔트리는 탭 스택을 바꿀 때마다
// 내려가며 자기 ViewModelStore·Lifecycle 을 버린다. 다시 들어온 엔트리에 옛 컨트롤러를 붙이면
// "ViewModelStore should be set before setGraph call" 로 죽으므로, 엔트리 컴포지션이 내려갈 때
// 세대를 올려 컨트롤러도 엔트리와 같은 수명으로 새로 만든다.
var mindRecordHostGeneration by remember { mutableIntStateOf(0) }
var timeLetterHostGeneration by remember { mutableIntStateOf(0) }
val rememberedMindRecordController = key(mindRecordHostGeneration) { rememberNavController() }
val rememberedTimeLetterController = key(timeLetterHostGeneration) { rememberNavController() }
val mindRecordController = mindRecordNavController ?: appState.legacyMindRecordController ?: rememberedMindRecordController
val timeLetterController = timeLetterNavController ?: rememberedTimeLetterController
val mindRecordEntry by mindRecordController.currentBackStackEntryAsState()
Expand Down Expand Up @@ -155,6 +164,7 @@ fun AppNavigation(
}

NotificationPermissionEffect(snackbarHostState = snackbarHostState)
NotificationEntryEffect(appState = appState, mainViewModel = mainViewModel)

Scaffold(
modifier = modifier,
Expand Down Expand Up @@ -203,12 +213,14 @@ fun AppNavigation(
HomeTabScreen(uiState = uiState, actions = actions)
}
entry<Route.MindRecord> {
DisposableEffect(Unit) { onDispose { mindRecordHostGeneration++ } }
MindRecordRootHost(
navController = mindRecordController,
actions = mindRecordNavActions,
)
}
entry<Route.TimeLetter> {
DisposableEffect(Unit) { onDispose { timeLetterHostGeneration++ } }
NavHost(navController = timeLetterController, startDestination = Route.TimeLetter::class) {
timeLetterNavGraph(navController = timeLetterController, actions = timeLetterNavActions)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package com.afternote.afternote_fe.navigation

import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.afternote.afternote_fe.MainViewModel
import com.afternote.core.common.notification.NotificationDestination
import com.afternote.core.ui.Route

/**
* Activity 가 큐에 넣은 알림 진입을 앱 셸이 소비해 목적지 탭으로 옮긴다.
*
* 로그인이 확정되고 앱 셸이 바텀바 스택 위에 있을 때만 소비한다. 로그아웃(온보딩 FLOW 스택)이면
* 큐에 남겨 두어 알림이 인증 관문을 건너뛰는 통로가 되지 않게 하고, 로그인이 끝나 스택이
* 바뀌는 순간 효과가 다시 돌아 그 목적지로 이어진다. 이동은 바텀바 탭을 누른 것과 같은
* [AppState.navigateToBottomBarRoute] 를 재사용해 백스택 규약을 한 벌로 유지한다.
*/
@Composable
internal fun NotificationEntryEffect(
appState: AppState,
mainViewModel: MainViewModel,
) {
val pendingEntry by mainViewModel.pendingNotificationEntry.collectAsStateWithLifecycle()
val authenticatedStartRoute by mainViewModel.startRoute.collectAsStateWithLifecycle()
val isReadyForDestination =
authenticatedStartRoute == Route.Home && appState.activeStack != AppStack.FLOW
val entry = pendingEntry
LaunchedEffect(entry?.identityKey, isReadyForDestination) {
if (entry == null || !isReadyForDestination) return@LaunchedEffect
appState.navigateToBottomBarRoute(entry.destination.toBottomBarRoute())
mainViewModel.consumeNotificationEntry(entry.identityKey)
}
}

private fun NotificationDestination.toBottomBarRoute(): Route =
when (this) {
NotificationDestination.HOME -> Route.Home
NotificationDestination.MIND_RECORD -> Route.MindRecord
NotificationDestination.TIME_LETTER -> Route.TimeLetter
NotificationDestination.AFTERNOTE -> Route.Afternote
}
Loading