我正在尝试学习Haskell,尤其是QuickCheck。虽然Haskell在线上有很多信息,但我仍在努力使用QuickCheck创建一些随机测试。
例如,我有以下脚本:
import Test.QuickCheck
whatAge :: Int -> Int -> Int -> Int -> Bool
whatAge age1 age2 age3 age4
| age1 + age2 + age3 + age4 == 5 = True
| otherwise = False
main = do
verboseCheck whatAge
我运行时显示:
*** Failed! Falsifiable (after 1 test):
0
0
0
0
足够好,它显示了一个功能为假的测试。
我想做的是:
能够在我的函数参数上放置一个范围,例如:
x1 range from 1 to 30
x2 range from 1 to 40
x3 range from 1 to 50
x4 range from 1 to 60
能够生成非重复测试
据我了解,QuickCheck不可能真正实现nr 3,因为我将不得不使用smallCheck,但是我不确定第1点和第2点。
答案 0 :(得分:0)
对于输入的简单属性,可以使用捕获它们的适当Arbitrary
实例创建一个新类型。所以:
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
import Data.Proxy
import GHC.TypeLits
import Test.QuickCheck
newtype Range (m :: Nat) (n :: Nat) a = Range { getVal :: a }
deriving (Eq, Ord, Read, Show, Num, Real, Enum, Integral)
numVal :: forall n a. (KnownNat n, Num a) => a
numVal = fromInteger (natVal @n Proxy)
instance (KnownNat m, KnownNat n, Arbitrary a, Integral a) => Arbitrary (Range m n a) where
arbitrary = fromInteger <$> choose (numVal @m, numVal @n)
shrink hi = go (numVal @m) where
go lo | lo == hi = [] | otherwise = lo : go ((lo+hi+1)`div`2) -- overflow? what's that? lmao
whatAge :: Range 1 30 Int -> Range 1 40 Int -> Range 1 50 Int -> Range 1 60 Int -> Bool
whatAge (Range age1) (Range age2) (Range age3) (Range age4)
= age1 + age2 + age3 + age4 == 5
在ghci中:
> verboseCheck whatAge
Failed:
Range {getVal = 17}
Range {getVal = 29}
Range {getVal = 3}
Range {getVal = 16}
Failed:
Range {getVal = 1}
Range {getVal = 29}
Range {getVal = 3}
Range {getVal = 16}
Failed:
Range {getVal = 1}
Range {getVal = 1}
Range {getVal = 3}
Range {getVal = 16}
Failed:
Range {getVal = 1}
Range {getVal = 1}
Range {getVal = 1}
Range {getVal = 16}
Failed:
Range {getVal = 1}
Range {getVal = 1}
Range {getVal = 1}
Range {getVal = 1}
*** Failed! Falsifiable (after 1 test and 4 shrinks):
Range {getVal = 1}
Range {getVal = 1}
Range {getVal = 1}
Range {getVal = 1}
对于更复杂的属性,如果不清楚如何直接创建满足该属性的随机值,则可以使用QuickCheck的(==>)
运算符。例如,对于上述范围检查:
> verboseCheck (\x -> (1 <= x && x <= 30) ==> x*2 < 60)
Skipped (precondition false):
0
Passed:
1
*** Failed! Falsifiable (after 33 tests):
30
要精确地进行200次测试,您可以调用quickCheckWith
进行200次测试;或者您可以通过手动调用arbitrary
上的媒体资源来直接generate
测试结果。