快速检查,使用函数定义任意实例,其结果取决于其参数

Bil*_*ain 0 testing haskell generator quickcheck

我有一个函数arbExample来生成一个随机Example数据类型,它取决于许多函数.

我试图通过做一些属性测试quickCheck prop_example,问题是我不知道如何定义一个Arbitrary实例Example使用arbExample.

我喜欢quickCheck prop_example在指定使用的Gens数据结构时运行arbExample.

data Example = Example
    { myInt  :: Int 
    , myList :: [String]
    } deriving (Show)

data Gens =  Gens
    { gen1 :: Gen Int
    , gen2 :: Gen String }

arbExample :: Gens -> Gen Example
arbExample gens = do 
    i  <- gen1 gens 
    xs <- vectorOf i (gen2 gens)
    return Example{myInt=i, myList=xs}

prop_example :: Example -> Property
prop_example example =  do
    let len = length (myList example) 
    monadicIO $ do 
        -- result of running some program
        successful <- run $ (\e -> return False) example  
        case successful of
            True  -> return ()
            False -> fail "failure "

instance Arbitrary Example where
    arbitrary =  arbExample _ {- ??? -}
Run Code Online (Sandbox Code Playgroud)

Eri*_*ikR 7

使用forAll具有签名的组合器:

forAll :: (Show a, Testable prop) => Gen a -> (a -> prop) -> Property
Run Code Online (Sandbox Code Playgroud)

一个简单的例子:

import Test.QuickCheck

genA :: Gen Int
genA = choose (-100,100)

genB :: Gen Int
genB = choose (1,100)

prop_example :: Int -> Bool
prop_example n = n > 0

testA = quickCheck $ forAll genA prop_example
testB = quickCheck $ forAll genB prop_example
Run Code Online (Sandbox Code Playgroud)

testA会失败但testB会成功.