Debian Codegraph @

test/hs/Test/Ganeti/TestCommon.hs

raw
1 {-# LANGUAGE CPP, FlexibleInstances #-}
2 {-# OPTIONS_GHC -fno-warn-orphans #-}
3
4 {-| Common helper functions and instances for all Ganeti tests.
5
6 -}
7
8 {-
9
10 Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc.
11 All rights reserved.
12
13 Redistribution and use in source and binary forms, with or without
14 modification, are permitted provided that the following conditions are
15 met:
16
17 1. Redistributions of source code must retain the above copyright notice,
18 this list of conditions and the following disclaimer.
19
20 2. Redistributions in binary form must reproduce the above copyright
21 notice, this list of conditions and the following disclaimer in the
22 documentation and/or other materials provided with the distribution.
23
24 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
25 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
26 TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
27 PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
28 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
30 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
31 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
32 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
33 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
34 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35
36 -}
37
38 module Test.Ganeti.TestCommon
39 ( maxMem
40 , maxDsk
41 , maxCpu
42 , maxSpindles
43 , maxVcpuRatio
44 , maxSpindleRatio
45 , maxNodes
46 , maxOpCodes
47 , (==?)
48 , (/=?)
49 , failTest
50 , passTest
51 , stableCover
52 , pythonCmd
53 , runPython
54 , checkPythonResult
55 , DNSChar(..)
56 , genPrintableAsciiChar
57 , genPrintableAsciiString
58 , genPrintableAsciiStringNE
59 , genPrintableByteString
60 , genName
61 , genFQDN
62 , genUUID
63 , genMaybe
64 , genSublist
65 , genMap
66 , genTags
67 , genFields
68 , genUniquesList
69 , SmallRatio(..)
70 , genSetHelper
71 , genSet
72 , genListSet
73 , genAndRestArguments
74 , genIPv4Address
75 , genIPv4Network
76 , genIp6Addr
77 , genIp6Net
78 , genOpCodesTagName
79 , genLuxiTagName
80 , netmask2NumHosts
81 , testSerialisation
82 , testArraySerialisation
83 , testDeserialisationFail
84 , resultProp
85 , readTestData
86 , genSample
87 , testParser
88 , genPropParser
89 , genNonNegative
90 , relativeError
91 , getTempFileName
92 , listOfUniqueBy
93 , counterexample
94 , cover'
95 ) where
96
97 import Control.Exception (catchJust)
98 import Control.Monad
99 import Control.Monad.Fail (MonadFail, fail)
100 import Data.Attoparsec.Text (Parser, parseOnly)
101 import Data.List
102 import qualified Data.Map as M
103 import Data.Text (pack)
104 import Data.Word
105 import qualified Data.ByteString as BS
106 import qualified Data.ByteString.UTF8 as UTF8
107 #if !MIN_VERSION_QuickCheck(2,10,0)
108 import Data.Char (isPrint)
109 #endif
110 import qualified Data.Set as Set
111 import System.Directory (getTemporaryDirectory, removeFile)
112 import System.Environment (getEnv)
113 import System.Exit (ExitCode(..))
114 import System.IO (hClose, openTempFile)
115 import System.IO.Error (isDoesNotExistError)
116 import System.Process (readProcessWithExitCode)
117 import qualified Test.HUnit as HUnit
118 import Test.QuickCheck
119 import Test.QuickCheck.Monadic
120 import qualified Text.JSON as J
121 import Numeric
122
123 import qualified Ganeti.BasicTypes as BasicTypes
124 import Ganeti.JSON (ArrayObject(..))
125 import Ganeti.Objects (TagSet(..))
126 import Ganeti.Types
127 import Ganeti.Utils.Monad (unfoldrM)
128
129 -- * Compatibility instances
130
131 instance MonadFail Gen where
132 fail = error "No monadfail instance"
133
134 instance MonadFail (Either String) where
135 fail x = Left x
136
137 -- * Arbitrary orphan instances
138
139 instance Arbitrary TagSet where
140 arbitrary = (TagSet . Set.fromList) <$> genTags
141
142 -- * Constants
143
144 -- | Maximum memory (1TiB, somewhat random value).
145 maxMem :: Int
146 maxMem = 1024 * 1024
147
148 -- | Maximum disk (8TiB, somewhat random value).
149 maxDsk :: Int
150 maxDsk = 1024 * 1024 * 8
151
152 -- | Max CPUs (1024, somewhat random value).
153 maxCpu :: Int
154 maxCpu = 1024
155
156 -- | Max spindles (1024, somewhat random value).
157 maxSpindles :: Int
158 maxSpindles = 1024
159
160 -- | Max vcpu ratio (random value).
161 maxVcpuRatio :: Double
162 maxVcpuRatio = 1024.0
163
164 -- | Max spindle ratio (random value).
165 maxSpindleRatio :: Double
166 maxSpindleRatio = 1024.0
167
168 -- | Max nodes, used just to limit arbitrary instances for smaller
169 -- opcode definitions (e.g. list of nodes in OpTestDelay).
170 maxNodes :: Int
171 maxNodes = 32
172
173 -- | Max opcodes or jobs in a submit job and submit many jobs.
174 maxOpCodes :: Int
175 maxOpCodes = 16
176
177 -- * Helper functions
178
179 -- | Checks for equality with proper annotation. The first argument is
180 -- the computed value, the second one the expected value.
181 (==?) :: (Show a, Eq a) => a -> a -> Property
182 (==?) x y = counterexample
183 ("Expected equality, but got mismatch\nexpected: " ++
184 show y ++ "\n but got: " ++ show x) (x == y)
185 infix 3 ==?
186
187 -- | Checks for inequality with proper annotation. The first argument
188 -- is the computed value, the second one the expected (not equal)
189 -- value.
190 (/=?) :: (Show a, Eq a) => a -> a -> Property
191 (/=?) x y = counterexample
192 ("Expected inequality, but got equality: '" ++
193 show x ++ "'.") (x /= y)
194 infix 3 /=?
195
196 -- | Show a message and fail the test.
197 failTest :: String -> Property
198 failTest msg = counterexample msg False
199
200 -- | A 'True' property.
201 passTest :: Property
202 passTest = property True
203
204 -- | QuickCheck 2.12 swapped the order of the first two arguments, so provide a
205 -- compatibility function here
206
207 cover' :: Testable prop => Double -> Bool -> String -> prop -> Property
208 #if MIN_VERSION_QuickCheck(2, 12, 0)
209 cover' = cover
210 #else
211 cover' p x = cover x (round p)
212 #endif
213
214 -- | A stable version of QuickCheck's `cover`. In its current implementation,
215 -- cover will not detect insufficient coverage if the actual coverage in the
216 -- sample is 0. Work around this by lifting the probability to at least
217 -- 10 percent.
218 -- The underlying issue is tracked at
219 -- https://github.com/nick8325/quickcheck/issues/26
220 stableCover :: Testable prop => Bool -> Double -> String -> prop -> Property
221 stableCover p percent s prop =
222 let newlabel = "(stabilized to at least 10%) " ++ s
223 in forAll (frequency [(1, return True), (9, return False)]) $ \ basechance ->
224 cover' (10 + (percent * 9 / 10)) (basechance || p) newlabel prop
225
226 -- | Return the python binary to use. If the PYTHON environment
227 -- variable is defined, use its value, otherwise use just \"python3\".
228 pythonCmd :: IO String
229 pythonCmd = catchJust (guard . isDoesNotExistError)
230 (getEnv "PYTHON") (const (return "python3"))
231
232 -- | Run Python with an expression, returning the exit code, standard
233 -- output and error.
234 runPython :: String -> String -> IO (ExitCode, String, String)
235 runPython expr stdin = do
236 py_binary <- pythonCmd
237 readProcessWithExitCode py_binary ["-c", expr] stdin
238
239 -- | Check python exit code, and fail via HUnit assertions if
240 -- non-zero. Otherwise, return the standard output.
241 checkPythonResult :: (ExitCode, String, String) -> IO String
242 checkPythonResult (py_code, py_stdout, py_stderr) = do
243 HUnit.assertEqual ("python exited with error: " ++ py_stderr)
244 ExitSuccess py_code
245 return py_stdout
246
247 -- * Arbitrary instances
248
249 -- | Defines a DNS name.
250 newtype DNSChar = DNSChar { dnsGetChar::Char }
251
252 instance Arbitrary DNSChar where
253 arbitrary = liftM DNSChar $ elements (['a'..'z'] ++ ['0'..'9'] ++ "_-")
254
255 instance Show DNSChar where
256 show = show . dnsGetChar
257
258 -- * Generators
259
260 -- | Generates printable ASCII characters (from ' ' to '~').
261 genPrintableAsciiChar :: Gen Char
262 genPrintableAsciiChar = choose ('\x20', '\x7e')
263
264 -- | Generates a short string (0 <= n <= 40 chars) from printable ASCII.
265 genPrintableAsciiString :: Gen String
266 genPrintableAsciiString = do
267 n <- choose (0, 40)
268 vectorOf n genPrintableAsciiChar
269
270 -- | Generates a short string (1 <= n <= 40 chars) from printable ASCII.
271 genPrintableAsciiStringNE :: Gen NonEmptyString
272 genPrintableAsciiStringNE = do
273 n <- choose (1, 40)
274 vectorOf n genPrintableAsciiChar >>= mkNonEmpty
275
276 -- | Generates a printable Unicode ByteString
277 genPrintableByteString :: Gen BS.ByteString
278 #if MIN_VERSION_QuickCheck(2, 10, 0)
279 genPrintableByteString = fmap (UTF8.fromString . getPrintableString) arbitrary
280 #else
281 genPrintableByteString =
282 fmap UTF8.fromString $ listOf (arbitrary `suchThat` isPrint)
283 #endif
284
285 -- | Generates a single name component.
286 genName :: Gen String
287 genName = do
288 n <- choose (1, 16)
289 dn <- vector n
290 return (map dnsGetChar dn)
291
292 -- | Generates an entire FQDN.
293 genFQDN :: Gen String
294 genFQDN = do
295 ncomps <- choose (1, 4)
296 names <- vectorOf ncomps genName
297 return $ intercalate "." names
298
299 -- | Generates a UUID-like string.
300 --
301 -- Only to be used for QuickCheck testing. For obtaining actual UUIDs use
302 -- the newUUID function in Ganeti.Utils
303 genUUID :: Gen String
304 genUUID = do
305 c1 <- vector 6
306 c2 <- vector 4
307 c3 <- vector 4
308 c4 <- vector 4
309 c5 <- vector 4
310 c6 <- vector 4
311 c7 <- vector 6
312 return $ map dnsGetChar c1 ++ "-" ++ map dnsGetChar c2 ++ "-" ++
313 map dnsGetChar c3 ++ "-" ++ map dnsGetChar c4 ++ "-" ++
314 map dnsGetChar c5 ++ "-" ++ map dnsGetChar c6 ++ "-" ++
315 map dnsGetChar c7
316
317 -- | Combinator that generates a 'Maybe' using a sub-combinator.
318 genMaybe :: Gen a -> Gen (Maybe a)
319 genMaybe subgen = frequency [ (1, pure Nothing), (3, Just <$> subgen) ]
320
321 -- | Generates a sublist of a given list, keeping the ordering.
322 -- The generated elements are always a subset of the list.
323 --
324 -- In order to better support corner cases, the size of the sublist is
325 -- chosen to have the uniform distribution.
326 genSublist :: [a] -> Gen [a]
327 genSublist xs = choose (0, l) >>= g xs l
328 where
329 l = length xs
330 g _ _ 0 = return []
331 g [] _ _ = return []
332 g ys n k | k == n = return ys
333 g (y:ys) n k = frequency [ (k, liftM (y :) (g ys (n - 1) (k - 1)))
334 , (n - k, g ys (n - 1) k)
335 ]
336
337 -- | Generates a map given generators for keys and values.
338 genMap :: (Ord k, Ord v) => Gen k -> Gen v -> Gen (M.Map k v)
339 genMap kg vg = M.fromList <$> listOf ((,) <$> kg <*> vg)
340
341 -- | Defines a tag type.
342 newtype TagChar = TagChar { tagGetChar :: Char }
343
344 -- | All valid tag chars. This doesn't need to match _exactly_
345 -- Ganeti's own tag regex, just enough for it to be close.
346 tagChar :: String
347 tagChar = ['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ ".+*/:@-"
348
349 instance Arbitrary TagChar where
350 arbitrary = liftM TagChar $ elements tagChar
351
352 -- | Generates a tag
353 genTag :: Gen [TagChar]
354 genTag = do
355 -- the correct value would be C.maxTagLen, but that's way too
356 -- verbose in unittests, and at the moment I don't see any possible
357 -- bugs with longer tags and the way we use tags in htools
358 n <- choose (1, 10)
359 vector n
360
361 -- | Generates a list of tags (correctly upper bounded).
362 genTags :: Gen [String]
363 genTags = do
364 -- the correct value would be C.maxTagsPerObj, but per the comment
365 -- in genTag, we don't use tags enough in htools to warrant testing
366 -- such big values
367 n <- choose (0, 10::Int)
368 tags <- mapM (const genTag) [1..n]
369 return $ map (map tagGetChar) tags
370
371 -- | Generates a fields list. This uses the same character set as a
372 -- DNS name (just for simplicity).
373 genFields :: Gen [String]
374 genFields = do
375 n <- choose (1, 32)
376 vectorOf n genName
377
378 -- | Generates a list of a given size with non-duplicate elements.
379 genUniquesList :: (Eq a, Arbitrary a, Ord a) => Int -> Gen a -> Gen [a]
380 genUniquesList cnt generator = do
381 set <- foldM (\set _ -> do
382 newelem <- generator `suchThat` (`Set.notMember` set)
383 return (Set.insert newelem set)) Set.empty [1..cnt]
384 return $ Set.toList set
385
386 newtype SmallRatio = SmallRatio Double deriving Show
387 instance Arbitrary SmallRatio where
388 arbitrary = liftM SmallRatio $ choose (0, 1)
389
390 -- | Helper for 'genSet', declared separately due to type constraints.
391 genSetHelper :: (Ord a) => [a] -> Maybe Int -> Gen (Set.Set a)
392 genSetHelper candidates size = do
393 size' <- case size of
394 Nothing -> choose (0, length candidates)
395 Just s | s > length candidates ->
396 error $ "Invalid size " ++ show s ++ ", maximum is " ++
397 show (length candidates)
398 | otherwise -> return s
399 foldM (\set _ -> do
400 newelem <- elements candidates `suchThat` (`Set.notMember` set)
401 return (Set.insert newelem set)) Set.empty [1..size']
402
403 -- | Generates a 'Set' of arbitrary elements.
404 genSet :: (Ord a, Bounded a, Enum a) => Maybe Int -> Gen (Set.Set a)
405 genSet = genSetHelper [minBound..maxBound]
406
407 -- | Generates a 'Set' of arbitrary elements wrapped in a 'ListSet'
408 genListSet :: (Ord a, Bounded a, Enum a) => Maybe Int
409 -> Gen (BasicTypes.ListSet a)
410 genListSet is = BasicTypes.ListSet <$> genSet is
411
412 -- | Generate an arbitrary element of and AndRestArguments field.
413 genAndRestArguments :: Gen (M.Map String J.JSValue)
414 genAndRestArguments = do
415 n <- choose (0::Int, 10)
416 let oneParam _ = do
417 name <- choose (15 ::Int, 25)
418 >>= flip vectorOf (elements tagChar)
419 intvalue <- arbitrary
420 value <- oneof [ J.JSString . J.toJSString <$> genName
421 , return $ J.showJSON (intvalue :: Int)
422 ]
423 return (name, value)
424 M.fromList `liftM` mapM oneParam [1..n]
425
426 -- | Generate an arbitrary IPv4 address in textual form.
427 genIPv4 :: Gen String
428 genIPv4 = do
429 a <- choose (1::Int, 255)
430 b <- choose (0::Int, 255)
431 c <- choose (0::Int, 255)
432 d <- choose (0::Int, 255)
433 return . intercalate "." $ map show [a, b, c, d]
434
435 genIPv4Address :: Gen IPv4Address
436 genIPv4Address = mkIPv4Address =<< genIPv4
437
438 -- | Generate an arbitrary IPv4 network in textual form.
439 genIPv4AddrRange :: Gen String
440 genIPv4AddrRange = do
441 pfxLen <- choose (8::Int, 30)
442 -- Generate a number that fits in pfxLen bits
443 addr <- choose(1::Int, 2^pfxLen-1)
444 let hostLen = 32 - pfxLen
445 -- ...and shift it left until it becomes a 32-bit number
446 -- with the low hostLen bits unset
447 net = addr * 2^hostLen
448 netBytes = [(net `div` 2^x) `mod` 256 | x <- [24::Int, 16, 8, 0]]
449 return $ intercalate "." (map show netBytes) ++ "/" ++ show pfxLen
450
451 genIPv4Network :: Gen IPv4Network
452 genIPv4Network = mkIPv4Network =<< genIPv4AddrRange
453
454 -- | Helper function to compute the number of hosts in a network
455 -- given the netmask. (For IPv4 only.)
456 netmask2NumHosts :: Word8 -> Int
457 netmask2NumHosts n = 2^(32-n)
458
459 -- | Generates an arbitrary IPv6 network address in textual form.
460 -- The generated address is not simpflified, e. g. an address like
461 -- "2607:f0d0:1002:0051:0000:0000:0000:0004" does not become
462 -- "2607:f0d0:1002:51::4"
463 genIp6Addr :: Gen String
464 genIp6Addr = do
465 rawIp <- vectorOf 8 $ choose (0::Integer, 65535)
466 return $ intercalate ":" (map (`showHex` "") rawIp)
467
468 -- | Helper function to convert an integer in to an IPv6 address in textual
469 -- form
470 ip6AddressFromNumber :: Integer -> [Char]
471 ip6AddressFromNumber ipInt =
472 -- chunksOf splits a sequence in chunks of n elements length each
473 -- chunksOf 4 "20010db80000" = ["2001", "0db8", "0000"]
474 let chunksOf :: Int -> [a] -> [[a]]
475 chunksOf _ [] = []
476 chunksOf n lst = take n lst : (chunksOf n $ drop n lst)
477 -- Left-pad a sequence with a fixed element if it's shorter than n
478 -- elements, or trim it to the first n elements otherwise
479 -- e.g. lPadTrim 6 '0' "abcd" = "00abcd"
480 lPadTrim :: Int -> a -> [a] -> [a]
481 lPadTrim n p lst
482 | length lst < n = lPadTrim n p $ p : lst
483 | otherwise = take n lst
484 rawIp = lPadTrim 32 '0' $ (`showHex` "") ipInt
485 in intercalate ":" $ chunksOf 4 rawIp
486
487 -- | Generates an arbitrary IPv6 network in textual form.
488 genIp6Net :: Gen String
489 genIp6Net = do
490 netmask <- choose (8::Int, 126)
491 raw_ip <- (* 2^(128-netmask)) <$> choose(1::Integer, 2^netmask-1)
492 return $ ip6AddressFromNumber raw_ip ++ "/" ++ show netmask
493
494 -- | Generates a valid, arbitrary tag name with respect to the given
495 -- 'TagKind' for opcodes.
496 genOpCodesTagName :: TagKind -> Gen (Maybe String)
497 genOpCodesTagName TagKindCluster = return Nothing
498 genOpCodesTagName _ = Just <$> genFQDN
499
500 -- | Generates a valid, arbitrary tag name with respect to the given
501 -- 'TagKind' for Luxi.
502 genLuxiTagName :: TagKind -> Gen String
503 genLuxiTagName TagKindCluster = return ""
504 genLuxiTagName _ = genFQDN
505
506 -- * Helper functions
507
508 -- | Checks for serialisation idempotence.
509 testSerialisation :: (Eq a, Show a, J.JSON a) => a -> Property
510 testSerialisation a =
511 case J.readJSON (J.showJSON a) of
512 J.Error msg -> failTest $ "Failed to deserialise: " ++ msg
513 J.Ok a' -> a ==? a'
514
515 -- | Checks for array serialisation idempotence.
516 testArraySerialisation :: (Eq a, Show a, ArrayObject a) => a -> Property
517 testArraySerialisation a =
518 case fromJSArray (toJSArray a) of
519 J.Error msg -> failTest $ "Failed to deserialise: " ++ msg
520 J.Ok a' -> a ==? a'
521
522 -- | Checks if the deserializer doesn't accept forbidden values.
523 -- The first argument is ignored, it just enforces the correct type.
524 testDeserialisationFail :: (Eq a, Show a, J.JSON a)
525 => a -> J.JSValue -> Property
526 testDeserialisationFail a val =
527 case liftM (`asTypeOf` a) $ J.readJSON val of
528 J.Error _ -> passTest
529 J.Ok x -> failTest $ "Parsed invalid value " ++ show val ++
530 " to: " ++ show x
531
532 -- | Result to PropertyM IO.
533 resultProp :: (Show a) => BasicTypes.GenericResult a b -> PropertyM IO b
534 resultProp (BasicTypes.Bad err) = stop . failTest $ show err
535 resultProp (BasicTypes.Ok val) = return val
536
537 -- | Return the source directory of Ganeti.
538 getSourceDir :: IO FilePath
539 getSourceDir = catchJust (guard . isDoesNotExistError)
540 (getEnv "TOP_SRCDIR")
541 (const (return "."))
542
543 -- | Returns the path of a file in the test data directory, given its name.
544 testDataFilename :: String -> String -> IO FilePath
545 testDataFilename datadir name = do
546 src <- getSourceDir
547 return $ src ++ datadir ++ name
548
549 -- | Returns the content of the specified haskell test data file.
550 readTestData :: String -> IO String
551 readTestData filename = do
552 name <- testDataFilename "/test/data/" filename
553 readFile name
554
555 -- | Generate arbitrary values in the IO monad. This is a simple
556 -- wrapper over 'sample''.
557 genSample :: Gen a -> IO a
558 genSample gen = do
559 values <- sample' gen
560 case values of
561 [] -> error "sample' returned an empty list of values??"
562 x:_ -> return x
563
564 -- | Function for testing whether a file is parsed correctly.
565 testParser :: (Show a, Eq a) => Parser a -> String -> a -> HUnit.Assertion
566 testParser parser fileName expectedContent = do
567 fileContent <- readTestData fileName
568 case parseOnly parser $ pack fileContent of
569 Left msg -> HUnit.assertFailure $ "Parsing failed: " ++ msg
570 Right obtained -> HUnit.assertEqual fileName expectedContent obtained
571
572 -- | Generate a property test for parsers.
573 genPropParser :: (Show a, Eq a) => Parser a -> String -> a -> Property
574 genPropParser parser s expected =
575 case parseOnly parser $ pack s of
576 Left msg -> failTest $ "Parsing failed: " ++ msg
577 Right obtained -> expected ==? obtained
578
579 -- | Generate an arbitrary non negative integer number
580 genNonNegative :: Gen Int
581 genNonNegative =
582 fmap fromEnum (arbitrary::Gen (Test.QuickCheck.NonNegative Int))
583
584 -- | Computes the relative error of two 'Double' numbers.
585 --
586 -- This is the \"relative error\" algorithm in
587 -- http:\/\/randomascii.wordpress.com\/2012\/02\/25\/
588 -- comparing-floating-point-numbers-2012-edition (URL split due to too
589 -- long line).
590 relativeError :: Double -> Double -> Double
591 relativeError d1 d2 =
592 let delta = abs $ d1 - d2
593 a1 = abs d1
594 a2 = abs d2
595 greatest = max a1 a2
596 in if delta == 0
597 then 0
598 else delta / greatest
599
600 -- | Helper to a get a temporary file name.
601 getTempFileName :: String -> IO FilePath
602 getTempFileName filename = do
603 tempdir <- getTemporaryDirectory
604 (fpath, handle) <- openTempFile tempdir filename
605 _ <- hClose handle
606 removeFile fpath
607 return fpath
608
609
610 -- | @listOfUniqueBy gen keyFun forbidden@: Generates a list of random length,
611 -- where all generated elements will be unique by the keying function
612 -- @keyFun@. They will also be distinct from all elements in @forbidden@ by
613 -- the keying function.
614 --
615 -- As for 'listOf', the maximum output length depends on the size parameter.
616 --
617 -- Example:
618 --
619 -- > listOfUniqueBy (arbitrary :: Gen String) (length) ["hey"]
620 -- > -- Generates a list of strings of different length, but not of length 3.
621 --
622 -- The passed @gen@ should not make key collisions too likely, since the
623 -- implementation uses `suchThat`, looping until enough unique elements
624 -- have been generated. If the @gen@ makes collisions likely, this function
625 -- will consequently be slow, or not terminate if it is not possible to
626 -- generate enough elements, like in:
627 --
628 -- > listOfUniqueBy (arbitrary :: Gen Int) (`mod` 2) []
629 -- > -- May not terminate depending on the size parameter of the Gen,
630 -- > -- since there are only 2 unique keys (0 and 1).
631 listOfUniqueBy :: (Ord b) => Gen a -> (a -> b) -> [a] -> Gen [a]
632 listOfUniqueBy gen keyFun forbidden = do
633 let keysOf = Set.fromList . map keyFun
634
635 k <- sized $ \n -> choose (0, n)
636 flip unfoldrM (0, keysOf forbidden) $ \(i, usedKeys) ->
637 if i == k
638 then return Nothing
639 else do
640 x <- gen `suchThat` ((`Set.notMember` usedKeys) . keyFun)
641 return $ Just (x, (i + 1, Set.insert (keyFun x) usedKeys))