Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Attempt to cancel the running test in case of a timeout #3969

Merged
merged 1 commit into from
Jan 26, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 23 additions & 7 deletions tests/shared/src/test/scala/cats/effect/Runners.scala
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,10 @@ trait Runners extends SpecificationLike with TestInstances with RunnersPlatform
Execution.result(test(Ticker(TestContext())))

def real[A: AsResult](test: => IO[A]): Execution =
Execution.withEnvAsync(_ => timeout(test.unsafeToFuture()(runtime()), executionTimeout))
Execution.withEnvAsync { _ =>
val (fut, cancel) = test.unsafeToFutureCancelable()(runtime())
timeout(fut, cancel, executionTimeout)
}

/*
* Hacky implementation of effectful property testing
Expand All @@ -53,7 +56,8 @@ trait Runners extends SpecificationLike with TestInstances with RunnersPlatform
def realWithRuntime[A: AsResult](test: IORuntime => IO[A]): Execution =
Execution.withEnvAsync { _ =>
val rt = runtime()
timeout(test(rt).unsafeToFuture()(rt), executionTimeout)
val (fut, cancel) = test(rt).unsafeToFutureCancelable()(rt)
timeout(fut, cancel, executionTimeout)
}

def completeAs[A: Eq: Show](expected: A)(implicit ticker: Ticker): Matcher[IO[A]] =
Expand Down Expand Up @@ -100,17 +104,29 @@ trait Runners extends SpecificationLike with TestInstances with RunnersPlatform
def mustEqual(a: A) = fa.flatMap { res => IO(res must beEqualTo(a)) }
}

private def timeout[A](f: Future[A], duration: FiniteDuration): Future[A] = {
private def timeout[A](
f: Future[A],
cancel: () => Future[Unit],
duration: FiniteDuration): Future[A] = {
val p = Promise[A]()
val r = runtime()
implicit val ec = r.compute

val cancel =
r.scheduler.sleep(duration, { () => p.tryFailure(new TestTimeoutException); () })
val cancelTimer =
r.scheduler
.sleep(
duration,
{ () =>
if (p.tryFailure(new TestTimeoutException)) {
cancel()
()
}
})

f.onComplete { result =>
p.tryComplete(result)
cancel.run()
if (p.tryComplete(result)) {
cancelTimer.run()
}
}

p.future
Expand Down
Loading