File: Test.hs

package info (click to toggle)
haskell-quickcheck 2.1.0.3-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 152 kB
  • ctags: 2
  • sloc: haskell: 1,508; makefile: 4
file content (335 lines) | stat: -rw-r--r-- 11,644 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
module Test.QuickCheck.Test where

--------------------------------------------------------------------------
-- imports

import Test.QuickCheck.Gen
import Test.QuickCheck.Property hiding ( Result( reason, interrupted ) )
import qualified Test.QuickCheck.Property as P
import Test.QuickCheck.Text
import Test.QuickCheck.State
import Test.QuickCheck.Exception

import System.Random
  ( RandomGen(..)
  , newStdGen
  , StdGen
  )

import Data.Char
  ( isSpace
  )

import Data.List
  ( sort
  , group
  , groupBy
  , intersperse
  )

--------------------------------------------------------------------------
-- quickCheck

-- * Running tests

-- | Args specifies arguments to the QuickCheck driver
data Args
  = Args
  { replay     :: Maybe (StdGen,Int) -- ^ should we replay a previous test?
  , maxSuccess :: Int                -- ^ maximum number of successful tests before succeeding
  , maxDiscard :: Int                -- ^ maximum number of discarded tests before giving up
  , maxSize    :: Int                -- ^ size to use for the biggest test cases
  }
 deriving ( Show, Read )

-- | Result represents the test result
data Result
  = Success                         -- a successful test run
    { labels      :: [(String,Int)] -- ^ labels and frequencies found during all tests
    }
  | GaveUp                          -- given up
    { numTests    :: Int            -- ^ number of successful tests performed
    , labels      :: [(String,Int)] -- ^ labels and frequencies found during all tests
    }
  | Failure                         -- failed test run
    { usedSeed    :: StdGen         -- ^ what seed was used
    , usedSize    :: Int            -- ^ what was the test size
    , reason      :: String         -- ^ what was the reason
    , labels      :: [(String,Int)] -- ^ labels and frequencies found during all successful tests
    }
  | NoExpectedFailure               -- the expected failure did not happen
    { labels      :: [(String,Int)] -- ^ labels and frequencies found during all successful tests
    }
 deriving ( Show, Read )

-- | isSuccess checks if the test run result was a success
isSuccess :: Result -> Bool
isSuccess Success{} = True
isSuccess _         = False

-- | stdArgs are the default test arguments used
stdArgs :: Args
stdArgs = Args
  { replay     = Nothing
  , maxSuccess = 100
  , maxDiscard = 500
  , maxSize    = 100
-- noShrinking flag?
  }

-- | Tests a property and prints the results to 'stdout'.
quickCheck :: Testable prop => prop -> IO ()
quickCheck p = quickCheckWith stdArgs p

-- | Tests a property, using test arguments, and prints the results to 'stdout'.
quickCheckWith :: Testable prop => Args -> prop -> IO ()
quickCheckWith args p = quickCheckWithResult args p >> return ()

-- | Tests a property, produces a test result, and prints the results to 'stdout'.
quickCheckResult :: Testable prop => prop -> IO Result
quickCheckResult p = quickCheckWithResult stdArgs p

