package eu.friedcutlet.yokan.ui.screens.reader import kotlin.test.AfterTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNull import kotlin.test.assertSame import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.joinAll import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.flow.toList class ReaderPageDownloadProgressTest { @Test fun unchangedPercentKeepsTheSameSnapshot() { ReaderPageDownloadProgress.report("page", 501, 1_000) val snapshot = ReaderPageDownloadProgress.progress.value ReaderPageDownloadProgress.report("page", 509, 1_000) assertSame(snapshot, ReaderPageDownloadProgress.progress.value) } @Test fun concurrentDownloadsDoNotLoseEachOthersProgress() = runTest { (0 until 100).map { index -> launch(Dispatchers.Default) { ReaderPageDownloadProgress.report("page-$index", 50, 100) } }.joinAll() repeat(100) { assertEquals(0.5f, ReaderPageDownloadProgress.progress.value["page-$it"]) } } @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) @Test fun pageSubscriberDoesNotReceiveOtherPagesUpdates() = runTest { val values = mutableListOf() backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { ReaderPageDownloadProgress.forUrl("watched").toList(values) } ReaderPageDownloadProgress.report("other", 10, 100) ReaderPageDownloadProgress.report("watched", 25, 100) ReaderPageDownloadProgress.report("other", 50, 100) ReaderPageDownloadProgress.clear("watched") assertEquals(listOf(null, 0.25f, null), values) } @AfterTest fun tearDown() { ReaderPageDownloadProgress.progress.value.keys.forEach(ReaderPageDownloadProgress::clear) } @Test fun reportsRatioAndClearsOnCompletion() { ReaderPageDownloadProgress.report("https://example/page1.jpg", receivedBytes = 250, totalBytes = 1_000) assertEquals(0.25f, ReaderPageDownloadProgress.progress.value["https://example/page1.jpg"]) ReaderPageDownloadProgress.report("https://example/page1.jpg", receivedBytes = 1_000, totalBytes = 1_000) assertNull(ReaderPageDownloadProgress.progress.value["https://example/page1.jpg"]) } @Test fun ignoresUnknownTotalsAndSupportsExplicitClear() { ReaderPageDownloadProgress.report("https://example/page2.jpg", receivedBytes = 10, totalBytes = null) ReaderPageDownloadProgress.report("https://example/page2.jpg", receivedBytes = 10, totalBytes = 0) assertNull(ReaderPageDownloadProgress.progress.value["https://example/page2.jpg"]) ReaderPageDownloadProgress.report("https://example/page3.jpg", receivedBytes = 900, totalBytes = 1_000) ReaderPageDownloadProgress.clear("https://example/page3.jpg") assertNull(ReaderPageDownloadProgress.progress.value["https://example/page3.jpg"]) } }