QC.hs 77.8 KB
Newer Older
1
{-# LANGUAGE TemplateHaskell #-}
2
3
4
5
6
7
{-# OPTIONS_GHC -fno-warn-orphans -fno-warn-unused-imports #-}

-- FIXME: should remove the no-warn-unused-imports option, once we get
-- around to testing function from all modules; until then, we keep
-- the (unused) imports here to generate correct coverage (0 for
-- modules we don't use)
8

9
{-| Unittests for ganeti-htools.
Iustin Pop's avatar
Iustin Pop committed
10
11
12
13
14

-}

{-

Iustin Pop's avatar
Iustin Pop committed
15
Copyright (C) 2009, 2010, 2011, 2012 Google Inc.
Iustin Pop's avatar
Iustin Pop committed
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.

-}

34
module Ganeti.HTools.QC
Iustin Pop's avatar
Iustin Pop committed
35
36
37
38
39
40
  ( testUtils
  , testPeerMap
  , testContainer
  , testInstance
  , testNode
  , testText
41
  , testSimu
Iustin Pop's avatar
Iustin Pop committed
42
43
44
45
46
  , testOpCodes
  , testJobs
  , testCluster
  , testLoader
  , testTypes
47
  , testCLI
Iustin Pop's avatar
Iustin Pop committed
48
  , testJSON
49
  , testLuxi
50
  , testSsconf
Agata Murawska's avatar
Agata Murawska committed
51
  , testRpc
Iustin Pop's avatar
Iustin Pop committed
52
  , testQlang
Iustin Pop's avatar
Iustin Pop committed
53
  ) where
54

55
import qualified Test.HUnit as HUnit
56
import Test.QuickCheck
Agata Murawska's avatar
Agata Murawska committed
57
import Test.QuickCheck.Monadic (assert, monadicIO, run, stop)
58
import Text.Printf (printf)
59
import Data.List (intercalate, nub, isPrefixOf)
60
import Data.Maybe
61
import qualified Data.Set as Set
Iustin Pop's avatar
Iustin Pop committed
62
import Control.Monad
Iustin Pop's avatar
Iustin Pop committed
63
import Control.Applicative
Iustin Pop's avatar
Iustin Pop committed
64
import qualified System.Console.GetOpt as GetOpt
Iustin Pop's avatar
Iustin Pop committed
65
import qualified Text.JSON as J
Iustin Pop's avatar
Iustin Pop committed
66
import qualified Data.Map
67
import qualified Data.IntMap as IntMap
68
69
70
import Control.Concurrent (forkIO)
import Control.Exception (bracket, catchJust)
import System.Directory (getTemporaryDirectory, removeFile)
71
72
import System.Environment (getEnv)
import System.Exit (ExitCode(..))
73
import System.IO (hClose, openTempFile)
74
75
import System.IO.Error (isEOFErrorType, ioeGetErrorType, isDoesNotExistError)
import System.Process (readProcessWithExitCode)
Iustin Pop's avatar
Iustin Pop committed
76

Iustin Pop's avatar
Iustin Pop committed
77
78
79
80
import qualified Ganeti.Confd as Confd
import qualified Ganeti.Config as Config
import qualified Ganeti.Daemon as Daemon
import qualified Ganeti.Hash as Hash
Iustin Pop's avatar
Iustin Pop committed
81
import qualified Ganeti.BasicTypes as BasicTypes
82
import qualified Ganeti.Jobs as Jobs
Iustin Pop's avatar
Iustin Pop committed
83
import qualified Ganeti.Logging as Logging
84
import qualified Ganeti.Luxi as Luxi
Iustin Pop's avatar
Iustin Pop committed
85
86
import qualified Ganeti.Objects as Objects
import qualified Ganeti.OpCodes as OpCodes
Iustin Pop's avatar
Iustin Pop committed
87
import qualified Ganeti.Qlang as Qlang
88
import qualified Ganeti.Rpc as Rpc
Iustin Pop's avatar
Iustin Pop committed
89
import qualified Ganeti.Runtime as Runtime
90
import qualified Ganeti.Ssconf as Ssconf
91
92
93
import qualified Ganeti.HTools.CLI as CLI
import qualified Ganeti.HTools.Cluster as Cluster
import qualified Ganeti.HTools.Container as Container
Iustin Pop's avatar
Iustin Pop committed
94
import qualified Ganeti.HTools.ExtLoader
Iustin Pop's avatar
Iustin Pop committed
95
import qualified Ganeti.HTools.Group as Group
96
97
import qualified Ganeti.HTools.IAlloc as IAlloc
import qualified Ganeti.HTools.Instance as Instance
98
import qualified Ganeti.HTools.JSON as JSON
99
import qualified Ganeti.HTools.Loader as Loader
100
import qualified Ganeti.HTools.Luxi as HTools.Luxi
101
102
import qualified Ganeti.HTools.Node as Node
import qualified Ganeti.HTools.PeerMap as PeerMap
103
import qualified Ganeti.HTools.Rapi
104
import qualified Ganeti.HTools.Simu as Simu
105
106
107
import qualified Ganeti.HTools.Text as Text
import qualified Ganeti.HTools.Types as Types
import qualified Ganeti.HTools.Utils as Utils
Iustin Pop's avatar
Iustin Pop committed
108
import qualified Ganeti.HTools.Version
109
import qualified Ganeti.Constants as C
110

111
import qualified Ganeti.HTools.Program as Program
112
113
114
115
116
import qualified Ganeti.HTools.Program.Hail
import qualified Ganeti.HTools.Program.Hbal
import qualified Ganeti.HTools.Program.Hscan
import qualified Ganeti.HTools.Program.Hspace

117
import Ganeti.HTools.QCHelper (testSuite)
Iustin Pop's avatar
Iustin Pop committed
118

119
120
-- * Constants

121
-- | Maximum memory (1TiB, somewhat random value).
Iustin Pop's avatar
Iustin Pop committed
122
123
124
maxMem :: Int
maxMem = 1024 * 1024

125
-- | Maximum disk (8TiB, somewhat random value).
Iustin Pop's avatar
Iustin Pop committed
126
maxDsk :: Int
Iustin Pop's avatar
Iustin Pop committed
127
maxDsk = 1024 * 1024 * 8
Iustin Pop's avatar
Iustin Pop committed
128

129
-- | Max CPUs (1024, somewhat random value).
Iustin Pop's avatar
Iustin Pop committed
130
131
132
maxCpu :: Int
maxCpu = 1024

133
134
135
136
137
138
139
140
-- | Max vcpu ratio (random value).
maxVcpuRatio :: Double
maxVcpuRatio = 1024.0

-- | Max spindle ratio (random value).
maxSpindleRatio :: Double
maxSpindleRatio = 1024.0

Iustin Pop's avatar
Iustin Pop committed
141
142
143
144
145
146
147
148
149
-- | Max nodes, used just to limit arbitrary instances for smaller
-- opcode definitions (e.g. list of nodes in OpTestDelay).
maxNodes :: Int
maxNodes = 32

-- | Max opcodes or jobs in a submit job and submit many jobs.
maxOpCodes :: Int
maxOpCodes = 16

150
151
152
153
-- | All disk templates (used later)
allDiskTemplates :: [Types.DiskTemplate]
allDiskTemplates = [minBound..maxBound]

154
-- | Null iPolicy, and by null we mean very liberal.
155
nullIPolicy :: Types.IPolicy
156
157
158
159
160
161
nullIPolicy = Types.IPolicy
  { Types.iPolicyMinSpec = Types.ISpec { Types.iSpecMemorySize = 0
                                       , Types.iSpecCpuCount   = 0
                                       , Types.iSpecDiskSize   = 0
                                       , Types.iSpecDiskCount  = 0
                                       , Types.iSpecNicCount   = 0
162
                                       , Types.iSpecSpindleUse = 0
163
164
165
166
167
168
                                       }
  , Types.iPolicyMaxSpec = Types.ISpec { Types.iSpecMemorySize = maxBound
                                       , Types.iSpecCpuCount   = maxBound
                                       , Types.iSpecDiskSize   = maxBound
                                       , Types.iSpecDiskCount  = C.maxDisks
                                       , Types.iSpecNicCount   = C.maxNics
169
                                       , Types.iSpecSpindleUse = maxBound
170
171
172
173
174
175
                                       }
  , Types.iPolicyStdSpec = Types.ISpec { Types.iSpecMemorySize = Types.unitMem
                                       , Types.iSpecCpuCount   = Types.unitCpu
                                       , Types.iSpecDiskSize   = Types.unitDsk
                                       , Types.iSpecDiskCount  = 1
                                       , Types.iSpecNicCount   = 1
176
                                       , Types.iSpecSpindleUse = 1
177
                                       }
178
  , Types.iPolicyDiskTemplates = [minBound..maxBound]
179
180
181
  , Types.iPolicyVcpuRatio = maxVcpuRatio -- somewhat random value, high
                                          -- enough to not impact us
  , Types.iPolicySpindleRatio = maxSpindleRatio
182
183
184
  }


Iustin Pop's avatar
Iustin Pop committed
185
186
defGroup :: Group.Group
defGroup = flip Group.setIdx 0 $
Iustin Pop's avatar
Iustin Pop committed
187
             Group.create "default" Types.defaultGroupID Types.AllocPreferred
188
                  nullIPolicy
Iustin Pop's avatar
Iustin Pop committed
189
190

defGroupList :: Group.List
Iustin Pop's avatar
Iustin Pop committed
191
defGroupList = Container.fromList [(Group.idx defGroup, defGroup)]
Iustin Pop's avatar
Iustin Pop committed
192
193
194
195

defGroupAssoc :: Data.Map.Map String Types.Gdx
defGroupAssoc = Data.Map.singleton (Group.uuid defGroup) (Group.idx defGroup)

196
197
-- * Helper functions

198
-- | Simple checker for whether OpResult is fail or pass.
Iustin Pop's avatar
Iustin Pop committed
199
200
201
202
isFailure :: Types.OpResult a -> Bool
isFailure (Types.OpFail _) = True
isFailure _ = False

Iustin Pop's avatar
Iustin Pop committed
203
204
205
206
207
208
209
-- | Checks for equality with proper annotation.
(==?) :: (Show a, Eq a) => a -> a -> Property
(==?) x y = printTestCase
            ("Expected equality, but '" ++
             show x ++ "' /= '" ++ show y ++ "'") (x == y)
infix 3 ==?

Iustin Pop's avatar
Iustin Pop committed
210
211
212
213
-- | Show a message and fail the test.
failTest :: String -> Property
failTest msg = printTestCase msg False

214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
-- | Return the python binary to use. If the PYTHON environment
-- variable is defined, use its value, otherwise use just \"python\".
pythonCmd :: IO String
pythonCmd = catchJust (guard . isDoesNotExistError)
            (getEnv "PYTHON") (const (return "python"))

-- | Run Python with an expression, returning the exit code, standard
-- output and error.
runPython :: String -> String -> IO (ExitCode, String, String)
runPython expr stdin = do
  py_binary <- pythonCmd
  readProcessWithExitCode py_binary ["-c", expr] stdin

-- | Check python exit code, and fail via HUnit assertions if
-- non-zero. Otherwise, return the standard output.
checkPythonResult :: (ExitCode, String, String) -> IO String
checkPythonResult (py_code, py_stdout, py_stderr) = do
  HUnit.assertEqual ("python exited with error: " ++ py_stderr)
       ExitSuccess py_code
  return py_stdout

235
-- | Update an instance to be smaller than a node.
236
237
setInstanceSmallerThanNode :: Node.Node
                           -> Instance.Instance -> Instance.Instance
238
setInstanceSmallerThanNode node inst =
Iustin Pop's avatar
Iustin Pop committed
239
240
241
242
  inst { Instance.mem = Node.availMem node `div` 2
       , Instance.dsk = Node.availDisk node `div` 2
       , Instance.vcpus = Node.availCpu node `div` 2
       }
243

244
-- | Create an instance given its spec.
245
createInstance :: Int -> Int -> Int -> Instance.Instance
246
createInstance mem dsk vcpus =
Iustin Pop's avatar
Iustin Pop committed
247
  Instance.create "inst-unnamed" mem dsk vcpus Types.Running [] True (-1) (-1)
248
    Types.DTDrbd8 1
249

250
-- | Create a small cluster by repeating a node spec.
251
252
makeSmallCluster :: Node.Node -> Int -> Node.List
makeSmallCluster node count =
253
254
255
256
257
258
259
  let origname = Node.name node
      origalias = Node.alias node
      nodes = map (\idx -> node { Node.name = origname ++ "-" ++ show idx
                                , Node.alias = origalias ++ "-" ++ show idx })
              [1..count]
      fn = flip Node.buildPeers Container.empty
      namelst = map (\n -> (Node.name n, fn n)) nodes
Iustin Pop's avatar
Iustin Pop committed
260
261
      (_, nlst) = Loader.assignIndices namelst
  in nlst
262

Iustin Pop's avatar
Iustin Pop committed
263
264
265
266
267
268
269
-- | Make a small cluster, both nodes and instances.
makeSmallEmptyCluster :: Node.Node -> Int -> Instance.Instance
                      -> (Node.List, Instance.List, Instance.Instance)
makeSmallEmptyCluster node count inst =
  (makeSmallCluster node count, Container.empty,
   setInstanceSmallerThanNode node inst)

270
-- | Checks if a node is "big" enough.
271
272
isNodeBig :: Int -> Node.Node -> Bool
isNodeBig size node = Node.availDisk node > size * Types.unitDsk
273
274
275
                      && Node.availMem node > size * Types.unitMem
                      && Node.availCpu node > size * Types.unitCpu

276
277
canBalance :: Cluster.Table -> Bool -> Bool -> Bool -> Bool
canBalance tbl dm im evac = isJust $ Cluster.tryBalance tbl dm im evac 0 0
278

279
-- | Assigns a new fresh instance to a cluster; this is not
280
-- allocation, so no resource checks are done.
281
282
283
284
285
286
287
assignInstance :: Node.List -> Instance.List -> Instance.Instance ->
                  Types.Idx -> Types.Idx ->
                  (Node.List, Instance.List)
assignInstance nl il inst pdx sdx =
  let pnode = Container.find pdx nl
      snode = Container.find sdx nl
      maxiidx = if Container.null il
Iustin Pop's avatar
Iustin Pop committed
288
289
                  then 0
                  else fst (Container.findMax il) + 1
290
291
292
293
294
295
296
297
      inst' = inst { Instance.idx = maxiidx,
                     Instance.pNode = pdx, Instance.sNode = sdx }
      pnode' = Node.setPri pnode inst'
      snode' = Node.setSec snode inst'
      nl' = Container.addTwo pdx pnode' sdx snode' nl
      il' = Container.add maxiidx inst' il
  in (nl', il')

298
299
300
301
302
303
304
-- | Generates a list of a given size with non-duplicate elements.
genUniquesList :: (Eq a, Arbitrary a) => Int -> Gen [a]
genUniquesList cnt =
  foldM (\lst _ -> do
           newelem <- arbitrary `suchThat` (`notElem` lst)
           return (newelem:lst)) [] [1..cnt]

305
306
-- | Checks if an instance is mirrored.
isMirrored :: Instance.Instance -> Bool
307
isMirrored = (/= Types.MirrorNone) . Instance.mirrorType
308
309
310
311
312
313
314

-- | Returns the possible change node types for a disk template.
evacModeOptions :: Types.MirrorType -> [Types.EvacMode]
evacModeOptions Types.MirrorNone     = []
evacModeOptions Types.MirrorInternal = [minBound..maxBound] -- DRBD can do all
evacModeOptions Types.MirrorExternal = [Types.ChangePrimary, Types.ChangeAll]

315
316
-- * Arbitrary instances

317
-- | Defines a DNS name.
318
newtype DNSChar = DNSChar { dnsGetChar::Char }
319

320
instance Arbitrary DNSChar where
Iustin Pop's avatar
Iustin Pop committed
321
322
323
  arbitrary = do
    x <- elements (['a'..'z'] ++ ['0'..'9'] ++ "_-")
    return (DNSChar x)
324

325
326
327
instance Show DNSChar where
  show = show . dnsGetChar

328
-- | Generates a single name component.
329
330
331
getName :: Gen String
getName = do
  n <- choose (1, 64)
Iustin Pop's avatar
Iustin Pop committed
332
  dn <- vector n
333
334
  return (map dnsGetChar dn)

335
-- | Generates an entire FQDN.
336
337
338
getFQDN :: Gen String
getFQDN = do
  ncomps <- choose (1, 4)
Iustin Pop's avatar
Iustin Pop committed
339
  names <- vectorOf ncomps getName
340
  return $ intercalate "." names
341

Iustin Pop's avatar
Iustin Pop committed
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
-- | Combinator that generates a 'Maybe' using a sub-combinator.
getMaybe :: Gen a -> Gen (Maybe a)
getMaybe subgen = do
  bool <- arbitrary
  if bool
    then Just <$> subgen
    else return Nothing

-- | Generates a fields list. This uses the same character set as a
-- DNS name (just for simplicity).
getFields :: Gen [String]
getFields = do
  n <- choose (1, 32)
  vectorOf n getName

357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
-- | Defines a tag type.
newtype TagChar = TagChar { tagGetChar :: Char }

-- | All valid tag chars. This doesn't need to match _exactly_
-- Ganeti's own tag regex, just enough for it to be close.
tagChar :: [Char]
tagChar = ['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ ".+*/:@-"

instance Arbitrary TagChar where
  arbitrary = do
    c <- elements tagChar
    return (TagChar c)

-- | Generates a tag
genTag :: Gen [TagChar]
genTag = do
  -- the correct value would be C.maxTagLen, but that's way too
  -- verbose in unittests, and at the moment I don't see any possible
  -- bugs with longer tags and the way we use tags in htools
  n <- choose (1, 10)
  vector n

-- | Generates a list of tags (correctly upper bounded).
genTags :: Gen [String]
genTags = do
  -- the correct value would be C.maxTagsPerObj, but per the comment
  -- in genTag, we don't use tags enough in htools to warrant testing
  -- such big values
  n <- choose (0, 10::Int)
  tags <- mapM (const genTag) [1..n]
  return $ map (map tagGetChar) tags

389
instance Arbitrary Types.InstanceStatus where
390
    arbitrary = elements [minBound..maxBound]
391

392
393
394
395
396
397
398
399
400
401
-- | Generates a random instance with maximum disk/mem/cpu values.
genInstanceSmallerThan :: Int -> Int -> Int -> Gen Instance.Instance
genInstanceSmallerThan lim_mem lim_dsk lim_cpu = do
  name <- getFQDN
  mem <- choose (0, lim_mem)
  dsk <- choose (0, lim_dsk)
  run_st <- arbitrary
  pn <- arbitrary
  sn <- arbitrary
  vcpus <- choose (0, lim_cpu)
402
403
  dt <- arbitrary
  return $ Instance.create name mem dsk vcpus run_st [] True pn sn dt 1
404
405
406
407
408
409
410
411

-- | Generates an instance smaller than a node.
genInstanceSmallerThanNode :: Node.Node -> Gen Instance.Instance
genInstanceSmallerThanNode node =
  genInstanceSmallerThan (Node.availMem node `div` 2)
                         (Node.availDisk node `div` 2)
                         (Node.availCpu node `div` 2)

412
413
-- let's generate a random instance
instance Arbitrary Instance.Instance where
414
  arbitrary = genInstanceSmallerThan maxMem maxDsk maxCpu
415

416
417
418
419
420
-- | Generas an arbitrary node based on sizing information.
genNode :: Maybe Int -- ^ Minimum node size in terms of units
        -> Maybe Int -- ^ Maximum node size (when Nothing, bounded
                     -- just by the max... constants)
        -> Gen Node.Node
421
422
genNode min_multiplier max_multiplier = do
  let (base_mem, base_dsk, base_cpu) =
Iustin Pop's avatar
Iustin Pop committed
423
424
425
426
427
        case min_multiplier of
          Just mm -> (mm * Types.unitMem,
                      mm * Types.unitDsk,
                      mm * Types.unitCpu)
          Nothing -> (0, 0, 0)
428
      (top_mem, top_dsk, top_cpu)  =
Iustin Pop's avatar
Iustin Pop committed
429
430
431
432
433
        case max_multiplier of
          Just mm -> (mm * Types.unitMem,
                      mm * Types.unitDsk,
                      mm * Types.unitCpu)
          Nothing -> (maxMem, maxDsk, maxCpu)
434
435
436
437
438
439
440
441
442
  name  <- getFQDN
  mem_t <- choose (base_mem, top_mem)
  mem_f <- choose (base_mem, mem_t)
  mem_n <- choose (0, mem_t - mem_f)
  dsk_t <- choose (base_dsk, top_dsk)
  dsk_f <- choose (base_dsk, dsk_t)
  cpu_t <- choose (base_cpu, top_cpu)
  offl  <- arbitrary
  let n = Node.create name (fromIntegral mem_t) mem_n mem_f
443
          (fromIntegral dsk_t) dsk_f (fromIntegral cpu_t) offl 1 0
Iustin Pop's avatar
Iustin Pop committed
444
445
      n' = Node.setPolicy nullIPolicy n
  return $ Node.buildPeers n' Container.empty
446

447
448
449
450
451
452
453
454
455
-- | Helper function to generate a sane node.
genOnlineNode :: Gen Node.Node
genOnlineNode = do
  arbitrary `suchThat` (\n -> not (Node.offline n) &&
                              not (Node.failN1 n) &&
                              Node.availDisk n > 0 &&
                              Node.availMem n > 0 &&
                              Node.availCpu n > 0)

456
457
-- and a random node
instance Arbitrary Node.Node where
Iustin Pop's avatar
Iustin Pop committed
458
  arbitrary = genNode Nothing Nothing
459

Iustin Pop's avatar
Iustin Pop committed
460
461
-- replace disks
instance Arbitrary OpCodes.ReplaceDisksMode where
462
  arbitrary = elements [minBound..maxBound]
Iustin Pop's avatar
Iustin Pop committed
463
464
465

instance Arbitrary OpCodes.OpCode where
  arbitrary = do
466
    op_id <- elements OpCodes.allOpIDs
Iustin Pop's avatar
Iustin Pop committed
467
468
    case op_id of
      "OP_TEST_DELAY" ->
Iustin Pop's avatar
Iustin Pop committed
469
470
        OpCodes.OpTestDelay <$> arbitrary <*> arbitrary
                 <*> resize maxNodes (listOf getFQDN)
Iustin Pop's avatar
Iustin Pop committed
471
      "OP_INSTANCE_REPLACE_DISKS" ->
Iustin Pop's avatar
Iustin Pop committed
472
473
        OpCodes.OpInstanceReplaceDisks <$> getFQDN <*> getMaybe getFQDN <*>
          arbitrary <*> resize C.maxDisks arbitrary <*> getMaybe getName
Iustin Pop's avatar
Iustin Pop committed
474
      "OP_INSTANCE_FAILOVER" ->
Iustin Pop's avatar
Iustin Pop committed
475
476
        OpCodes.OpInstanceFailover <$> getFQDN <*> arbitrary <*>
          getMaybe getFQDN
Iustin Pop's avatar
Iustin Pop committed
477
      "OP_INSTANCE_MIGRATE" ->
Iustin Pop's avatar
Iustin Pop committed
478
479
        OpCodes.OpInstanceMigrate <$> getFQDN <*> arbitrary <*>
          arbitrary <*> arbitrary <*> getMaybe getFQDN
Iustin Pop's avatar
Iustin Pop committed
480
      _ -> fail "Wrong opcode"
Iustin Pop's avatar
Iustin Pop committed
481

482
483
484
485
486
487
instance Arbitrary Jobs.OpStatus where
  arbitrary = elements [minBound..maxBound]

instance Arbitrary Jobs.JobStatus where
  arbitrary = elements [minBound..maxBound]

488
489
newtype SmallRatio = SmallRatio Double deriving Show
instance Arbitrary SmallRatio where
Iustin Pop's avatar
Iustin Pop committed
490
491
492
  arbitrary = do
    v <- choose (0, 1)
    return $ SmallRatio v
493

494
495
496
497
498
499
instance Arbitrary Types.AllocPolicy where
  arbitrary = elements [minBound..maxBound]

instance Arbitrary Types.DiskTemplate where
  arbitrary = elements [minBound..maxBound]

500
instance Arbitrary Types.FailMode where
Iustin Pop's avatar
Iustin Pop committed
501
  arbitrary = elements [minBound..maxBound]
502

503
504
505
instance Arbitrary Types.EvacMode where
  arbitrary = elements [minBound..maxBound]

506
instance Arbitrary a => Arbitrary (Types.OpResult a) where
Iustin Pop's avatar
Iustin Pop committed
507
  arbitrary = arbitrary >>= \c ->
Iustin Pop's avatar
Iustin Pop committed
508
              if c
Iustin Pop's avatar
Iustin Pop committed
509
510
                then Types.OpGood <$> arbitrary
                else Types.OpFail <$> arbitrary
511

512
513
instance Arbitrary Types.ISpec where
  arbitrary = do
514
    mem_s <- arbitrary::Gen (NonNegative Int)
515
516
    dsk_c <- arbitrary::Gen (NonNegative Int)
    dsk_s <- arbitrary::Gen (NonNegative Int)
517
518
    cpu_c <- arbitrary::Gen (NonNegative Int)
    nic_c <- arbitrary::Gen (NonNegative Int)
519
    su    <- arbitrary::Gen (NonNegative Int)
520
521
    return Types.ISpec { Types.iSpecMemorySize = fromIntegral mem_s
                       , Types.iSpecCpuCount   = fromIntegral cpu_c
522
523
                       , Types.iSpecDiskSize   = fromIntegral dsk_s
                       , Types.iSpecDiskCount  = fromIntegral dsk_c
524
                       , Types.iSpecNicCount   = fromIntegral nic_c
525
                       , Types.iSpecSpindleUse = fromIntegral su
526
527
                       }

528
529
530
531
532
533
534
535
-- | Generates an ispec bigger than the given one.
genBiggerISpec :: Types.ISpec -> Gen Types.ISpec
genBiggerISpec imin = do
  mem_s <- choose (Types.iSpecMemorySize imin, maxBound)
  dsk_c <- choose (Types.iSpecDiskCount imin, maxBound)
  dsk_s <- choose (Types.iSpecDiskSize imin, maxBound)
  cpu_c <- choose (Types.iSpecCpuCount imin, maxBound)
  nic_c <- choose (Types.iSpecNicCount imin, maxBound)
536
  su    <- choose (Types.iSpecSpindleUse imin, maxBound)
537
538
539
540
541
  return Types.ISpec { Types.iSpecMemorySize = fromIntegral mem_s
                     , Types.iSpecCpuCount   = fromIntegral cpu_c
                     , Types.iSpecDiskSize   = fromIntegral dsk_s
                     , Types.iSpecDiskCount  = fromIntegral dsk_c
                     , Types.iSpecNicCount   = fromIntegral nic_c
542
                     , Types.iSpecSpindleUse = fromIntegral su
543
                     }
544
545
546
547

instance Arbitrary Types.IPolicy where
  arbitrary = do
    imin <- arbitrary
548
549
550
551
    istd <- genBiggerISpec imin
    imax <- genBiggerISpec istd
    num_tmpl <- choose (0, length allDiskTemplates)
    dts  <- genUniquesList num_tmpl
552
553
    vcpu_ratio <- choose (1.0, maxVcpuRatio)
    spindle_ratio <- choose (1.0, maxSpindleRatio)
554
555
556
557
    return Types.IPolicy { Types.iPolicyMinSpec = imin
                         , Types.iPolicyStdSpec = istd
                         , Types.iPolicyMaxSpec = imax
                         , Types.iPolicyDiskTemplates = dts
558
                         , Types.iPolicyVcpuRatio = vcpu_ratio
559
                         , Types.iPolicySpindleRatio = spindle_ratio
560
561
                         }

Agata Murawska's avatar
Agata Murawska committed
562
563
564
instance Arbitrary Objects.Hypervisor where
  arbitrary = elements [minBound..maxBound]

Iustin Pop's avatar
Iustin Pop committed
565
instance Arbitrary Objects.PartialNDParams where
566
  arbitrary = Objects.PartialNDParams <$> arbitrary <*> arbitrary
Iustin Pop's avatar
Iustin Pop committed
567

Agata Murawska's avatar
Agata Murawska committed
568
569
570
571
instance Arbitrary Objects.Node where
  arbitrary = Objects.Node <$> getFQDN <*> getFQDN <*> getFQDN
              <*> arbitrary <*> arbitrary <*> arbitrary <*> getFQDN
              <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
Iustin Pop's avatar
Iustin Pop committed
572
              <*> arbitrary <*> arbitrary <*> getFQDN <*> arbitrary
573
              <*> (Set.fromList <$> genTags)
Agata Murawska's avatar
Agata Murawska committed
574
575
576
577
578
579
580
581
582
583

instance Arbitrary Rpc.RpcCallAllInstancesInfo where
  arbitrary = Rpc.RpcCallAllInstancesInfo <$> arbitrary

instance Arbitrary Rpc.RpcCallInstanceList where
  arbitrary = Rpc.RpcCallInstanceList <$> arbitrary

instance Arbitrary Rpc.RpcCallNodeInfo where
  arbitrary = Rpc.RpcCallNodeInfo <$> arbitrary <*> arbitrary

Iustin Pop's avatar
Iustin Pop committed
584
-- | Custom 'Qlang.Filter' generator (top-level), which enforces a
585
-- (sane) limit on the depth of the generated filters.
Iustin Pop's avatar
Iustin Pop committed
586
genFilter :: Gen Qlang.Filter
587
588
589
590
591
genFilter = choose (0, 10) >>= genFilter'

-- | Custom generator for filters that correctly halves the state of
-- the generators at each recursive step, per the QuickCheck
-- documentation, in order not to run out of memory.
Iustin Pop's avatar
Iustin Pop committed
592
genFilter' :: Int -> Gen Qlang.Filter
593
genFilter' 0 =
Iustin Pop's avatar
Iustin Pop committed
594
595
596
597
598
599
600
601
602
  oneof [ return Qlang.EmptyFilter
        , Qlang.TrueFilter     <$> getName
        , Qlang.EQFilter       <$> getName <*> value
        , Qlang.LTFilter       <$> getName <*> value
        , Qlang.GTFilter       <$> getName <*> value
        , Qlang.LEFilter       <$> getName <*> value
        , Qlang.GEFilter       <$> getName <*> value
        , Qlang.RegexpFilter   <$> getName <*> getName
        , Qlang.ContainsFilter <$> getName <*> value
603
        ]
Iustin Pop's avatar
Iustin Pop committed
604
605
    where value = oneof [ Qlang.QuotedString <$> getName
                        , Qlang.NumericValue <$> arbitrary
606
607
                        ]
genFilter' n = do
Iustin Pop's avatar
Iustin Pop committed
608
609
610
  oneof [ Qlang.AndFilter  <$> vectorOf n'' (genFilter' n')
        , Qlang.OrFilter   <$> vectorOf n'' (genFilter' n')
        , Qlang.NotFilter  <$> genFilter' n'
611
612
613
614
615
        ]
  where n' = n `div` 2 -- sub-filter generator size
        n'' = max n' 2 -- but we don't want empty or 1-element lists,
                       -- so use this for and/or filter list length

Iustin Pop's avatar
Iustin Pop committed
616
617
618
instance Arbitrary Qlang.ItemType where
  arbitrary = elements [minBound..maxBound]

619
-- * Actual tests
Iustin Pop's avatar
Iustin Pop committed
620

621
622
-- ** Utils tests

623
-- | Helper to generate a small string that doesn't contain commas.
624
genNonCommaString :: Gen [Char]
625
626
627
628
genNonCommaString = do
  size <- choose (0, 20) -- arbitrary max size
  vectorOf size (arbitrary `suchThat` ((/=) ','))

629
630
-- | If the list is not just an empty element, and if the elements do
-- not contain commas, then join+split should be idempotent.
631
prop_Utils_commaJoinSplit :: Property
Iustin Pop's avatar
Iustin Pop committed
632
prop_Utils_commaJoinSplit =
633
634
  forAll (choose (0, 20)) $ \llen ->
  forAll (vectorOf llen genNonCommaString `suchThat` ((/=) [""])) $ \lst ->
Iustin Pop's avatar
Iustin Pop committed
635
  Utils.sepSplit ',' (Utils.commaJoin lst) ==? lst
Iustin Pop's avatar
Iustin Pop committed
636

637
-- | Split and join should always be idempotent.
638
prop_Utils_commaSplitJoin :: [Char] -> Property
Iustin Pop's avatar
Iustin Pop committed
639
prop_Utils_commaSplitJoin s =
Iustin Pop's avatar
Iustin Pop committed
640
  Utils.commaJoin (Utils.sepSplit ',' s) ==? s
641

642
-- | fromObjWithDefault, we test using the Maybe monad and an integer
643
-- value.
644
prop_Utils_fromObjWithDefault :: Integer -> String -> Bool
645
prop_Utils_fromObjWithDefault def_value random_key =
Iustin Pop's avatar
Iustin Pop committed
646
  -- a missing key will be returned with the default
647
  JSON.fromObjWithDefault [] random_key def_value == Just def_value &&
Iustin Pop's avatar
Iustin Pop committed
648
  -- a found key will be returned as is, not with default
649
  JSON.fromObjWithDefault [(random_key, J.showJSON def_value)]
Iustin Pop's avatar
Iustin Pop committed
650
       random_key (def_value+1) == Just def_value
651

652
-- | Test that functional if' behaves like the syntactic sugar if.
Iustin Pop's avatar
Iustin Pop committed
653
654
prop_Utils_if'if :: Bool -> Int -> Int -> Gen Prop
prop_Utils_if'if cnd a b =
Iustin Pop's avatar
Iustin Pop committed
655
  Utils.if' cnd a b ==? if cnd then a else b
656

Guido Trotter's avatar
Guido Trotter committed
657
-- | Test basic select functionality
Iustin Pop's avatar
Iustin Pop committed
658
659
660
661
prop_Utils_select :: Int      -- ^ Default result
                  -> [Int]    -- ^ List of False values
                  -> [Int]    -- ^ List of True values
                  -> Gen Prop -- ^ Test result
Guido Trotter's avatar
Guido Trotter committed
662
prop_Utils_select def lst1 lst2 =
Iustin Pop's avatar
Iustin Pop committed
663
  Utils.select def (flist ++ tlist) ==? expectedresult
Iustin Pop's avatar
Iustin Pop committed
664
665
666
    where expectedresult = Utils.if' (null lst2) def (head lst2)
          flist = zip (repeat False) lst1
          tlist = zip (repeat True)  lst2
Guido Trotter's avatar
Guido Trotter committed
667
668

-- | Test basic select functionality with undefined default
Iustin Pop's avatar
Iustin Pop committed
669
prop_Utils_select_undefd :: [Int]            -- ^ List of False values
Guido Trotter's avatar
Guido Trotter committed
670
                         -> NonEmptyList Int -- ^ List of True values
Iustin Pop's avatar
Iustin Pop committed
671
                         -> Gen Prop         -- ^ Test result
Guido Trotter's avatar
Guido Trotter committed
672
prop_Utils_select_undefd lst1 (NonEmpty lst2) =
Iustin Pop's avatar
Iustin Pop committed
673
  Utils.select undefined (flist ++ tlist) ==? head lst2
Iustin Pop's avatar
Iustin Pop committed
674
675
    where flist = zip (repeat False) lst1
          tlist = zip (repeat True)  lst2
Guido Trotter's avatar
Guido Trotter committed
676
677

-- | Test basic select functionality with undefined list values
Iustin Pop's avatar
Iustin Pop committed
678
prop_Utils_select_undefv :: [Int]            -- ^ List of False values
Guido Trotter's avatar
Guido Trotter committed
679
                         -> NonEmptyList Int -- ^ List of True values
Iustin Pop's avatar
Iustin Pop committed
680
                         -> Gen Prop         -- ^ Test result
Guido Trotter's avatar
Guido Trotter committed
681
prop_Utils_select_undefv lst1 (NonEmpty lst2) =
Iustin Pop's avatar
Iustin Pop committed
682
  Utils.select undefined cndlist ==? head lst2
Iustin Pop's avatar
Iustin Pop committed
683
684
685
    where flist = zip (repeat False) lst1
          tlist = zip (repeat True)  lst2
          cndlist = flist ++ tlist ++ [undefined]
686

687
prop_Utils_parseUnit :: NonNegative Int -> Property
Iustin Pop's avatar
Iustin Pop committed
688
prop_Utils_parseUnit (NonNegative n) =
Iustin Pop's avatar
Iustin Pop committed
689
690
691
692
693
694
695
696
697
698
  Utils.parseUnit (show n) ==? Types.Ok n .&&.
  Utils.parseUnit (show n ++ "m") ==? Types.Ok n .&&.
  Utils.parseUnit (show n ++ "M") ==? Types.Ok (truncate n_mb::Int) .&&.
  Utils.parseUnit (show n ++ "g") ==? Types.Ok (n*1024) .&&.
  Utils.parseUnit (show n ++ "G") ==? Types.Ok (truncate n_gb::Int) .&&.
  Utils.parseUnit (show n ++ "t") ==? Types.Ok (n*1048576) .&&.
  Utils.parseUnit (show n ++ "T") ==? Types.Ok (truncate n_tb::Int) .&&.
  printTestCase "Internal error/overflow?"
    (n_mb >=0 && n_gb >= 0 && n_tb >= 0) .&&.
  property (Types.isBad (Utils.parseUnit (show n ++ "x")::Types.Result Int))
699
  where n_mb = (fromIntegral n::Rational) * 1000 * 1000 / 1024 / 1024
Iustin Pop's avatar
Iustin Pop committed
700
701
        n_gb = n_mb * 1000
        n_tb = n_gb * 1000
Iustin Pop's avatar
Iustin Pop committed
702

703
-- | Test list for the Utils module.
704
testSuite "Utils"
Iustin Pop's avatar
Iustin Pop committed
705
706
707
708
709
710
711
712
713
            [ 'prop_Utils_commaJoinSplit
            , 'prop_Utils_commaSplitJoin
            , 'prop_Utils_fromObjWithDefault
            , 'prop_Utils_if'if
            , 'prop_Utils_select
            , 'prop_Utils_select_undefd
            , 'prop_Utils_select_undefv
            , 'prop_Utils_parseUnit
            ]
714

715
716
717
-- ** PeerMap tests

-- | Make sure add is idempotent.
718
719
prop_PeerMap_addIdempotent :: PeerMap.PeerMap
                           -> PeerMap.Key -> PeerMap.Elem -> Property
Iustin Pop's avatar
Iustin Pop committed
720
prop_PeerMap_addIdempotent pmap key em =
Iustin Pop's avatar
Iustin Pop committed
721
  fn puniq ==? fn (fn puniq)
722
    where fn = PeerMap.add key em
723
          puniq = PeerMap.accumArray const pmap
724

725
-- | Make sure remove is idempotent.
726
prop_PeerMap_removeIdempotent :: PeerMap.PeerMap -> PeerMap.Key -> Property
727
prop_PeerMap_removeIdempotent pmap key =
Iustin Pop's avatar
Iustin Pop committed
728
  fn puniq ==? fn (fn puniq)
729
    where fn = PeerMap.remove key
730
731
          puniq = PeerMap.accumArray const pmap

732
-- | Make sure a missing item returns 0.
733
prop_PeerMap_findMissing :: PeerMap.PeerMap -> PeerMap.Key -> Property
734
prop_PeerMap_findMissing pmap key =
Iustin Pop's avatar
Iustin Pop committed
735
  PeerMap.find key (PeerMap.remove key puniq) ==? 0
736
    where puniq = PeerMap.accumArray const pmap
737

738
-- | Make sure an added item is found.
739
740
prop_PeerMap_addFind :: PeerMap.PeerMap
                     -> PeerMap.Key -> PeerMap.Elem -> Property
Iustin Pop's avatar
Iustin Pop committed
741
prop_PeerMap_addFind pmap key em =
Iustin Pop's avatar
Iustin Pop committed
742
  PeerMap.find key (PeerMap.add key em puniq) ==? em
743
    where puniq = PeerMap.accumArray const pmap
744

745
-- | Manual check that maxElem returns the maximum indeed, or 0 for null.
746
prop_PeerMap_maxElem :: PeerMap.PeerMap -> Property
747
prop_PeerMap_maxElem pmap =
Iustin Pop's avatar
Iustin Pop committed
748
  PeerMap.maxElem puniq ==? if null puniq then 0
Iustin Pop's avatar
Iustin Pop committed
749
                              else (maximum . snd . unzip) puniq
750
    where puniq = PeerMap.accumArray const pmap
751

752
-- | List of tests for the PeerMap module.
753
testSuite "PeerMap"
Iustin Pop's avatar
Iustin Pop committed
754
755
756
757
758
759
            [ 'prop_PeerMap_addIdempotent
            , 'prop_PeerMap_removeIdempotent
            , 'prop_PeerMap_maxElem
            , 'prop_PeerMap_addFind
            , 'prop_PeerMap_findMissing
            ]
760

761
-- ** Container tests
762

Iustin Pop's avatar
Iustin Pop committed
763
764
-- we silence the following due to hlint bug fixed in later versions
{-# ANN prop_Container_addTwo "HLint: ignore Avoid lambda" #-}
765
prop_Container_addTwo :: [Container.Key] -> Int -> Int -> Bool
766
prop_Container_addTwo cdata i1 i2 =
Iustin Pop's avatar
Iustin Pop committed
767
768
  fn i1 i2 cont == fn i2 i1 cont &&
  fn i1 i2 cont == fn i1 i2 (fn i1 i2 cont)
769
    where cont = foldl (\c x -> Container.add x x c) Container.empty cdata
770
771
          fn x1 x2 = Container.addTwo x1 x1 x2 x2

772
prop_Container_nameOf :: Node.Node -> Property
773
774
775
prop_Container_nameOf node =
  let nl = makeSmallCluster node 1
      fnode = head (Container.elems nl)
Iustin Pop's avatar
Iustin Pop committed
776
  in Container.nameOf nl (Node.idx fnode) ==? Node.name fnode
777

778
-- | We test that in a cluster, given a random node, we can find it by
779
-- its name and alias, as long as all names and aliases are unique,
780
-- and that we fail to find a non-existing name.
Iustin Pop's avatar
Iustin Pop committed
781
prop_Container_findByName :: Property
782
783
prop_Container_findByName =
  forAll (genNode (Just 1) Nothing) $ \node ->
784
785
  forAll (choose (1, 20)) $ \ cnt ->
  forAll (choose (0, cnt - 1)) $ \ fidx ->
786
787
788
789
  forAll (genUniquesList (cnt * 2)) $ \ allnames ->
  forAll (arbitrary `suchThat` (`notElem` allnames)) $ \ othername ->
  let names = zip (take cnt allnames) (drop cnt allnames)
      nl = makeSmallCluster node cnt
790
791
792
793
794
      nodes = Container.elems nl
      nodes' = map (\((name, alias), nn) -> (Node.idx nn,
                                             nn { Node.name = name,
                                                  Node.alias = alias }))
               $ zip names nodes
Iustin Pop's avatar
Iustin Pop committed
795
      nl' = Container.fromList nodes'
796
      target = snd (nodes' !! fidx)
797
798
799
800
  in Container.findByName nl' (Node.name target) ==? Just target .&&.
     Container.findByName nl' (Node.alias target) ==? Just target .&&.
     printTestCase "Found non-existing name"
       (isNothing (Container.findByName nl' othername))
801

802
testSuite "Container"
Iustin Pop's avatar
Iustin Pop committed
803
804
805
806
            [ 'prop_Container_addTwo
            , 'prop_Container_nameOf
            , 'prop_Container_findByName
            ]
807

808
809
-- ** Instance tests

810
811
-- Simple instance tests, we only have setter/getters

812
prop_Instance_creat :: Instance.Instance -> Property
Iustin Pop's avatar
Iustin Pop committed
813
prop_Instance_creat inst =
Iustin Pop's avatar
Iustin Pop committed
814
  Instance.name inst ==? Instance.alias inst
Iustin Pop's avatar
Iustin Pop committed
815

816
prop_Instance_setIdx :: Instance.Instance -> Types.Idx -> Property
817
prop_Instance_setIdx inst idx =
Iustin Pop's avatar
Iustin Pop committed
818
  Instance.idx (Instance.setIdx inst idx) ==? idx
819

820
prop_Instance_setName :: Instance.Instance -> String -> Bool
821
prop_Instance_setName inst name =
Iustin Pop's avatar
Iustin Pop committed
822
823
  Instance.name newinst == name &&
  Instance.alias newinst == name
824
    where newinst = Instance.setName inst name
Iustin Pop's avatar
Iustin Pop committed
825

826
prop_Instance_setAlias :: Instance.Instance -> String -> Bool
Iustin Pop's avatar
Iustin Pop committed
827
prop_Instance_setAlias inst name =
Iustin Pop's avatar
Iustin Pop committed
828
829
  Instance.name newinst == Instance.name inst &&
  Instance.alias newinst == name
830
    where newinst = Instance.setAlias inst name
831

832
prop_Instance_setPri :: Instance.Instance -> Types.Ndx -> Property
833
prop_Instance_setPri inst pdx =
Iustin Pop's avatar
Iustin Pop committed
834
  Instance.pNode (Instance.setPri inst pdx) ==? pdx
835

836
prop_Instance_setSec :: Instance.Instance -> Types.Ndx -> Property
837
prop_Instance_setSec inst sdx =
Iustin Pop's avatar
Iustin Pop committed
838
  Instance.sNode (Instance.setSec inst sdx) ==? sdx
839

840
prop_Instance_setBoth :: Instance.Instance -> Types.Ndx -> Types.Ndx -> Bool
841
prop_Instance_setBoth inst pdx sdx =
Iustin Pop's avatar
Iustin Pop committed
842
  Instance.pNode si == pdx && Instance.sNode si == sdx
843
    where si = Instance.setBoth inst pdx sdx
844

845
prop_Instance_shrinkMG :: Instance.Instance -> Property
Iustin Pop's avatar
Iustin Pop committed
846
prop_Instance_shrinkMG inst =
Iustin Pop's avatar
Iustin Pop committed
847
848
849
850
  Instance.mem inst >= 2 * Types.unitMem ==>
    case Instance.shrinkByType inst Types.FailMem of
      Types.Ok inst' -> Instance.mem inst' == Instance.mem inst - Types.unitMem
      _ -> False
Iustin Pop's avatar
Iustin Pop committed
851

852
prop_Instance_shrinkMF :: Instance.Instance -> Property
Iustin Pop's avatar
Iustin Pop committed
853
prop_Instance_shrinkMF inst =
Iustin Pop's avatar
Iustin Pop committed
854
  forAll (choose (0, 2 * Types.unitMem - 1)) $ \mem ->
Iustin Pop's avatar
Iustin Pop committed
855
856
    let inst' = inst { Instance.mem = mem}
    in Types.isBad $ Instance.shrinkByType inst' Types.FailMem
Iustin Pop's avatar
Iustin Pop committed
857

858
prop_Instance_shrinkCG :: Instance.Instance -> Property
Iustin Pop's avatar
Iustin Pop committed
859
prop_Instance_shrinkCG inst =
Iustin Pop's avatar
Iustin Pop committed
860
861
862
863
864
  Instance.vcpus inst >= 2 * Types.unitCpu ==>
    case Instance.shrinkByType inst Types.FailCPU of
      Types.Ok inst' ->
        Instance.vcpus inst' == Instance.vcpus inst - Types.unitCpu
      _ -> False
Iustin Pop's avatar
Iustin Pop committed
865

866
prop_Instance_shrinkCF :: Instance.Instance -> Property
Iustin Pop's avatar
Iustin Pop committed
867
prop_Instance_shrinkCF inst =
Iustin Pop's avatar
Iustin Pop committed
868
  forAll (choose (0, 2 * Types.unitCpu - 1)) $ \vcpus ->
Iustin Pop's avatar
Iustin Pop committed
869
870
    let inst' = inst { Instance.vcpus = vcpus }
    in Types.isBad $ Instance.shrinkByType inst' Types.FailCPU
Iustin Pop's avatar
Iustin Pop committed
871

872
prop_Instance_shrinkDG :: Instance.Instance -> Property
Iustin Pop's avatar
Iustin Pop committed
873
prop_Instance_shrinkDG inst =
Iustin Pop's avatar
Iustin Pop committed
874
875
876
877
878
  Instance.dsk inst >= 2 * Types.unitDsk ==>
    case Instance.shrinkByType inst Types.FailDisk of
      Types.Ok inst' ->
        Instance.dsk inst' == Instance.dsk inst - Types.unitDsk
      _ -> False
Iustin Pop's avatar
Iustin Pop committed
879

880
prop_Instance_shrinkDF :: Instance.Instance -> Property
Iustin Pop's avatar
Iustin Pop committed
881
prop_Instance_shrinkDF inst =
Iustin Pop's avatar
Iustin Pop committed
882
  forAll (choose (0, 2 * Types.unitDsk - 1)) $ \dsk ->
Iustin Pop's avatar
Iustin Pop committed
883
884
    let inst' = inst { Instance.dsk = dsk }
    in Types.isBad $ Instance.shrinkByType inst' Types.FailDisk
Iustin Pop's avatar
Iustin Pop committed
885

886
prop_Instance_setMovable :: Instance.Instance -> Bool -> Property
Iustin Pop's avatar
Iustin Pop committed
887
prop_Instance_setMovable inst m =
Iustin Pop's avatar
Iustin Pop committed
888
  Instance.movable inst' ==? m
889
    where inst' = Instance.setMovable inst m
Iustin Pop's avatar
Iustin Pop committed
890

891
testSuite "Instance"
Iustin Pop's avatar
Iustin Pop committed
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
            [ 'prop_Instance_creat
            , 'prop_Instance_setIdx
            , 'prop_Instance_setName
            , 'prop_Instance_setAlias
            , 'prop_Instance_setPri
            , 'prop_Instance_setSec
            , 'prop_Instance_setBoth
            , 'prop_Instance_shrinkMG
            , 'prop_Instance_shrinkMF
            , 'prop_Instance_shrinkCG
            , 'prop_Instance_shrinkCF
            , 'prop_Instance_shrinkDG
            , 'prop_Instance_shrinkDF
            , 'prop_Instance_setMovable
            ]
Iustin Pop's avatar
Iustin Pop committed
907