-->

如何分辨快速检查,以产生一个参数唯一有效的列表索引?(How to tell QuickCheck

2019-08-01 07:46发布

说我想要写的一些单元测试(!!)功能。

my_prop xs n = ...

我想限制N到唯一有效的指标,我知道我可以做类似

my_prop xs n = (not.null) (drop n xs) ==> ...

但是,这使得它如此,绝大多数的产生情况是无效而被扔掉。 有没有一种方法,我可以做一些事情,以便快速检查产生xs第一列表,并使用它的值只生成有效的情况下n

Answer 1:

使用forAll ,你可以指定一个发电机为n依赖于早期的参数,如

my_prop (NonEmpty xs) = forAll (choose (0, length xs - 1)) $ \n -> ...


Answer 2:

你可以做一个发电机,仅创建有效的索引,并写入你的财产像

import Test.QuickCheck
import Test.QuickCheck.Gen
import System.Random

indices :: [a] -> Gen Int
indices xs = MkGen $ \sg _ -> fst $ randomR (0, length xs - 1) sg

my_prop :: [Char] -> Property
my_prop xs = not (null xs) ==> forAll (indices xs) (\i -> xs !! i /= '0')

消除Int的说法。



Answer 3:

正如丹尼尔·瓦格纳认为,一种可能性是创造我自己的数据类型,并给它一个Arbitrary实例。

data ListAndIndex a = ListAndIndex [a] Int deriving (Show)

instance Arbitrary a => Arbitrary (ListAndIndex a) where
   arbitrary = do
     (NonEmpty xs) <- arbitrary
     n  <- elements [0..(length xs - 1)]
     return $ ListAndIndex xs n

NonEmpty是从自定义类型Test.QuickCheck.Modifiers产生非空列表。



文章来源: How to tell QuickCheck to generate only valid list indices for a parameter?