我的目标是能够定义一组测试方法和一组测试用例(输入/输出数据),然后执行它们的所有组合。目标是避免在说相同功能的 3 个不同实现和功能应满足的 4 个测试用例时一遍又一遍地重写相同的代码。天真的方法需要我编写 12 行代码:
测试方法1测试用例1
测试方法1测试用例2
...
测试方法3测试用例4
我有一种直觉,认为 Haskell 应该提供一种以某种方式抽象这种模式的方法。我目前想到的最好的事情是这段代码:
import Control.Applicative
data TestMethod a = TM a
data TestData inp res = TD inp res
runMetod (TM m) (TD x res) = m x == res
runAllMethods ((m, inp):xs) = show (runMetod m inp) ++ "\n" ++ runAllMethods xs
runAllMethods _ = ""
head1 = head
head2 (x:xs) = x
testMethods = [TM head1, TM head2]
testData = [TD [1,2,3] 1, TD [4,5,6] 4]
combos = (,) <$> testMethods <*> testData
main = putStrLn $ runAllMethods combos
这有效,针对两个 2 函数计算 2 个测试并打印出 4 个成功:
True
True
True
True
但是,这仅适用于相同类型的列表,即使 head 函数与列表类型无关。我想收集任何列表的测试数据,如下所示:
import Control.Applicative
data TestMethod a = TM a
data TestData inp res = TD inp res
runMetod (TM m) (TD x res) = m x == res
runAllMethods ((m, inp):xs) = show (runMetod m inp) ++ "\n" ++ runAllMethods xs
runAllMethods _ = ""
head1 = head
head2 (x:xs) = x
testMethods = [TM head1, TM head2]
testData = [TD [1,2,3] 1, TD ['a','b','c'] 'a']
combos = (,) <$> testMethods <*> testData
main = putStrLn $ runAllMethods combos
但这失败并出现错误:
main.hs:12:21: error:
No instance for (Num Char) arising from the literal ‘1’
In the expression: 1
In the first argument of ‘TD’, namely ‘[1, 2, 3]’
In the expression: TD [1, 2, 3] 1
是否有可能以某种方式实现此测试功能 X 测试用例交叉测试?
最佳答案
你真的应该使用 QuickCheck 或类似的东西,就像 hnefatl 说的那样。 但只是为了好玩,让我们将您的想法付诸实践。
所以你有一个多态函数和很多不同类型的测试用例。唯一重要的是您可以应用每种类型的函数。
让我们看看您的函数。它的类型是 [a] -> a
。你的测试数据应该是什么样的?它应该由一个列表和一个值组成,并且应该支持相等比较。这会引导您得出如下定义:
{-# LANGUAGE GADTs #-}
{-# LANGUAGE ImpredicativeTypes #-}
{-# LANGUAGE RankNTypes #-}
data TestData where
TestData :: Eq a => [a] -> a -> TestData
您需要启用 GADTs
语言扩展才能工作。为了使下面的工作正常,您需要这两个扩展(尽管可以使用类型类来概括整个事情以避免这种情况,只需看看 QuickCheck)。
现在测试一下:
head1 = head
head2 (a : as) = a
test :: (forall a . [a] -> a) -> TestData -> Bool
test f (TestData as a) = f as == a
testAll :: [(forall a . [a] -> a)] -> [TestData] -> Bool
testAll fs testDatas = and $ test <$> fs <*> testDatas
main = putStrLn $ if testAll [head1, head2] [TestData "Foo" 'F', TestData [1..] 1]
then "Success!"
else "Oh noez!"
我将留给您针对不同的测试函数类型对此进行概括。
关于haskell - 在 Haskell 中运行测试和测试用例的所有组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48278322/