1

我为一个使用 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? :("
4

2 回答 2

1

您可以使用temporary包的功能来创建具有预期数据的临时文件,然后测试数据是否被管道正确读取。

顺便说一句,您Pipe正在使用readFile执行惰性 I/O。惰性 I/O 和管道等流库不能很好地混合,实际上后者主要作为前者的替代品存在!

也许您应该改用执行严格 I/O 的函数,例如openFilegetLine.

严格 I/O 的一个烦恼是它迫使您更仔细地考虑资源分配。如何确保每个文件句柄在最后关闭,或者在出错的情况下?实现此目的的一种可能方法是在ResourceT IOmonad 中工作,而不是直接在IO.

于 2016-08-27T16:16:38.803 回答
1

诀窍是使用toListMPipes ListTmonad 转换器。

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-09-08T08:47:37.290 回答