QC.hs 84.6 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
  , testConfd
Iustin Pop's avatar
Iustin Pop committed
54
  ) where
55

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

Iustin Pop's avatar
Iustin Pop committed
78
import qualified Ganeti.Confd as Confd
79
80
import qualified Ganeti.Confd.Server as Confd.Server
import qualified Ganeti.Confd.Utils as Confd.Utils
Iustin Pop's avatar
Iustin Pop committed
81
82
83
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
84
import qualified Ganeti.BasicTypes as BasicTypes
85
import qualified Ganeti.Jobs as Jobs
Iustin Pop's avatar
Iustin Pop committed
86
import qualified Ganeti.Logging as Logging
87
import qualified Ganeti.Luxi as Luxi
Iustin Pop's avatar
Iustin Pop committed
88
89
import qualified Ganeti.Objects as Objects
import qualified Ganeti.OpCodes as OpCodes
90
import qualified Ganeti.Rpc as Rpc
91
import qualified Ganeti.Query.Language as Qlang
Iustin Pop's avatar
Iustin Pop committed
92
import qualified Ganeti.Runtime as Runtime
93
import qualified Ganeti.Ssconf as Ssconf
94
95
96
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
97
import qualified Ganeti.HTools.ExtLoader
Iustin Pop's avatar
Iustin Pop committed
98
import qualified Ganeti.HTools.Group as Group
99
100
import qualified Ganeti.HTools.IAlloc as IAlloc
import qualified Ganeti.HTools.Instance as Instance
101
import qualified Ganeti.HTools.JSON as JSON
102
import qualified Ganeti.HTools.Loader as Loader
103
import qualified Ganeti.HTools.Luxi as HTools.Luxi
104
105
import qualified Ganeti.HTools.Node as Node
import qualified Ganeti.HTools.PeerMap as PeerMap
106
import qualified Ganeti.HTools.Rapi
107
import qualified Ganeti.HTools.Simu as Simu
108
109
110
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
111
import qualified Ganeti.HTools.Version
112
import qualified Ganeti.Constants as C
113

114
import qualified Ganeti.HTools.Program as Program
115
116
117
118
119
import qualified Ganeti.HTools.Program.Hail
import qualified Ganeti.HTools.Program.Hbal
import qualified Ganeti.HTools.Program.Hscan
import qualified Ganeti.HTools.Program.Hspace

120
import Test.Ganeti.TestHelper (testSuite)
Iustin Pop's avatar
Iustin Pop committed
121

122
123
-- * Constants

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

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

132
-- | Max CPUs (1024, somewhat random value).
Iustin Pop's avatar
Iustin Pop committed
133
134
135
maxCpu :: Int
maxCpu = 1024

136
137
138
139
140
141
142
143
-- | 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
144
145
146
147
148
149
150
151
152
-- | 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

153
154
155
156
-- | All disk templates (used later)
allDiskTemplates :: [Types.DiskTemplate]
allDiskTemplates = [minBound..maxBound]

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


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

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

196
197
defGroupAssoc :: Map.Map String Types.Gdx
defGroupAssoc = Map.singleton (Group.uuid defGroup) (Group.idx defGroup)
Iustin Pop's avatar
Iustin Pop committed
198

199
200
-- * Helper functions

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

Iustin Pop's avatar
Iustin Pop committed
206
207
208
209
210
211
212
-- | 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
213
214
215
216
-- | Show a message and fail the test.
failTest :: String -> Property
failTest msg = printTestCase msg False

217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
-- | 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

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

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

253
-- | Create a small cluster by repeating a node spec.
254
255
makeSmallCluster :: Node.Node -> Int -> Node.List
makeSmallCluster node count =
256
257
258
259
260
261
262
  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
263
264
      (_, nlst) = Loader.assignIndices namelst
  in nlst
265

Iustin Pop's avatar
Iustin Pop committed
266
267
268
269
270
271
272
-- | 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)

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

279
280
canBalance :: Cluster.Table -> Bool -> Bool -> Bool -> Bool
canBalance tbl dm im evac = isJust $ Cluster.tryBalance tbl dm im evac 0 0
281

