2

我目前正在编写一个 Haskell 库来替换一个封闭源代码的 3rd 方命令行应用程序。这个第 3 方 CLI 有一个我已经复制的规范,但实际上二进制允许的输入比规范多得多。

我希望能够使用 生成输入QuickCheck,然后将库中函数的结果与第 3 方 CLI 应用程序的标准输出进行比较。我陷入困境的部分是如何在属性测试中引入 IO。

这是我到目前为止的代码:

{-# LANGUAGE OverloadedStrings #-}

import qualified Data.Text as T
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck

-- This function lives in my library, this is just a sample
-- the actual function does things but is still pure, and has the type Text -> Int
exampleCountFuncInModule :: T.Text -> Int
exampleCountFuncInModule t = T.length t

-- contrived example generator
genSmallString :: Gen T.Text
genSmallString = do 
    smallList <- T.pack <$> resize 2 (listOf1 arbitraryASCIIChar)
    pure ("^" `T.append` smallList)

main :: IO ()
main = do
    hspec $ do
        prop "some property" $ do
            verbose $ forAll genSmallString $ \xs -> (not . T.null) xs ==> do
                let myCount = exampleCountFuncInModule xs
                -- Want to run external program here, and read the result as an Int
                let otherProgramCount = 2
                myCount == otherProgramCount

我发现 QuickCheck 有一个ioProperty,这似乎是我想要的,我只是不确定如何将它融入我已经拥有的东西中。

4

1 回答 1

3

我想我想通了,我用了这个:

test :: Text -> IO Bool 
test t = do
    (exitCode, stdOut, stdErr) <- callCmd $ "bin/cliTool" :| [Text.unpack t]
    let cliCount = read stdOut :: Int
    let myCount = countOfThingsInString t
    return $ cliCount == myCount

然后在我的 hspec 测试中:

main :: IO ()
main = do
    hspec $ do
       describe "tests" $ do
            prop "test IO" $ do
                verbose $ forAll arbitrarySmallSpecifier (ioProperty . test)
于 2021-12-28T21:32:39.440 回答