我是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
问题:
答案 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