ProcessLogger解析“ sbt测试”结果

时间:2019-03-20 03:37:23

标签: scala sbt

我试图给Scala一个目录,以在其上运行sbt test,然后获取其返回的行。然后,我将继续查看有关testSuite数量及其失败或成功的信息。这将涉及使用regex。它将失败,并显示以下错误:

package custom.processLogger

import java.io.File


import scala.sys.process.{Process, ProcessLogger}

object SbtLogger extends App{

  val baseDir = new File("/Users/gakuo/Documents/ThesisProject/ShoppingCartExample")
  val assemble = Process(Seq("sbt", "test","run"), baseDir).!!.trim
  println(assemble)
  val (out, err) = (new StringBuffer(), new StringBuffer())
  val logger = ProcessLogger(
      out.append(_),
      err.append(_)
  )
 println(out.toString)
 println(err.toString)

}

错误如下:

Exception in thread "main" java.lang.RuntimeException: Nonzero exit value: 1
    at scala.sys.package$.error(package.scala:30)
    at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.slurp(ProcessBuilderImpl.scala:138)
    at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.$bang$bang(ProcessBuilderImpl.scala:108)
    at custom.processLogger.SbtLogger$.delayedEndpoint$custom$processLogger$SbtLogger$1(SbtLogger.scala:13)
    at custom.processLogger.SbtLogger$delayedInit$body.apply(SbtLogger.scala:8)
    at scala.Function0.apply$mcV$sp(Function0.scala:39)
    at scala.Function0.apply$mcV$sp$(Function0.scala:39)
    at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:17)
    at scala.App.$anonfun$main$1$adapted(App.scala:80)
    at scala.collection.immutable.List.foreach(List.scala:392)
    at scala.App.main(App.scala:80)
    at scala.App.main$(App.scala:78)
    at custom.processLogger.SbtLogger$.main(SbtLogger.scala:8)
    at custom.processLogger.SbtLogger.main(SbtLogger.scala)

Process finished with exit code 1

1 个答案:

答案 0 :(得分:0)

请注意,!!!之间的区别在于当进程以非零值退出时引发异常:

def !!(log: ProcessLogger): String

  

开始该过程   由此构建器表示的对象,将阻止直到退出并返回   输出为字符串。标准错误发送到提供的   ProcessLogger。如果退出代码不为零,则会引发异常。

def !(log: ProcessLogger): Int

  

启动此构建器代表的进程,直到退出为止一直阻塞,   并返回退出代码。标准输出和错误被发送到   给定ProcessLogger。

测试失败将导致返回值非零,因此!!将引发异常。另一方面,!不会抛出,因此这是一个可能的解决方案:

import java.io.File
import scala.sys.process.{Process, ProcessLogger}

object SbtLogger extends App{
  val (out, err) = (new StringBuffer(), new StringBuffer())
  val logger = ProcessLogger(
    line => out.append(line + '\n'),
    line => err.append(line + '\n')
  )

  val baseDir = new File("/Users/gakuo/Documents/ThesisProject/ShoppingCartExample")
  Process(Seq("sbt", "test"), baseDir) ! logger

  println(out)
}

请注意我们如何将logger传递给

Process(Seq("sbt", "test"), baseDir) ! logger

这将使out存储最终过程的输出。