【问题标题】:Random tests generated by Haskell HSpec propertyHaskell HSpec 属性生成的随机测试
【发布时间】:2017-03-12 21:54:37
【问题描述】:

我正在使用 Hspec 和 Quickcheck http://hspec.github.io/ 运行测试

提供的执行随机测试用例的示例是

it "returns the first element of an *arbitrary* list" $
      property $ \x xs -> head (x:xs) == (x :: Int)

有关联的输出:

returns the first element of an *arbitrary* list 

如何查看为测试生成的实际运行时值?因此,在上面的示例中,示例所需的输出将包括为 x 和 xs 传递的值,例如:

returns the first element of an *arbitrary* list 
    \x xy head (x:xs) == (x :: Int) with x = 'a' and xs = "bc" holds 

【问题讨论】:

  • 您可以使用 debug.trace 作为快速而肮脏的解决方案
  • 您能否详细解释一下您为什么打算这样做?

标签: haskell random quickcheck hspec


【解决方案1】:

没有。 Hspec 的运行器禁用任何 QuickCheck 输出。此外,随机测试会产生很多噪音。但是,有一个解决方法:

import Test.Hspec
import Test.QuickCheck
import Test.QuickCheck.Test (isSuccess)

verboseProperty :: Testable prop => prop -> Expectation
verboseProperty p = verboseCheckResult p >>= (`shouldBe` True) . isSuccess

main = hspec $ describe "head" $
  it "returns the first element of an *arbitrary* list" $
    verboseProperty $ \x xs -> head (x:xs) == (x :: Int)

但是,格式会有所不同:

returns the first element of an *arbitrary* list
Passed:  
0
[]
Passed: 
1
[-1]
Passed:  
2
[-2]
Passed:  
3
[]
Passed:  
0
[]
Passed:  
1
[2,-5,5,5]
Passed:  
0
[-3,-1,-5,3]
…

当然还有更多的缺点,但这可能是一个简单的出路。但是通过测试并没有那么有趣,更重要的是反例——默认显示。

【讨论】:

    【解决方案2】:

    使用新版本的 HSpec (>= 2.5.0) 你只需要这样写:

    it "returns the first element of an *arbitrary* list" $
      verbose $ \x xs -> head (x:xs) == (x :: Int)
    

    看这里的讨论:https://github.com/hspec/hspec/issues/257

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多