如何测试假设其输入来自智能构造函数的函数?

问题描述

tl;博士

我想了解如何使用 Test.QuickCheck 来测试其参数传递给智能构造函数和/或假定为来自智能构造函数函数

长版

一个模块中,我有一个像这样的用户定义类型:

newtype SpecialStr = SpecialStr { getStr :: String }

顾名思义,SpecialStr 非常特殊,包裹起来的String 不是“任何”字符串,但它必须满足某些属性。为了强制执行此操作,我不会从模块中导出值构造函数,而是导出 smart constructor:

specialStr :: String -> SpecialStr
specialStr str = assert (isValid str) $ SpecialStr str
  where
    isValid :: String -> Bool
    isValid = and . map (`elem` "abcdef") -- this is just an example logic

当然,我已经定义了一些与这些 SpecialStr 一起操作的函数,例如

someFunc :: String -> [SpecialStr]
someFunc str = -- uses smart constructor
someOtherFunc :: (Int,SpecialStr) -> Whatever
someOtherFunc = -- assumes the input has been created via the smart constructor,i.e. assumes it's valid

可能 someFunc 被输入 String,然后输出 [SpecialStr][1..] 压缩,结果被输入 someOtherFunc,只是做一个随机的例子。

现在我的问题是:如何使用 QuickCheck 测试这些函数

解决方法

有智能构造函数吗?编写一个智能任意实例。

instance Arbitrary SpecialStr where
    arbitrary = SpecialStr <$> listOf (choose ('a','f'))
    shrink (SpecialStr s) = SpecialStr (shrinkList (enumFromTo 'a') s)

然后像往常一样写你的属性。

-- check that someOtherFunc is hypermonotonic in the SpecialStrings
quickCheck (\n1 n2 s1 s2 -> someOtherFunc (n1,min s1 s2) <= someOtherFunc (n2,max s1 s2))

...或者其他什么。