-- | Tests a property, using test arguments, produces a test result, and prints the results to 'stdout'.
quickCheckWithResult :: Testable prop => Args -> prop -> IO Result
quickCheckWithResult args p =
  do tm  <- newTerminal
     rnd <- case replay args of
              Nothing      -> newStdGen
              Just (rnd,_) -> return rnd
     test MkState{ terminal          = tm
                 , maxSuccessTests   = maxSuccess args
                 , maxDiscardedTests = maxDiscard args
                 , computeSize       = case replay args of
                                         Nothing    -> computeSize (maxSuccess args) (maxSize args)
                                         Just (_,s) -> \_ _ -> s
                 , numSuccessTests   = 0
                 , numDiscardedTests = 0
                 , collected         = []
                 , expectedFailure   = False
                 , randomSeed        = rnd
                 , isShrinking       = False
                 , numSuccessShrinks = 0
                 , numTryShrinks     = 0
                 } (unGen (property p))
  where computeSize maxSuccess maxSize n d
          -- e.g. with maxSuccess = 250, maxSize = 100, goes like this:
          -- 0, 1, 2, ..., 99, 0, 1, 2, ..., 99, 0, 2, 4, ..., 98.
          | n `roundTo` maxSize + maxSize <= maxSuccess ||
            n >= maxSuccess ||
            maxSuccess `mod` maxSize == 0 = n `mod` maxSize + d `div` 10
          | otherwise =
            (n `mod` maxSize) * maxSize `div` (maxSuccess `mod` maxSize) + d `div` 10
        n `roundTo` m = (n `div` m) * m

--------------------------------------------------------------------------
-- main test loop

test :: State -> (StdGen -> Int -> Prop) -> IO Result
test st f
  | numSuccessTests st   >= maxSuccessTests st   = doneTesting st f
  | numDiscardedTests st >= maxDiscardedTests st = giveUp st f
  | otherwise                                    = runATest st f

doneTesting :: State -> (StdGen -> Int -> Prop) -> IO Result
doneTesting st f =
  do -- CALLBACK done_testing?
     if expectedFailure st then
       putPart (terminal st)
         ( "+++ OK, passed "
        ++ show (numSuccessTests st)
        ++ " tests"
         )
      else
       putPart (terminal st)
         ( bold ("*** Failed!")
        ++ " Passed "
        ++ show (numSuccessTests st)
        ++ " tests (expected failure)"
         )
     success st
     if expectedFailure st then
       return Success{ labels = summary st }
      else
       return NoExpectedFailure{ labels = summary st }
  
giveUp :: State -> (StdGen -> Int -> Prop) -> IO Result
giveUp st f =
  do -- CALLBACK gave_up?
     putPart (terminal st)
       ( bold ("*** Gave up!")
      ++ " Passed only "
      ++ show (numSuccessTests st)
      ++ " tests"
       )
     success st
     return GaveUp{ numTests = numSuccessTests st
                  , labels   = summary st
                  }

runATest :: State -> (StdGen -> Int -> Prop) -> IO Result
runATest st f =
  do -- CALLBACK before_test
     putTemp (terminal st)
        ( "("
       ++ number (numSuccessTests st) "test"
       ++ concat [ "; " ++ show (numDiscardedTests st) ++ " discarded"
                 | numDiscardedTests st > 0
                 ]
       ++ ")"
        )
     let size = computeSize st (numSuccessTests st) (numDiscardedTests st)
     MkRose mres ts <- protectRose (unProp (f rnd1 size))
     res <- mres
     callbackPostTest st res
     
     case ok res of
       Just True -> -- successful test
         do test st{ numSuccessTests = numSuccessTests st + 1
                   , randomSeed      = rnd2
                   , collected       = stamp res : collected st
                   , expectedFailure = expect res
                   } f
       
       Nothing -> -- discarded test
         do test st{ numDiscardedTests = numDiscardedTests st + 1
                   , randomSeed        = rnd2
                   , expectedFailure   = expect res
                   } f
         
       Just False -> -- failed test
         do if expect res
              then putPart (terminal st) (bold "*** Failed! ")
              else putPart (terminal st) "+++ OK, failed as expected. "
            putTemp (terminal st)
              ( short 30 (P.reason res)
             ++ " (after "
             ++ number (numSuccessTests st+1) "test"
             ++ ")..."
              )
            foundFailure st res ts
            if not (expect res) then
              return Success{ labels = summary st }
             else
              return Failure{ usedSeed    = randomSeed st -- correct! (this will be split first)
                            , usedSize    = size
                            , reason      = P.reason res
                            , labels      = summary st
                            }
 where
  (rnd1,rnd2) = split (randomSeed st)

