我目前正在撰寫一個 Haskell 庫來替換一個封閉源代碼的 3rd 方命令列應用程式。這個 3rd 方 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,這似乎是我想要的,我只是不確定如何將它融入我已經擁有的。
uj5u.com熱心網友回復:
我想我想通了,我用了這個:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/400951.html