282
-- | Assigns a new fresh instance to a cluster; this is not
283
-- allocation, so no resource checks are done.
284
285
286
287
288
289
290
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
291
292
                  then 0
                  else fst (Container.findMax il) + 1
293
294
295
296
297
298
299
300
      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')

301
302
303
304
305
306
307
-- | 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]

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

-- | 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]

318
319
-- * Arbitrary instances

320
-- | Defines a DNS name.
321
newtype DNSChar = DNSChar { dnsGetChar::Char }
322

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

328
329
330
instance Show DNSChar where
  show = show . dnsGetChar

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

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

Iustin Pop's avatar
Iustin Pop committed
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
-- | 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

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
389
390
391
-- | 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

392
instance Arbitrary Types.InstanceStatus where
393
    arbitrary = elements [minBound..maxBound]
394

395
396
397
398
399
400
401
402
403
404
-- | 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)
405
406
  dt <- arbitrary
  return $ Instance.create name mem dsk vcpus run_st [] True pn sn dt 1
407
408
409
410
411
412
413
414

-- | 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)

415
416
-- let's generate a random instance
instance Arbitrary Instance.Instance where
417
  arbitrary = genInstanceSmallerThan maxMem maxDsk maxCpu
418

419
420
421
422
423
-- | 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
424
425
genNode min_multiplier max_multiplier = do
  let (base_mem, base_dsk, base_cpu) =
Iustin Pop's avatar
Iustin Pop committed
426
427
428
429
430
        case min_multiplier of
          Just mm -> (mm * Types.unitMem,
                      mm * Types.unitDsk,
                      mm * Types.unitCpu)
          Nothing -> (0, 0, 0)
431
      (top_mem, top_dsk, top_cpu)  =
Iustin Pop's avatar
Iustin Pop committed
432
433
434
435
436
        case max_multiplier of
          Just mm -> (mm * Types.unitMem,
                      mm * Types.unitDsk,
                      mm * Types.unitCpu)
          Nothing -> (maxMem, maxDsk, maxCpu)
437
438
439
440
441
442
443
444
445
  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
446
          (fromIntegral dsk_t) dsk_f (fromIntegral cpu_t) offl 1 0
Iustin Pop's avatar
Iustin Pop committed
447
448
      n' = Node.setPolicy nullIPolicy n
  return $ Node.buildPeers n' Container.empty
449

450
451
452
453
454
455
456
457
458
-- | 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)

459
460
-- and a random node
instance Arbitrary Node.Node where
Iustin Pop's avatar
Iustin Pop committed
461
  arbitrary = genNode Nothing Nothing
462

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

467
468
469
instance Arbitrary OpCodes.DiskIndex where
  arbitrary = choose (0, C.maxDisks - 1) >>= OpCodes.mkDiskIndex

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

488
489
490
491
492
493
instance Arbitrary Jobs.OpStatus where
  arbitrary = elements [minBound..maxBound]

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

494
495
newtype SmallRatio = SmallRatio Double deriving Show
instance Arbitrary SmallRatio where
Iustin Pop's avatar
Iustin Pop committed
496
497
498
  arbitrary = do
    v <- choose (0, 1)
    return $ SmallRatio v
499

500
501
502
503
504
505
instance Arbitrary Types.AllocPolicy where
  arbitrary = elements [minBound..maxBound]

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

506
instance Arbitrary Types.FailMode where
Iustin Pop's avatar
Iustin Pop committed
507
  arbitrary = elements [minBound..maxBound]
508

509
510
511
instance Arbitrary Types.EvacMode where
  arbitrary = elements [minBound..maxBound]

512
instance Arbitrary a => Arbitrary (Types.OpResult a) where
Iustin Pop's avatar
Iustin Pop committed
513
  arbitrary = arbitrary >>= \c ->
Iustin Pop's avatar
Iustin Pop committed
514
              if c
Iustin Pop's avatar
Iustin Pop committed
515
516
                then Types.OpGood <$> arbitrary
                else Types.OpFail <$> arbitrary
517

518
519
instance Arbitrary Types.ISpec where
  arbitrary = do
520
    mem_s <- arbitrary::Gen (NonNegative Int)
