QuickCheck测试随机挂起

时间:2013-08-12 20:43:30

标签: haskell quickcheck

我是Haskell的新手。我正在玩QuickCheck测试,尝试测试一个简单的函数calculateStrengthSingle(参见下面的测试者来源)

# Fighter.hs
module Fighter
( Quantity(Quantity)
, Fighter(TeamPlayer, LoneWolf, Polymorph)
, Strength(Strength)
, calculateStrengthSingle)
where

import System.Random

data Strength = Strength Double

instance Eq Strength where
    Strength s1 == Strength s2 =
        s1 == s2

instance Ord Strength where
    Strength s1 < Strength s2 =
        s1 < s2

data Quantity = Quantity Int deriving (Show)

instance Random Quantity where
    randomR (Quantity lo, Quantity hi) g =
        let rand = randomR (lo, hi) g
            (r, g1) = rand
        in (Quantity r, g1)
    random g =
        let rand = random g
            (r, g1) = rand
        in (Quantity r, g1)

data Fighter = TeamPlayer
             | LoneWolf
             | Polymorph
    deriving (Show)


calculateStrengthSingle :: Quantity -> Fighter -> Strength
calculateStrengthSingle (Quantity number) TeamPlayer =
    Strength(log (fromIntegral number))
calculateStrengthSingle _ _ = Strength 0.0

测试看起来像这样

# TestFighter.hs
import qualified Test.QuickCheck as QuickCheck
import Fighter

prop_StrengthPositive quantity fighter =
    Fighter.calculateStrengthSingle quantity fighter >= Strength 0.0

instance QuickCheck.Arbitrary Fighter.Fighter where
    arbitrary = QuickCheck.oneof([return Fighter.TeamPlayer, return Fighter.LoneWolf, return Fighter.Polymorph])

instance QuickCheck.Arbitrary Fighter.Quantity where
    arbitrary = QuickCheck.choose(Fighter.Quantity 1, Fighter.Quantity 10)

main :: IO()
main = do
    QuickCheck.quickCheck prop_StrengthPositive

当我runhaskell TestFighter.hs时,输出(1 test)(数字正在变化,有时它是0,有时它是4)并且CPU是100%加载的。一分钟左右没有任何事情发生。当我通过Ctrl+C中断程序时,会吐出类似

的内容
^C*** Failed! Exception: 'user interrupt' (after 1 test):  
Quantity 2
TeamPlayer

问题:

  1. 我在哪里陷入困境?
  2. 如何调试无限计算的情况,比如这个?

2 个答案:

答案 0 :(得分:6)

您尚未正确定义Ord的{​​{1}}个实例。您需要定义Strength而不是<=

仅定义<时,函数<进入无限循环,因为它是根据<=定义的,而compare是根据{{1}定义的}。最低定义需要定义compare<=

以下是compare实例

的固定代码
<=

答案 1 :(得分:1)

您可以尝试使用-o 1作为参数运行测试,这会在一秒钟后导致超时。然后它可以显示导致程序挂起的输入。它没有告诉你问题的确切位置,但它是一个良好的开端。

编辑:这就是我使用cabal的测试框架

的方法
test-Suite runTests
   hs-source-dirs:      src, test
   type:                exitcode-stdio-1.0
   main-is:             RunTests.hs
   other-modules:
                       <...>

  build-depends:       base >= 3 && < 5,
                       HUnit,
                       test-framework,
                       test-framework-th,
                       test-framework-hunit,
                       test-framework-quickcheck2,
                       QuickCheck,

为了在我的描述中完整,我使用:

构建
cabal-dev install --enable-tests