Debian Codegraph @

test/hs/Test/Ganeti/Objects.hs

raw
1 {-# LANGUAGE TemplateHaskell, TypeSynonymInstances, FlexibleInstances,
2 OverloadedStrings #-}
3 {-# OPTIONS_GHC -fno-warn-orphans #-}
4
5 {-| Unittests for ganeti-htools.
6
7 -}
8
9 {-
10
11 Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc.
12 All rights reserved.
13
14 Redistribution and use in source and binary forms, with or without
15 modification, are permitted provided that the following conditions are
16 met:
17
18 1. Redistributions of source code must retain the above copyright notice,
19 this list of conditions and the following disclaimer.
20
21 2. Redistributions in binary form must reproduce the above copyright
22 notice, this list of conditions and the following disclaimer in the
23 documentation and/or other materials provided with the distribution.
24
25 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
26 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
27 TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28 PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
29 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
30 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
32 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36
37 -}
38
39 module Test.Ganeti.Objects
40 ( testObjects
41 , Node(..)
42 , genConfigDataWithNetworks
43 , genDisk
44 , genDiskWithChildren
45 , genEmptyCluster
46 , genInst
47 , genInstWithNets
48 , genValidNetwork
49 , genBitStringMaxLen
50 ) where
51
52 import Test.QuickCheck
53 import qualified Test.HUnit as HUnit
54
55 import Control.Monad
56 import qualified Data.ByteString as BS
57 import qualified Data.ByteString.UTF8 as UTF8
58 import Data.Char
59 import qualified Data.List as List
60 import qualified Data.Map as Map
61 import Data.Maybe (fromMaybe)
62 import Data.Word (Word32)
63 import GHC.Exts (IsString(..))
64 import System.Time (ClockTime(..))
65 import qualified Text.JSON as J
66
67 import Test.Ganeti.Query.Language ()
68 import Test.Ganeti.SlotMap (genSlotLimit)
69 import Test.Ganeti.TestHelper
70 import Test.Ganeti.TestCommon
71 import Test.Ganeti.Types ()
72
73 import qualified Ganeti.Constants as C
74 import qualified Ganeti.ConstantUtils as CU
75 import Ganeti.Network
76 import Ganeti.Objects as Objects
77 import qualified Ganeti.Objects.BitArray as BA
78 import Ganeti.JSON
79 import Ganeti.Types
80
81 -- * Arbitrary instances
82
83 instance Arbitrary (Container DataCollectorConfig) where
84 arbitrary = do
85 let names = map UTF8.fromString $ CU.toList C.dataCollectorNames
86 activations <- vector $ length names
87 timeouts <- vector $ length names
88 let configs = zipWith DataCollectorConfig activations timeouts
89 return GenericContainer {
90 fromContainer = Map.fromList $ zip names configs }
91
92 instance Arbitrary BS.ByteString where
93 arbitrary = genPrintableByteString
94
95 instance Arbitrary a => Arbitrary (Private a) where
96 arbitrary = Private <$> arbitrary
97
98 $(genArbitrary ''PartialNDParams)
99
100 instance Arbitrary (Container J.JSValue) where
101 arbitrary = return $ GenericContainer Map.empty
102
103 instance Arbitrary Node where
104 arbitrary = Node <$> genFQDN <*> genFQDN <*> genFQDN
105 <*> arbitrary <*> arbitrary <*> arbitrary <*> genFQDN
106 <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
107 <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
108 <*> fmap UTF8.fromString genUUID <*> arbitrary
109 <*> arbitrary
110
111 $(genArbitrary ''BlockDriver)
112
113 $(genArbitrary ''DiskMode)
114
115 instance Arbitrary LogicalVolume where
116 arbitrary = LogicalVolume <$> validName <*> validName
117 where
118 validName = -- we intentionally omit '.' and '-' to avoid forbidden names
119 listOf1 $ elements (['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ "+_")
120
121 instance Arbitrary DiskLogicalId where
122 arbitrary = oneof [ LIDPlain <$> arbitrary
123 , LIDDrbd8 <$> genFQDN <*> genFQDN <*> arbitrary
124 <*> arbitrary <*> arbitrary <*> arbitrary
125 , LIDFile <$> arbitrary <*> arbitrary
126 , LIDBlockDev <$> arbitrary <*> arbitrary
127 , LIDRados <$> arbitrary <*> arbitrary
128 ]
129
130 -- | 'Disk' 'arbitrary' instance. Since we don't test disk hierarchy
131 -- properties, we only generate disks with no children (FIXME), as
132 -- generating recursive datastructures is a bit more work.
133 instance Arbitrary Disk where
134 arbitrary =
135 frequency [ (2, liftM RealDisk $ RealDiskData <$> arbitrary
136 <*> pure [] <*> arbitrary
137 <*> arbitrary <*> arbitrary <*> arbitrary
138 <*> arbitrary <*> arbitrary <*> arbitrary
139 <*> arbitrary <*> arbitrary <*> arbitrary
140 <*> arbitrary)
141 , (1, liftM ForthcomingDisk $ ForthcomingDiskData <$> arbitrary
142 <*> pure [] <*> arbitrary
143 <*> arbitrary <*> arbitrary <*> arbitrary
144 <*> arbitrary <*> arbitrary <*> arbitrary
145 <*> arbitrary <*> arbitrary <*> arbitrary
146 <*> arbitrary)
147 ]
148
149 -- FIXME: we should generate proper values, >=0, etc., but this is
150 -- hard for partial ones, where all must be wrapped in a 'Maybe'
151 $(genArbitrary ''PartialBeParams)
152
153 $(genArbitrary ''AdminState)
154
155 $(genArbitrary ''AdminStateSource)
156
157 $(genArbitrary ''PartialNicParams)
158
159 $(genArbitrary ''PartialNic)
160
161 instance Arbitrary ForthcomingInstanceData where
162 arbitrary =
163 ForthcomingInstanceData
164 -- name
165 <$> genMaybe genFQDN
166 -- primary node
167 <*> genMaybe genFQDN
168 -- OS
169 <*> genMaybe genFQDN
170 -- hypervisor
171 <*> arbitrary
172 -- hvparams
173 -- FIXME: add non-empty hvparams when they're a proper type
174 <*> pure (GenericContainer Map.empty)
175 -- beparams
176 <*> arbitrary
177 -- osparams
178 <*> pure (GenericContainer Map.empty)
179 -- osparams_private
180 <*> pure (GenericContainer Map.empty)
181 -- admin_state
182 <*> genMaybe arbitrary
183 -- admin_state_source
184 <*> genMaybe arbitrary
185 -- nics
186 <*> arbitrary
187 -- disks
188 <*> vectorOf 5 arbitrary
189 -- disks active
190 <*> genMaybe arbitrary
191 -- network port
192 <*> arbitrary
193 -- ts
194 <*> arbitrary <*> arbitrary
195 -- uuid
196 <*> arbitrary
197 -- serial
198 <*> arbitrary
199 -- tags
200 <*> arbitrary
201
202 instance Arbitrary RealInstanceData where
203 arbitrary =
204 RealInstanceData
205 -- name
206 <$> genFQDN
207 -- primary node
208 <*> genFQDN
209 -- OS
210 <*> genFQDN
211 -- hypervisor
212 <*> arbitrary
213 -- hvparams
214 -- FIXME: add non-empty hvparams when they're a proper type
215 <*> pure (GenericContainer Map.empty)
216 -- beparams
217 <*> arbitrary
218 -- osparams
219 <*> pure (GenericContainer Map.empty)
220 -- osparams_private
221 <*> pure (GenericContainer Map.empty)
222 -- admin_state
223 <*> arbitrary
224 -- admin_state_source
225 <*> arbitrary
226 -- nics
227 <*> arbitrary
228 -- disks
229 <*> vectorOf 5 arbitrary
230 -- disks active
231 <*> arbitrary
232 -- network port
233 <*> arbitrary
234 -- ts
235 <*> arbitrary <*> arbitrary
236 -- uuid
237 <*> arbitrary
238 -- serial
239 <*> arbitrary
240 -- tags
241 <*> arbitrary
242
243 instance Arbitrary Instance where
244 arbitrary = frequency [ (1, ForthcomingInstance <$> arbitrary)
245 , (3, RealInstance <$> arbitrary)
246 ]
247
248 -- | Generates an instance that is connected to the given networks
249 -- and possibly some other networks
250 genInstWithNets :: [String] -> Gen Instance
251 genInstWithNets nets = do
252 plain_inst <- RealInstance <$> arbitrary
253 enhanceInstWithNets plain_inst nets
254
255 -- | Generates an instance that is connected to some networks
256 genInst :: Gen Instance
257 genInst = genInstWithNets []
258
259 -- | Enhances a given instance with network information, by connecting it to the
260 -- given networks and possibly some other networks
261 enhanceInstWithNets :: Instance -> [String] -> Gen Instance
262 enhanceInstWithNets inst nets = do
263 mac <- arbitrary
264 ip <- arbitrary
265 nicparams <- arbitrary
266 name <- arbitrary
267 uuid <- arbitrary
268 -- generate some more networks than the given ones
269 num_more_nets <- choose (0,3)
270 more_nets <- vectorOf num_more_nets genUUID
271 let genNic net = PartialNic mac ip nicparams net name uuid
272 partial_nics = map (genNic . Just)
273 (List.nub (nets ++ more_nets))
274 new_inst = case inst of
275 RealInstance rinst ->
276 RealInstance rinst { realInstNics = partial_nics }
277 ForthcomingInstance _ -> inst
278 return new_inst
279
280 genDiskWithChildren :: Int -> Gen Disk
281 genDiskWithChildren num_children = do
282 logicalid <- arbitrary
283 children <- vectorOf num_children (genDiskWithChildren 0)
284 nodes <- arbitrary
285 ivname <- genName
286 size <- arbitrary
287 mode <- arbitrary
288 name <- genMaybe genName
289 spindles <- arbitrary
290 params <- arbitrary
291 uuid <- fmap UTF8.fromString genUUID
292 serial <- arbitrary
293 time <- arbitrary
294 return . RealDisk $
295 RealDiskData logicalid children nodes ivname size mode name
296 spindles params uuid serial time time
297
298 genDisk :: Gen Disk
299 genDisk = genDiskWithChildren 3
300
301 -- | FIXME: This generates completely random data, without normal
302 -- validation rules.
303 $(genArbitrary ''PartialISpecParams)
304
305 $(genArbitrary ''FilledISpecParams)
306 $(genArbitrary ''MinMaxISpecs)
307 $(genArbitrary ''FilledIPolicy)
308 $(genArbitrary ''IpFamily)
309 $(genArbitrary ''FilledNDParams)
310 $(genArbitrary ''FilledNicParams)
311 $(genArbitrary ''FilledBeParams)
312
313 -- | FIXME: This generates completely random data, without normal
314 -- validation rules.
315 $(genArbitrary ''PartialIPolicy)
316
317 -- | No real arbitrary instance for 'ClusterHvParams' yet.
318 instance Arbitrary ClusterHvParams where
319 arbitrary = return $ GenericContainer Map.empty
320
321 -- | No real arbitrary instance for 'OsHvParams' yet.
322 instance Arbitrary OsHvParams where
323 arbitrary = return $ GenericContainer Map.empty
324
325 -- | No real arbitrary instance for 'GroupDiskParams' yet.
326 instance Arbitrary GroupDiskParams where
327 arbitrary = return $ GenericContainer Map.empty
328
329 instance Arbitrary ClusterNicParams where
330 arbitrary = (GenericContainer . Map.singleton (UTF8.fromString C.ppDefault))
331 <$> arbitrary
332
333 instance Arbitrary OsParams where
334 arbitrary = (GenericContainer . Map.fromList) <$> arbitrary
335
336 instance Arbitrary Objects.ClusterOsParamsPrivate where
337 arbitrary = (GenericContainer . Map.fromList) <$> arbitrary
338
339 instance Arbitrary ClusterOsParams where
340 arbitrary = (GenericContainer . Map.fromList) <$> arbitrary
341
342 instance Arbitrary ClusterBeParams where
343 arbitrary = (GenericContainer . Map.fromList) <$> arbitrary
344
345 $(genArbitrary ''Cluster)
346
347 instance Arbitrary ConfigData where
348 arbitrary = genEmptyCluster 0 >>= genConfigDataWithNetworks
349
350 instance Arbitrary AddressPool where
351 arbitrary = AddressPool . BA.fromList <$> arbitrary
352
353 instance Arbitrary Network where
354 arbitrary = genValidNetwork
355
356 instance Arbitrary FilterAction where
357 arbitrary = oneof
358 [ pure Accept
359 , pure Pause
360 , pure Reject
361 , pure Continue
362 , RateLimit <$> genSlotLimit
363 ]
364
365 instance Arbitrary FilterPredicate where
366 arbitrary = oneof
367 [ FPJobId <$> arbitrary
368 , FPOpCode <$> arbitrary
369 , FPReason <$> arbitrary
370 ]
371
372 instance Arbitrary FilterRule where
373 arbitrary = FilterRule <$> arbitrary
374 <*> arbitrary
375 <*> arbitrary
376 <*> arbitrary
377 <*> arbitrary
378 <*> fmap UTF8.fromString genUUID
379
380 instance Arbitrary SshKeyType where
381 arbitrary = oneof
382 [ pure RSA
383 , pure DSA
384 , pure ECDSA
385 ]
386
387 -- | Generates a network instance with minimum netmasks of /24. Generating
388 -- bigger networks slows down the tests, because long bit strings are generated
389 -- for the reservations.
390 genValidNetwork :: Gen Objects.Network
391 genValidNetwork = do
392 -- generate netmask for the IPv4 network
393 netmask <- fromIntegral <$> choose (24::Int, 30)
394 let hostLen = 32-netmask
395 name <- genName >>= mkNonEmpty
396 mac_prefix <- genMaybe genName
397 net <- Objects.ip4AddressFromNumber . (* 2^hostLen) . fromIntegral <$>
398 choose (1::Int, 2^netmask-1)
399 net6 <- genMaybe genIp6Net
400 gateway <- genMaybe arbitrary
401 gateway6 <- genMaybe genIp6Addr
402 res <- liftM Just (genBitString $ netmask2NumHosts netmask)
403 ext_res <- liftM Just (genBitString $ netmask2NumHosts netmask)
404 uuid <- arbitrary
405 ctime <- arbitrary
406 mtime <- arbitrary
407 let n = Network name mac_prefix (mkIp4Network net netmask) net6 gateway
408 gateway6 res ext_res uuid ctime mtime 0 emptyTagSet
409 return n
410
411 -- | Generate an arbitrary string consisting of '0' and '1' of the given length.
412 genBitString :: Int -> Gen AddressPool
413 genBitString len =
414 (AddressPool . BA.fromList) `liftM` vectorOf len (elements [False, True])
415
416 -- | Generate an arbitrary string consisting of '0' and '1' of the maximum given
417 -- length.
418 genBitStringMaxLen :: Int -> Gen AddressPool
419 genBitStringMaxLen maxLen = choose (0, maxLen) >>= genBitString
420
421 -- | Generator for config data with an empty cluster (no instances),
422 -- with N defined nodes.
423 genEmptyCluster :: Int -> Gen ConfigData
424 genEmptyCluster ncount = do
425 nodes <- vector ncount
426 version <- arbitrary
427 grp <- arbitrary
428 let guuid = uuidOf grp
429 nodes' = zipWith (\n idx ->
430 let newname = takeWhile (/= '.') (nodeName n)
431 ++ "-" ++ show idx
432 in ( UTF8.fromString newname
433 , n { nodeGroup = guuid, nodeName = newname}))
434 nodes [(1::Int)..]
435 nodemap = Map.fromList nodes'
436 contnodes = if Map.size nodemap /= ncount
437 then error ("Inconsistent node map, duplicates in" ++
438 " node name list? Names: " ++
439 show (map fst nodes'))
440 else GenericContainer nodemap
441 continsts = GenericContainer Map.empty
442 networks = GenericContainer Map.empty
443 disks = GenericContainer Map.empty
444 filters = GenericContainer Map.empty
445 let contgroups = GenericContainer $ Map.singleton (UTF8.fromString guuid) grp
446 serial <- arbitrary
447 -- timestamp fields
448 ctime <- arbitrary
449 mtime <- arbitrary
450 cluster <- resize 8 arbitrary
451 let c = ConfigData version cluster contnodes contgroups continsts networks
452 disks filters ctime mtime serial
453 return c
454
455 -- | FIXME: make an even simpler base version of creating a cluster.
456
457 -- | Generates config data with a couple of networks.
458 genConfigDataWithNetworks :: ConfigData -> Gen ConfigData
459 genConfigDataWithNetworks old_cfg = do
460 num_nets <- choose (0, 3)
461 -- generate a list of network names (no duplicates)
462 net_names <- genUniquesList num_nets genName >>= mapM mkNonEmpty
463 -- generate a random list of networks (possibly with duplicate names)
464 nets <- vectorOf num_nets genValidNetwork
465 -- use unique names for the networks
466 let nets_unique = map ( \(name, net) -> net { networkName = name } )
467 (zip net_names nets)
468 net_map = GenericContainer $ Map.fromList
469 (map (\n -> (UTF8.fromString $ uuidOf n, n)) nets_unique)
470 new_cfg = old_cfg { configNetworks = net_map }
471 return new_cfg
472
473 -- * Test properties
474
475 -- | Tests that fillDict behaves correctly
476 prop_fillDict :: [(Int, Int)] -> [(Int, Int)] -> Property
477 prop_fillDict defaults custom =
478 let d_map = Map.fromList defaults
479 d_keys = map fst defaults
480 c_map = Map.fromList custom
481 c_keys = map fst custom
482 in conjoin [ counterexample "Empty custom filling"
483 (fillDict d_map Map.empty [] == d_map)
484 , counterexample "Empty defaults filling"
485 (fillDict Map.empty c_map [] == c_map)
486 , counterexample "Delete all keys"
487 (fillDict d_map c_map (d_keys++c_keys) == Map.empty)
488 ]
489
490 prop_LogicalVolume_serialisation :: LogicalVolume -> Property
491 prop_LogicalVolume_serialisation = testSerialisation
492
493 prop_LogicalVolume_deserialisationFail :: Property
494 prop_LogicalVolume_deserialisationFail =
495 conjoin . map (testDeserialisationFail (LogicalVolume "" "")) $
496 [ J.JSArray []
497 , J.JSString $ J.toJSString "/abc"
498 , J.JSString $ J.toJSString "abc/"
499 , J.JSString $ J.toJSString "../."
500 , J.JSString $ J.toJSString "g/snapshot"
501 , J.JSString $ J.toJSString "g/a_mimagex"
502 , J.JSString $ J.toJSString "g/r;3"
503 ]
504
505 -- | Test that the serialisation of 'DiskLogicalId', which is
506 -- implemented manually, is idempotent. Since we don't have a
507 -- standalone JSON instance for DiskLogicalId (it's a data type that
508 -- expands over two fields in a JSObject), we test this by actially
509 -- testing entire Disk serialisations. So this tests two things at
510 -- once, basically.
511 prop_Disk_serialisation :: Disk -> Property
512 prop_Disk_serialisation = testSerialisation
513
514 prop_Disk_array_serialisation :: Disk -> Property
515 prop_Disk_array_serialisation = testArraySerialisation
516
517 -- | Check that node serialisation is idempotent.
518 prop_Node_serialisation :: Node -> Property
519 prop_Node_serialisation = testSerialisation
520
521 -- | Check that instance serialisation is idempotent.
522 prop_Inst_serialisation :: Instance -> Property
523 prop_Inst_serialisation = testSerialisation
524
525 -- | Check that address pool serialisation is idempotent.
526 prop_AddressPool_serialisation :: AddressPool -> Property
527 prop_AddressPool_serialisation = testSerialisation
528
529 -- | Check that network serialisation is idempotent.
530 prop_Network_serialisation :: Network -> Property
531 prop_Network_serialisation = testSerialisation
532
533 -- | Check that filter action serialisation is idempotent.
534 prop_FilterAction_serialisation :: FilterAction -> Property
535 prop_FilterAction_serialisation = testSerialisation
536
537 -- | Check that filter predicate serialisation is idempotent.
538 prop_FilterPredicate_serialisation :: FilterPredicate -> Property
539 prop_FilterPredicate_serialisation = testSerialisation
540
541 -- | Check config serialisation.
542 prop_Config_serialisation :: Property
543 prop_Config_serialisation =
544 forAll (choose (0, maxNodes `div` 4) >>= genEmptyCluster) testSerialisation
545
546 -- | Custom HUnit test to check the correspondence between Haskell-generated
547 -- networks and their Python decoded, validated and re-encoded version.
548 -- For the technical background of this unit test, check the documentation
549 -- of "case_py_compat_types" of test/hs/Test/Ganeti/Opcodes.hs
550 casePyCompatNetworks :: HUnit.Assertion
551 casePyCompatNetworks = do
552 let num_networks = 500::Int
553 networks <- genSample (vectorOf num_networks genValidNetwork)
554 let networks_with_properties = map getNetworkProperties networks
555 serialized = J.encode networks
556 -- check for non-ASCII fields, usually due to 'arbitrary :: String'
557 mapM_ (\net -> when (any (not . isAscii) (J.encode net)) .
558 HUnit.assertFailure $
559 "Network has non-ASCII fields: " ++ show net
560 ) networks
561 py_stdout <-
562 runPython "from ganeti import network\n\
563 \from ganeti import objects\n\
564 \from ganeti import serializer\n\
565 \import sys\n\
566 \net_data = serializer.Load(sys.stdin.read())\n\
567 \decoded = [objects.Network.FromDict(n) for n in net_data]\n\
568 \encoded = []\n\
569 \for net in decoded:\n\
570 \ a = network.AddressPool(net)\n\
571 \ encoded.append((a.GetFreeCount(), a.GetReservedCount(), \\\n\
572 \ net.ToDict()))\n\
573 \sys.stdout.buffer.write(serializer.Dump(encoded))" serialized
574 >>= checkPythonResult
575 let deserialised = J.decode py_stdout::J.Result [(Int, Int, Network)]
576 decoded <- case deserialised of
577 J.Ok ops -> return ops
578 J.Error msg ->
579 HUnit.assertFailure ("Unable to decode networks: " ++ msg)
580 -- this already raised an expection, but we need it
581 -- for proper types
582 >> fail "Unable to decode networks"
583 HUnit.assertEqual "Mismatch in number of returned networks"
584 (length decoded) (length networks_with_properties)
585 mapM_ (uncurry (HUnit.assertEqual "Different result after encoding/decoding")
586 ) $ zip networks_with_properties decoded
587
588 -- | Creates a tuple of the given network combined with some of its properties
589 -- to be compared against the same properties generated by the python code.
590 getNetworkProperties :: Network -> (Int, Int, Network)
591 getNetworkProperties net =
592 (getFreeCount net, getReservedCount net, net)
593
594 -- | Tests the compatibility between Haskell-serialized node groups and their
595 -- python-decoded and encoded version.
596 casePyCompatNodegroups :: HUnit.Assertion
597 casePyCompatNodegroups = do
598 let num_groups = 500::Int
599 groups <- genSample (vectorOf num_groups genNodeGroup)
600 let serialized = J.encode groups
601 -- check for non-ASCII fields, usually due to 'arbitrary :: String'
602 mapM_ (\group -> when (any (not . isAscii) (J.encode group)) .
603 HUnit.assertFailure $
604 "Node group has non-ASCII fields: " ++ show group
605 ) groups
606 py_stdout <-
607 runPython "from ganeti import objects\n\
608 \from ganeti import serializer\n\
609 \import sys\n\
610 \group_data = serializer.Load(sys.stdin.read())\n\
611 \decoded = [objects.NodeGroup.FromDict(g) for g in group_data]\n\
612 \encoded = [g.ToDict() for g in decoded]\n\
613 \sys.stdout.buffer.write(serializer.Dump(encoded))" serialized
614 >>= checkPythonResult
615 let deserialised = J.decode py_stdout::J.Result [NodeGroup]
616 decoded <- case deserialised of
617 J.Ok ops -> return ops
618 J.Error msg ->
619 HUnit.assertFailure ("Unable to decode node groups: " ++ msg)
620 -- this already raised an expection, but we need it
621 -- for proper types
622 >> fail "Unable to decode node groups"
623 HUnit.assertEqual "Mismatch in number of returned node groups"
624 (length decoded) (length groups)
625 mapM_ (uncurry (HUnit.assertEqual "Different result after encoding/decoding")
626 ) $ zip groups decoded
627
628 -- | Generates a node group with up to 3 networks.
629 -- | FIXME: This generates still somewhat completely random data, without normal
630 -- validation rules.
631 genNodeGroup :: Gen NodeGroup
632 genNodeGroup = do
633 name <- genFQDN
634 members <- pure []
635 ndparams <- arbitrary
636 alloc_policy <- arbitrary
637 ipolicy <- arbitrary
638 diskparams <- pure (GenericContainer Map.empty)
639 num_networks <- choose (0, 3)
640 net_uuid_list <- vectorOf num_networks (arbitrary::Gen BS.ByteString)
641 nic_param_list <- vectorOf num_networks (arbitrary::Gen PartialNicParams)
642 net_map <- pure (GenericContainer . Map.fromList $
643 zip net_uuid_list nic_param_list)
644 hv_state <- arbitrary
645 disk_state <- arbitrary
646 -- timestamp fields
647 ctime <- arbitrary
648 mtime <- arbitrary
649 uuid <- genFQDN `suchThat` (/= name)
650 serial <- arbitrary
651 tags <- arbitrary
652 let group = NodeGroup name members ndparams alloc_policy ipolicy diskparams
653 net_map hv_state disk_state ctime mtime (UTF8.fromString uuid)
654 serial tags
655 return group
656
657 instance Arbitrary NodeGroup where
658 arbitrary = genNodeGroup
659
660 instance Arbitrary Ip4Address where
661 arbitrary = liftM mkIp4Address $ (,,,) <$> choose (0, 255)
662 <*> choose (0, 255)
663 <*> choose (0, 255)
664 <*> choose (0, 255)
665
666 $(genArbitrary ''Ip4Network)
667
668 -- | Tests conversions of ip addresses from/to numbers.
669 prop_ip4AddressAsNum :: Ip4Address -> Property
670 prop_ip4AddressAsNum ip4 =
671 ip4AddressFromNumber (ip4AddressToNumber ip4) ==? ip4
672
673 -- | Tests that the number produced by 'ip4AddressToNumber' has the correct
674 -- order of bytes.
675 prop_ip4AddressToNumber :: Word32 -> Property
676 prop_ip4AddressToNumber w =
677 let byte :: Int -> Word32
678 byte i = (w `div` (256^i)) `mod` 256
679 ipaddr = List.intercalate "." $ map (show . byte) [3,2..0]
680 in ip4AddressToNumber <$> readIp4Address ipaddr
681 ==? (return (toInteger w) :: Either String Integer)
682
683 -- | IsString instance for 'Ip4Address', to help write the tests.
684 instance IsString Ip4Address where
685 fromString s =
686 fromMaybe (error $ "Failed to parse address from " ++ s) (readIp4Address s)
687
688 -- | Tests a few simple cases of IPv4 next address.
689 caseNextIp4Address :: HUnit.Assertion
690 caseNextIp4Address = do
691 HUnit.assertEqual "" "0.0.0.1" $ nextIp4Address "0.0.0.0"
692 HUnit.assertEqual "" "0.0.0.0" $ nextIp4Address "255.255.255.255"
693 HUnit.assertEqual "" "1.2.3.5" $ nextIp4Address "1.2.3.4"
694 HUnit.assertEqual "" "1.3.0.0" $ nextIp4Address "1.2.255.255"
695 HUnit.assertEqual "" "1.2.255.63" $ nextIp4Address "1.2.255.62"
696
697 -- | Tests the compatibility between Haskell-serialized instances and their
698 -- python-decoded and encoded version.
699 -- Note: this can be enhanced with logical validations on the decoded objects
700 casePyCompatInstances :: HUnit.Assertion
701 casePyCompatInstances = do
702 let num_inst = 500::Int
703 instances <- genSample (vectorOf num_inst genInst)
704 let serialized = J.encode instances
705 -- check for non-ASCII fields, usually due to 'arbitrary :: String'
706 mapM_ (\inst -> when (any (not . isAscii) (J.encode inst)) .
707 HUnit.assertFailure $
708 "Instance has non-ASCII fields: " ++ show inst
709 ) instances
710 py_stdout <-
711 runPython "from ganeti import objects\n\
712 \from ganeti import serializer\n\
713 \import sys\n\
714 \inst_data = serializer.Load(sys.stdin.read())\n\
715 \decoded = [objects.Instance.FromDict(i) for i in inst_data]\n\
716 \encoded = [i.ToDict() for i in decoded]\n\
717 \sys.stdout.buffer.write(serializer.Dump(encoded))" serialized
718 >>= checkPythonResult
719 let deserialised = J.decode py_stdout::J.Result [Instance]
720 decoded <- case deserialised of
721 J.Ok ops -> return ops
722 J.Error msg ->
723 HUnit.assertFailure ("Unable to decode instance: " ++ msg)
724 -- this already raised an expection, but we need it
725 -- for proper types
726 >> fail "Unable to decode instances"
727 HUnit.assertEqual "Mismatch in number of returned instances"
728 (length decoded) (length instances)
729 mapM_ (uncurry (HUnit.assertEqual "Different result after encoding/decoding")
730 ) $ zip instances decoded
731
732 -- | A helper function for creating 'LIDPlain' values.
733 mkLIDPlain :: String -> String -> DiskLogicalId
734 mkLIDPlain = (LIDPlain .) . LogicalVolume
735
736 -- | Tests that the logical ID is correctly found in a plain disk
737 caseIncludeLogicalIdPlain :: HUnit.Assertion
738 caseIncludeLogicalIdPlain =
739 let vg_name = "xenvg" :: String
740 lv_name = "1234sdf-qwef-2134-asff-asd2-23145d.data" :: String
741 lv = LogicalVolume vg_name lv_name
742 time = TOD 0 0
743 d = RealDisk $
744 RealDiskData (LIDPlain lv) [] ["node1.example.com"] "diskname"
745 1000 DiskRdWr
746 Nothing Nothing Nothing "asdfgr-1234-5123-daf3-sdfw-134f43"
747 0 time time
748 in
749 HUnit.assertBool "Unable to detect that plain Disk includes logical ID" $
750 includesLogicalId lv d
751
752 -- | Tests that the logical ID is correctly found in a DRBD disk
753 caseIncludeLogicalIdDrbd :: HUnit.Assertion
754 caseIncludeLogicalIdDrbd =
755 let vg_name = "xenvg" :: String
756 lv_name = "1234sdf-qwef-2134-asff-asd2-23145d.data" :: String
757 time = TOD 0 0
758 d = RealDisk $
759 RealDiskData
760 (LIDDrbd8 "node1.example.com" "node2.example.com" 2000 1 5
761 (Private "secret"))
762 [ RealDisk $ RealDiskData (mkLIDPlain "onevg" "onelv") []
763 ["node1.example.com", "node2.example.com"] "disk1" 1000 DiskRdWr
764 Nothing Nothing Nothing "145145-asdf-sdf2-2134-asfd-534g2x"
765 0 time time
766 , RealDisk $ RealDiskData (mkLIDPlain vg_name lv_name) []
767 ["node1.example.com", "node2.example.com"] "disk2" 1000 DiskRdWr
768 Nothing Nothing Nothing "6gd3sd-423f-ag2j-563b-dg34-gj3fse"
769 0 time time
770 ] ["node1.example.com", "node2.example.com"] "diskname" 1000 DiskRdWr
771 Nothing Nothing Nothing
772 "asdfgr-1234-5123-daf3-sdfw-134f43" 0 time time
773 in
774 HUnit.assertBool "Unable to detect that plain Disk includes logical ID" $
775 includesLogicalId (LogicalVolume vg_name lv_name) d
776
777 -- | Tests that the logical ID is correctly NOT found in a plain disk
778 caseNotIncludeLogicalIdPlain :: HUnit.Assertion
779 caseNotIncludeLogicalIdPlain =
780 let vg_name = "xenvg" :: String
781 lv_name = "1234sdf-qwef-2134-asff-asd2-23145d.data" :: String
782 time = TOD 0 0
783 d = RealDisk $
784 RealDiskData (mkLIDPlain "othervg" "otherlv") [] ["node1.example.com"]
785 "diskname" 1000 DiskRdWr Nothing Nothing Nothing
786 "asdfgr-1234-5123-daf3-sdfw-134f43"
787 0 time time
788 in
789 HUnit.assertBool "Unable to detect that plain Disk includes logical ID" $
790 not (includesLogicalId (LogicalVolume vg_name lv_name) d)
791
792 testSuite "Objects"
793 [ 'prop_fillDict
794 , 'prop_LogicalVolume_serialisation
795 , 'prop_LogicalVolume_deserialisationFail
796 , 'prop_Disk_serialisation
797 , 'prop_Disk_array_serialisation
798 , 'prop_Inst_serialisation
799 , 'prop_AddressPool_serialisation
800 , 'prop_Network_serialisation
801 , 'prop_Node_serialisation
802 , 'prop_Config_serialisation
803 , 'prop_FilterAction_serialisation
804 , 'prop_FilterPredicate_serialisation
805 , 'casePyCompatNetworks
806 , 'casePyCompatNodegroups
807 , 'casePyCompatInstances
808 , 'prop_ip4AddressAsNum
809 , 'prop_ip4AddressToNumber
810 , 'caseNextIp4Address
811 , 'caseIncludeLogicalIdPlain
812 , 'caseIncludeLogicalIdDrbd
813 , 'caseNotIncludeLogicalIdPlain
814 ]