QuickCheckUtils.hs 11.1 KB
Newer Older
1
2
-- | This module provides quickcheck utilities, e.g. arbitrary and show
-- instances, and comparison functions, so we can focus on the actual properties
bos's avatar
bos committed
3
-- in the 'Tests.Properties' module.
4
5
6
--
{-# LANGUAGE CPP, FlexibleInstances, TypeSynonymInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
bos's avatar
bos committed
7
module Tests.QuickCheckUtils
8
9
10
11
12
    (
      genUnicode
    , unsquare
    , smallArbitrary

13
    , BigBounded(..)
bos's avatar
bos committed
14
    , BigInt(..)
bos's avatar
bos committed
15
    , NotEmpty(..)
16

bos's avatar
bos committed
17
    , Small(..)
18
19
    , small

20
21
22
    , Precision(..)
    , precision

23
    , integralRandomR
24

bos's avatar
bos committed
25
    , DecodeErr(..)
26
    , genDecodeErr
27

bos's avatar
bos committed
28
    , Stringy(..)
29
30
31
    , eq
    , eqP

bos's avatar
bos committed
32
    , Encoding(..)
bos's avatar
bos committed
33

34
    , write_read
35
36
    ) where

bos's avatar
bos committed
37
import Control.Applicative ((<$>))
38
39
40
import Control.Arrow (first, (***))
import Control.DeepSeq (NFData (..), deepseq)
import Control.Exception (bracket)
41
42
import Data.String (IsString, fromString)
import Data.Text.Foreign (I16)
43
import Data.Text.Lazy.Builder.RealFloat (FPFormat(..))
bos's avatar
bos committed
44
import Data.Word (Word8, Word16)
45
import Debug.Trace (trace)
bos's avatar
bos committed
46
import System.Random (Random(..), RandomGen)
47
import Test.QuickCheck hiding (Fixed(..), Small (..), (.&.))
48
import Test.QuickCheck.Monadic (assert, monadicIO, run)
49
import Test.QuickCheck.Unicode (string)
bos's avatar
bos committed
50
import Tests.Utils
51
52
import qualified Data.ByteString as B
import qualified Data.Text as T
53
import qualified Data.Text.Encoding.Error as T
54
55
import qualified Data.Text.Internal.Fusion as TF
import qualified Data.Text.Internal.Fusion.Common as TF
bos's avatar
bos committed
56
import qualified Data.Text.Internal.Lazy as TL
bos's avatar
bos committed
57
58
import qualified Data.Text.Internal.Lazy.Fusion as TLF
import qualified Data.Text.Lazy as TL
59
60
import qualified System.IO as IO

bos's avatar
bos committed
61
62
63
64
65
#if !MIN_VERSION_base(4,4,0)
import Data.Int (Int64)
import Data.Word (Word, Word64)
#endif

66
67
68
genUnicode :: IsString a => Gen a
genUnicode = fromString <$> string

69
70
71
72
73
instance Random I16 where
    randomR = integralRandomR
    random  = randomR (minBound,maxBound)

instance Arbitrary I16 where
bos's avatar
bos committed
74
75
    arbitrary     = arbitrarySizedIntegral
    shrink        = shrinkIntegral
76
77
78

instance Arbitrary B.ByteString where
    arbitrary     = B.pack `fmap` arbitrary
bos's avatar
bos committed
79
    shrink        = map B.pack . shrink . B.unpack
80

bos's avatar
bos committed
81
#if !MIN_VERSION_base(4,4,0)
bos's avatar
bos committed
82
83
84
85
86
87
88
89
instance Random Int64 where
    randomR = integralRandomR
    random  = randomR (minBound,maxBound)

instance Random Word where
    randomR = integralRandomR
    random  = randomR (minBound,maxBound)

bos's avatar
bos committed
90
91
92
93
instance Random Word8 where
    randomR = integralRandomR
    random  = randomR (minBound,maxBound)

bos's avatar
bos committed
94
instance Random Word64 where
bos's avatar
bos committed
95
96
97
98
    randomR = integralRandomR
    random  = randomR (minBound,maxBound)
#endif

99
100
101
102
103
104
105
106
107
108
-- For tests that have O(n^2) running times or input sizes, resize
-- their inputs to the square root of the originals.
unsquare :: (Arbitrary a, Show a, Testable b) => (a -> b) -> Property
unsquare = forAll smallArbitrary

smallArbitrary :: (Arbitrary a, Show a) => Gen a
smallArbitrary = sized $ \n -> resize (smallish n) arbitrary
  where smallish = round . (sqrt :: Double -> Double) . fromIntegral . abs

instance Arbitrary T.Text where
109
    arbitrary = T.pack `fmap` string
bos's avatar
bos committed
110
    shrink = map T.pack . shrink . T.unpack
111
112
113

instance Arbitrary TL.Text where
    arbitrary = (TL.fromChunks . map notEmpty) `fmap` smallArbitrary
bos's avatar
bos committed
114
    shrink = map TL.pack . shrink . TL.unpack
115

bos's avatar
bos committed
116
117
118
119
newtype BigInt = Big Integer
               deriving (Eq, Show)

instance Arbitrary BigInt where
120
    arbitrary = choose (1::Int,200) >>= \e -> Big <$> choose (10^(e-1),10^e)
bos's avatar
bos committed
121
122
123
    shrink (Big a) = [Big (a `div` 2^(l-e)) | e <- shrink l]
      where l = truncate (log (fromIntegral a) / log 2 :: Double) :: Integer

124
125
126
127
128
129
newtype BigBounded a = BigBounded a
                     deriving (Eq, Show)

instance (Bounded a, Random a, Arbitrary a) => Arbitrary (BigBounded a) where
    arbitrary = BigBounded <$> choose (minBound, maxBound)

130
131
132
133
134
135
136
137
138
139
140
newtype NotEmpty a = NotEmpty { notEmpty :: a }
    deriving (Eq, Ord)

instance Show a => Show (NotEmpty a) where
    show (NotEmpty a) = show a

instance Functor NotEmpty where
    fmap f (NotEmpty a) = NotEmpty (f a)

instance Arbitrary a => Arbitrary (NotEmpty [a]) where
    arbitrary   = sized (\n -> NotEmpty `fmap` (choose (1,n+1) >>= vector))
bos's avatar
bos committed
141
    shrink      = shrinkNotEmpty null
142
143
144

instance Arbitrary (NotEmpty T.Text) where
    arbitrary   = (fmap T.pack) `fmap` arbitrary
bos's avatar
bos committed
145
    shrink      = shrinkNotEmpty T.null
146
147
148

instance Arbitrary (NotEmpty TL.Text) where
    arbitrary   = (fmap TL.pack) `fmap` arbitrary
bos's avatar
bos committed
149
    shrink      = shrinkNotEmpty TL.null
150
151
152

instance Arbitrary (NotEmpty B.ByteString) where
    arbitrary   = (fmap B.pack) `fmap` arbitrary
bos's avatar
bos committed
153
154
155
156
157
    shrink      = shrinkNotEmpty B.null

shrinkNotEmpty :: Arbitrary a => (a -> Bool) -> NotEmpty a -> [NotEmpty a]
shrinkNotEmpty isNull (NotEmpty xs) =
  [ NotEmpty xs' | xs' <- shrink xs, not (isNull xs') ]
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

data Small = S0  | S1  | S2  | S3  | S4  | S5  | S6  | S7
           | S8  | S9  | S10 | S11 | S12 | S13 | S14 | S15
           | S16 | S17 | S18 | S19 | S20 | S21 | S22 | S23
           | S24 | S25 | S26 | S27 | S28 | S29 | S30 | S31
    deriving (Eq, Ord, Enum, Bounded)

small :: Integral a => Small -> a
small = fromIntegral . fromEnum

intf :: (Int -> Int -> Int) -> Small -> Small -> Small
intf f a b = toEnum ((fromEnum a `f` fromEnum b) `mod` 32)

instance Show Small where
    show = show . fromEnum

instance Read Small where
    readsPrec n = map (first toEnum) . readsPrec n

instance Num Small where
    fromInteger = toEnum . fromIntegral
    signum _ = 1
    abs = id
    (+) = intf (+)
    (-) = intf (-)
    (*) = intf (*)

instance Real Small where
    toRational = toRational . fromEnum

instance Integral Small where
    toInteger = toInteger . fromEnum
    quotRem a b = (toEnum x, toEnum y)
        where (x, y) = fromEnum a `quotRem` fromEnum b

instance Random Small where
    randomR = integralRandomR
    random  = randomR (minBound,maxBound)

instance Arbitrary Small where
198
    arbitrary     = choose (minBound, maxBound)
bos's avatar
bos committed
199
    shrink        = shrinkIntegral
200
201
202
203
204

integralRandomR :: (Integral a, RandomGen g) => (a,a) -> g -> (a,g)
integralRandomR  (a,b) g = case randomR (fromIntegral a :: Integer,
                                         fromIntegral b :: Integer) g of
                            (x,h) -> (fromIntegral x, h)
205

206
207
data DecodeErr = Lenient | Ignore | Strict | Replace
               deriving (Show, Eq)
208

209
210
211
212
213
genDecodeErr :: DecodeErr -> Gen T.OnDecodeError
genDecodeErr Lenient = return T.lenientDecode
genDecodeErr Ignore  = return T.ignore
genDecodeErr Strict  = return T.strictDecode
genDecodeErr Replace = arbitrary
214
215

instance Arbitrary DecodeErr where
216
    arbitrary = elements [Lenient, Ignore, Strict, Replace]
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

class Stringy s where
    packS    :: String -> s
    unpackS  :: s -> String
    splitAtS :: Int -> s -> (s,s)
    packSChunkSize :: Int -> String -> s
    packSChunkSize _ = packS

instance Stringy String where
    packS    = id
    unpackS  = id
    splitAtS = splitAt

instance Stringy (TF.Stream Char) where
    packS        = TF.streamList
    unpackS      = TF.unstreamList
    splitAtS n s = (TF.take n s, TF.drop n s)

instance Stringy T.Text where
    packS    = T.pack
    unpackS  = T.unpack
    splitAtS = T.splitAt

instance Stringy TL.Text where
    packSChunkSize k = TLF.unstreamChunks k . TF.streamList
    packS    = TL.pack
    unpackS  = TL.unpack
    splitAtS = ((TL.lazyInvariant *** TL.lazyInvariant) .) .
               TL.splitAt . fromIntegral

-- Do two functions give the same answer?
eq :: (Eq a, Show a) => (t -> a) -> (t -> a) -> t -> Bool
eq a b s  = a s =^= b s

-- What about with the RHS packed?
eqP :: (Eq a, Show a, Stringy s) =>
       (String -> a) -> (s -> a) -> String -> Word8 -> Bool
eqP f g s w  = eql "orig" (f s) (g t) &&
               eql "mini" (f s) (g mini) &&
               eql "head" (f sa) (g ta) &&
               eql "tail" (f sb) (g tb)
    where t             = packS s
          mini          = packSChunkSize 10 s
          (sa,sb)       = splitAt m s
          (ta,tb)       = splitAtS m t
          l             = length s
          m | l == 0    = n
            | otherwise = n `mod` l
          n             = fromIntegral w
          eql d a b
            | a =^= b   = True
            | otherwise = trace (d ++ ": " ++ show a ++ " /= " ++ show b) False

270
271
272
instance Arbitrary FPFormat where
    arbitrary = elements [Exponent, Fixed, Generic]

273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
newtype Precision a = Precision (Maybe Int)
                    deriving (Eq, Show)

precision :: a -> Precision a -> Maybe Int
precision _ (Precision prec) = prec

arbitraryPrecision :: Int -> Gen (Precision a)
arbitraryPrecision maxDigits = Precision <$> do
  n <- choose (-1,maxDigits)
  return $ if n == -1
           then Nothing
           else Just n

instance Arbitrary (Precision Float) where
    arbitrary = arbitraryPrecision 11
    shrink    = map Precision . shrink . precision undefined

instance Arbitrary (Precision Double) where
    arbitrary = arbitraryPrecision 22
    shrink    = map Precision . shrink . precision undefined

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
336
337
338
339
340
341
342
343
344
345
-- Work around lack of Show instance for TextEncoding.
data Encoding = E String IO.TextEncoding

instance Show Encoding where show (E n _) = "utf" ++ n

instance Arbitrary Encoding where
    arbitrary = oneof . map return $
      [ E "8" IO.utf8, E "8_bom" IO.utf8_bom, E "16" IO.utf16
      , E "16le" IO.utf16le, E "16be" IO.utf16be, E "32" IO.utf32
      , E "32le" IO.utf32le, E "32be" IO.utf32be
      ]

windowsNewlineMode :: IO.NewlineMode
windowsNewlineMode = IO.NewlineMode
    { IO.inputNL = IO.CRLF, IO.outputNL = IO.CRLF
    }

instance Arbitrary IO.NewlineMode where
    arbitrary = oneof . map return $
      [ IO.noNewlineTranslation, IO.universalNewlineMode, IO.nativeNewlineMode
      , windowsNewlineMode
      ]

instance Arbitrary IO.BufferMode where
    arbitrary = oneof [ return IO.NoBuffering,
                        return IO.LineBuffering,
                        return (IO.BlockBuffering Nothing),
                        (IO.BlockBuffering . Just . (+1) . fromIntegral) `fmap`
                        (arbitrary :: Gen Word16) ]

-- This test harness is complex!  What property are we checking?
--
-- Reading after writing a multi-line file should give the same
-- results as were written.
--
-- What do we vary while checking this property?
-- * The lines themselves, scrubbed to contain neither CR nor LF.  (By
--   working with a list of lines, we ensure that the data will
--   sometimes contain line endings.)
-- * Encoding.
-- * Newline translation mode.
-- * Buffering.
write_read :: (NFData a, Eq a)
           => ([b] -> a)
           -> ((Char -> Bool) -> a -> b)
           -> (IO.Handle -> a -> IO ())
           -> (IO.Handle -> IO a)
           -> Encoding
           -> IO.NewlineMode
           -> IO.BufferMode
           -> [a]
           -> Property
bos's avatar
bos committed
346
write_read unline filt writer reader (E _ _) nl buf ts =
347
348
349
350
351
352
353
354
355
356
357
358
359
360
    monadicIO $ assert . (==t) =<< run act
  where t = unline . map (filt (not . (`elem` "\r\n"))) $ ts
        act = withTempFile $ \path h -> do
                -- hSetEncoding h enc
                IO.hSetNewlineMode h nl
                IO.hSetBuffering h buf
                () <- writer h t
                IO.hClose h
                bracket (IO.openFile path IO.ReadMode) IO.hClose $ \h' -> do
                  -- hSetEncoding h' enc
                  IO.hSetNewlineMode h' nl
                  IO.hSetBuffering h' buf
                  r <- reader h'
                  r `deepseq` return r