Haskell 单元测试使用 IO monad

标签 haskell io monads ghci hunit

我正在尝试为返回 IO monad 的 haskell 函数编写 HUnit 测试,因为它们执行文件 I/O。有没有办法做到这一点?现在我正在尝试编写一个只返回 Bool 的方法,这可以作为我的测试

combine :: FilePath -> FilePath -> Bool
combine fp1 fp2 = do
  cs <- readFile fp1
  let (_,y,z) = strToHuff cs
  let _ = writeToFile fp2 z y
  (a, b) <- readFromFile fp2
  z == a && b == y

但这给了我以下错误:
FileWriter.hs:153:3: Couldn't match type ‘IO b0’ with ‘Bool’ …
    Expected type: IO String -> (String -> IO b0) -> Bool
      Actual type: IO String -> (String -> IO b0) -> IO b0
    In a stmt of a 'do' block: cs <- readFile fp1
    In the expression:
      do { cs <- readFile fp1;
           let (_, y, z) = strToHuff cs;
           let _ = writeToFile "try1.txt" z y;
           (a, b) <- readFromFile fp2;
           .... }
    In an equation for ‘combine’:
        combine fp1 fp2
          = do { cs <- readFile fp1;
                 let (_, y, z) = ...;
                 let _ = ...;
                 .... }
FileWriter.hs:157:3: Couldn't match expected type ‘IO b0’ with actual type ‘Bool’ …
    In a stmt of a 'do' block: z == a && b == y
    In the expression:
      do { cs <- readFile fp1;
           let (_, y, z) = strToHuff cs;
           let _ = writeToFile "try1.txt" z y;
           (a, b) <- readFromFile fp2;
           .... }
    In an equation for ‘combine’:
        combine fp1 fp2
          = do { cs <- readFile fp1;
                 let (_, y, z) = ...;
                 let _ = ...;
                 .... }
Compilation failed.

最佳答案

就像@user2407038 在评论中所说的和在 HUnit user manual 中提到的一样HUnit 测试在 IO monad 中运行.

下面是一个例子:

testFilesEqual = TestCase (do x <- readFile "a.txt"
                              y <- readFile "b.txt"
                              assertEqual "files not equal" x y)
# a.txt == b.txt
λ> runTestTT testFilesEqual
Cases: 1  Tried: 0  Errors: 0  Failures: 0
Counts {cases = 1, tried = 1, errors = 0, failures = 0}

# a.txt != b.txt
λ> runTestTT testFilesEqual
### Failure:
files not equal
expected: "hello\n"
but got: "world\n"
Cases: 1  Tried: 1  Errors: 0  Failures: 1
Counts {cases = 1, tried = 1, errors = 0, failures = 1}

关于Haskell 单元测试使用 IO monad,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34168538/

相关文章:

performance - 使用 Haskell 进行竞争性编程

haskell - 在 Persistent Yesod 中进行多对多的最佳方式是什么?

c - 使用 fopen() 读取文件无法正常工作

java - 将输入发送到图形进程?

lisp - 范畴论术语中的 Lisp `quote` 特殊形式是什么?

haskell - 什么是单子(monad)类别的仿函数?

haskell - 我可以在 Haskell 中声明一个 NULL 值吗?

haskell - 如何在 Haskell 中将守卫与模式匹配结合起来? (我可以吗?)

java - NullPointerException:无法列出目录中的文件

haskell - 嵌套 do 语法