谁能给我测试使用一元快速检查IO操作的一个简单的例子?

有帮助吗?

解决方案

Test.QuickCheck .Monadic 模块,可以测试一元代码,即使在运行IO东西。

一个一元性试验是类型PropertyM m a,其中m是测试在运行单子和a最终忽略的。在PropertyM IO a的情况下,你的单子测试转换为使用Property一个monadicIO;对于所有其他单子,你用monadic,而不是(这需要一个函数来运行单子,一些不具备IO)。

在一个monadic测试,returned出单子的值将被忽略。要检查的表达,使用assert; asserting假值将失败的考验。使用run以执行该单子的代码进行测试。

有在您的处置等一元行动。例如,pick将产生新的测试输入了Gen a的,和pre将检查试验的先决条件。这些是被测试,如果测试输入或前提条件本身取决于经由单子计算的值是有用的,在这种情况下产生的输入或检查precontions的正常方式将不起作用。

下面是测试一些代码IO的例子:我们检查写的东西到一个临时文件后,我们可以看到同样的数据备份。为了演示,我们将实行,我们至少写一个字节到文件的前提条件。这两个测试性能做同样的事情;一个使用pickpre不必要,而另一个却没有。

import System.Directory (removeFile)
import System.IO (hGetContents, hPutStr, hSeek, openBinaryTempFile, SeekMode (..))
import Test.QuickCheck (arbitrary, Property, quickCheck, (==>))
import Test.QuickCheck.Monadic (assert, monadicIO, pick, pre, run)

-- Demonstrating pick and pre as well:
prop_writeThenRead :: Property
prop_writeThenRead = monadicIO $ do writtenData <- pick arbitrary
                                    pre $ not (null writtenData)
                                    readData <- run $ writeThenRead writtenData
                                    assert $ writtenData == readData

-- A more idiomatic way to write the above:
prop_writeThenRead2 :: [Char] -> Property
prop_writeThenRead2 writtenData = not (null writtenData) ==> monadicIO test
    where test = do readData <- run $ writeThenRead writtenData
                    assert $ writtenData == readData

writeThenRead :: [Char] -> IO [Char]
writeThenRead output = do (path, h) <- openBinaryTempFile "/tmp" "quickcheck.tmp"
                          removeFile path
                          hPutStr h output
                          hSeek h AbsoluteSeek 0
                          hGetContents h

main :: IO ()
main = do quickCheck prop_writeThenRead
          quickCheck prop_writeThenRead2

其他提示

用于测试一元码的标准参考是“测试一元代码与快速检查“。它示出了在单子的上下文中测试各种方式如IO

但你真的应该考虑发布一个更具体的问题,关于它是什么,你想测试。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top