【发布时间】:2016-08-27 15:49:20
【问题描述】:
我为一个使用 Pipes 的项目编写了一个程序,我很喜欢它!但是,我正在努力对我的代码进行单元测试。
我有一系列 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? :("
【问题讨论】:
-
将您的管道转换为生产者或效果器,并使用toListM 或简单地使用
runEffect来实现值。显然,您必须决定如何为管道创建和提供测试数据。 -
runEffect只会给我一个m r,在这种情况下是IO ()。不确定这应该有什么帮助? -
不是
runEffect classify,而是runEffect (giveDataToClassify classify)——就像我说的,你的管道接受一个输入,你必须决定什么输入是什么,只需将你的管道组合成适当的使用管道创建输出而不需要输入的适当方式(我认为在pipes这是Producer)。例如,toListM $ mapM_ yield [ Person "Bob" 10, Person "June" 20 ] >-> classify做你想做的事吗?注意\xs -> toListM $ mapM_ yield xs >-> classify的类型是[Person] -> IO [(Person, Classification)],这在我看来是一种与 HSpec 兼容的形式。 -
我知道我需要向管道提供数据。我的问题是
runEffect调用在IOmonad 中,它无法评估为hspec 的it所需的Expectation。 -
查看type of
it,它需要一个Example a => a参数,并且您有一个Example Expectation的实例(即Example (IO ())),其语义是抛出一个HUnitFailure异常表示失败测试并抛出Result异常(似乎?)表示测试成功。哪个(几乎)符合要求。我觉得奇怪的是没有Example a => Example (IO a)实例,甚至没有Example (IO Result)- 似乎这些对你有用。也许您应该尝试自己编写它们?
标签: haskell haskell-pipes hspec