在scala规范中同步before/after方法?

5 scala elasticsearch

class TokenSearchTest extends Specification {
  "Dummy test should" should {
    "work" in new TokensSearch {
      // Do things that assume that the
      // before method has done its work.

      true must beTrue
    }
  }
}

trait TokensSearch extends BeforeAfter {
  lazy val elasticSearchTestHost = "http://localhost:9200/"
  lazy val elasticSearchTestIndex = elasticSearchTestHost + "test_index"
  def before = {
    println("Setting up tokens index.")
    val resultFuture = WS.url(elasticSearchTestIndex).put("")
    Await.result(resultFuture, 5 seconds)
    resultFuture.map{ response => println("Put: " + response.json) }
  }
  def after = {
    println("Deleting tokens index.")
    val resultFuture = WS.url(elasticSearchTestIndex).delete()
    Await.result(resultFuture, 5 seconds)
    resultFuture.map{ response => println("Delete: " + response.json) }
  }
}
Run Code Online (Sandbox Code Playgroud)

如果我不包括Await.result,则before和after方法有时会交错,导致put和delete没有以正确的顺序发生(在put发生之前尝试删除):

Delete: {"error":"IndexMissingException[[test_index] missing]","status":404}
Put: {"acknowledged":true}
Run Code Online (Sandbox Code Playgroud)

我是scala的新手,所以不知道这是否是实现这种并发性的最佳方法,或者我是否误解了该测试的运行方式.

在这里使用等待好吗?有更常见的做法吗?还有其他意见吗?

Ash*_*ynd 4

对我来说Await,在这里使用似乎没问题,因为如果您不before同步进行调用,您确实无法保证它会在内部测试开始之前完成(毕竟,能够在某个方法完成之前继续流程是使用 Futures 的全部意义,对吧?:))

如果您需要确保事物的特定顺序,那么这Await是执行此操作的标准方法之一。也许您可以添加recoverWith更优雅地处理超时。