使用 Cabal 而不是使用 diff 和 make 的简单单元测试

Simple unit tests using Cabal instead of using diff and make

我想为我的 Haskell 应用程序重写我的 shell 测试代码,以仅使用 Haskell 和 Cabal。 (出于便携性原因)

当前测试架构如下所示

make      ->    binary                                     ->  ok or fail
make test ->    diff $(binary test-in) test-supposed-out   ->

我想要类似的东西

cabal build  ->  binary                                             ->  ok or fail
cabal test   ->  ...testing with test-in and test-supposed-out...   ->

请问最简单的方法是什么?

谢谢。

Tasty is a simple and versatile framework in which to run various kinds of tests. (I mostly use it for QuickCheck 测试,如果您还没有测试过,我强烈建议您也去看看。)

您所询问的特定类型的测试称为(至少在 Tasty 中)黄金 测试。因此,例如,如果您要测试的程序是

module ComplicatedProc where

import System.IO
import System.Environment (getArgs)

complicatedProc :: String -> Handle -> IO ()
complicatedProc input outHandle = do
   hPutStr outHandle $ drop 37 input ++ take 46 input

main :: IO ()
main = do
  [inpFp] <- getArgs
  input <- readFile inpFp
  complicatedProc input stdout

那么你可以把它改成美味测试 test/golden.hs:

import Test.Tasty
import Test.Tasty.Golden

import ComplicatedProc (complicatedProc)

import System.IO

main :: IO ()
main = do
 complicAlgo_input <- readFile "test-in"
 let complicAlgo_outFp = "test-supposed-out"
 defaultMain $ testGroup "Tests" -- †
   [ goldenVsFile "complicatedAlgo (golden)"
      "test-supposed-out" complicAlgo_outFp
      ( withFile complicAlgo_outFp WriteMode
            $ complicatedProc complicAlgo_input )
   ]

使用像

这样的.cabal文件
cabal-version:       >=1.10

name:                compli-algo
version:             5.7.6.8
build-type:          Simple
-- ...

library
  exposed-modules:     ComplicatedProc
  build-depends:       base
  default-language:    Haskell2010

test-suite compli-algo-goldentest
  main-is:         golden.hs
  type:            exitcode-stdio-1.0
  build-depends:       base
                       , compli-algo
                       , tasty >=1.4 && <1.5
                       , tasty-golden >=2.3 && <2.4
  hs-source-dirs:   test

如果您要测试的程序已输出到 stdout 硬编码(例如,以 print 语句的形式),那么您可能需要 hack around this 一点。


这里根本不需要 testGroup,但实际上您可能希望在其中进行多项测试那个文件。 Tasty 允许您以任何有用的层次顺序创建任意 测试树