简单的haskell单元测试 [英] Simple haskell unit testing
问题描述
我想通过 99个Haskell问题,我想专注于解决方案,但与测试。如果我将第一个问题的解决方案作为3行 .hs
文件,则可以使用
myLast :: [a] - > a
myLast [x] = x
myLast(_:xs)= myLast xs
我可以添加的最小代码量是多少,以便我可以添加内联测试并使用 runhaskell
?
QuickCheck (其中basicaly生成测试输入为你)可能是测试纯功能的最好方法。如果有问题的函数有标准库的类比,那么你可以使用标准函数作为模型来测试你的函数:
{ - #LANGUAGE TemplateHaskell# - }
import Test.QuickCheck
import Test.QuickCheck.All
myLast :: [a] - > a
myLast [x] = x
myLast(_:xs)= myLast xs
- 这里我们指定'myLast'应该返回完全相同的结果
- 作为'最后'的任何给定的'xs'
prop_myLast xs = myLast xs ==上一个xs
返回[] - 需要GHC 7.8
- quickCheckAll为所有'prop_ *'属性生成测试用例
main = $(quickCheckAll)
如果你运行它,你会得到:
=== prop_myLast on tmp3.hs:12 ===
***失败!例外:'tmp3.hs:(7,1) - (8,25):函数myLast'中的非穷举模式(1测试后):
[]
False
因为您的 myLast
不处理 [ ]
case(它应该但应该抛出一个像'last'的错误)。
但是在这里,我们可以简单地调整我们的测试,但指定只应使用非空字符串(使用 ==>
combinator):
prop_myLast xs = length xs> 0 ==> myLast xs == last xs
这使得所有100个自动生成的测试用例都可以通过 myLast
:
=== prop_myLast on tmp3.hs:11 ===
+++ OK,通过了100次测试。
True
PS另一种指定 myLast
行为可能是:
$ b $ pre $ prop_myLast2 x xs = myLast(xs ++ [x])== x
或者更好:
prop_myLast3 x xs = x`notElem` xs ==> myLast(xs ++ [x])== x
I want to go through 99 Haskell Problems, and I want to concentrate on the solution but with testing. If I have the solution to the first problem as a 3 line .hs
file,
myLast :: [a] -> a
myLast [x] = x
myLast (_:xs) = myLast xs
What is the minimal amount of code I can add to this so that I can add tests inline and run them with runhaskell
?
QuickCheck (which basicaly generates test inputs for you) is probably the best way to test pure function. And if a function in question has an analog from the standard library you can just test your function using the standard one as a model:
{-# LANGUAGE TemplateHaskell #-}
import Test.QuickCheck
import Test.QuickCheck.All
myLast :: [a] -> a
myLast [x] = x
myLast (_:xs) = myLast xs
-- here we specify that 'myLast' should return exactly the same result
-- as 'last' for any given 'xs'
prop_myLast xs = myLast xs == last xs
return [] -- need this for GHC 7.8
-- quickCheckAll generates test cases for all 'prop_*' properties
main = $(quickCheckAll)
If you run it you'll get:
=== prop_myLast on tmp3.hs:12 ===
*** Failed! Exception: 'tmp3.hs:(7,1)-(8,25): Non-exhaustive patterns in function myLast' (after 1 test):
[]
False
because your myLast
doesn't handle []
case (it should but should probably throw an error like 'last').
But here we can simply adjust our test but specifying that only non-empty strings should be used (using ==>
combinator):
prop_myLast xs = length xs > 0 ==> myLast xs == last xs
Which makes all 100 auto-generated test cases to pass for myLast
:
=== prop_myLast on tmp3.hs:11 ===
+++ OK, passed 100 tests.
True
PS Another way to specify myLast
behavior may be:
prop_myLast2 x xs = myLast (xs++[x]) == x
Or better:
prop_myLast3 x xs = x `notElem` xs ==> myLast (xs++[x]) == x
这篇关于简单的haskell单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!