如果测试中存在“Nothing == Nothing”条件,HUnit 不允许编译测试用例

HUnit does not allow to compile test cases if `Nothing == Nothing` condition is present in the test

我遇到了一个奇怪的 HUnit 行为。如果测试中存在 Nothing == Nothing 条件,则不允许编译测试用例。这是我重现此行为的代码:

module TestTest where 

import Control.Exception
import Control.Monad
import Test.HUnit
import Test.AssertError

testTests = test [ 
    "test A01"  ~: "x == x" ~: True ~=? Nothing == Nothing,
    "test _"    ~: "empty test" ~: True ~=? True
    ]

runTests :: IO Counts
runTests = do
    runTestTT testTests

尝试在 ghci returns 中加载包含此内容的文件,出现以下错误:

[2 of 2] Compiling TestTest         ( Test/TestTest.hs, interpreted )

Test/TestTest.hs:9:49:
    No instance for (Eq a0) arising from a use of ‘==’
    The type variable ‘a0’ is ambiguous
    Note: there are several potential instances:
      instance Eq Counts -- Defined in ‘Test.HUnit.Base’
      instance Eq Node -- Defined in ‘Test.HUnit.Base’
      instance Eq State -- Defined in ‘Test.HUnit.Base’
      ...plus 53 others
    In the second argument of ‘(~=?)’, namely ‘Nothing == Nothing’
    In the second argument of ‘(~:)’, namely
      ‘True ~=? Nothing == Nothing’
    In the second argument of ‘(~:)’, namely
      ‘"x == x" ~: True ~=? Nothing == Nothing’
Failed, modules loaded: Test.AssertError.

请注意,同一测试用例中的条件 Just 2 == Just 2 工作正常。如果我在 ghci 中键入 Nothing == Nothing,它会按预期 returns True

知道为什么 HUnit 会这样吗?这是错误还是预期行为?

问题是您指定了两个 Nothing,而其中的 none 暗示了 a 的类型。当然,您可以推断 Nothing 无关紧要。但是 Haskell 并不是这样推理的:它对 "to what (==) function should I point?".

感兴趣

您可以通过明确类型来解决问题。例如:

testTests = test [ 
  "test A01"  ~: "x == x" ~: True ~=? (Nothing <b>:: Maybe Int</b>) == Nothing,
  "test _"    ~: "empty test" ~: True ~=? True
  ]