我为一个使用管道的项目编写了一个程序,我很喜欢它!然而,我很难对我的代码进行单元测试。
我有一系列Pipe In Out IO ()
类型的函数(例如),我希望用HSpec测试这些函数。我该怎么做呢?
例如,假设我有这个域:
data Person = Person String Int | Unknown deriving (Show, Eq)
data Classification = Friend | Foe | Undecided deriving Show
而这个管道:
classify :: Pipe Person (Person, Classification) IO ()
classify = do
p@(Person name _) <- await
case name of
"Alex" -> yield (p, Friend)
"Bob" -> yield (p, Foe)
_ -> yield (p, Undecided)
我想写一个规范:
main = hspec $ do
describe "readFileP" $
it "yields all the lines of a file"
pendingWith "How can I test this Pipe? :("
发布于 2016-09-08 08:47:37
诀窍是使用来自管道的toListM
,ListT
单台变压器。
import Pipes
import qualified Pipes.Prelude as P
import Test.Hspec
data Person = Person String Int | Unknown deriving (Show, Eq)
data Classification = Friend | Foe | Undecided deriving (Show, Eq)
classify :: Pipe Person (Person, Classification) IO ()
classify = do
p@(Person name _) <- await
case name of
"Alex" -> yield (p, Friend)
"Bob" -> yield (p, Foe)
_ -> yield (p, Undecided)
该测试使用ListT转换器将管道转换为ListT,并使用HSpec进行断言:
main = hspec $ do
describe "classify" $ do
it "correctly finds friends" $ do
[(p, cl)] <- P.toListM $ each [Person "Alex" 31] >-> classify
p `shouldBe` (Person "Alex" 31)
cl `shouldBe` Friend
注意,您不必使用each
,这可能是一个调用yield
的简单生产者。
发布于 2016-08-27 16:16:38
您可以使用temporary
包的函数创建带有预期数据的临时文件,然后测试管道是否正确读取数据。
顺便说一句,您的Pipe
正在使用执行惰性I/O的readFile
,而像管道这样的流库并不能很好地混合,事实上后者主要是作为前者的替代而存在的!
也许您应该使用执行严格I/O的函数,比如openFile
和getLine
。
严格I/O的一个烦恼是,它迫使您更仔细地考虑资源分配。如何确保每个文件句柄在结束时关闭,或者在出现错误时关闭?实现这一目标的一种可能方法是在ResourceT IO
monad中工作,而不是直接在IO
中工作。
https://stackoverflow.com/questions/39182947
复制相似问题