Yokan / rebuild
Course 1 8624561

LibraryAiringServiceTest.kt

composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/LibraryAiringServiceTest.kt

test / fixture192 lines
1package eu.friedcutlet.yokan.services.library23import eu.friedcutlet.yokan.database.*4import eu.friedcutlet.yokan.services.http.*5import kotlinx.coroutines.*6import kotlinx.coroutines.test.*7import kotlinx.serialization.json.*8import kotlin.test.*910@OptIn(ExperimentalCoroutinesApi::class)11class LibraryAiringServiceTest {12    private val now = 1_800_000_000_000L13    private fun database(count: Int = 1) = InMemoryYokanDatabase(emptySnapshot().copy(14        mangas = (1L..count.toLong()).map { DbManga(id = it, name = "Private title $it", link = "/title/$it", sourceId = 1,15            itemType = DbItemType.Anime, favorite = true) },16        tracks = (1L..count.toLong()).map { DbTrack(id = it, mangaId = it, mediaId = it + 100, syncId = 2,17            itemType = DbItemType.Anime, status = DbTrackStatus.Watching) },18        trackPreferences = listOf(DbTrackPreference(syncId = 2, oauth = "private-token")),19    ))20    private fun ids(request: HttpRequest) = DatabaseJson.parseToJsonElement(checkNotNull(request.body)).jsonObject21        .getValue("variables").jsonObject.getValue("ids").jsonArray.map { it.jsonPrimitive.int }22    private fun response(request: HttpRequest, at: Long = now + 100_000, missing: Boolean = false): HttpResponse {23        val mal = checkNotNull(request.body).contains("idMal_in")24        return HttpResponse(200, buildJsonObject { putJsonObject("data") { putJsonObject("Page") {25            putJsonArray("media") { ids(request).forEach { id -> add(buildJsonObject {26                put("id", if (mal) id + 1000 else id); put("idMal", if (mal) id else id + 1000); put("type", "ANIME")27                put("nextAiringEpisode", if (missing) JsonNull else buildJsonObject { put("airingAt", at / 1000); put("episode", 12) })28            }) } }29        } } }.toString())30    }31    private fun TestScope.service(db: InMemoryYokanDatabase, http: HttpService, timeout: Long = 20_000) =32        LibraryAiringService(db, http, backgroundScope, { now }, requestIntervalMillis = 0, requestTimeoutMillis = timeout)3334    @Test fun refreshIsExplicitAndPersistsPublicSchedulesWithoutSendingTitlesOrCredentials() = runTest {35        val db = database()36        val http = RecordingHttpService { response(it) }37        val service = service(db, http)38        assertTrue(http.requests.isEmpty())39        val before = db.snapshot()40        assertEquals(LibraryAiringRefreshResult(updated = 1), service.refresh())41        val saved = checkNotNull(db.manga(1))42        assertEquals(now + 100_000, saved.nextEpisodeAiringAt)43        assertEquals(12, saved.nextEpisodeNumber)44        assertEquals(now, saved.airingScheduleUpdatedAt)45        assertNotEquals(before, db.snapshot())46        val request = http.requests.single()47        assertEquals("https://graphql.anilist.co", request.url)48        assertEquals("POST", request.method)49        assertFalse(checkNotNull(request.body).contains("Private title"))50        assertFalse(checkNotNull(request.body).contains("private-token"))51        assertTrue(request.headers.keys.none { it.equals("Authorization", true) || it.equals("Cookie", true) })52        val restarted = InMemoryYokanDatabase(checkNotNull(decodeDatabaseSnapshot(encodeDatabaseSnapshot(db.snapshot()))))53        assertEquals(saved.nextEpisodeAiringAt, restarted.manga(1)?.nextEpisodeAiringAt)54    }5556    @Test fun requestsAreBatchedByPublicIdentityAndDuplicateSourceEntriesShareOneLookup() = runTest {57        val db = database(105)58        db.upsertTrack(checkNotNull(db.tracks().lastOrNull()).copy(mediaId = 101))59        val batches = mutableListOf<List<Int>>()60        val result = service(db, HttpService { batches += ids(it); response(it) }).refresh()61        assertEquals(listOf(50, 50, 4), batches.map { it.size })62        assertEquals(104, batches.flatten().toSet().size)63        assertEquals(105, result.updated)64        assertTrue(db.mangas().all { it.nextEpisodeAiringAt == now + 100_000 })65    }6667    @Test fun malAndExplicitMetadataIdsUseTheCorrectNamespaceAndUnsupportedEntriesMakeNoRequests() = runTest {68        val db = database(4)69        db.upsertTrack(checkNotNull(db.tracks().firstOrNull()).copy(syncId = 1))70        db.removeTrack(2)71        db.updateSettings(db.settings().copy(titleMetadata = listOf(DbTitleMetadata(2, "222", "MyAnimeList"))))72        db.upsertTrack(checkNotNull(db.tracks().firstOrNull { it.id == 3L }).copy(itemType = DbItemType.Manga))73        db.upsertManga(checkNotNull(db.manga(4)).copy(favorite = false))74        val http = RecordingHttpService { response(it) }75        val result = service(db, http).refresh()76        assertEquals(2, result.updated)77        assertEquals(1, result.unavailable)78        assertEquals(1, http.requests.size)79        assertTrue(checkNotNull(http.requests.single().body).contains("idMal_in"))80        assertEquals(setOf(101, 222), ids(http.requests.single()).toSet())81        assertEquals(0L, db.manga(3)?.nextEpisodeAiringAt)82        val unsupported = database()83        unsupported.removeTrack(1)84        assertEquals(LibraryAiringRefreshResult(unavailable = 1), service(unsupported, HttpService { error("Unexpected lookup") }).refresh())85    }8687    @Test fun sourceReplacementDeletionUnfavoriteAndRebindingRejectLateResponses() = runTest {88        for (mutation in listOf<(InMemoryYokanDatabase) -> Unit>(89            { db -> db.upsertManga(checkNotNull(db.manga(1)).copy(sourceId = 8, link = "/replacement")) },90            { db -> db.removeManga(1) },91            { db -> db.upsertManga(checkNotNull(db.manga(1)).copy(favorite = false)) },92            { db -> db.upsertTrack(checkNotNull(db.tracks().singleOrNull()).copy(mediaId = 999)) },93        )) {94            val db = database()95            val result = service(db, HttpService { request -> mutation(db); response(request) }).refresh()96            assertEquals(0, result.updated)97            assertTrue(db.manga(1)?.nextEpisodeAiringAt in listOf(null, 0L))98        }99    }100101    @Test fun providerFailuresAndMalformedResponsesPreserveSavedSchedules() = runTest {102        val malformed = listOf(103            HttpResponse(429, "rate limited"), HttpResponse(500, "failed"), HttpResponse(200, "not json"),104            HttpResponse(200, "{\"errors\":[{\"message\":\"private remote detail\"}],\"data\":{\"Page\":{\"media\":[]}}}"),105            HttpResponse(200, "{\"data\":{\"Page\":{\"media\":[{\"id\":101,\"type\":\"ANIME\"}]}}}"),106            HttpResponse(200, "{\"data\":{\"Page\":{\"media\":[{\"id\":101,\"type\":\"MANGA\",\"nextAiringEpisode\":null}]}}}"),107        )108        malformed.forEach { reply ->109            val db = database()110            db.upsertManga(checkNotNull(db.manga(1)).copy(nextEpisodeAiringAt = now + 1_000_000))111            assertEquals(1, service(db, HttpService { reply }).refresh().failed)112            assertEquals(now + 1_000_000, db.manga(1)?.nextEpisodeAiringAt)113        }114    }115116    @Test fun explicitNoScheduleClearsAnOldAnnouncementButMissingIdentityDoesNot() = runTest {117        val db = database()118        db.upsertManga(checkNotNull(db.manga(1)).copy(nextEpisodeAiringAt = now + 1_000_000))119        assertEquals(1, service(db, HttpService { HttpResponse(200, "{\"data\":{\"Page\":{\"media\":[]}}}") }).refresh().unavailable)120        assertEquals(now + 1_000_000, db.manga(1)?.nextEpisodeAiringAt)121        assertEquals(1, service(db, HttpService { response(it, missing = true) }).refresh().unavailable)122        assertEquals(0L, db.manga(1)?.nextEpisodeAiringAt)123    }124125    @Test fun streamingResponseBoundStopsTheTransferBeforeUnboundedAllocation() = runTest {126        val db = database()127        var chunks = 0128        val transport = object : HttpService {129            override suspend fun request(request: HttpRequest): HttpResponse = error("Must stream")130            override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {131                repeat(100) { chunks++; onChunk(ByteArray(32 * 1024)) }132                return HttpStreamResponse(200)133            }134        }135        assertEquals(1, service(db, transport).refresh().failed)136        assertEquals(9, chunks)137        assertEquals(0L, db.manga(1)?.nextEpisodeAiringAt)138    }139140    @Test fun timeoutIsAnOrdinaryFailureAndDoesNotKillTheProfileOrFutureRefreshes() = runTest {141        val db = database()142        var slow = true143        val service = service(db, HttpService { if (slow) delay(100); response(it) }, timeout = 5)144        assertEquals(1, service.refresh().failed)145        assertTrue(backgroundScope.isActive)146        slow = false147        assertEquals(1, service.refresh().updated)148    }149150    @Test fun callerCancellationJoinsItsTransferAndLeavesTheOwnerAvailable() = runTest {151        val db = database()152        val started = CompletableDeferred<Unit>()153        var finalized = false154        val service = service(db, HttpService { started.complete(Unit); try { awaitCancellation() } finally { finalized = true } })155        val request = async { service.refresh() }156        started.await()157        request.cancelAndJoin()158        assertTrue(finalized)159        assertTrue(backgroundScope.isActive)160        assertEquals(0L, db.manga(1)?.nextEpisodeAiringAt)161    }162163    @Test fun retiringOneProfileCancelsAndJoinsOnlyItsCapturedWork() = runTest {164        val a = database()165        val b = database()166        val owner = CoroutineScope(SupervisorJob() + StandardTestDispatcher(testScheduler))167        val started = CompletableDeferred<Unit>()168        var finalized = false169        val serviceA = LibraryAiringService(a, HttpService { started.complete(Unit); try { awaitCancellation() } finally { finalized = true } }, owner,170            { now }, requestIntervalMillis = 0)171        val request = async { serviceA.refresh() }172        try {173            started.await()174            owner.coroutineContext[Job]?.cancelAndJoin()175            request.join()176            assertTrue(finalized)177            assertTrue(request.isCancelled)178            assertEquals(0L, a.manga(1)?.nextEpisodeAiringAt)179            assertEquals(1, service(b, HttpService { response(it) }).refresh().updated)180            assertEquals(now + 100_000, b.manga(1)?.nextEpisodeAiringAt)181        } finally { owner.cancel(); request.cancelAndJoin() }182    }183184    @Test fun requestsAreRateSpacedAcrossBatches() = runTest {185        val db = database(51)186        val times = mutableListOf<Long>()187        val service = LibraryAiringService(db, HttpService { times += testScheduler.currentTime; response(it) }, backgroundScope,188            { now + testScheduler.currentTime }, requestIntervalMillis = 2100)189        assertEquals(51, service.refresh().updated)190        assertEquals(listOf(0L, 2100L), times)191    }192}193

Search chapters, reference and source filenames.