运行“cabal测试”通过了,尽管存在测试失败



我有一个Cabal测试目标:

test-suite Tests
  type:              exitcode-stdio-1.0
  main-is:           Main.hs
  hs-source-dirs:    test, src
  build-depends:     base, …
  default-language:  Haskell2010

和简单的测试Main.hs:

import Test.HUnit
testSanity = TestCase $ assertEqual "Should fail" 2 1
main = runTestTT testSanity

现在正在运行的cabal test通过:

Test suite Tests: RUNNING...
Test suite Tests: PASS
Test suite logged to: dist/test/Project-0.1.0-Tests.log
1 of 1 test suites (1 of 1 test cases) passed.

即使在测试套件日志中正确记录了失败:

Test suite Tests: RUNNING...
Cases: 1  Tried: 0  Errors: 0  Failures: 0
### Failure:
Should fail
expected: 2
 but got: 1
Cases: 1  Tried: 1  Errors: 0  Failures: 1
Test suite Tests: PASS
Test suite logged to: dist/test/Project-0.1.0-Tests.log

我做错了什么?

main必须是IO a类型,其中a可以是任何类型,并且该值不以任何方式与程序的POSIX退出状态绑定。您需要查看runTest返回的Counts,并显式地选择成功或失败的输出代码。

import System.Exit
main :: IO ()
main = do
    cs@(Counts _ _ errs fails) <- runTestTT testSanity
    putStrLn (showCounts cs)
    if (errs > 0 || fails > 0) 
        then exitFailure
        else exitSuccess

我相信exitcode-stdio-1.0期望测试通过程序的退出代码来传达失败。但是,如果您在shell中手动运行测试程序(查看dist/build目录),我想你会发现退出代码总是0。

这是一个相关的SO问题,建议你的测试应该调用exitFailure,如果你的套件没有通过:

快速检查故障退出状态,以及cabal集成

FWIW,当使用stack:

时它可以正常工作
$ mkdir new-dir
$ cd new-dir
$ stack new
(edit new-template.cabal to add HUnit as a test dependency)
(add test case to test/Spec.hs)
$ stack test

可能stack也在扫描测试输出

最新更新