on master help sign in
Improve Arbitrary instances
commit17ac55dfc31178b571ca2e6c8b088f5281c23e56 authorBryan O'Sullivan <bos@serpentine.com> dateTue 7 Jan 2014, 21:53 (13 years ago) parent54f61ef
1 file changed+15−2
tests/Tests/QuickCheckUtils.hs+15−2
tests/Tests/QuickCheckUtils.hs+15−2
@@ -58,10 +58,12 @@ instance Random I16 where
5858 random = randomR (minBound,maxBound)
5959
6060instance Arbitrary I16 where
61− arbitrary = choose (minBound,maxBound)
61+ arbitrary = arbitrarySizedIntegral
62+ shrink = shrinkIntegral
6263
6364instance Arbitrary B.ByteString where
6465 arbitrary = B.pack `fmap` arbitrary
66+ shrink = map B.pack . shrink . B.unpack
6567
6668#if !MIN_VERSION_base(4,4,0)
6769instance Random Word8 where
@@ -130,9 +132,11 @@ smallArbitrary = sized $ \n -> resize (smallish n) arbitrary
130132
131133instance Arbitrary T.Text where
132134 arbitrary = T.pack `fmap` arbitrary
135+ shrink = map T.pack . shrink . T.unpack
133136
134137instance Arbitrary TL.Text where
135138 arbitrary = (TL.fromChunks . map notEmpty) `fmap` smallArbitrary
139+ shrink = map TL.pack . shrink . TL.unpack
136140
137141newtype NotEmpty a = NotEmpty { notEmpty :: a }
138142 deriving (Eq, Ord)
@@ -145,15 +149,23 @@ instance Functor NotEmpty where
145149
146150instance Arbitrary a => Arbitrary (NotEmpty [a]) where
147151 arbitrary = sized (\n -> NotEmpty `fmap` (choose (1,n+1) >>= vector))
152+ shrink = shrinkNotEmpty null
148153
149154instance Arbitrary (NotEmpty T.Text) where
150155 arbitrary = (fmap T.pack) `fmap` arbitrary
156+ shrink = shrinkNotEmpty T.null
151157
152158instance Arbitrary (NotEmpty TL.Text) where
153159 arbitrary = (fmap TL.pack) `fmap` arbitrary
160+ shrink = shrinkNotEmpty TL.null
154161
155162instance Arbitrary (NotEmpty B.ByteString) where
156163 arbitrary = (fmap B.pack) `fmap` arbitrary
164+ shrink = shrinkNotEmpty B.null
165+
166+shrinkNotEmpty :: Arbitrary a => (a -> Bool) -> NotEmpty a -> [NotEmpty a]
167+shrinkNotEmpty isNull (NotEmpty xs) =
168+ [ NotEmpty xs' | xs' <- shrink xs, not (isNull xs') ]
157169
158170data Small = S0 | S1 | S2 | S3 | S4 | S5 | S6 | S7
159171 | S8 | S9 | S10 | S11 | S12 | S13 | S14 | S15
@@ -194,7 +206,8 @@ instance Random Small where
194206 random = randomR (minBound,maxBound)
195207
196208instance Arbitrary Small where
197− arbitrary = choose (minBound,maxBound)
209+ arbitrary = arbitrarySizedIntegral
210+ shrink = shrinkIntegral
198211
199212integralRandomR :: (Integral a, RandomGen g) => (a,a) -> g -> (a,g)
200213integralRandomR (a,b) g = case randomR (fromIntegral a :: Integer,