@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) package eu.friedcutlet.yokan.services.scheduling import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withContext import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse class BackgroundTaskCompletionTest { @Test fun expiryBeforeDispatchStillCompletesOnceWithoutRunningWork() = runTest { var executed = false val completions = mutableListOf() val job = launchCompletingBackgroundTask(this, { executed = true; ProfileWorkResult.Skipped }, completions::add) job.cancelAndJoin() testScheduler.runCurrent() assertFalse(executed); assertEquals(listOf(false), completions) } @Test fun expiryWaitsForFinalizersBeforeReportingFailure() = runTest { val entered = CompletableDeferred(); val release = CompletableDeferred() val completions = mutableListOf() var finalized = false val job = launchCompletingBackgroundTask(this, { try { entered.complete(Unit); awaitCancellation() } finally { withContext(NonCancellable) { release.await(); finalized = true } } }, { completions += it; assertEquals(true, finalized) }) entered.await(); job.cancel(); testScheduler.runCurrent() assertEquals(emptyList(), completions) release.complete(Unit); job.join() assertEquals(listOf(false), completions) } @Test fun completedAndStaleTasksSucceedWhileRecoverableFailuresDoNot() = runTest { val outcomes = listOf( ProfileWorkResult.Completed(PeriodicTaskOutcome(PeriodicTaskStatus.Completed, "Done")), ProfileWorkResult.Completed(PeriodicTaskOutcome(PeriodicTaskStatus.Skipped, "Disabled")), ProfileWorkResult.Skipped, ProfileWorkResult.Completed(PeriodicTaskOutcome(PeriodicTaskStatus.Failed, "Failed")), ProfileWorkResult.Retry, ) val completions = mutableListOf() for (outcome in outcomes) launchCompletingBackgroundTask(this, { outcome }, completions::add).join() assertEquals(listOf(true, true, true, false, false), completions) } @Test fun taskExceptionsCompleteWithFailureAndLeaveTheHostAlive() = runTest { val parent = SupervisorJob() val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler)) val completions = mutableListOf() launchCompletingBackgroundTask(scope, { error("Task failure") }, completions::add).join() assertEquals(listOf(false), completions) assertEquals(true, parent.isActive) launchCompletingBackgroundTask(scope, { ProfileWorkResult.Skipped }, completions::add).join() assertEquals(listOf(false, true), completions) parent.cancelAndJoin() } }