521
522
    dsk_c <- arbitrary::Gen (NonNegative Int)
    dsk_s <- arbitrary::Gen (NonNegative Int)
523
524
    cpu_c <- arbitrary::Gen (NonNegative Int)
    nic_c <- arbitrary::Gen (NonNegative Int)
525
    su    <- arbitrary::Gen (NonNegative Int)
526
527
    return Types.ISpec { Types.iSpecMemorySize = fromIntegral mem_s
                       , Types.iSpecCpuCount   = fromIntegral cpu_c
528
529
                       , Types.iSpecDiskSize   = fromIntegral dsk_s
                       , Types.iSpecDiskCount  = fromIntegral dsk_c
530
                       , Types.iSpecNicCount   = fromIntegral nic_c
531
                       , Types.iSpecSpindleUse = fromIntegral su
532
533
                       }

534
535
536
537
538
539
540
541
-- | 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)
542
  su    <- choose (Types.iSpecSpindleUse imin, maxBound)
543
544
545
546
547
  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
548
                     , Types.iSpecSpindleUse = fromIntegral su
549
                     }
550
551
552
553

instance Arbitrary Types.IPolicy where
  arbitrary = do
    imin <- arbitrary
554
555
556
557
    istd <- genBiggerISpec imin
    imax <- genBiggerISpec istd
    num_tmpl <- choose (0, length allDiskTemplates)
    dts  <- genUniquesList num_tmpl
558
559
    vcpu_ratio <- choose (1.0, maxVcpuRatio)
    spindle_ratio <- choose (1.0, maxSpindleRatio)
560
561
562
563
    return Types.IPolicy { Types.iPolicyMinSpec = imin
                         , Types.iPolicyStdSpec = istd
                         , Types.iPolicyMaxSpec = imax
                         , Types.iPolicyDiskTemplates = dts
564
                         , Types.iPolicyVcpuRatio = vcpu_ratio
565
                         , Types.iPolicySpindleRatio = spindle_ratio
566
567
                         }

Agata Murawska's avatar
Agata Murawska committed
568
569
570
instance Arbitrary Objects.Hypervisor where
  arbitrary = elements [minBound..maxBound]

Iustin Pop's avatar
Iustin Pop committed
571
instance Arbitrary Objects.PartialNDParams where
572
  arbitrary = Objects.PartialNDParams <$> arbitrary <*> arbitrary
Iustin Pop's avatar
Iustin Pop committed
573

Agata Murawska's avatar
Agata Murawska committed
574
575
576
577
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
578
              <*> arbitrary <*> arbitrary <*> getFQDN <*> arbitrary
579
              <*> (Set.fromList <$> genTags)
Agata Murawska's avatar
Agata Murawska committed
580
581
582
583
584
585
586
587
588
589

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
590
-- | Custom 'Qlang.Filter' generator (top-level), which enforces a
591
-- (sane) limit on the depth of the generated filters.
Iustin Pop's avatar
Iustin Pop committed
592
genFilter :: Gen (Qlang.Filter Qlang.FilterField)
593
594
595
596
597
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
598
genFilter' :: Int -> Gen (Qlang.Filter Qlang.FilterField)
599
genFilter' 0 =
Iustin Pop's avatar
Iustin Pop committed
600
601
602
603
604
605
606
  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
607
        , Qlang.RegexpFilter   <$> getName <*> arbitrary
Iustin Pop's avatar
Iustin Pop committed
608
        , Qlang.ContainsFilter <$> getName <*> value
609
        ]
Iustin Pop's avatar
Iustin Pop committed
610
611
    where value = oneof [ Qlang.QuotedString <$> getName
                        , Qlang.NumericValue <$> arbitrary
612
613
                        ]
genFilter' n = do
Iustin Pop's avatar
Iustin Pop committed
614
615
616
  oneof [ Qlang.AndFilter  <$> vectorOf n'' (genFilter' n')
        , Qlang.OrFilter   <$> vectorOf n'' (genFilter' n')
        , Qlang.NotFilter  <$> genFilter' n'
617
618
619
620
621
        ]
  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
622
623
624
instance Arbitrary Qlang.ItemType where
  arbitrary = elements [minBound..maxBound]

