QuickCheckUtils.hs 9.33 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
--
Bodigrim's avatar
Bodigrim committed
5
6
7
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE DeriveFunctor #-}

8
{-# OPTIONS_GHC -fno-warn-orphans #-}
Bodigrim's avatar
Bodigrim committed
9

bos's avatar
bos committed
10
module Tests.QuickCheckUtils
Bodigrim's avatar
Bodigrim committed
11
    ( BigInt(..)
bos's avatar
bos committed
12
    , NotEmpty(..)
Bodigrim's avatar
Bodigrim committed
13
    , Sqrt(..)
Bodigrim's avatar
Bodigrim committed
14
    , SpacyString(..)
15

16
17
18
    , Precision(..)
    , precision

bos's avatar
bos committed
19
    , DecodeErr(..)
20
    , genDecodeErr
21

bos's avatar
bos committed
22
    , Stringy(..)
Xia Li-yao's avatar
Xia Li-yao committed
23
    , unpack2
24
25
    , eq
    , eqP
Bodigrim's avatar
Bodigrim committed
26
    , eqPSqrt
27
28

    , write_read
29
30
    ) where

Bodigrim's avatar
Bodigrim committed
31
import Control.Arrow ((***))
32
33
import Control.DeepSeq (NFData (..), deepseq)
import Control.Exception (bracket)
Bodigrim's avatar
Bodigrim committed
34
import Data.Char (isSpace)
35
import Data.Text.Foreign (I8)
36
import Data.Text.Lazy.Builder.RealFloat (FPFormat(..))
bos's avatar
bos committed
37
import Data.Word (Word8, Word16)
38
import Test.QuickCheck (Arbitrary(..), arbitraryUnicodeChar, arbitraryBoundedEnum, getUnicodeString, arbitrarySizedIntegral, shrinkIntegral, Property, ioProperty, discard, counterexample, scale, (===), (.&&.), NonEmptyList(..))
39
import Test.QuickCheck.Gen (Gen, choose, chooseAny, elements, frequency, listOf, oneof, resize, sized)
bos's avatar
bos committed
40
import Tests.Utils
41
import qualified Data.ByteString as B
42
import qualified Data.ByteString.Lazy as BL
43
import qualified Data.Text as T
44
import qualified Data.Text.Encoding.Error as T
45
46
import qualified Data.Text.Internal.Fusion as TF
import qualified Data.Text.Internal.Fusion.Common as TF
bos's avatar
bos committed
47
import qualified Data.Text.Internal.Lazy as TL
bos's avatar
bos committed
48
49
import qualified Data.Text.Internal.Lazy.Fusion as TLF
import qualified Data.Text.Lazy as TL
50
51
import qualified System.IO as IO

52
53
54
genWord8 :: Gen Word8
genWord8 = chooseAny

55
instance Arbitrary I8 where
bos's avatar
bos committed
56
57
    arbitrary     = arbitrarySizedIntegral
    shrink        = shrinkIntegral
58
59

instance Arbitrary B.ByteString where
60
    arbitrary     = B.pack `fmap` listOf genWord8
bos's avatar
bos committed
61
    shrink        = map B.pack . shrink . B.unpack
62

63
64
65
66
67
68
69
70
71
72
73
74
75
76
instance Arbitrary BL.ByteString where
    arbitrary = oneof
      [ BL.fromChunks <$> arbitrary
      -- so that a single utf8 code point could appear split over up to 4 chunks
      , BL.fromChunks . map B.singleton <$> listOf genWord8
      -- so that a code point with 4 byte long utf8 representation
      -- could appear split over 3 non-singleton chunks
      , (\a b c -> BL.fromChunks [a, b, c])
        <$> arbitrary
        <*> ((\a b -> B.pack [a, b]) <$> genWord8 <*> genWord8)
        <*> arbitrary
      ]
    shrink xs = BL.fromChunks <$> shrink (BL.toChunks xs)

Bodigrim's avatar
Bodigrim committed
77
-- | For tests that have O(n^2) running times or input sizes, resize
78
-- their inputs to the square root of the originals.
Bodigrim's avatar
Bodigrim committed
79
80
newtype Sqrt a = Sqrt { unSqrt :: a }
    deriving (Eq, Show)
81

Bodigrim's avatar
Bodigrim committed
82
83
84
85
86
instance Arbitrary a => Arbitrary (Sqrt a) where
    arbitrary = fmap Sqrt $ sized $ \n -> resize (smallish n) arbitrary
        where
            smallish = round . (sqrt :: Double -> Double) . fromIntegral . abs
    shrink = map Sqrt . shrink . unSqrt
87
88

instance Arbitrary T.Text where
89
90
91
92
    arbitrary = do
        t <- (T.pack . getUnicodeString) `fmap` scale (* 2) arbitrary
        -- Generate chunks that start in the middle of their buffers.
        (\i -> T.drop i t) <$> choose (0, T.length t)
bos's avatar
bos committed
93
    shrink = map T.pack . shrink . T.unpack
94
95

instance Arbitrary TL.Text where
Bodigrim's avatar
Bodigrim committed
96
    arbitrary = (TL.fromChunks . map notEmpty . unSqrt) `fmap` arbitrary
bos's avatar
bos committed
97
    shrink = map TL.pack . shrink . TL.unpack
98

bos's avatar
bos committed
99
100
101
102
newtype BigInt = Big Integer
               deriving (Eq, Show)

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

107
newtype NotEmpty a = NotEmpty { notEmpty :: a }
Bodigrim's avatar
Bodigrim committed
108
    deriving (Eq, Ord, Show)
109
110

instance Arbitrary (NotEmpty T.Text) where
Bodigrim's avatar
Bodigrim committed
111
112
113
    arbitrary   = fmap (NotEmpty . T.pack . getNonEmpty) arbitrary
    shrink      = fmap (NotEmpty . T.pack . getNonEmpty)
                . shrink . NonEmpty . T.unpack . notEmpty
114
115

instance Arbitrary (NotEmpty TL.Text) where
Bodigrim's avatar
Bodigrim committed
116
117
118
    arbitrary   = fmap (NotEmpty . TL.pack . getNonEmpty) arbitrary
    shrink      = fmap (NotEmpty . TL.pack . getNonEmpty)
                . shrink . NonEmpty . TL.unpack . notEmpty
119

120
data DecodeErr = Lenient | Ignore | Strict | Replace
Bodigrim's avatar
Bodigrim committed
121
               deriving (Show, Eq, Bounded, Enum)
122

123
124
125
126
genDecodeErr :: DecodeErr -> Gen T.OnDecodeError
genDecodeErr Lenient = return T.lenientDecode
genDecodeErr Ignore  = return T.ignore
genDecodeErr Strict  = return T.strictDecode
127
128
genDecodeErr Replace = (\c _ _ -> c) <$> frequency
  [ (1, return Nothing)
Bodigrim's avatar
Bodigrim committed
129
  , (50, Just <$> arbitraryUnicodeChar)
130
  ]
131
132

instance Arbitrary DecodeErr where
Bodigrim's avatar
Bodigrim committed
133
    arbitrary = arbitraryBoundedEnum
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

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

Xia Li-yao's avatar
Xia Li-yao committed
164
165
166
unpack2 :: (Stringy s) => (s,s) -> (String,String)
unpack2 = unpackS *** unpackS

167
-- Do two functions give the same answer?
168
eq :: (Eq a, Show a) => (t -> a) -> (t -> a) -> t -> Property
169
170
171
172
eq a b s  = a s =^= b s

-- What about with the RHS packed?
eqP :: (Eq a, Show a, Stringy s) =>
173
174
175
176
177
       (String -> a) -> (s -> a) -> String -> Word8 -> Property
eqP f g s w  = counterexample "orig" (f s =^= g t) .&&.
               counterexample "mini" (f s =^= g mini) .&&.
               counterexample "head" (f sa =^= g ta) .&&.
               counterexample "tail" (f sb =^= g tb)
178
179
180
181
182
183
184
185
186
    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

Bodigrim's avatar
Bodigrim committed
187
eqPSqrt :: (Eq a, Show a, Stringy s) =>
188
       (String -> a) -> (s -> a) -> Sqrt String -> Word8 -> Property
Bodigrim's avatar
Bodigrim committed
189
190
eqPSqrt f g s = eqP f g (unSqrt s)

191
instance Arbitrary FPFormat where
Bodigrim's avatar
Bodigrim committed
192
    arbitrary = arbitraryBoundedEnum
193

194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
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

215
216
instance Arbitrary IO.Newline where
    arbitrary = oneof [return IO.LF, return IO.CRLF]
217
218

instance Arbitrary IO.NewlineMode where
219
    arbitrary = IO.NewlineMode <$> arbitrary <*> arbitrary
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238

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.)
-- * Newline translation mode.
-- * Buffering.
239
write_read :: (NFData a, Eq a, Show a)
240
241
242
243
244
245
246
247
           => ([b] -> a)
           -> ((Char -> Bool) -> a -> b)
           -> (IO.Handle -> a -> IO ())
           -> (IO.Handle -> IO a)
           -> IO.NewlineMode
           -> IO.BufferMode
           -> [a]
           -> Property
