Skip to content

Commit

Permalink
Missing test for TimerManager (#69)
Browse files Browse the repository at this point in the history
  • Loading branch information
wkal-pubnub authored Sep 6, 2024
1 parent 1e73d44 commit c987d95
Showing 1 changed file with 41 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import kotlin.time.Duration.Companion.seconds

class TimerManagerTest {
@Test
fun cancelOneOff() = runTest {
fun destroy_oneOffTask() = runTest {
val timerManager = createTimerManager()
val completable1 = CompletableDeferred<Unit>()
val completable2 = CompletableDeferred<Unit>()
Expand All @@ -41,7 +41,7 @@ class TimerManagerTest {
}

@Test
fun cancelPeriodic() = runTest {
fun destroy_periodicTask() = runTest {
val timerManager = createTimerManager()
val counter = atomic(0)
val counter2 = atomic(0)
Expand Down Expand Up @@ -71,4 +71,43 @@ class TimerManagerTest {
assertEquals(1, counter.value)
assertEquals(3, counter2.value)
}

@Test
fun cancelSingleTasks() = runTest {
val timerManager = createTimerManager()
val counter = atomic(0)
val counter2 = atomic(0)
val counter3 = atomic(0)

// this should run 1 time
val timer1 = timerManager.runWithDelay(1.seconds) {
counter.incrementAndGet()
}
// this should run 3 times
// let's also try to start it from a background thread to test if cancellation works in that case
val timer2 = withContext(Dispatchers.Default) {
timerManager.runPeriodically(0.5.seconds) {
counter2.incrementAndGet()
}
}
// this should not run
val timer3 = timerManager.runWithDelay(2.seconds) {
counter3.incrementAndGet()
}

withContext(Dispatchers.Default) {
delay(1.75.seconds)
}
timer1.cancel()
timer2.cancel()
timer3.cancel()

withContext(Dispatchers.Default) {
delay(1.seconds)
}

assertEquals(1, counter.value)
assertEquals(3, counter2.value)
assertEquals(0, counter3.value)
}
}

0 comments on commit c987d95

Please sign in to comment.