625
626
627
instance Arbitrary Qlang.FilterRegex where
  arbitrary = getName >>= Qlang.mkRegex -- a name should be a good regex

628
-- * Actual tests
Iustin Pop's avatar
Iustin Pop committed
629

630
631
-- ** Utils tests

632
-- | Helper to generate a small string that doesn't contain commas.
633
genNonCommaString :: Gen [Char]
634
635
636
637
genNonCommaString = do
  size <- choose (0, 20) -- arbitrary max size
  vectorOf size (arbitrary `suchThat` ((/=) ','))

638
639
-- | If the list is not just an empty element, and if the elements do
-- not contain commas, then join+split should be idempotent.
640
prop_Utils_commaJoinSplit :: Property
Iustin Pop's avatar
Iustin Pop committed
641
prop_Utils_commaJoinSplit =
642
643
  forAll (choose (0, 20)) $ \llen ->
  forAll (vectorOf llen genNonCommaString `suchThat` ((/=) [""])) $ \lst ->
Iustin Pop's avatar
Iustin Pop committed
644
  Utils.sepSplit ',' (Utils.commaJoin lst) ==? lst
Iustin Pop's avatar
Iustin Pop committed
645

646
-- | Split and join should always be idempotent.
647
prop_Utils_commaSplitJoin :: [Char] -> Property
Iustin Pop's avatar
Iustin Pop committed
648
prop_Utils_commaSplitJoin s =
Iustin Pop's avatar
Iustin Pop committed
649
  Utils.commaJoin (Utils.sepSplit ',' s) ==? s
650

651
-- | fromObjWithDefault, we test using the Maybe monad and an integer
652
-- value.
653
prop_Utils_fromObjWithDefault :: Integer -> String -> Bool
654
prop_Utils_fromObjWithDefault def_value random_key =
Iustin Pop's avatar
Iustin Pop committed
655
  -- a missing key will be returned with the default
656
  JSON.fromObjWithDefault [] random_key def_value == Just def_value &&
Iustin Pop's avatar
Iustin Pop committed
657
  -- a found key will be returned as is, not with default
658
  JSON.fromObjWithDefault [(random_key, J.showJSON def_value)]
Iustin Pop's avatar
Iustin Pop committed
659
       random_key (def_value+1) == Just def_value
660

661
-- | Test that functional if' behaves like the syntactic sugar if.
Iustin Pop's avatar
Iustin Pop committed
662
663
prop_Utils_if'if :: Bool -> Int -> Int -> Gen Prop
prop_Utils_if'if cnd a b =
Iustin Pop's avatar
Iustin Pop committed
664
  Utils.if' cnd a b ==? if cnd then a else b
665

Guido Trotter's avatar
Guido Trotter committed
666
-- | Test basic select functionality
Iustin Pop's avatar
Iustin Pop committed
667
668
669
670
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
671
prop_Utils_select def lst1 lst2 =
Iustin Pop's avatar
Iustin Pop committed
672
  Utils.select def (flist ++ tlist) ==? expectedresult
Iustin Pop's avatar
Iustin Pop committed
673
674
675
    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
676
677

-- | Test basic select functionality with undefined default
Iustin Pop's avatar
Iustin Pop committed
678
prop_Utils_select_undefd :: [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_undefd lst1 (NonEmpty lst2) =
Iustin Pop's avatar
Iustin Pop committed
682
  Utils.select undefined (flist ++ tlist) ==? head lst2
Iustin Pop's avatar
Iustin Pop committed
683
684
    where flist = zip (repeat False) lst1
          tlist = zip (repeat True)  lst2
Guido Trotter's avatar
Guido Trotter committed
685
686

-- | Test basic select functionality with undefined list values
Iustin Pop's avatar
Iustin Pop committed
687
prop_Utils_select_undefv :: [Int]            -- ^ List of False values
Guido Trotter's avatar
Guido Trotter committed
688
                         -> NonEmptyList Int -- ^ List of True values
Iustin Pop's avatar
Iustin Pop committed
689
                         -> Gen Prop         -- ^ Test result
Guido Trotter's avatar
Guido Trotter committed
690
prop_Utils_select_undefv lst1 (NonEmpty lst2) =
Iustin Pop's avatar
Iustin Pop committed
691
  Utils.select undefined cndlist ==? head lst2
Iustin Pop's avatar
Iustin Pop committed
692
693
694
    where flist = zip (repeat False) lst1
          tlist = zip (repeat True)  lst2
          cndlist = flist ++ tlist ++ [undefined]
695

696
prop_Utils_parseUnit :: NonNegative Int -> Property
Iustin Pop's avatar
Iustin Pop committed
697
prop_Utils_parseUnit (NonNegative n) =
Iustin Pop's avatar
Iustin Pop committed
698
699
700
701
702
703
704
705
706
707
  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))
