Skip to content

Commit a8de3e0

Browse files
committed
Retry cancelable test in cancellationunittest
1 parent 1b67399 commit a8de3e0

File tree

1 file changed

+29
-3
lines changed

1 file changed

+29
-3
lines changed

cats-effects/src/test/scala/com/baeldung/scala/catseffects/CancellationUnitTest.scala

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,39 @@ import cats.effect.kernel.CancelScope.Cancelable
44
import cats.effect.{IO, Resource}
55
import cats.effect.unsafe.implicits.global
66
import cats.implicits.catsSyntaxTuple2Parallel
7+
import org.scalatest.{Failed, Outcome, Retries, Canceled}
78
import org.scalatest.matchers.should.Matchers
9+
import org.scalatest.tags.Retryable
810
import org.scalatest.wordspec.AnyWordSpec
9-
import java.util.concurrent.atomic.AtomicBoolean
1011

12+
import java.util.concurrent.atomic.AtomicBoolean
1113
import scala.concurrent.duration.DurationInt
1214

13-
class CancellationUnitTest extends AnyWordSpec with Matchers {
15+
@Retryable
16+
class CancellationUnitTest extends AnyWordSpec with Matchers with Retries {
17+
18+
val retries = 5
19+
20+
override def withFixture(test: NoArgTest): Outcome = {
21+
if (isRetryable(test)) withFixture(test, retries)
22+
else super.withFixture(test)
23+
}
24+
25+
def withFixture(test: NoArgTest, count: Int): Outcome = {
26+
val outcome = super.withFixture(test)
27+
outcome match {
28+
case Failed(_) | Canceled(_) =>
29+
if (count == 1) super.withFixture(test)
30+
else {
31+
println(
32+
s"Retrying SchedulerUnitTest flaky test `${test.name}`, Attempts remaining: ${count - 1}"
33+
)
34+
// scheduling the retry after 1 second
35+
withRetry(1.seconds)(withFixture(test, count - 1))
36+
}
37+
case other => other
38+
}
39+
}
1440

1541
"Cancellation" should {
1642
"cancel the fiber directly and execute the action on cancellation" in {
@@ -87,7 +113,7 @@ class CancellationUnitTest extends AnyWordSpec with Matchers {
87113
val flag = new AtomicBoolean(false)
88114
val ioa = IO.blocking {
89115
while (!flag.get()) {
90-
Thread.sleep(15)
116+
Thread.sleep(25)
91117
println(s"counter = $counter")
92118
counter += 1
93119
}

0 commit comments

Comments
 (0)