Find the value that failed for quickcheck

天涯浪子 提交于 2019-12-04 23:34:22

I couldn't find anything in the QuickCheck API to do this in a nice way, but here's something I hacked together using the monadic QuickCheck API. It intercepts and logs the inputs to your property in an IORef, and assumes that if it failed, the last one was the culprit and returns it in a Just. If the test passed, the result is Nothing. This can probably be refined a bit but for simple one-argument properties it should do the job.

import Control.Monad
import Data.IORef
import Test.QuickCheck
import Test.QuickCheck.Monadic

prop_failIfZero :: Int -> Bool
prop_failIfZero n = n /= 0

quickCheck' :: (Arbitrary a, Show a) => (a -> Bool) -> IO (Maybe a)
quickCheck' prop = do input <- newIORef Nothing
                      result <- quickCheckWithResult args (logInput input prop)
                      case result of
                         Failure {} -> readIORef input
                         _ -> return Nothing
  where
    logInput input prop x = monadicIO $ do run $ writeIORef input (Just x)
                                           assert (prop x)
    args = stdArgs { chatty = False }

main = do failed <- quickCheck' prop_failIfZero
          case failed of
              Just x -> putStrLn $ "The input that failed was: " ++ show x
              Nothing -> putStrLn "The test passed"

One way would be to use the sample' method, manually run the test and find the values in which it fails. For example, testing a faulty double function:

import Test.QuickCheck

double :: Int -> Int
double x | x < 10 = 2 * x
         | otherwise = 13

doubleTest :: Int -> Bool
doubleTest x = x + x == double x

tester :: IO ()
tester = do
  values <- sample' arbitrary
  let failedValues = filter (not . doubleTest) values
  print failedValues

The only problem is sample' only generates 11 test values, that may not be enough to trigger the bug.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!