由Haskell HSpec属性生成的随机测试

时间:2017-03-12 21:54:37

标签: haskell random quickcheck hspec

我正在使用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 

2 个答案:

答案 0 :(得分: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]
…

当然有更多的缺点,但这可能是一个简单的方法。但传递测试并不那么有趣,它是更重要的反例 - 默认显示。

答案 1 :(得分:1)

使用新版本的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