248
249
write_read _ _ _ _ (IO.NewlineMode IO.LF IO.CRLF) _ _ = discard
write_read unline filt writer reader nl buf ts = ioProperty $
250
251
252
253
254
    (===t) <$> act
  where
    t = unline . map (filt (not . (`elem` "\r\n"))) $ ts

    act = withTempFile $ \path h -> do
255
            IO.hSetEncoding h IO.utf8
256
257
258
259
260
            IO.hSetNewlineMode h nl
            IO.hSetBuffering h buf
            () <- writer h t
            IO.hClose h
            bracket (IO.openFile path IO.ReadMode) IO.hClose $ \h' -> do
261
              IO.hSetEncoding h' IO.utf8
262
263
264
265
              IO.hSetNewlineMode h' nl
              IO.hSetBuffering h' buf
              r <- reader h'
              r `deepseq` return r
Bodigrim's avatar
Bodigrim committed
266
267
268
269
270
271
272
273
274
275
276
277
278
279

-- Generate various Unicode space characters with high probability
arbitrarySpacyChar :: Gen Char
arbitrarySpacyChar = oneof
  [ arbitraryUnicodeChar
  , elements $ filter isSpace [minBound..maxBound]
  ]

newtype SpacyString = SpacyString { getSpacyString :: String }
  deriving (Eq, Ord, Show, Read)

instance Arbitrary SpacyString where
  arbitrary = SpacyString `fmap` listOf arbitrarySpacyChar
  shrink (SpacyString xs) = SpacyString `fmap` shrink xs