sbt 条件 if else 样式配置

sbt conditional if else style configuration

我希望能够使用命令行在并行和串行执行 Scala 测试之间切换。

使用 "test.par" 系统的工作示例 属性:

val parallelTestOpt = Option(System.getProperty("test.par"))

testOptions in IntegrationTest += Tests.Argument(
  //Configure distributor's pool size
  parallelTestOpt.map(count =>s"-P$count").getOrElse("-P1")
)

lazy val root = (project in file("."))
  .configs(IntegrationTest)
  .settings(Defaults.itSettings,
      //If suites are executed in parallel
      IntegrationTest / parallelExecution := parallelTestOpt.exists(_ != "1"),
      IntegrationTest / testForkedParallel := parallelTestOpt.exists(_ != "1")
  )

"problematic" 部分是 parallelTestOpt.map(count =>s"-P$count").getOrElse("-P1")。当未指定 "test.par" 属性 时,我不想提供默认值“-P1”。实现该目标的最佳做法是什么?

也许整个概念是错误的,我应该用不同的方式来做?

作为替代方法,考虑将并行性问题分离到 single-argument custom command

commands += Command.single("testpar") { (state, numOfThreads) =>
  s"""set IntegrationTest / testOptions  += Tests.Argument("-P$numOfThreads")"""::
     "set IntegrationTest / parallelExecution := true" ::
     "set IntegrationTest / testForkedParallel := true" ::
     "IntegrationTest / test" :: state
}

并执行,比方说,testpar 6 到 运行 有 6 个线程池。


解决注释,为了编译时安全尝试

commands += Command.single("testpar") { (state, numOfThreads) =>
  val extracted = Project.extract(state)
  val stateWithParallel= extracted.appendWithSession(
    Seq(
      IntegrationTest / testOptions  += Tests.Argument(s"-P$numOfThreads"),
      IntegrationTest / parallelExecution := true,
      IntegrationTest / testForkedParallel := true,
    ),
    state
  )
  extracted.runTask(IntegrationTest / test, stateWithParallel)
  state
}