Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

introduce discardUnless #374

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Test/QuickCheck.hs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ module Test.QuickCheck
, suchThat
, suchThatMap
, suchThatMaybe
, suchThatDiscard
, applyArbitrary2
, applyArbitrary3
, applyArbitrary4
Expand Down
11 changes: 11 additions & 0 deletions src/Test/QuickCheck/Gen.hs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import Control.Applicative
( Applicative(..) )

import Test.QuickCheck.Random
import Test.QuickCheck.Exception
import Data.List (sortBy)
import Data.Ord
import Data.Maybe
Expand Down Expand Up @@ -293,6 +294,16 @@ gen `suchThatMaybe` p = sized (\n -> try n (2*n))
x <- resize m gen
if p x then return (Just x) else try (m+1) n

-- | Tries to generate a value that satisfies a predicate.
-- If it fails to do so it discards the test case if the result
-- is used in the test.
suchThatDiscard :: Gen a -> (a -> Bool) -> Gen a
suchThatDiscard g p = do
a <- g
MaximilianAlgehed marked this conversation as resolved.
Show resolved Hide resolved
if p a
then pure a
else discard

-- | Randomly uses one of the given generators. The input list
-- must be non-empty.
oneof :: WITHCALLSTACK([Gen a] -> Gen a)
Expand Down
4 changes: 4 additions & 0 deletions tests/DiscardRatio.hs
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,7 @@ main = do
putStrLn "\nExpecting success (discard ratio 40): x < 50 ==> True"
quickCheckYes $ withDiscardRatio 40 p50
quickCheckYesWith stdArgs{maxDiscardRatio = 40} p50

quickCheckNo $ forAll (choose (1 :: Int, 10) `suchThatDiscard` const False) $ \ x -> x == x
quickCheckYes $ forAll (choose (1 :: Int, 10) `suchThatDiscard` const False) $ \ _ -> True
quickCheckYes $ forAll (choose (1 :: Int, 10) `suchThatDiscard` (> 3)) $ \ x -> x == x
Loading