QC.hs 37.8 KB
Newer Older
1
{-| Unittests for ganeti-htools.
Iustin Pop's avatar
Iustin Pop committed
2
3
4
5
6

-}

{-

7
Copyright (C) 2009, 2010, 2011 Google Inc.
Iustin Pop's avatar
Iustin Pop committed
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

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.

-}

26
module Ganeti.HTools.QC
27
28
    ( testUtils
    , testPeerMap
29
30
31
32
    , testContainer
    , testInstance
    , testNode
    , testText
Iustin Pop's avatar
Iustin Pop committed
33
    , testOpCodes
34
    , testJobs
35
    , testCluster
Iustin Pop's avatar
Iustin Pop committed
36
    , testLoader
37
    , testTypes
38
    ) where
39
40

import Test.QuickCheck
Iustin Pop's avatar
Iustin Pop committed
41
import Data.List (findIndex, intercalate, nub, isPrefixOf)
42
import Data.Maybe
Iustin Pop's avatar
Iustin Pop committed
43
44
import Control.Monad
import qualified Text.JSON as J
Iustin Pop's avatar
Iustin Pop committed
45
import qualified Data.Map
46
import qualified Data.IntMap as IntMap
Iustin Pop's avatar
Iustin Pop committed
47
import qualified Ganeti.OpCodes as OpCodes
48
import qualified Ganeti.Jobs as Jobs
Iustin Pop's avatar
Iustin Pop committed
49
import qualified Ganeti.Luxi
50
51
52
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
53
import qualified Ganeti.HTools.ExtLoader
54
55
56
import qualified Ganeti.HTools.IAlloc as IAlloc
import qualified Ganeti.HTools.Instance as Instance
import qualified Ganeti.HTools.Loader as Loader
Iustin Pop's avatar
Iustin Pop committed
57
import qualified Ganeti.HTools.Luxi
58
import qualified Ganeti.HTools.Node as Node
Iustin Pop's avatar
Iustin Pop committed
59
import qualified Ganeti.HTools.Group as Group
60
import qualified Ganeti.HTools.PeerMap as PeerMap
61
import qualified Ganeti.HTools.Rapi
Iustin Pop's avatar
Iustin Pop committed
62
import qualified Ganeti.HTools.Simu
63
64
65
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
66
import qualified Ganeti.HTools.Version
67
import qualified Ganeti.Constants as C
68

69
70
71
72
73
import qualified Ganeti.HTools.Program.Hail
import qualified Ganeti.HTools.Program.Hbal
import qualified Ganeti.HTools.Program.Hscan
import qualified Ganeti.HTools.Program.Hspace

Iustin Pop's avatar
Iustin Pop committed
74
75
76
run :: Testable prop => prop -> Args -> IO Result
run = flip quickCheckWithResult

77
78
-- * Constants

79
-- | Maximum memory (1TiB, somewhat random value).
Iustin Pop's avatar
Iustin Pop committed
80
81
82
maxMem :: Int
maxMem = 1024 * 1024

83
-- | Maximum disk (8TiB, somewhat random value).
Iustin Pop's avatar
Iustin Pop committed
84
maxDsk :: Int
Iustin Pop's avatar
Iustin Pop committed
85
maxDsk = 1024 * 1024 * 8
Iustin Pop's avatar
Iustin Pop committed
86

87
-- | Max CPUs (1024, somewhat random value).
Iustin Pop's avatar
Iustin Pop committed
88
89
90
maxCpu :: Int
maxCpu = 1024

Iustin Pop's avatar
Iustin Pop committed
91
92
93
94
95
96
defGroup :: Group.Group
defGroup = flip Group.setIdx 0 $
               Group.create "default" Utils.defaultGroupID
                    Types.AllocPreferred

defGroupList :: Group.List
Iustin Pop's avatar
Iustin Pop committed
97
defGroupList = Container.fromList [(Group.idx defGroup, defGroup)]
Iustin Pop's avatar
Iustin Pop committed
98
99
100
101

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

102
103
-- * Helper functions

104
-- | Simple checker for whether OpResult is fail or pass.
Iustin Pop's avatar
Iustin Pop committed
105
106
107
108
isFailure :: Types.OpResult a -> Bool
isFailure (Types.OpFail _) = True
isFailure _ = False

109
-- | Update an instance to be smaller than a node.
110
setInstanceSmallerThanNode node inst =
111
112
113
    inst { Instance.mem = Node.availMem node `div` 2
         , Instance.dsk = Node.availDisk node `div` 2
         , Instance.vcpus = Node.availCpu node `div` 2
114
115
         }

116
-- | Create an instance given its spec.
117
createInstance mem dsk vcpus =
118
    Instance.create "inst-unnamed" mem dsk vcpus "running" [] True (-1) (-1)
119
                    Types.DTDrbd8
120

121
-- | Create a small cluster by repeating a node spec.
122
123
124
125
126
makeSmallCluster :: Node.Node -> Int -> Node.List
makeSmallCluster node count =
    let fn = Node.buildPeers node Container.empty
        namelst = map (\n -> (Node.name n, n)) (replicate count fn)
        (_, nlst) = Loader.assignIndices namelst
127
    in nlst
128

129
-- | Checks if a node is "big" enough.
130
131
132
133
134
isNodeBig :: Node.Node -> Int -> Bool
isNodeBig node size = Node.availDisk node > size * Types.unitDsk
                      && Node.availMem node > size * Types.unitMem
                      && Node.availCpu node > size * Types.unitCpu

135
136
canBalance :: Cluster.Table -> Bool -> Bool -> Bool -> Bool
canBalance tbl dm im evac = isJust $ Cluster.tryBalance tbl dm im evac 0 0
137

138
-- | Assigns a new fresh instance to a cluster; this is not
139
-- allocation, so no resource checks are done.
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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
                then 0
                else fst (Container.findMax il) + 1
      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')

157
158
-- * Arbitrary instances

159
-- | Defines a DNS name.
160
newtype DNSChar = DNSChar { dnsGetChar::Char }
161