708
  where n_mb = (fromIntegral n::Rational) * 1000 * 1000 / 1024 / 1024
Iustin Pop's avatar
Iustin Pop committed
709
710
        n_gb = n_mb * 1000
        n_tb = n_gb * 1000
Iustin Pop's avatar
Iustin Pop committed
711

712
-- | Test list for the Utils module.
713
testSuite "Utils"
Iustin Pop's avatar
Iustin Pop committed
714
715
716
717
718
719
720
721
722
            [ '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
            ]
723

724
725
726
-- ** PeerMap tests

-- | Make sure add is idempotent.
727
728
prop_PeerMap_addIdempotent :: PeerMap.PeerMap
                           -> PeerMap.Key -> PeerMap.Elem -> Property
Iustin Pop's avatar
Iustin Pop committed
729
prop_PeerMap_addIdempotent pmap key em =
Iustin Pop's avatar
Iustin Pop committed
730
  fn puniq ==? fn (fn puniq)
731
    where fn = PeerMap.add key em
732
          puniq = PeerMap.accumArray const pmap
733

734
-- | Make sure remove is idempotent.
735
prop_PeerMap_removeIdempotent :: PeerMap.PeerMap -> PeerMap.Key -> Property
736
prop_PeerMap_removeIdempotent pmap key =
Iustin Pop's avatar
Iustin Pop committed
737
  fn puniq ==? fn (fn puniq)
738
    where fn = PeerMap.remove key
739
740
          puniq = PeerMap.accumArray const pmap

741
-- | Make sure a missing item returns 0.
742
prop_PeerMap_findMissing :: PeerMap.PeerMap -> PeerMap.Key -> Property
743
prop_PeerMap_findMissing pmap key =
Iustin Pop's avatar
Iustin Pop committed
744
  PeerMap.find key (PeerMap.remove key puniq) ==? 0
745
    where puniq = PeerMap.accumArray const pmap
746

747
-- | Make sure an added item is found.
748
749
prop_PeerMap_addFind :: PeerMap.PeerMap
                     -> PeerMap.Key -> PeerMap.Elem -> Property
Iustin Pop's avatar
Iustin Pop committed
750
prop_PeerMap_addFind pmap key em =
Iustin Pop's avatar
Iustin Pop committed
751
  PeerMap.find key (PeerMap.add key em puniq) ==? em
752
    where puniq = PeerMap.accumArray const pmap
753

754
-- | Manual check that maxElem returns the maximum indeed, or 0 for null.
755
prop_PeerMap_maxElem :: PeerMap.PeerMap -> Property
756
prop_PeerMap_maxElem pmap =
Iustin Pop's avatar
Iustin Pop committed
757
  PeerMap.maxElem puniq ==? if null puniq then 0
Iustin Pop's avatar
Iustin Pop committed
758
                              else (maximum . snd . unzip) puniq
759
    where puniq = PeerMap.accumArray const pmap
760

761
-- | List of tests for the PeerMap module.
762
testSuite "PeerMap"
Iustin Pop's avatar
Iustin Pop committed
763
764
765
766
767
768
            [ 'prop_PeerMap_addIdempotent
            , 'prop_PeerMap_removeIdempotent
            , 'prop_PeerMap_maxElem
            , 'prop_PeerMap_addFind
            , 'prop_PeerMap_findMissing
            ]
769

770
-- ** Container tests
771

Iustin Pop's avatar
Iustin Pop committed
772
773
-- we silence the following due to hlint bug fixed in later versions
{-# ANN prop_Container_addTwo "HLint: ignore Avoid lambda" #-}
774
prop_Container_addTwo :: [Container.Key] -> Int -> Int -> Bool
775
prop_Container_addTwo cdata i1 i2 =
Iustin Pop's avatar
Iustin Pop committed
776
777
  fn i1 i2 cont == fn i2 i1 cont &&
  fn i1 i2 cont == fn i1 i2 (fn i1 i2 cont)
778
    where cont = foldl (\c x -> Container.add x x c) Container.empty cdata
779
780
          fn x1 x2 = Container.addTwo x1 x1 x2 x2

781
prop_Container_nameOf :: Node.Node -> Property
782
783
784
prop_Container_nameOf node =
  let nl = makeSmallCluster node 1
      fnode = head (Container.elems nl)
Iustin Pop's avatar
Iustin Pop committed
785
  in Container.nameOf nl (Node.idx fnode) ==? Node.name fnode
786

787
-- | We test that in a cluster, given a random node, we can find it by
788
-- its name and alias, as long as all names and aliases are unique,
789
-- and that we fail to find a non-existing name.
Iustin Pop's avatar
Iustin Pop committed
790
prop_Container_findByName :: Property
791
792
prop_Container_findByName =
  forAll (genNode (Just 1) Nothing) $ \node ->
793
794
  forAll (choose (1, 20)) $ \ cnt ->
  forAll (choose (0, cnt - 1)) $ \ fidx ->
795
796
797
798
  forAll (genUniquesList (cnt * 2)) $ \ allnames ->
  forAll (arbitrary `suchThat` (`notElem` allnames)) $ \ othername ->
  let names = zip (take cnt allnames) (drop cnt allnames)
      nl = makeSmallCluster node cnt
799
800
801
802
803
      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
804
      nl' = Container.fromList nodes'
805
      target = snd (nodes' !! fidx)
806
807
808
809
  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))
810

811
testSuite "Container"
Iustin Pop's avatar
Iustin Pop committed
812
813
814
815
            [ 'prop_Container_addTwo
            , 'prop_Container_nameOf
            , 'prop_Container_findByName
            ]
816

817
818
-- ** Instance tests

819
820
-- Simple instance tests, we only have setter/getters

821
prop_Instance_creat :: Instance.Instance -> Property
Iustin Pop's avatar
Iustin Pop committed
822
prop_Instance_creat inst =
Iustin Pop's avatar
Iustin Pop committed
823
  Instance.name inst ==? Instance.alias inst
Iustin Pop's avatar
Iustin Pop committed
824

825
prop_Instance_setIdx :: Instance.Instance -> Types.Idx -> Property
826
prop_Instance_setIdx inst idx =
Iustin Pop's avatar
Iustin Pop committed
827
  Instance.idx (Instance.setIdx inst idx) ==? idx
828

829
prop_Instance_setName :: Instance.Instance -> String -> Bool
830
prop_Instance_setName inst name =
Iustin Pop's avatar
Iustin Pop committed
831
832
  Instance.name newinst == name &&
  Instance.alias newinst == name
833
    where newinst = Instance.setName inst name
Iustin Pop's avatar
Iustin Pop committed
834

835
prop_Instance_setAlias :: Instance.Instance -> String -> Bool
Iustin Pop's avatar
Iustin Pop committed
836
prop_Instance_setAlias inst name =
Iustin Pop's avatar
Iustin Pop committed
837
838
  Instance.name newinst == Instance.name inst &&
  Instance.alias newinst == name
839
    where newinst = Instance.setAlias inst name
840

841
prop_Instance_setPri :: Instance.Instance -> Types.Ndx -> Property
842
prop_Instance_setPri inst pdx =
Iustin Pop's avatar
Iustin Pop committed
843
  Instance.pNode (Instance.setPri inst pdx) ==? pdx
844

845
prop_Instance_setSec :: Instance.Instance -> Types.Ndx -> Property
846
prop_Instance_setSec inst sdx =
Iustin Pop's avatar
Iustin Pop committed
847
  Instance.sNode (Instance.setSec inst sdx) ==? sdx
