简体   繁体   English

如何告诉QuickCheck只为参数生成有效的列表索引?

[英]How to tell QuickCheck to generate only valid list indices for a parameter?

Say I want to write some unit tests for the (!!) function. 假设我想为(!!)函数编写一些单元测试。

my_prop xs n = ...

I want to restrict n to only valid indexes and I know I could do something like 我想将n限制为仅有效的索引,我知道我可以做类似的事情

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

But this makes it so that the vast majority of the generated cases are invalid and get thrown away. 但这使得绝大多数生成的案例都无效并被抛弃。 Is there a way I can set things up so that QuickCheck generates the xs list first and uses its value to generate only valid cases of n ? 有没有办法设置,以便QuickCheck首先生成xs列表并使用其值仅生成n有效情况?

使用forAll ,您可以为n指定一个生成器 ,它取决于先前的参数,例如

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

You can make a generator that only creates valid indices and write your property like 你可以创建一个只生成有效索引的生成器并编写你的属性

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')

eliminating the Int argument. 消除Int参数。

As suggested by Daniel Wagner, one possibility is creating my own datatype and giving it an Arbitrary instance. 正如Daniel Wagner所建议的,一种可能性是创建我自己的数据类型并为其提供一个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 is from a custom type in Test.QuickCheck.Modifiers for generating non empty lists. NonEmpty来自Test.QuickCheck.Modifiers的自定义类型,用于生成非空列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM