簡體   English   中英

Haskell Unit使用IO monad進行測試

[英]Haskell Unit tests using IO monad

我正在嘗試為返回IO monads的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用戶手冊中提到的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}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM