我在模块中有一个看起来像这样的函数:
module MyLibrary (throwIfNegative) where
throwIfNegative :: Integral i => i -> String
throwIfNegative n | n < 0 = error "negative"
| otherwise = "no worries"
我当然可以返回Maybe String
或其他一些变体,但我认为用一个负数来调用此函数是一个程序员错误是公平的,所以在这里使用error
是合理的。 / p>
现在,因为我希望我的测试覆盖率达到100%,所以我想要一个检查此行为的测试用例。我试过这个
import Control.Exception
import Test.HUnit
import MyLibrary
case_negative =
handleJust errorCalls (const $ return ()) $ do
evaluate $ throwIfNegative (-1)
assertFailure "must throw when given a negative number"
where errorCalls (ErrorCall _) = Just ()
main = runTestTT $ TestCase case_negative
它有点奏效,但在使用优化进行编译时失败了:
$ ghc --make -O Test.hs
$ ./Test
### Failure:
must throw when given a negative number
Cases: 1 Tried: 1 Errors: 0 Failures: 1
我不确定这里发生了什么。看起来尽管我使用了evaluate
,但是函数没有得到评估。此外,如果我执行以下任何步骤,它将再次起作用:
throwIfNegative
移至与测试用例相同的模块throwIfNegative
我认为这是因为它导致优化的应用方式不同。有什么指针吗?
答案 0 :(得分:8)
优化,严格和imprecise exceptions可能有点棘手。
上面重现此问题的最简单方法是在NOINLINE
上使用throwIfNegative
(该函数不会跨模块边界内联):
import Control.Exception
import Test.HUnit
throwIfNegative :: Int -> String
throwIfNegative n | n < 0 = error "negative"
| otherwise = "no worries"
{-# NOINLINE throwIfNegative #-}
case_negative =
handleJust errorCalls (const $ return ()) $ do
evaluate $ throwIfNegative (-1)
assertFailure "must throw when given a negative number"
where errorCalls (ErrorCall _) = Just ()
main = runTestTT $ TestCase case_negative
通过优化,阅读核心,GHC正确地内联evaluate
(?):
catch#
@ ()
@ SomeException
(\ _ ->
case throwIfNegative (I# (-1)) of _ -> ...
然后在案例审核程序之外浮出对throwIfError
的调用:
lvl_sJb :: String
lvl_sJb = throwIfNegative lvl_sJc
lvl_sJc = I# (-1)
throwIfNegative =
\ (n_adO :: Int) ->
case n_adO of _ { I# x_aBb ->
case <# x_aBb 0 of _ {
False -> lvl_sCw; True -> error lvl_sCy
奇怪的是,此时,没有其他代码现在调用lvl_sJb
,因此整个测试变为死代码,并被剥离 - GHC已确定它未被使用!
使用seq
代替evaluate
非常高兴:
case_negative =
handleJust errorCalls (const $ return ()) $ do
throwIfNegative (-1) `seq` assertFailure "must throw when given a negative number"
where errorCalls (ErrorCall _) = Just ()
或爆炸模式:
case_negative =
handleJust errorCalls (const $ return ()) $ do
let !x = throwIfNegative (-1)
assertFailure "must throw when given a negative number"
where errorCalls (ErrorCall _) = Just ()
所以我认为我们应该看看evaluate
的语义:
-- | Forces its argument to be evaluated to weak head normal form when
-- the resultant 'IO' action is executed. It can be used to order
-- evaluation with respect to other 'IO' operations; its semantics are
-- given by
--
-- > evaluate x `seq` y ==> y
-- > evaluate x `catch` f ==> (return $! x) `catch` f
-- > evaluate x >>= f ==> (return $! x) >>= f
--
-- /Note:/ the first equation implies that @(evaluate x)@ is /not/ the
-- same as @(return $! x)@. A correct definition is
--
-- > evaluate x = (return $! x) >>= return
--
evaluate :: a -> IO a
evaluate a = IO $ \s -> let !va = a in (# s, va #) -- NB. see #2273
#2273 bug是一个非常有趣的读物。
我认为GHC在这里做了一些可疑的事情,建议不要使用evalaute
(而是直接使用seq
)。这需要更多地考虑GHC在严格性方面做了什么。
我filed a bug report帮助GHC总部做出决定。