Quickcheck,使用一个函数来定义任意实例,该函数的结果取决于它的参数 [英] Quickcheck, defining Arbitrary instances using a function whose result depends on its arguments

查看:116
本文介绍了Quickcheck,使用一个函数来定义任意实例,该函数的结果取决于它的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数 arbExample 来产生一个随机的示例数据类型,这个数据类型取决于许多函数。

我试图通过做 quickCheck prop_example 来做一些属性测试,问题是我不知道如何使用 arbExample 示例定义一个任意实例。

我喜欢在指定 Gens quickCheck prop_example $ c>数据结构 arbExample 使用。

  data示例=示例
{myInt :: Int
,myList :: [String]
}派生(显示)

数据Gens = Gens
{gen1 :: Gen Int
,gen2 :: Gen String}

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

prop_example ::示例 - >属性
prop_example示例= do
let len = length(myList示例)
monadicIO $ do
- 运行程序的结果
成功< - 运行$( \e - > return False)示例

的成功案例True - > return()
False - >失败失败

实例任意示例,其中
任意= arbExample _ { - ??? - }


解决方案

使用 forAll combinator具有签名:

  forAll ::(Show a,Testable prop)=> Gen a  - > (a  - > prop) - >物业

一个简单的例子:

  import Test.QuickCheck 

genA :: Gen Int
genA =选择(-100,100)

genB :: Gen Int
genB =选择(1,100)

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

testA = quickCheck $ forAll genA prop_example
testB = quickCheck $ forAll genB prop_example

testA 会失败,但 testB 会成功。


I have a function arbExample to generate a random Example data type which depends on a numbers of functions.

I am trying to do some property testing by doing quickCheck prop_example, the problem is I don't know how to define an Arbitrary instance for Example which uses arbExample.

I like to be able run quickCheck prop_example while specifying the Gens data structure which arbExample uses.

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 _ {- ??? -}

解决方案

Use the forAll combinator which has the signature:

forAll :: (Show a, Testable prop) => Gen a -> (a -> prop) -> Property

A quick example:

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

testA will fail but testB will succeed.

这篇关于Quickcheck,使用一个函数来定义任意实例,该函数的结果取决于它的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