加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 18:16:32 所属栏目:安全 来源:网络整理
导读: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 { laz
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) }
  }
}

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

Delete: {"error":"IndexMissingException[[test_index] missing]","status":404}
Put: {"acknowledged":true}

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

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

解决方法

对我来说使用Await似乎没关系,因为如果你没有同步执行你的呼叫,你确实无法保证它会在你的内部测试开始之前完成(毕竟,能够在某个方法之前继续流程)完成是使用Futures的重点,对吧?:))

如果您需要确保某些事情的顺序,那么Await是执行此AFAIK的标准方法之一.也许您可以添加recoverWith以更优雅地处理超时.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读