162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
instance Arbitrary DNSChar where
    arbitrary = do
      x <- elements (['a'..'z'] ++ ['0'..'9'] ++ "_-")
      return (DNSChar x)

getName :: Gen String
getName = do
  n <- choose (1, 64)
  dn <- vector n::Gen [DNSChar]
  return (map dnsGetChar dn)


getFQDN :: Gen String
getFQDN = do
  felem <- getName
  ncomps <- choose (1, 4)
  frest <- vector ncomps::Gen [[DNSChar]]
  let frest' = map (map dnsGetChar) frest
  return (felem ++ "." ++ intercalate "." frest')

182
183
184
-- let's generate a random instance
instance Arbitrary Instance.Instance where
    arbitrary = do
185
      name <- getFQDN
Iustin Pop's avatar
Iustin Pop committed
186
187
      mem <- choose (0, maxMem)
      dsk <- choose (0, maxDsk)
188
189
190
191
192
193
194
195
      run_st <- elements [ C.inststErrorup
                         , C.inststErrordown
                         , C.inststAdmindown
                         , C.inststNodedown
                         , C.inststNodeoffline
                         , C.inststRunning
                         , "no_such_status1"
                         , "no_such_status2"]
196
197
      pn <- arbitrary
      sn <- arbitrary
Iustin Pop's avatar
Iustin Pop committed
198
      vcpus <- choose (0, maxCpu)
199
      return $ Instance.create name mem dsk vcpus run_st [] True pn sn
200
                               Types.DTDrbd8
201

202
203
204
205
206
-- | 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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
genNode min_multiplier max_multiplier = do
  let (base_mem, base_dsk, base_cpu) =
          case min_multiplier of
            Just mm -> (mm * Types.unitMem,
                        mm * Types.unitDsk,
                        mm * Types.unitCpu)
            Nothing -> (0, 0, 0)
      (top_mem, top_dsk, top_cpu)  =
          case max_multiplier of
            Just mm -> (mm * Types.unitMem,
                        mm * Types.unitDsk,
                        mm * Types.unitCpu)
            Nothing -> (maxMem, maxDsk, maxCpu)
  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
          (fromIntegral dsk_t) dsk_f (fromIntegral cpu_t) offl 0
  return $ Node.buildPeers n Container.empty

232
233
-- and a random node
instance Arbitrary Node.Node where
234
    arbitrary = genNode Nothing Nothing
235

Iustin Pop's avatar
Iustin Pop committed
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
-- replace disks
instance Arbitrary OpCodes.ReplaceDisksMode where
  arbitrary = elements [ OpCodes.ReplaceOnPrimary
                       , OpCodes.ReplaceOnSecondary
                       , OpCodes.ReplaceNewSecondary
                       , OpCodes.ReplaceAuto
                       ]

instance Arbitrary OpCodes.OpCode where
  arbitrary = do
    op_id <- elements [ "OP_TEST_DELAY"
                      , "OP_INSTANCE_REPLACE_DISKS"
                      , "OP_INSTANCE_FAILOVER"
                      , "OP_INSTANCE_MIGRATE"
                      ]
    (case op_id of
        "OP_TEST_DELAY" ->
          liftM3 OpCodes.OpTestDelay arbitrary arbitrary arbitrary
        "OP_INSTANCE_REPLACE_DISKS" ->
255
          liftM5 OpCodes.OpInstanceReplaceDisks arbitrary arbitrary
Iustin Pop's avatar
Iustin Pop committed
256
257
          arbitrary arbitrary arbitrary
        "OP_INSTANCE_FAILOVER" ->
258
          liftM2 OpCodes.OpInstanceFailover arbitrary arbitrary
Iustin Pop's avatar
Iustin Pop committed
259
        "OP_INSTANCE_MIGRATE" ->
260
          liftM4 OpCodes.OpInstanceMigrate arbitrary arbitrary arbitrary
261
          arbitrary
Iustin Pop's avatar
Iustin Pop committed
262
263
        _ -> fail "Wrong opcode")

264
265
266
267
268
269
instance Arbitrary Jobs.OpStatus where
  arbitrary = elements [minBound..maxBound]

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

270
271
272
273
274
275
newtype SmallRatio = SmallRatio Double deriving Show
instance Arbitrary SmallRatio where
    arbitrary = do
      v <- choose (0, 1)
      return $ SmallRatio v

276
277
278
279
280
281
instance Arbitrary Types.AllocPolicy where
  arbitrary = elements [minBound..maxBound]

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

282
-- * Actual tests
Iustin Pop's avatar
Iustin Pop committed
283

284
285
286
287
-- ** Utils tests

-- | If the list is not just an empty element, and if the elements do
-- not contain commas, then join+split should be idempotent.
Iustin Pop's avatar
Iustin Pop committed
288
289
290
291
292
prop_Utils_commaJoinSplit =
    forAll (arbitrary `suchThat`
            (\l -> l /= [""] && all (not . elem ',') l )) $ \lst ->
    Utils.sepSplit ',' (Utils.commaJoin lst) == lst

293
-- | Split and join should always be idempotent.
294
295
prop_Utils_commaSplitJoin s = Utils.commaJoin (Utils.sepSplit ',' s) == s

296
-- | fromObjWithDefault, we test using the Maybe monad and an integer
297
-- value.
298
299
300
301
302
303
prop_Utils_fromObjWithDefault def_value random_key =
    -- a missing key will be returned with the default
    Utils.fromObjWithDefault [] random_key def_value == Just def_value &&
    -- a found key will be returned as is, not with default
    Utils.fromObjWithDefault [(random_key, J.showJSON def_value)]
         random_key (def_value+1) == Just def_value
Iustin Pop's avatar
Iustin Pop committed
304
        where _types = def_value :: Integer
305

306
307
308
309
-- | Test that functional if' behaves like the syntactic sugar if.
prop_Utils_if'if :: Bool -> Int -> Int -> Bool
prop_Utils_if'if cnd a b = Utils.if' cnd a b == if cnd then a else b

Guido Trotter's avatar
Guido Trotter committed
310
-- | Test basic select functionality
311
312
313
314
prop_Utils_select :: Int   -- ^ Default result
                  -> [Int] -- ^ List of False values
                  -> [Int] -- ^ List of True values
                  -> Bool  -- ^ Test result
Guido Trotter's avatar
Guido Trotter committed
315
prop_Utils_select def lst1 lst2 =
316
  Utils.select def cndlist == expectedresult
Guido Trotter's avatar
Guido Trotter committed
317
  where expectedresult = Utils.if' (null lst2) def (head lst2)
318
319
        flist = map (\e -> (False, e)) lst1
        tlist = map (\e -> (True, e)) lst2
Guido Trotter's avatar
Guido Trotter committed
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
        cndlist = flist ++ tlist

-- | Test basic select functionality with undefined default
prop_Utils_select_undefd :: [Int] -- ^ List of False values
                         -> NonEmptyList Int -- ^ List of True values
                         -> Bool  -- ^ Test result
prop_Utils_select_undefd lst1 (NonEmpty lst2) =
  Utils.select undefined cndlist == head lst2
  where flist = map (\e -> (False, e)) lst1
        tlist = map (\e -> (True, e)) lst2
        cndlist = flist ++ tlist

-- | Test basic select functionality with undefined list values
prop_Utils_select_undefv :: [Int] -- ^ List of False values
                         -> NonEmptyList Int -- ^ List of True values
                         -> Bool  -- ^ Test result
prop_Utils_select_undefv lst1 (NonEmpty lst2) =
  Utils.select undefined cndlist == head lst2
  where flist = map (\e -> (False, e)) lst1
        tlist = map (\e -> (True, e)) lst2
        cndlist = flist ++ tlist ++ [undefined]
341

Iustin Pop's avatar
Iustin Pop committed
342
343
344
345
346
347
348
349
350
351
352
353
354
prop_Utils_parseUnit (NonNegative n) =
    Utils.parseUnit (show n) == Types.Ok n &&
    Utils.parseUnit (show n ++ "m") == Types.Ok n &&
    (case Utils.parseUnit (show n ++ "M") of
      Types.Ok m -> if n > 0
                    then m < n  -- for positive values, X MB is less than X MiB
                    else m == 0 -- but for 0, 0 MB == 0 MiB
      Types.Bad _ -> False) &&
    Utils.parseUnit (show n ++ "g") == Types.Ok (n*1024) &&
    Utils.parseUnit (show n ++ "t") == Types.Ok (n*1048576) &&
    Types.isBad (Utils.parseUnit (show n ++ "x")::Types.Result Int)
    where _types = (n::Int)

355
-- | Test list for the Utils module.
356
357
358
testUtils =
  [ run prop_Utils_commaJoinSplit
  , run prop_Utils_commaSplitJoin
359
  , run prop_Utils_fromObjWithDefault
360
361
  , run prop_Utils_if'if
  , run prop_Utils_select
Guido Trotter's avatar
Guido Trotter committed
362
363
  , run prop_Utils_select_undefd
  , run prop_Utils_select_undefv
Iustin Pop's avatar
Iustin Pop committed
364
  , run prop_Utils_parseUnit
365
366
  ]

367
368
369
-- ** PeerMap tests

-- | Make sure add is idempotent.
Iustin Pop's avatar
Iustin Pop committed
370
prop_PeerMap_addIdempotent pmap key em =
371
    fn puniq == fn (fn puniq)
372
    where _types = (pmap::PeerMap.PeerMap,
Iustin Pop's avatar
Iustin Pop committed
373
374
                    key::PeerMap.Key, em::PeerMap.Elem)
          fn = PeerMap.add key em
375
          puniq = PeerMap.accumArray const pmap
376

377
-- | Make sure remove is idempotent.
378
379
prop_PeerMap_removeIdempotent pmap key =
    fn puniq == fn (fn puniq)
380
381
    where _types = (pmap::PeerMap.PeerMap, key::PeerMap.Key)
          fn = PeerMap.remove key
382
383
          puniq = PeerMap.accumArray const pmap

384
-- | Make sure a missing item returns 0.
385
386
prop_PeerMap_findMissing pmap key =
    PeerMap.find key (PeerMap.remove key puniq) == 0
387
    where _types = (pmap::PeerMap.PeerMap, key::PeerMap.Key)
388
389
          puniq = PeerMap.accumArray const pmap

390
-- | Make sure an added item is found.
Iustin Pop's avatar
Iustin Pop committed
391
392
prop_PeerMap_addFind pmap key em =
    PeerMap.find key (PeerMap.add key em puniq) == em
393
    where _types = (pmap::PeerMap.PeerMap,
Iustin Pop's avatar
Iustin Pop committed
394
                    key::PeerMap.Key, em::PeerMap.Elem)
395
          puniq = PeerMap.accumArray const pmap
396

397
-- | Manual check that maxElem returns the maximum indeed, or 0 for null.
398
399
400
prop_PeerMap_maxElem pmap =
    PeerMap.maxElem puniq == if null puniq then 0
                             else (maximum . snd . unzip) puniq
401
    where _types = pmap::PeerMap.PeerMap
402
403
          puniq = PeerMap.accumArray const pmap

404
-- | List of tests for the PeerMap module.
405
testPeerMap =
406
407
408
409
410
411
412
    [ run prop_PeerMap_addIdempotent
    , run prop_PeerMap_removeIdempotent
    , run prop_PeerMap_maxElem
    , run prop_PeerMap_addFind
    , run prop_PeerMap_findMissing
    ]

413
-- ** Container tests
414
415
416
417
418
419
420
421
422

prop_Container_addTwo cdata i1 i2 =
    fn i1 i2 cont == fn i2 i1 cont &&
       fn i1 i2 cont == fn i1 i2 (fn i1 i2 cont)
    where _types = (cdata::[Int],
                    i1::Int, i2::Int)
          cont = foldl (\c x -> Container.add x x c) Container.empty cdata
          fn x1 x2 = Container.addTwo x1 x1 x2 x2

423
424
425
426
427
prop_Container_nameOf node =
  let nl = makeSmallCluster node 1
      fnode = head (Container.elems nl)
  in Container.nameOf nl (Node.idx fnode) == Node.name fnode

428
-- | We test that in a cluster, given a random node, we can find it by
429
-- its name and alias, as long as all names and aliases are unique,
430
-- and that we fail to find a non-existing name.
431
432
433
434
435
436
437
438
439
440
441
442
443
prop_Container_findByName node othername =
  forAll (choose (1, 20)) $ \ cnt ->
  forAll (choose (0, cnt - 1)) $ \ fidx ->
  forAll (vector cnt) $ \ names ->
  (length . nub) (map fst names ++ map snd names) ==
  length names * 2 &&
  not (othername `elem` (map fst names ++ map snd names)) ==>
  let nl = makeSmallCluster node cnt
      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
444
      nl' = Container.fromList nodes'
445
446
447
448
449
      target = snd (nodes' !! fidx)
  in Container.findByName nl' (Node.name target) == Just target &&
     Container.findByName nl' (Node.alias target) == Just target &&
     Container.findByName nl' othername == Nothing

450
testContainer =
451
452
453
454
    [ run prop_Container_addTwo
    , run prop_Container_nameOf
    , run prop_Container_findByName
    ]
455

456
457
-- ** Instance tests

458
459
-- Simple instance tests, we only have setter/getters

Iustin Pop's avatar
Iustin Pop committed
460
461
462
prop_Instance_creat inst =
    Instance.name inst == Instance.alias inst

463
464
465
466
467
prop_Instance_setIdx inst idx =
    Instance.idx (Instance.setIdx inst idx) == idx
    where _types = (inst::Instance.Instance, idx::Types.Idx)

prop_Instance_setName inst name =
Iustin Pop's avatar
Iustin Pop committed
468
469
470
471
472
473
474
475
    Instance.name newinst == name &&
    Instance.alias newinst == name
    where _types = (inst::Instance.Instance, name::String)
          newinst = Instance.setName inst name

prop_Instance_setAlias inst name =
    Instance.name newinst == Instance.name inst &&
    Instance.alias newinst == name
476
    where _types = (inst::Instance.Instance, name::String)
Iustin Pop's avatar
Iustin Pop committed
477
          newinst = Instance.setAlias inst name
478
479

prop_Instance_setPri inst pdx =
480
    Instance.pNode (Instance.setPri inst pdx) == pdx
481
482
483
    where _types = (inst::Instance.Instance, pdx::Types.Ndx)

prop_Instance_setSec inst sdx =
484
    Instance.sNode (Instance.setSec inst sdx) == sdx
485
486
487
    where _types = (inst::Instance.Instance, sdx::Types.Ndx)

prop_Instance_setBoth inst pdx sdx =
488
    Instance.pNode si == pdx && Instance.sNode si == sdx
489
490
491
    where _types = (inst::Instance.Instance, pdx::Types.Ndx, sdx::Types.Ndx)
          si = Instance.setBoth inst pdx sdx

Iustin Pop's avatar
Iustin Pop committed
492
493
494
495
prop_Instance_runStatus_True =
    forAll (arbitrary `suchThat`
            ((`elem` Instance.runningStates) . Instance.runSt))
    Instance.running
Iustin Pop's avatar
Iustin Pop committed
496
497
498

prop_Instance_runStatus_False inst =
    let run_st = Instance.running inst
499
        run_tx = Instance.runSt inst
Iustin Pop's avatar
Iustin Pop committed
500
    in
501
      run_tx `notElem` Instance.runningStates ==> not run_st
Iustin Pop's avatar
Iustin Pop committed
502

Iustin Pop's avatar
Iustin Pop committed
503
504
505
506
507
508
509
510
prop_Instance_shrinkMG inst =
    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

prop_Instance_shrinkMF inst =
Iustin Pop's avatar
Iustin Pop committed
511
512
513
    forAll (choose (0, 2 * Types.unitMem - 1)) $ \mem ->
    let inst' = inst { Instance.mem = mem}
    in Types.isBad $ Instance.shrinkByType inst' Types.FailMem
Iustin Pop's avatar
Iustin Pop committed
514
515
516
517
518
519
520
521
522

prop_Instance_shrinkCG inst =
    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

prop_Instance_shrinkCF inst =
Iustin Pop's avatar
Iustin Pop committed
523
524
525
    forAll (choose (0, 2 * Types.unitCpu - 1)) $ \vcpus ->
    let inst' = inst { Instance.vcpus = vcpus }
    in Types.isBad $ Instance.shrinkByType inst' Types.FailCPU
Iustin Pop's avatar
Iustin Pop committed
526
527
528
529
530
531
532
533
534

prop_Instance_shrinkDG inst =
    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

prop_Instance_shrinkDF inst =
Iustin Pop's avatar
Iustin Pop committed
535
536
537
    forAll (choose (0, 2 * Types.unitDsk - 1)) $ \dsk ->
    let inst' = inst { Instance.dsk = dsk }
    in Types.isBad $ Instance.shrinkByType inst' Types.FailDisk
Iustin Pop's avatar
Iustin Pop committed
538
539
540

prop_Instance_setMovable inst m =
    Instance.movable inst' == m
541
    where inst' = Instance.setMovable inst m
Iustin Pop's avatar
Iustin Pop committed
542

543
testInstance =
Iustin Pop's avatar
Iustin Pop committed
544
545
    [ run prop_Instance_creat
    , run prop_Instance_setIdx
546
    , run prop_Instance_setName
Iustin Pop's avatar
Iustin Pop committed
547
    , run prop_Instance_setAlias
548
549
550
    , run prop_Instance_setPri
    , run prop_Instance_setSec
    , run prop_Instance_setBoth
Iustin Pop's avatar
Iustin Pop committed
551
552
    , run prop_Instance_runStatus_True
    , run prop_Instance_runStatus_False
Iustin Pop's avatar
Iustin Pop committed
553
554
555
556
557
558
559
    , run prop_Instance_shrinkMG
    , run prop_Instance_shrinkMF
    , run prop_Instance_shrinkCG
    , run prop_Instance_shrinkCF
    , run prop_Instance_shrinkDG
    , run prop_Instance_shrinkDF
    , run prop_Instance_setMovable
Iustin Pop's avatar
Iustin Pop committed
560
561
    ]

562
563
-- ** Text backend tests

Iustin Pop's avatar
Iustin Pop committed
564
565
-- Instance text loader tests

Iustin Pop's avatar
Iustin Pop committed
566
567
prop_Text_Load_Instance name mem dsk vcpus status
                        (NonEmpty pnode) snode
568
                        (NonNegative pdx) (NonNegative sdx) autobal dt =
569
    pnode /= snode && pdx /= sdx ==>
Iustin Pop's avatar
Iustin Pop committed
570
571
572
    let vcpus_s = show vcpus
        dsk_s = show dsk
        mem_s = show mem
Iustin Pop's avatar
Iustin Pop committed
573
574
        ndx = if null snode
              then [(pnode, pdx)]
575
              else [(pnode, pdx), (snode, sdx)]
576
        nl = Data.Map.fromList ndx
577
        tags = ""
Iustin Pop's avatar
Iustin Pop committed
578
        sbal = if autobal then "Y" else "N"
579
        sdt = Types.dtToString dt
580
        inst = Text.loadInst nl
Iustin Pop's avatar
Iustin Pop committed
581
               [name, mem_s, dsk_s, vcpus_s, status,
582
                sbal, pnode, snode, sdt, tags]
583
        fail1 = Text.loadInst nl
Iustin Pop's avatar
Iustin Pop committed
584
               [name, mem_s, dsk_s, vcpus_s, status,
585
                sbal, pnode, pnode, tags]
Iustin Pop's avatar
Iustin Pop committed
586
587
        _types = ( name::String, mem::Int, dsk::Int
                 , vcpus::Int, status::String
Iustin Pop's avatar
Iustin Pop committed
588
                 , snode::String
Iustin Pop's avatar
Iustin Pop committed
589
                 , autobal::Bool)
Iustin Pop's avatar
Iustin Pop committed
590
591
    in
      case inst of
592
593
594
595
        Types.Bad msg -> printTestCase ("Failed to load instance: " ++ msg)
                         False
        Types.Ok (_, i) -> printTestCase ("Mismatch in some field while\
                                          \ loading the instance") $
Iustin Pop's avatar
Iustin Pop committed
596
597
598
599
600
601
            Instance.name i == name &&
            Instance.vcpus i == vcpus &&
            Instance.mem i == mem &&
            Instance.pNode i == pdx &&
            Instance.sNode i == (if null snode
                                 then Node.noSecondary
602
                                 else sdx) &&
603
            Instance.autoBalance i == autobal &&
604
            Types.isBad fail1
Iustin Pop's avatar
Iustin Pop committed
605
606

prop_Text_Load_InstanceFail ktn fields =
607
    length fields /= 10 ==>
Iustin Pop's avatar
Iustin Pop committed
608
    case Text.loadInst nl fields of
609
610
611
612
      Types.Ok _ -> printTestCase "Managed to load instance from invalid\
                                  \ data" False
      Types.Bad msg -> printTestCase ("Unrecognised error message: " ++ msg) $
                       "Invalid/incomplete instance data: '" `isPrefixOf` msg
613
    where nl = Data.Map.fromList ktn
Iustin Pop's avatar
Iustin Pop committed
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628

prop_Text_Load_Node name tm nm fm td fd tc fo =
    let conv v = if v < 0
                    then "?"
                    else show v
        tm_s = conv tm
        nm_s = conv nm
        fm_s = conv fm
        td_s = conv td
        fd_s = conv fd
        tc_s = conv tc
        fo_s = if fo
               then "Y"
               else "N"
        any_broken = any (< 0) [tm, nm, fm, td, fd, tc]
Iustin Pop's avatar
Iustin Pop committed
629
630
631
        gid = Group.uuid defGroup
    in case Text.loadNode defGroupAssoc
           [name, tm_s, nm_s, fm_s, td_s, fd_s, tc_s, fo_s, gid] of
Iustin Pop's avatar
Iustin Pop committed
632
633
634
635
         Nothing -> False
         Just (name', node) ->
             if fo || any_broken
             then Node.offline node
636
637
638
639
640
641
642
643
             else Node.name node == name' && name' == name &&
                  Node.alias node == name &&
                  Node.tMem node == fromIntegral tm &&
                  Node.nMem node == nm &&
                  Node.fMem node == fm &&
                  Node.tDsk node == fromIntegral td &&
                  Node.fDsk node == fd &&
                  Node.tCpu node == fromIntegral tc
Iustin Pop's avatar
Iustin Pop committed
644
645

prop_Text_Load_NodeFail fields =
Iustin Pop's avatar
Iustin Pop committed
646
    length fields /= 8 ==> isNothing $ Text.loadNode Data.Map.empty fields
Iustin Pop's avatar
Iustin Pop committed
647

648
prop_Text_NodeLSIdempotent node =
Iustin Pop's avatar
Iustin Pop committed
649
650
    (Text.loadNode defGroupAssoc.
         Utils.sepSplit '|' . Text.serializeNode defGroupList) n ==
651
652
653
654
    Just (Node.name n, n)
    -- override failN1 to what loadNode returns by default
    where n = node { Node.failN1 = True, Node.offline = False }

655
testText =
Iustin Pop's avatar
Iustin Pop committed
656
    [ run prop_Text_Load_Instance
Iustin Pop's avatar
Iustin Pop committed
657
658
659
    , run prop_Text_Load_InstanceFail
    , run prop_Text_Load_Node
    , run prop_Text_Load_NodeFail
660
    , run prop_Text_NodeLSIdempotent
661
662
    ]

663
-- ** Node tests
664

Iustin Pop's avatar
Iustin Pop committed
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
prop_Node_setAlias node name =
    Node.name newnode == Node.name node &&
    Node.alias newnode == name
    where _types = (node::Node.Node, name::String)
          newnode = Node.setAlias node name

prop_Node_setOffline node status =
    Node.offline newnode == status
    where newnode = Node.setOffline node status

prop_Node_setXmem node xm =
    Node.xMem newnode == xm
    where newnode = Node.setXmem node xm

prop_Node_setMcpu node mc =
    Node.mCpu newnode == mc
    where newnode = Node.setMcpu node mc

683
684
-- | Check that an instance add with too high memory or disk will be
-- rejected.
Iustin Pop's avatar
Iustin Pop committed
685
686
687
688
689
690
prop_Node_addPriFM node inst = Instance.mem inst >= Node.fMem node &&
                               not (Node.failN1 node)
                               ==>
                               case Node.addPri node inst'' of
                                 Types.OpFail Types.FailMem -> True
                                 _ -> False
691
    where _types = (node::Node.Node, inst::Instance.Instance)
Iustin Pop's avatar
Iustin Pop committed
692
693
694
695
696
697
698
699
700
701
702
703
704
          inst' = setInstanceSmallerThanNode node inst
          inst'' = inst' { Instance.mem = Instance.mem inst }

prop_Node_addPriFD node inst = Instance.dsk inst >= Node.fDsk node &&
                               not (Node.failN1 node)
                               ==>
                               case Node.addPri node inst'' of
                                 Types.OpFail Types.FailDisk -> True
                                 _ -> False
    where _types = (node::Node.Node, inst::Instance.Instance)
          inst' = setInstanceSmallerThanNode node inst
          inst'' = inst' { Instance.dsk = Instance.dsk inst }

Iustin Pop's avatar
Iustin Pop committed
705
706
707
708
709
prop_Node_addPriFC node inst (Positive extra) =
    not (Node.failN1 node) ==>
        case Node.addPri node inst'' of
          Types.OpFail Types.FailCPU -> True
          _ -> False
Iustin Pop's avatar
Iustin Pop committed
710
711
    where _types = (node::Node.Node, inst::Instance.Instance)
          inst' = setInstanceSmallerThanNode node inst
Iustin Pop's avatar
Iustin Pop committed
712
          inst'' = inst' { Instance.vcpus = Node.availCpu node + extra }
713

714
715
-- | Check that an instance add with too high memory or disk will be
-- rejected.
716
prop_Node_addSec node inst pdx =
717
718
    (Instance.mem inst >= (Node.fMem node - Node.rMem node) ||
     Instance.dsk inst >= Node.fDsk node) &&
Iustin Pop's avatar
Iustin Pop committed
719
    not (Node.failN1 node)
Iustin Pop's avatar
Iustin Pop committed
720
    ==> isFailure (Node.addSec node inst pdx)
721
        where _types = (node::Node.Node, inst::Instance.Instance, pdx::Int)
722

723
-- | Checks for memory reservation changes.
724
prop_Node_rMem inst =
725
    forAll (arbitrary `suchThat` ((> Types.unitMem) . Node.fMem)) $ \node ->
726
727
    -- ab = auto_balance, nb = non-auto_balance
    -- we use -1 as the primary node of the instance
728
    let inst' = inst { Instance.pNode = -1, Instance.autoBalance = True }
729
        inst_ab = setInstanceSmallerThanNode node inst'
730
        inst_nb = inst_ab { Instance.autoBalance = False }
731
        -- now we have the two instances, identical except the
732
        -- autoBalance attribute
733
734
735
736
737
738
739
740
741
        orig_rmem = Node.rMem node
        inst_idx = Instance.idx inst_ab
        node_add_ab = Node.addSec node inst_ab (-1)
        node_add_nb = Node.addSec node inst_nb (-1)
        node_del_ab = liftM (flip Node.removeSec inst_ab) node_add_ab
        node_del_nb = liftM (flip Node.removeSec inst_nb) node_add_nb
    in case (node_add_ab, node_add_nb, node_del_ab, node_del_nb) of
         (Types.OpGood a_ab, Types.OpGood a_nb,
          Types.OpGood d_ab, Types.OpGood d_nb) ->
742
             printTestCase "Consistency checks failed" $
743
744
745
746
747
748
749
750
751
             Node.rMem a_ab >  orig_rmem &&
             Node.rMem a_ab - orig_rmem == Instance.mem inst_ab &&
             Node.rMem a_nb == orig_rmem &&
             Node.rMem d_ab == orig_rmem &&
             Node.rMem d_nb == orig_rmem &&
             -- this is not related to rMem, but as good a place to
             -- test as any
             inst_idx `elem` Node.sList a_ab &&
             not (inst_idx `elem` Node.sList d_ab)
752
753
         x -> printTestCase ("Failed to add/remove instances: " ++ show x)
              False
754

755
-- | Check mdsk setting.
Iustin Pop's avatar
Iustin Pop committed
756
757
758
759
760
prop_Node_setMdsk node mx =
    Node.loDsk node' >= 0 &&
    fromIntegral (Node.loDsk node') <= Node.tDsk node &&
    Node.availDisk node' >= 0 &&
    Node.availDisk node' <= Node.fDsk node' &&
Iustin Pop's avatar
Iustin Pop committed
761
762
    fromIntegral (Node.availDisk node') <= Node.tDsk node' &&
    Node.mDsk node' == mx'
Iustin Pop's avatar
Iustin Pop committed
763
764
765
766
767
768
769
    where _types = (node::Node.Node, mx::SmallRatio)
          node' = Node.setMdsk node mx'
          SmallRatio mx' = mx

-- Check tag maps
prop_Node_tagMaps_idempotent tags =
    Node.delTags (Node.addTags m tags) tags == m
770
    where m = Data.Map.empty
Iustin Pop's avatar
Iustin Pop committed
771
772
773
774

prop_Node_tagMaps_reject tags =
    not (null tags) ==>
    any (\t -> Node.rejectAddTags m [t]) tags
775
    where m = Node.addTags Data.Map.empty tags
Iustin Pop's avatar
Iustin Pop committed
776

Iustin Pop's avatar
Iustin Pop committed
777
778
779
780
781
prop_Node_showField node =
  forAll (elements Node.defaultFields) $ \ field ->
  fst (Node.showHeader field) /= Types.unknownField &&
  Node.showField node field /= Types.unknownField

782
783
784
785
786
787
788

prop_Node_computeGroups nodes =
  let ng = Node.computeGroups nodes
      onlyuuid = map fst ng
  in length nodes == sum (map (length . snd) ng) &&
     all (\(guuid, ns) -> all ((== guuid) . Node.group) ns) ng &&
     length (nub onlyuuid) == length onlyuuid &&
Iustin Pop's avatar
Iustin Pop committed
789
     (null nodes || not (null ng))
790

791
testNode =
Iustin Pop's avatar
Iustin Pop committed
792
793
794
795
796
    [ run prop_Node_setAlias
    , run prop_Node_setOffline
    , run prop_Node_setMcpu
    , run prop_Node_setXmem
    , run prop_Node_addPriFM
Iustin Pop's avatar
Iustin Pop committed
797
798
    , run prop_Node_addPriFD
    , run prop_Node_addPriFC
799
    , run prop_Node_addSec
800
    , run prop_Node_rMem
Iustin Pop's avatar
Iustin Pop committed
801
802
803
    , run prop_Node_setMdsk
    , run prop_Node_tagMaps_idempotent
    , run prop_Node_tagMaps_reject
Iustin Pop's avatar
Iustin Pop committed
804
    , run prop_Node_showField
805
    , run prop_Node_computeGroups
806
    ]
807
808


809
-- ** Cluster tests
810

811
812
-- | Check that the cluster score is close to zero for a homogeneous
-- cluster.
Iustin Pop's avatar
Iustin Pop committed
813
814
prop_Score_Zero node =
    forAll (choose (1, 1024)) $ \count ->
Iustin Pop's avatar
Iustin Pop committed
815
    (not (Node.offline node) && not (Node.failN1 node) && (count > 0) &&
816
     (Node.tDsk node > 0) && (Node.tMem node > 0)) ==>
817
    let fn = Node.buildPeers node Container.empty
818
819
        nlst = replicate count fn
        score = Cluster.compCVNodes nlst
820
821
    -- we can't say == 0 here as the floating point errors accumulate;
    -- this should be much lower than the default score in CLI.hs
Iustin Pop's avatar
Iustin Pop committed
822
    in score <= 1e-12
823

824
-- | Check that cluster stats are sane.
Iustin Pop's avatar
Iustin Pop committed
825
826
827
prop_CStats_sane node =
    forAll (choose (1, 1024)) $ \count ->
    (not (Node.offline node) && not (Node.failN1 node) &&
828
     (Node.availDisk node > 0) && (Node.availMem node > 0)) ==>
Iustin Pop's avatar
Iustin Pop committed
829
830
    let fn = Node.buildPeers node Container.empty
        nlst = zip [1..] $ replicate count fn::[(Types.Ndx, Node.Node)]
Iustin Pop's avatar
Iustin Pop committed
831
        nl = Container.fromList nlst
Iustin Pop's avatar
Iustin Pop committed
832
833
834
835
        cstats = Cluster.totalResources nl
    in Cluster.csAdsk cstats >= 0 &&
       Cluster.csAdsk cstats <= Cluster.csFdsk cstats

836
-- | Check that one instance is allocated correctly, without
837
-- rebalances needed.
838
839
840
841
842
843
844
845
846
847
prop_ClusterAlloc_sane node inst =
    forAll (choose (5, 20)) $ \count ->
    not (Node.offline node)
            && not (Node.failN1 node)
            && Node.availDisk node > 0
            && Node.availMem node > 0
            ==>
    let nl = makeSmallCluster node count
        il = Container.empty
        inst' = setInstanceSmallerThanNode node inst
848
849
    in case Cluster.genAllocNodes defGroupList nl 2 True >>=
       Cluster.tryAlloc nl il inst' of
850
         Types.Bad _ -> False
851
852
         Types.Ok as ->
             case Cluster.asSolutions as of
853
               [] -> False
854
               (xnl, xi, _, cv):[] ->
855
                   let il' = Container.add (Instance.idx xi) xi il
856
                       tbl = Cluster.Table xnl il' cv []
857
                   in not (canBalance tbl True True False)
858
859
860
861
               _ -> False

-- | Checks that on a 2-5 node cluster, we can allocate a random
-- instance spec via tiered allocation (whatever the original instance
862
-- spec), on either one or two nodes.
863
864
865
866
867
868
869
870
871
prop_ClusterCanTieredAlloc node inst =
    forAll (choose (2, 5)) $ \count ->
    forAll (choose (1, 2)) $ \rqnodes ->
    not (Node.offline node)
            && not (Node.failN1 node)
            && isNodeBig node 4
            ==>
    let nl = makeSmallCluster node count
        il = Container.empty
872
        allocnodes = Cluster.genAllocNodes defGroupList nl rqnodes True
Iustin Pop's avatar
Iustin Pop committed
873
    in case allocnodes >>= \allocnodes' ->
874
        Cluster.tieredAlloc nl il (Just 1) inst allocnodes' [] [] of
875
         Types.Bad _ -> False
876
877
878
         Types.Ok (_, _, il', ixes, cstats) -> not (null ixes) &&
                                      IntMap.size il' == length ixes &&
                                      length ixes == length cstats
879
880

-- | Checks that on a 4-8 node cluster, once we allocate an instance,
881
-- we can also evacuate it.
882
883
884
885
886
887
888
889
890
prop_ClusterAllocEvac node inst =
    forAll (choose (4, 8)) $ \count ->
    not (Node.offline node)
            && not (Node.failN1 node)
            && isNodeBig node 4
            ==>
    let nl = makeSmallCluster node count
        il = Container.empty
        inst' = setInstanceSmallerThanNode node inst
891
892
    in case Cluster.genAllocNodes defGroupList nl 2 True >>=
       Cluster.tryAlloc nl il inst' of
893
         Types.Bad _ -> False
894
895
         Types.Ok as ->
             case Cluster.asSolutions as of
896
               [] -> False
897
               (xnl, xi, _, _):[] ->
898
899
                   let sdx = Instance.sNode xi
                       il' = Container.add (Instance.idx xi) xi il
900
                   in case Cluster.tryEvac xnl il' [Instance.idx xi] [sdx] of
901
902
903
904
905
                        Just _ -> True
                        _ -> False
               _ -> False

-- | Check that allocating multiple instances on a cluster, then
906
-- adding an empty node, results in a valid rebalance.
907
908
prop_ClusterAllocBalance =
    forAll (genNode (Just 5) (Just 128)) $ \node ->
909
    forAll (choose (3, 5)) $ \count ->
910
    not (Node.offline node) && not (Node.failN1 node) ==>
911
912
913
    let nl = makeSmallCluster node count
        (hnode, nl') = IntMap.deleteFindMax nl
        il = Container.empty
914
        allocnodes = Cluster.genAllocNodes defGroupList nl' 2 True
915
        i_templ = createInstance Types.unitMem Types.unitDsk Types.unitCpu
Iustin Pop's avatar
Iustin Pop committed
916
    in case allocnodes >>= \allocnodes' ->
917
        Cluster.iterateAlloc nl' il (Just 5) i_templ allocnodes' [] [] of
918
         Types.Bad _ -> False
919
         Types.Ok (_, xnl, il', _, _) ->
920
921
922
                   let ynl = Container.add (Node.idx hnode) hnode xnl
                       cv = Cluster.compCV ynl
                       tbl = Cluster.Table ynl il' cv []
923
                   in canBalance tbl True True False
924

925
-- | Checks consistency.
926
927
928
prop_ClusterCheckConsistency node inst =
  let nl = makeSmallCluster node 3
      [node1, node2, node3] = Container.elems nl
Iustin Pop's avatar
Iustin Pop committed
929
      node3' = node3 { Node.group = 1 }
930
931
932
933
      nl' = Container.add (Node.idx node3') node3' nl
      inst1 = Instance.setBoth inst (Node.idx node1) (Node.idx node2)
      inst2 = Instance.setBoth inst (Node.idx node1) Node.noSecondary
      inst3 = Instance.setBoth inst (Node.idx node1) (Node.idx node3)
Iustin Pop's avatar
Iustin Pop committed
934
      ccheck = Cluster.findSplitInstances nl' . Container.fromList
935
936
937
938
  in null (ccheck [(0, inst1)]) &&
     null (ccheck [(0, inst2)]) &&
     (not . null $ ccheck [(0, inst3)])

939
-- | For now, we only test that we don't lose instances during the split.
940
941
942
943
944
945
946
947
948
prop_ClusterSplitCluster node inst =
  forAll (choose (0, 100)) $ \icnt ->
  let nl = makeSmallCluster node 2
      (nl', il') = foldl (\(ns, is) _ -> assignInstance ns is inst 0 1)
                   (nl, Container.empty) [1..icnt]
      gni = Cluster.splitCluster nl' il'
  in sum (map (Container.size . snd . snd) gni) == icnt &&
     all (\(guuid, (nl'', _)) -> all ((== guuid) . Node.group)
                                 (Container.elems nl'')) gni
949

950
testCluster =
951
    [ run prop_Score_Zero
Iustin Pop's avatar
Iustin Pop committed
952
    , run prop_CStats_sane
953
954
955
956
    , run prop_ClusterAlloc_sane
    , run prop_ClusterCanTieredAlloc
    , run prop_ClusterAllocEvac
    , run prop_ClusterAllocBalance
957
    , run prop_ClusterCheckConsistency
958
    , run prop_ClusterSplitCluster
959
    ]
Iustin Pop's avatar
Iustin Pop committed
960

961
-- ** OpCodes tests
Iustin Pop's avatar
Iustin Pop committed
962

963
-- | Check that opcode serialization is idempotent.
Iustin Pop's avatar
Iustin Pop committed
964
965
966
967
prop_OpCodes_serialization op =
  case J.readJSON (J.showJSON op) of
    J.Error _ -> False
    J.Ok op' -> op == op'
968
  where _types = op::OpCodes.OpCode
Iustin Pop's avatar
Iustin Pop committed
969
970
971
972

testOpCodes =
  [ run prop_OpCodes_serialization
  ]
Iustin Pop's avatar
Iustin Pop committed
973

974
975
976
-- ** Jobs tests

-- | Check that (queued) job\/opcode status serialization is idempotent.
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
prop_OpStatus_serialization os =
  case J.readJSON (J.showJSON os) of
    J.Error _ -> False
    J.Ok os' -> os == os'
  where _types = os::Jobs.OpStatus

prop_JobStatus_serialization js =
  case J.readJSON (J.showJSON js) of
    J.Error _ -> False
    J.Ok js' -> js == js'
  where _types = js::Jobs.JobStatus

testJobs =
  [ run prop_OpStatus_serialization
  , run prop_JobStatus_serialization
  ]

994
-- ** Loader tests
Iustin Pop's avatar
Iustin Pop committed
995
996

prop_Loader_lookupNode ktn inst node =
997
998
  Loader.lookupNode nl inst node == Data.Map.lookup node nl
  where nl = Data.Map.fromList ktn
Iustin Pop's avatar
Iustin Pop committed
999
1000

prop_Loader_lookupInstance kti inst =
1001
1002
1003
1004
1005
1006
1007
1008
  Loader.lookupInstance il inst == Data.Map.lookup inst il
  where il = Data.Map.fromList kti

prop_Loader_assignIndices nodes =
  Data.Map.size nassoc == length nodes &&
  Container.size kt == length nodes &&
  (if not (null nodes)
   then maximum (IntMap.keys kt) == length nodes - 1
Iustin Pop's avatar
Iustin Pop committed
1009
   else True)
1010
  where (nassoc, kt) = Loader.assignIndices (map (\n -> (Node.name n, n)) nodes)