如何在规范中包含外部源文件以指定度量?

时间:2011-06-17 10:13:13

标签: scala specs

我正在使用Specs2来编写测量库的规范。为了验证计算的度量,我有许多源文件,涵盖标准案例以及许多极端案例。我手动分析它们以了解确切的措施,但为了记录所有内容并自动化它,这应该是Specs2规范的一部分。

到目前为止,我将一些源文件复制到我的规范中,并将其作为字符串传递给验证方法。但是,这有缺点,内联代码不再被检查 - 外部文件由标准编译器验证,所以我确定它是有效的代码。传递文件名没有问题,但是我的规范应该在生成的HTML报告中包含源代码,而不仅仅是指向一个必须挖掘并手动查看的文件。在这里给你一些想法是我现在正在使用的代码


class CountVisitorSpec extends Specification { def is =

    "Given the ${com/example/Test1.java} source, the visitor should deliver a count of ${16}" ! new GivenThen {
        def extract(text: String) = {
            val (filename, count) = extract2(text)
            val file = classOf[CountVisitorSpec].getClassLoader.getResource(filename).getFile
            val src = Path(file).slurpString
            val visitor = new CountVisitor
            AstAnalyzer.runWith(src, visitor)
            visitor.count must_== count.toLong
        }
    }
}

是否有人有想法,如何指向外部文件以便将它们作为初始输入包含在生成的HTML报告中?

1 个答案:

答案 0 :(得分:2)

这应该只是封装你想要的东西:

 def withFile(name: String, description: String)(ex: String => Result) = {
   ("Given the ${"+file+"},"+description) ^ new GivenThen {
     def extract(text: String) = ex(text)
   } ^
   linkToSource(file)^ // if you want to create a Markdown link to the source file
   includeSource(file) // if you want to include the source code    
 } 

 def linkToSource(fileName: String)  = "[source]("+fileName+")"
 def includeSource(fileName: String) = "<code class=\"prettyprint\">"+Path(file).slurpString+"</code>"  

然后:

  class CountVisitorSpec extends Specification { def is =

     withFile("com/example/Test1.java", "the visitor should deliver a count of ${16}", 
              (text: String) => {
                val (filename, count) = extract2(text)
                val file = classOf[CountVisitorSpec].getClassLoader.getResource(filename).getFile
                val src = Path(file).slurpString
                val visitor = new CountVisitor
                AstAnalyzer.runWith(src, visitor)
                visitor.count must_== count.toLong
              }
      }
   }