【问题标题】:How to set a timeout for Async suite in Scalatest?如何在 Scalatest 中为异步套件设置超时?
【发布时间】:2021-04-20 11:51:12
【问题描述】:

考虑以下单元测试示例:

class MySpec extends AsyncFlatSpec {

  "this" should "fail after some timeout" in {
    val resultFuture: Future[_] = Promise().future
    
    for (result <- resultFuture) yield {
      assert(result == ???) // some assertions
      assert(result == ???) // some assertions
      assert(result == ???) // some assertions
    }
  }
}

问题

如果resultFuture 从不 完成,则测试套件也永远不会完成。 据我了解,这是由于SerialExecutionContext 的实现方式所致。

问题

有什么“好”的方法可以为这种测试设置超时,这样如果未来没有完成,测试就会失败,而不是永远阻塞整个测试套件?


更新和澄清

虽然解决方案 https://stackoverflow.com/a/65746143/96766https://stackoverflow.com/a/65749840/96766(由 @matthias-berndt 和 @tomer-shetah 发布)适用于线程阻塞的情况,但这并不是我想要的。

让我对这个问题做一个重要的澄清。在我的情况下,未来最终不会完成,但永远不会完成。例如,当从从未解析的Promise 获得Future 时(没有人调用successfailure)。在这种情况下,建议的解决方案仍然会无限阻塞。

有没有办法为AsyncSpec 解决这个问题,而无需使用真正的基于池的执行上下文和Await-ing 未来?

【问题讨论】:

标签: scala scalatest asynctest


【解决方案1】:

使用来自scalatesteventually

  1. 扩展Eventually
  2. 使用以下代码设置检查的超时和间隔
 import scala.concurrent.duration._
 eventually(timeout(1 minutes), interval(5 seconds)) {
    resultFuture.futureValue shouldBe ???
}

【讨论】:

  • 看起来很有希望,但它似乎对我没有任何帮助。我设置了 2 秒超时,但测试仍然被阻止。
【解决方案2】:
【解决方案3】:

您可以使用特征TimeLimits。例如,你可以有一个测试类:

class MySpec extends AsyncFlatSpec with TimeLimits {

  "this" should "fail" in {
    failAfter(2.seconds) {
      val resultFuture: Future[_] = Future {
        Thread.sleep(3000)
      }

      assert(true)
    }
  }

  "this" should "pass" in {
    failAfter(2.seconds) {
      val resultFuture: Future[_] = Future {
        Thread.sleep(1000)
      }

      assert(true)
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    • 2019-08-24
    • 2020-07-16
    • 2011-11-24
    • 1970-01-01
    • 2018-10-10
    • 2013-07-16
    相关资源
    最近更新 更多