Skip to content

Instantly share code, notes, and snippets.

@justinhj
Last active July 18, 2017 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinhj/1de64d25af06dd2c38289c680c3d5a3c to your computer and use it in GitHub Desktop.
Save justinhj/1de64d25af06dd2c38289c680c3d5a3c to your computer and use it in GitHub Desktop.
import org.scalatest._
import scala.concurrent.{Future, TimeoutException}
import scala.concurrent.duration._
class TestFutureUtil extends AsyncFlatSpec with Matchers with OptionValues with Inside with Inspectors {
implicit override def executionContext = scala.concurrent.ExecutionContext.Implicits.global
"futureWithTimeout" should "complete the users future when it returns before the timeout" in {
def myFuture = Future[Int] {
//println(s"starting user future ${System.currentTimeMillis()}")
Thread.sleep((2 seconds).toMillis)
//println(s"user future done ${System.currentTimeMillis()}")
100
}
FutureUtil.futureWithTimeout(myFuture, 3 seconds).map {
result => if(result == 100) succeed else fail
}
}
it should "not complete the future when it returns after the timeout" in {
lazy val myFuture = Future[Int] {
//println(s"user future waiting 4 seconds ${System.currentTimeMillis()}")
Thread.sleep((4 seconds).toMillis)
//println(s"user future done at ${System.currentTimeMillis()}")
100
}
recoverToSucceededIf[TimeoutException] {
FutureUtil.futureWithTimeout(myFuture, 2 seconds)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment