使用IO monad的Haskell单元测试 [英] Haskell Unit tests using IO monad

查看:61
本文介绍了使用IO monad的Haskell单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为haskell函数编写HUnit测试,这些函数返回IO monad,因为它们执行文件I/O.有什么办法吗?现在,我正在尝试编写一个仅返回Bool的方法,可以作为我的测试

I am trying to write HUnit tests for haskell functions that return IO monads because they perform file I/O. Is there any way to do this? Right now I am trying to write a method that just returns a Bool and that can be my test

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在评论中所说的那样,并在

Like what @user2407038 said in the comments and as mentioned in the HUnit user manual HUnit tests run in the 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}

这篇关于使用IO monad的Haskell单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