AutomaticUpdateConditionsViewModelTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/settings/library/AutomaticUpdateConditionsViewModelTest.kt
1package eu.friedcutlet.yokan.ui.screens.settings.library23import eu.friedcutlet.yokan.ui.ViewModelTestHost4import eu.friedcutlet.yokan.data.*5import eu.friedcutlet.yokan.database.*6import eu.friedcutlet.yokan.services.scheduling.*7import kotlinx.coroutines.*8import kotlinx.coroutines.test.*9import kotlin.test.*1011@OptIn(ExperimentalCoroutinesApi::class)12class AutomaticUpdateConditionsViewModelTest {13 private val host = ViewModelTestHost()14 private val dispatcher = host.dispatcher15 @AfterTest fun after() = host.close()1617 @Test fun policyChangesCancelAndJoinOldTelemetryAndPublishTheNewCheck() = runTest(dispatcher) {18 val repo = DefaultYokanRepository(InMemoryYokanDatabase(emptySnapshot()))19 val settings = SettingsStore(repo, backgroundScope) {}20 val requests = mutableListOf<Boolean>()21 var finalized = false22 val gate = AutomaticUpdateGate(read = { power ->23 requests += power24 if (!power) try { awaitCancellation() } finally { finalized = true }25 UpdateDeviceConditions(connected = true, externalPower = true)26 }, clock = { 100 })27 val vm = host.create { AutomaticUpdateConditionsViewModel(settings, gate, dispatcher) }28 runCurrent()29 assertTrue(requests.isEmpty(), "Opening legacy defaults does not request device telemetry")30 settings.updateDb { db -> db.copy(features = db.features.copy(library = db.features.library.copy(31 deviceConstraints = DbAutomaticUpdateConstraints(DbUpdateNetwork.Connected)))) }32 runCurrent()33 assertTrue(vm.state.value.checking)34 settings.updateDb { db -> db.copy(features = db.features.copy(library = db.features.library.copy(35 deviceConstraints = DbAutomaticUpdateConstraints(DbUpdateNetwork.Connected, requireExternalPower = true)))) }36 runCurrent()37 assertTrue(finalized)38 assertEquals(listOf(false, true), requests)39 assertFalse(vm.state.value.checking)40 assertTrue(checkNotNull(vm.state.value.admission).allowed)41 }4243 @Test fun unrelatedSettingsDoNotReprobeAndExplicitChecksBypassTheCache() = runTest(dispatcher) {44 val db = emptySnapshot().let { it.copy(settings = it.settings.copy(features = it.settings.features.copy(library = it.settings.features.library.copy(45 deviceConstraints = DbAutomaticUpdateConstraints(DbUpdateNetwork.Connected))))) }46 val repo = DefaultYokanRepository(InMemoryYokanDatabase(db))47 val settings = SettingsStore(repo, backgroundScope) {}48 var calls = 049 val gate = AutomaticUpdateGate(read = { calls++; UpdateDeviceConditions(connected = true) }, clock = { 100 })50 val vm = host.create { AutomaticUpdateConditionsViewModel(settings, gate, dispatcher) }51 runCurrent()52 assertEquals(1, calls)53 settings.updateDb { it.copy(incognitoMode = !it.incognitoMode) }54 runCurrent()55 assertEquals(1, calls)56 vm.refresh()57 runCurrent()58 assertEquals(2, calls)59 assertFalse(vm.state.value.checking)60 }61}62