package eu.friedcutlet.yokan.database import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.launch import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest @OptIn(ExperimentalCoroutinesApi::class) class BrowserSnapshotPersistenceTest { @Test fun steadyChangesStillSaveAtMaxWaitThenOnceAfterQuiet() = runTest { val changes = MutableSharedFlow() var writes = 0 backgroundScope.launch { coalesceWrites(changes, quietMillis = 1_000L, maxWaitMillis = 10_000L) { writes++ } } runCurrent() repeat(50) { change -> // one change every 500 ms for 25 s: a plain debounce never fires changes.emit(change) advanceTimeBy(500L) } assertEquals(2, writes) advanceTimeBy(1_001L) assertEquals(3, writes) advanceTimeBy(60_000L) assertEquals(3, writes) } @Test fun storedSnapshotIsCompactAndOmitsPageCache() { val snapshot = seedDatabaseSnapshot().copy( mangas = listOf(DbManga(id = 1, name = "Kept")), pageCache = listOf(DbChapterPageUrls(chapterId = 1, urls = listOf("https://example.test/1.png"))), ) val raw = encodeBrowserSnapshot(snapshot) assertFalse(raw.contains('\n')) assertEquals(snapshot.copy(pageCache = emptyList()), decodeDatabaseSnapshot(raw)) } }