hug*_*omg 16 haskell quickcheck
假设我想为(!!)
函数编写一些单元测试.
my_prop xs n = ...
Run Code Online (Sandbox Code Playgroud)
我想将n限制为仅有效的索引,我知道我可以做类似的事情
my_prop xs n = (not.null) (drop n xs) ==> ...
Run Code Online (Sandbox Code Playgroud)
但这使得绝大多数生成的案例都无效并被抛弃.有没有办法我可以设置,以便QuickCheck xs
首先生成列表并使用其值只生成有效的情况n
?
ham*_*mar 17
使用forAll
,您可以指定一个生成器,n
该生成器取决于先前的参数,例如
my_prop (NonEmpty xs) = forAll (choose (0, length xs - 1)) $ \n -> ...
Run Code Online (Sandbox Code Playgroud)
Dan*_*her 10
你可以创建一个只生成有效索引的生成器并编写你的属性
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')
Run Code Online (Sandbox Code Playgroud)
消除Int
争论.
正如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
Run Code Online (Sandbox Code Playgroud)
NonEmpty
来自自定义类型Test.QuickCheck.Modifiers
用于生成非空列表.