summary :: State -> [(String,Int)]
summary st = reverse
           . sort
           . map (\ss -> (head ss, (length ss * 100) `div` numSuccessTests st))
           . group
           . sort
           $ [ concat (intersperse ", " s')
             | s <- collected st
             , let s' = [ t | (t,_) <- s ]
             , not (null s')
             ]

success :: State -> IO ()
success st =
  case labels ++ covers of
    []    -> do putLine (terminal st) "."
    [pt]  -> do putLine (terminal st)
                  ( " ("
                 ++ dropWhile isSpace pt
                 ++ ")."
                  )
    cases -> do putLine (terminal st) ":"
                sequence_ [ putLine (terminal st) pt | pt <- cases ]
 where
  labels = reverse
         . sort
         . map (\ss -> (showP ((length ss * 100) `div` numSuccessTests st) ++ head ss))
         . group
         . sort
         $ [ concat (intersperse ", " s')
           | s <- collected st
           , let s' = [ t | (t,0) <- s ]
           , not (null s')
           ]
  
  covers = [ ("only " ++ show occurP ++ "% " ++ fst (head lps) ++ "; not " ++ show reqP ++ "%")
           | lps <- groupBy first
                  . sort
                  $ [ lp
                    | lps <- collected st
                    , lp <- maxi lps
                    , snd lp > 0
                    ]
           , let occurP = (100 * length lps) `div` maxSuccessTests st
                 reqP   = maximum (map snd lps)
           , occurP < reqP
           ]
  
  (x,_) `first` (y,_) = x == y 

  maxi = map (\lps -> (fst (head lps), maximum (map snd lps)))
       . groupBy first
       . sort

  showP p = (if p < 10 then " " else "") ++ show p ++ "% "

--------------------------------------------------------------------------
-- main shrinking loop

foundFailure :: State -> P.Result -> [Rose (IO P.Result)] -> IO ()
foundFailure st res ts =
  do localMin st{ numTryShrinks = 0, isShrinking = True } res ts

localMin :: State -> P.Result -> [Rose (IO P.Result)] -> IO ()
localMin st res [] = localMinFound st res
localMin st res _ | P.interrupted res = localMinFound st res

localMin st res (t : ts) =
  do -- CALLBACK before_test
     MkRose mres' ts' <- protectRose t
     res' <- mres'
     putTemp (terminal st)
       ( short 35 (P.reason res)
      ++ " (after " ++ number (numSuccessTests st+1) "test"
      ++ concat [ " and "
               ++ show (numSuccessShrinks st)
               ++ concat [ "." ++ show (numTryShrinks st) | numTryShrinks st > 0 ]
               ++ " shrink"
               ++ (if numSuccessShrinks st == 1
                   && numTryShrinks st == 0
                   then "" else "s")
                | numSuccessShrinks st > 0 || numTryShrinks st > 0
                ]
      ++ ")..."
       )
     callbackPostTest st res'
     if ok res' == Just False
       then foundFailure st{ numSuccessShrinks = numSuccessShrinks st + 1 } res' ts'
       else localMin st{ numTryShrinks = numTryShrinks st + 1 } res ts

localMinFound :: State -> P.Result -> IO ()
localMinFound st res =
  do putLine (terminal st)
       ( P.reason res
      ++ " (after " ++ number (numSuccessTests st+1) "test"
      ++ concat [ " and " ++ number (numSuccessShrinks st) "shrink"
                | numSuccessShrinks st > 0
                ]
      ++ "):  "
       )
     callbackPostFinalFailure st res

--------------------------------------------------------------------------
-- callbacks

callbackPostTest :: State -> P.Result -> IO ()
callbackPostTest st res =
  sequence_ [ f st res | PostTest f <- callbacks res ]

callbackPostFinalFailure :: State -> P.Result -> IO ()
callbackPostFinalFailure st res =
  sequence_ [ f st res | PostFinalFailure f <- callbacks res ]

--------------------------------------------------------------------------
-- the end.