@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) package eu.friedcutlet.yokan.ui.screens.together import eu.friedcutlet.yokan.database.DbSyncPreference import eu.friedcutlet.yokan.database.InMemoryYokanDatabase import eu.friedcutlet.yokan.database.emptySnapshot import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.services.http.ProfileTestEngine import eu.friedcutlet.yokan.services.together.HubSession import eu.friedcutlet.yokan.services.together.ProfileTogetherSession import eu.friedcutlet.yokan.ui.ViewModelTestHost import kotlin.test.AfterTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNull import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest import org.jetbrains.compose.resources.getString import yokan.composeapp.generated.resources.Res import yokan.composeapp.generated.resources.together_login_to_join class TogetherViewModelTest { private val host = ViewModelTestHost() @AfterTest fun tearDown() = host.close() @Test fun joinConnectsTheRoomAndLeaveClearsIt() = runTest { val engine = ProfileTestEngine(host.dispatcher) { awaitCancellation() } val together = together(backgroundScope) { engine } val vm = host.create { TogetherViewModel(together, { Hub }, host.dispatcher) } vm.join("abc") runCurrent() assertEquals("ABC", vm.state.value.client?.code) assertEquals("ABC", vm.state.value.room?.code) assertNull(vm.state.value.message) vm.leave() runCurrent() assertNull(together.client.value) assertNull(vm.state.value.room) assertEquals(1, engine.closeCalls) } @Test fun joinWithoutHubAsksToLogInAndDismissClearsTheMessage() = runTest { val together = together(backgroundScope) { error("No hub, no socket") } val vm = host.create { TogetherViewModel(together, { null }, host.dispatcher) } vm.join("ABC") runCurrent() assertEquals(getString(Res.string.together_login_to_join), vm.state.value.message) assertNull(together.client.value) vm.dismissMessage() assertNull(vm.state.value.message) } @Test fun joinFailureBecomesAMessage() = runTest { val together = together(backgroundScope) { error("Hub unreachable") } val vm = host.create { TogetherViewModel(together, { Hub }, host.dispatcher) } vm.join("ABC") runCurrent() assertEquals("Hub unreachable", vm.state.value.message) assertNull(vm.state.value.room) } private fun together(scope: CoroutineScope, engine: (ProfileId) -> ProfileTestEngine) = ProfileTogetherSession(ProfileId.Default, database(), scope, engine) private fun database() = InMemoryYokanDatabase(emptySnapshot()).also { it.upsertSyncPreference(Preference) } private companion object { val Preference = DbSyncPreference(syncId = 1, server = "https://hub.test", authToken = "owner-token", deviceId = "owner-device") val Hub = HubSession("https://hub.test", "owner-token", "owner-device") } }