848

849
prop_Instance_setBoth :: Instance.Instance -> Types.Ndx -> Types.Ndx -> Bool
850
prop_Instance_setBoth inst pdx sdx =
Iustin Pop's avatar
Iustin Pop committed
851
  Instance.pNode si == pdx && Instance.sNode si == sdx
852
    where si = Instance.setBoth inst pdx sdx
853

854
prop_Instance_shrinkMG :: Instance.Instance -> Property
Iustin Pop's avatar
Iustin Pop committed
855
prop_Instance_shrinkMG inst =
Iustin Pop's avatar
Iustin Pop committed
856
857
858
859
  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
860

861
prop_Instance_shrinkMF :: Instance.Instance -> Property
Iustin Pop's avatar
Iustin Pop committed
862
prop_Instance_shrinkMF inst =
Iustin Pop's avatar
Iustin Pop committed
863
  forAll (choose (0, 2 * Types.unitMem - 1)) $ \mem ->
Iustin Pop's avatar
Iustin Pop committed
864
865
    let inst' = inst { Instance.mem = mem}
    in Types.isBad $ Instance.shrinkByType inst' Types.FailMem
Iustin Pop's avatar
Iustin Pop committed
866

867
prop_Instance_shrinkCG :: Instance.Instance -> Property
Iustin Pop's avatar
Iustin Pop committed
868
prop_Instance_shrinkCG inst =
Iustin Pop's avatar
Iustin Pop committed
869
870
871
872
873
  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
874

875
prop_Instance_shrinkCF :: Instance.Instance -> Property
Iustin Pop's avatar
Iustin Pop committed
876
prop_Instance_shrinkCF inst =
Iustin Pop's avatar
Iustin Pop committed
877
  forAll (choose (0, 2 * Types.unitCpu - 1)) $ \vcpus ->
Iustin Pop's avatar
Iustin Pop committed
878
879
    let inst' = inst { Instance.vcpus = vcpus }
    in Types.isBad $ Instance.shrinkByType inst' Types.FailCPU
Iustin Pop's avatar
Iustin Pop committed
880

881
prop_Instance_shrinkDG :: Instance.Instance -> Property
Iustin Pop's avatar
Iustin Pop committed
882
prop_Instance_shrinkDG inst =
Iustin Pop's avatar
Iustin Pop committed
883
884
885
886
887
  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
888

889
prop_Instance_shrinkDF :: Instance.Instance -> Property
Iustin Pop's avatar
Iustin Pop committed
890
prop_Instance_shrinkDF inst =
Iustin Pop's avatar
Iustin Pop committed
891
  forAll (choose (0, 2 * Types.unitDsk - 1)) $ \dsk ->
Iustin Pop's avatar
Iustin Pop committed
892
893
    let inst' = inst { Instance.dsk = dsk }
    in Types.isBad $ Instance.shrinkByType inst' Types.FailDisk
Iustin Pop's avatar
Iustin Pop committed
894

895
prop_Instance_setMovable :: Instance.Instance -> Bool -> Property
Iustin Pop's avatar
Iustin Pop committed
896
prop_Instance_setMovable inst m =
Iustin Pop's avatar
Iustin Pop committed
897
  Instance.movable inst' ==? m
898
    where inst' = Instance.setMovable inst m
Iustin Pop's avatar
Iustin Pop committed
899

900
testSuite "Instance"
Iustin Pop's avatar
Iustin Pop committed
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
            [ '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
916

917
918
919
-- ** Backends

-- *** Text backend tests
920

Iustin Pop's avatar
Iustin Pop committed
921
922
-- Instance text loader tests

923
924
925
926
prop_Text_Load_Instance :: String -> Int -> Int -> Int -> Types.InstanceStatus
                        -> NonEmptyList Char -> [Char]
                        -> NonNegative Int -> NonNegative Int -> Bool
                        -> Types.DiskTemplate -> Int -> Property
Iustin Pop's avatar
Iustin Pop committed
927
928
prop_Text_Load_Instance name mem dsk vcpus status
                        (NonEmpty pnode) snode
René Nussbaumer's avatar