OpCodes.hs 24 KB
Newer Older
1
2
3
4
5
6
7
8
9
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}

{-| Unittests for ganeti-htools.

-}

{-

10
Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc.
11
12
13
14
15
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.

-}

module Test.Ganeti.OpCodes
  ( testOpCodes
  , OpCodes.OpCode(..)
  ) where

34
35
import Test.HUnit as HUnit
import Test.QuickCheck as QuickCheck
36
37

import Control.Applicative
38
39
import Control.Monad
import Data.Char
40
import Data.List
41
import qualified Data.Map as Map
42
import qualified Text.JSON as J
43
import Text.Printf (printf)
44
45
46

import Test.Ganeti.TestHelper
import Test.Ganeti.TestCommon
47
import Test.Ganeti.Types ()
48
import Test.Ganeti.Query.Language
49

50
import Ganeti.BasicTypes
51
52
import qualified Ganeti.Constants as C
import qualified Ganeti.OpCodes as OpCodes
53
54
import Ganeti.Types
import Ganeti.OpParams
55
import Ganeti.JSON
56

Iustin Pop's avatar
Iustin Pop committed
57
58
{-# ANN module "HLint: ignore Use camelCase" #-}

59
60
-- * Arbitrary instances

61
instance Arbitrary OpCodes.TagObject where
62
63
64
  arbitrary = oneof [ OpCodes.TagInstance <$> genFQDN
                    , OpCodes.TagNode     <$> genFQDN
                    , OpCodes.TagGroup    <$> genFQDN
65
66
                    , pure OpCodes.TagCluster
                    ]
67

68
$(genArbitrary ''OpCodes.ReplaceDisksMode)
69

70
71
$(genArbitrary ''DiskAccess)

72
73
$(genArbitrary ''InstReasonSrc)

74
75
76
instance Arbitrary OpCodes.DiskIndex where
  arbitrary = choose (0, C.maxDisks - 1) >>= OpCodes.mkDiskIndex

77
instance Arbitrary INicParams where
78
79
  arbitrary = INicParams <$> genMaybe genNameNE <*> genMaybe genName <*>
              genMaybe genNameNE <*> genMaybe genNameNE
80

81
82
instance Arbitrary IDiskParams where
  arbitrary = IDiskParams <$> arbitrary <*> arbitrary <*>
83
84
              genMaybe genNameNE <*> genMaybe genNameNE <*>
              genMaybe genNameNE
85

86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
instance Arbitrary RecreateDisksInfo where
  arbitrary = oneof [ pure RecreateDisksAll
                    , RecreateDisksIndices <$> arbitrary
                    , RecreateDisksParams <$> arbitrary
                    ]

instance Arbitrary DdmOldChanges where
  arbitrary = oneof [ DdmOldIndex <$> arbitrary
                    , DdmOldMod   <$> arbitrary
                    ]

instance (Arbitrary a) => Arbitrary (SetParamsMods a) where
  arbitrary = oneof [ pure SetParamsEmpty
                    , SetParamsDeprecated <$> arbitrary
                    , SetParamsNew        <$> arbitrary
                    ]

Iustin Pop's avatar
Iustin Pop committed
103
104
105
106
107
instance Arbitrary ExportTarget where
  arbitrary = oneof [ ExportTargetLocal <$> genNodeNameNE
                    , ExportTargetRemote <$> pure []
                    ]

108
109
110
111
112
instance Arbitrary OpCodes.OpCode where
  arbitrary = do
    op_id <- elements OpCodes.allOpIDs
    case op_id of
      "OP_TEST_DELAY" ->
113
114
        OpCodes.OpTestDelay <$> arbitrary <*> arbitrary <*>
          genNodeNamesNE <*> arbitrary
115
      "OP_INSTANCE_REPLACE_DISKS" ->
116
117
118
        OpCodes.OpInstanceReplaceDisks <$> genFQDN <*> arbitrary <*>
          arbitrary <*> arbitrary <*> genDiskIndices <*>
          genMaybe genNodeNameNE <*> genMaybe genNameNE
119
      "OP_INSTANCE_FAILOVER" ->
120
121
        OpCodes.OpInstanceFailover <$> genFQDN <*> arbitrary <*> arbitrary <*>
          genMaybe genNodeNameNE <*> arbitrary <*> genMaybe genNameNE
122
      "OP_INSTANCE_MIGRATE" ->
123
124
125
        OpCodes.OpInstanceMigrate <$> genFQDN <*> arbitrary <*> arbitrary <*>
          genMaybe genNodeNameNE <*> arbitrary <*>
          arbitrary <*> arbitrary <*> genMaybe genNameNE <*> arbitrary
126
127
128
129
      "OP_TAGS_GET" ->
        OpCodes.OpTagsGet <$> arbitrary <*> arbitrary
      "OP_TAGS_SEARCH" ->
        OpCodes.OpTagsSearch <$> genNameNE
130
      "OP_TAGS_SET" ->
131
        OpCodes.OpTagsSet <$> arbitrary <*> genTags
132
      "OP_TAGS_DEL" ->
133
        OpCodes.OpTagsSet <$> arbitrary <*> genTags
134
135
136
137
138
      "OP_CLUSTER_POST_INIT" -> pure OpCodes.OpClusterPostInit
      "OP_CLUSTER_DESTROY" -> pure OpCodes.OpClusterDestroy
      "OP_CLUSTER_QUERY" -> pure OpCodes.OpClusterQuery
      "OP_CLUSTER_VERIFY" ->
        OpCodes.OpClusterVerify <$> arbitrary <*> arbitrary <*>
139
          genSet Nothing <*> genSet Nothing <*> arbitrary <*>
140
          genMaybe genNameNE
141
142
143
144
      "OP_CLUSTER_VERIFY_CONFIG" ->
        OpCodes.OpClusterVerifyConfig <$> arbitrary <*> arbitrary <*>
          genSet Nothing <*> arbitrary
      "OP_CLUSTER_VERIFY_GROUP" ->
145
        OpCodes.OpClusterVerifyGroup <$> genNameNE <*> arbitrary <*>
146
147
148
          arbitrary <*> genSet Nothing <*> genSet Nothing <*> arbitrary
      "OP_CLUSTER_VERIFY_DISKS" -> pure OpCodes.OpClusterVerifyDisks
      "OP_GROUP_VERIFY_DISKS" ->
149
        OpCodes.OpGroupVerifyDisks <$> genNameNE
150
      "OP_CLUSTER_REPAIR_DISK_SIZES" ->
151
        OpCodes.OpClusterRepairDiskSizes <$> genNodeNamesNE
152
      "OP_CLUSTER_CONFIG_QUERY" ->
153
        OpCodes.OpClusterConfigQuery <$> genFieldsNE
154
      "OP_CLUSTER_RENAME" ->
155
        OpCodes.OpClusterRename <$> genNameNE
156
157
      "OP_CLUSTER_SET_PARAMS" ->
        OpCodes.OpClusterSetParams <$> emptyMUD <*> emptyMUD <*>
158
159
160
161
          arbitrary <*> genMaybe (listOf1 arbitrary >>= mkNonEmpty) <*>
          genMaybe genEmptyContainer <*> emptyMUD <*>
          genMaybe genEmptyContainer <*> genMaybe genEmptyContainer <*>
          genMaybe genEmptyContainer <*> genMaybe arbitrary <*>
162
163
164
          arbitrary <*> arbitrary <*> arbitrary <*>
          arbitrary <*> arbitrary <*> arbitrary <*>
          emptyMUD <*> emptyMUD <*> arbitrary <*>
165
          arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*>
166
          arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
167
168
169
170
171
172
173
174
175
176
177
178
      "OP_CLUSTER_REDIST_CONF" -> pure OpCodes.OpClusterRedistConf
      "OP_CLUSTER_ACTIVATE_MASTER_IP" ->
        pure OpCodes.OpClusterActivateMasterIp
      "OP_CLUSTER_DEACTIVATE_MASTER_IP" ->
        pure OpCodes.OpClusterDeactivateMasterIp
      "OP_QUERY" ->
        OpCodes.OpQuery <$> arbitrary <*> arbitrary <*> arbitrary <*> genFilter
      "OP_QUERY_FIELDS" ->
        OpCodes.OpQueryFields <$> arbitrary <*> arbitrary
      "OP_OOB_COMMAND" ->
        OpCodes.OpOobCommand <$> genNodeNamesNE <*> arbitrary <*>
          arbitrary <*> arbitrary <*> (arbitrary `suchThat` (>0))
179
      "OP_NODE_REMOVE" -> OpCodes.OpNodeRemove <$> genNodeNameNE
180
      "OP_NODE_ADD" ->
181
        OpCodes.OpNodeAdd <$> genNodeNameNE <*> emptyMUD <*> emptyMUD <*>
182
183
          genMaybe genName <*> genMaybe genNameNE <*> arbitrary <*>
          genMaybe genNameNE <*> arbitrary <*> arbitrary <*> emptyMUD
184
      "OP_NODE_QUERY" ->
185
        OpCodes.OpNodeQuery <$> genFieldsNE <*> genNamesNE <*> arbitrary
186
187
188
189
      "OP_NODE_QUERYVOLS" ->
        OpCodes.OpNodeQueryvols <$> arbitrary <*> genNodeNamesNE
      "OP_NODE_QUERY_STORAGE" ->
        OpCodes.OpNodeQueryStorage <$> arbitrary <*> arbitrary <*>
190
          genNodeNamesNE <*> genNameNE
191
192
      "OP_NODE_MODIFY_STORAGE" ->
        OpCodes.OpNodeModifyStorage <$> genNodeNameNE <*> arbitrary <*>
193
          genNameNE <*> pure emptyJSObject
194
195
      "OP_REPAIR_NODE_STORAGE" ->
        OpCodes.OpRepairNodeStorage <$> genNodeNameNE <*> arbitrary <*>
196
          genNameNE <*> arbitrary
197
198
199
      "OP_NODE_SET_PARAMS" ->
        OpCodes.OpNodeSetParams <$> genNodeNameNE <*> arbitrary <*>
          emptyMUD <*> emptyMUD <*> arbitrary <*> arbitrary <*> arbitrary <*>
200
          arbitrary <*> arbitrary <*> arbitrary <*> genMaybe genNameNE <*>
201
          emptyMUD <*> arbitrary
202
203
204
205
      "OP_NODE_POWERCYCLE" ->
        OpCodes.OpNodePowercycle <$> genNodeNameNE <*> arbitrary
      "OP_NODE_MIGRATE" ->
        OpCodes.OpNodeMigrate <$> genNodeNameNE <*> arbitrary <*>
206
207
          arbitrary <*> genMaybe genNodeNameNE <*> arbitrary <*>
          arbitrary <*> genMaybe genNameNE
208
209
      "OP_NODE_EVACUATE" ->
        OpCodes.OpNodeEvacuate <$> arbitrary <*> genNodeNameNE <*>
210
          genMaybe genNodeNameNE <*> genMaybe genNameNE <*> arbitrary
211
      "OP_INSTANCE_CREATE" ->
212
        OpCodes.OpInstanceCreate <$> genFQDN <*> arbitrary <*>
213
          arbitrary <*> arbitrary <*> arbitrary <*> pure emptyJSObject <*>
214
215
          arbitrary <*> arbitrary <*> arbitrary <*> genMaybe genNameNE <*>
          pure emptyJSObject <*> arbitrary <*> genMaybe genNameNE <*>
216
217
          arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*>
          arbitrary <*> arbitrary <*> pure emptyJSObject <*>
218
219
220
221
222
          genMaybe genNameNE <*>
          genMaybe genNodeNameNE <*> genMaybe genNodeNameNE <*>
          genMaybe (pure []) <*> genMaybe genNodeNameNE <*>
          arbitrary <*> genMaybe genNodeNameNE <*>
          genMaybe genNodeNameNE <*> genMaybe genNameNE <*>
223
          arbitrary <*> arbitrary <*> (genTags >>= mapM mkNonEmpty)
224
      "OP_INSTANCE_MULTI_ALLOC" ->
225
226
        OpCodes.OpInstanceMultiAlloc <$> genMaybe genNameNE <*> pure [] <*>
          arbitrary
227
      "OP_INSTANCE_REINSTALL" ->
228
229
        OpCodes.OpInstanceReinstall <$> genFQDN <*> arbitrary <*>
          genMaybe genNameNE <*> genMaybe (pure emptyJSObject)
230
      "OP_INSTANCE_REMOVE" ->
231
        OpCodes.OpInstanceRemove <$> genFQDN <*> arbitrary <*> arbitrary
232
      "OP_INSTANCE_RENAME" ->
233
        OpCodes.OpInstanceRename <$> genFQDN <*> genNodeNameNE <*>
234
235
          arbitrary <*> arbitrary
      "OP_INSTANCE_STARTUP" ->
236
        OpCodes.OpInstanceStartup <$> genFQDN <*> arbitrary <*> arbitrary <*>
237
238
239
          pure emptyJSObject <*> pure emptyJSObject <*>
          arbitrary <*> arbitrary
      "OP_INSTANCE_SHUTDOWN" ->
240
        OpCodes.OpInstanceShutdown <$> genFQDN <*> arbitrary <*> arbitrary <*>
241
242
          arbitrary <*> arbitrary
      "OP_INSTANCE_REBOOT" ->
243
        OpCodes.OpInstanceReboot <$> genFQDN <*> arbitrary <*>
244
          arbitrary <*> arbitrary <*> ((,) <$> arbitrary <*> genStringNE)
245
      "OP_INSTANCE_MOVE" ->
246
        OpCodes.OpInstanceMove <$> genFQDN <*> arbitrary <*> arbitrary <*>
247
          genNodeNameNE <*> arbitrary
248
      "OP_INSTANCE_CONSOLE" -> OpCodes.OpInstanceConsole <$> genFQDN
249
      "OP_INSTANCE_ACTIVATE_DISKS" ->
250
        OpCodes.OpInstanceActivateDisks <$> genFQDN <*>
251
252
          arbitrary <*> arbitrary
      "OP_INSTANCE_DEACTIVATE_DISKS" ->
253
        OpCodes.OpInstanceDeactivateDisks <$> genFQDN <*> arbitrary
254
      "OP_INSTANCE_RECREATE_DISKS" ->
255
256
        OpCodes.OpInstanceRecreateDisks <$> genFQDN <*> arbitrary <*>
          genNodeNamesNE <*> genMaybe genNameNE
Iustin Pop's avatar
Iustin Pop committed
257
258
      "OP_INSTANCE_QUERY" ->
        OpCodes.OpInstanceQuery <$> genFieldsNE <*> genNamesNE <*> arbitrary
259
260
261
262
      "OP_INSTANCE_QUERY_DATA" ->
        OpCodes.OpInstanceQueryData <$> arbitrary <*>
          genNodeNamesNE <*> arbitrary
      "OP_INSTANCE_SET_PARAMS" ->
263
        OpCodes.OpInstanceSetParams <$> genFQDN <*> arbitrary <*>
264
265
          arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*>
          pure emptyJSObject <*> arbitrary <*> pure emptyJSObject <*>
266
267
268
          arbitrary <*> genMaybe genNodeNameNE <*> genMaybe genNodeNameNE <*>
          genMaybe genNameNE <*> pure emptyJSObject <*> arbitrary <*>
          arbitrary <*> arbitrary
269
      "OP_INSTANCE_GROW_DISK" ->
270
        OpCodes.OpInstanceGrowDisk <$> genFQDN <*> arbitrary <*>
271
272
          arbitrary <*> arbitrary <*> arbitrary
      "OP_INSTANCE_CHANGE_GROUP" ->
273
274
        OpCodes.OpInstanceChangeGroup <$> genFQDN <*> arbitrary <*>
          genMaybe genNameNE <*> genMaybe (resize maxNodes (listOf genNameNE))
Iustin Pop's avatar
Iustin Pop committed
275
276
      "OP_GROUP_ADD" ->
        OpCodes.OpGroupAdd <$> genNameNE <*> arbitrary <*>
277
          emptyMUD <*> genMaybe genEmptyContainer <*>
Iustin Pop's avatar
Iustin Pop committed
278
279
280
281
282
283
284
285
          emptyMUD <*> emptyMUD <*> emptyMUD
      "OP_GROUP_ASSIGN_NODES" ->
        OpCodes.OpGroupAssignNodes <$> genNameNE <*> arbitrary <*>
          genNodeNamesNE
      "OP_GROUP_QUERY" ->
        OpCodes.OpGroupQuery <$> genFieldsNE <*> genNamesNE
      "OP_GROUP_SET_PARAMS" ->
        OpCodes.OpGroupSetParams <$> genNameNE <*> arbitrary <*>
286
          emptyMUD <*> genMaybe genEmptyContainer <*>
Iustin Pop's avatar
Iustin Pop committed
287
288
289
290
291
292
293
          emptyMUD <*> emptyMUD <*> emptyMUD
      "OP_GROUP_REMOVE" ->
        OpCodes.OpGroupRemove <$> genNameNE
      "OP_GROUP_RENAME" ->
        OpCodes.OpGroupRename <$> genNameNE <*> genNameNE
      "OP_GROUP_EVACUATE" ->
        OpCodes.OpGroupEvacuate <$> genNameNE <*> arbitrary <*>
294
          genMaybe genNameNE <*> genMaybe genNamesNE
Iustin Pop's avatar
Iustin Pop committed
295
296
      "OP_OS_DIAGNOSE" ->
        OpCodes.OpOsDiagnose <$> genFieldsNE <*> genNamesNE
297
298
      "OP_EXT_STORAGE_DIAGNOSE" ->
        OpCodes.OpOsDiagnose <$> genFieldsNE <*> genNamesNE
Iustin Pop's avatar
Iustin Pop committed
299
300
301
      "OP_BACKUP_QUERY" ->
        OpCodes.OpBackupQuery <$> arbitrary <*> genNodeNamesNE
      "OP_BACKUP_PREPARE" ->
302
        OpCodes.OpBackupPrepare <$> genFQDN <*> arbitrary
Iustin Pop's avatar
Iustin Pop committed
303
      "OP_BACKUP_EXPORT" ->
304
        OpCodes.OpBackupExport <$> genFQDN <*> arbitrary <*>
Iustin Pop's avatar
Iustin Pop committed
305
          arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*>
306
          arbitrary <*> genMaybe (pure []) <*> genMaybe genNameNE
Iustin Pop's avatar
Iustin Pop committed
307
      "OP_BACKUP_REMOVE" ->
308
        OpCodes.OpBackupRemove <$> genFQDN
Iustin Pop's avatar
Iustin Pop committed
309
310
311
      "OP_TEST_ALLOCATOR" ->
        OpCodes.OpTestAllocator <$> arbitrary <*> arbitrary <*>
          genNameNE <*> pure [] <*> pure [] <*>
312
          arbitrary <*> genMaybe genNameNE <*>
Iustin Pop's avatar
Iustin Pop committed
313
          (genTags >>= mapM mkNonEmpty) <*>
314
315
316
          arbitrary <*> arbitrary <*> genMaybe genNameNE <*>
          arbitrary <*> genMaybe genNodeNamesNE <*> arbitrary <*>
          genMaybe genNamesNE <*> arbitrary <*> arbitrary
Iustin Pop's avatar
Iustin Pop committed
317
318
      "OP_TEST_JQUEUE" ->
        OpCodes.OpTestJqueue <$> arbitrary <*> arbitrary <*>
319
          resize 20 (listOf genFQDN) <*> arbitrary
Iustin Pop's avatar
Iustin Pop committed
320
321
322
      "OP_TEST_DUMMY" ->
        OpCodes.OpTestDummy <$> pure J.JSNull <*> pure J.JSNull <*>
          pure J.JSNull <*> pure J.JSNull
323
      "OP_NETWORK_ADD" ->
324
        OpCodes.OpNetworkAdd <$> genNameNE <*> genIp4Net <*>
325
326
          genMaybe genIp4Addr <*> pure Nothing <*> pure Nothing <*>
          genMaybe genMacPrefix <*> genMaybe (listOf genIp4Addr) <*>
Iustin Pop's avatar
Iustin Pop committed
327
          arbitrary <*> (genTags >>= mapM mkNonEmpty)
328
329
330
      "OP_NETWORK_REMOVE" ->
        OpCodes.OpNetworkRemove <$> genNameNE <*> arbitrary
      "OP_NETWORK_SET_PARAMS" ->
331
        OpCodes.OpNetworkSetParams <$> genNameNE <*>
332
333
334
          genMaybe genIp4Addr <*> pure Nothing <*> pure Nothing <*>
          genMaybe genMacPrefix <*> genMaybe (listOf genIp4Addr) <*>
          genMaybe (listOf genIp4Addr)
335
336
337
338
      "OP_NETWORK_CONNECT" ->
        OpCodes.OpNetworkConnect <$> genNameNE <*> genNameNE <*>
          arbitrary <*> genNameNE <*> arbitrary
      "OP_NETWORK_DISCONNECT" ->
339
        OpCodes.OpNetworkDisconnect <$> genNameNE <*> genNameNE
340
      "OP_NETWORK_QUERY" ->
341
        OpCodes.OpNetworkQuery <$> genFieldsNE <*> genNamesNE <*> arbitrary
Iustin Pop's avatar
Iustin Pop committed
342
343
344
      "OP_RESTRICTED_COMMAND" ->
        OpCodes.OpRestrictedCommand <$> arbitrary <*> genNodeNamesNE <*>
          genNameNE
345
      _ -> fail $ "Undefined arbitrary for opcode " ++ op_id
346

347
348
349
350
instance Arbitrary OpCodes.CommonOpParams where
  arbitrary = OpCodes.CommonOpParams <$> arbitrary <*> arbitrary <*>
                arbitrary <*> resize 5 arbitrary <*> genMaybe genName

351
352
-- * Helper functions

353
354
355
356
357
358
-- | Empty JSObject.
emptyJSObject :: J.JSObject J.JSValue
emptyJSObject = J.toJSObject []

-- | Empty maybe unchecked dictionary.
emptyMUD :: Gen (Maybe (J.JSObject J.JSValue))
359
emptyMUD = genMaybe $ pure emptyJSObject
360
361
362
363
364

-- | Generates an empty container.
genEmptyContainer :: (Ord a) => Gen (GenericContainer a b)
genEmptyContainer = pure . GenericContainer $ Map.fromList []

365
366
367
368
-- | Generates list of disk indices.
genDiskIndices :: Gen [DiskIndex]
genDiskIndices = do
  cnt <- choose (0, C.maxDisks)
369
  genUniquesList cnt arbitrary
370
371
372

-- | Generates a list of node names.
genNodeNames :: Gen [String]
373
genNodeNames = resize maxNodes (listOf genFQDN)
374

375
376
-- | Generates a list of node names in non-empty string type.
genNodeNamesNE :: Gen [NonEmptyString]
Iustin Pop's avatar
Iustin Pop committed
377
genNodeNamesNE = genNodeNames >>= mapM mkNonEmpty
378

379
380
-- | Gets a node name in non-empty type.
genNodeNameNE :: Gen NonEmptyString
381
genNodeNameNE = genFQDN >>= mkNonEmpty
382

383
384
-- | Gets a name (non-fqdn) in non-empty type.
genNameNE :: Gen NonEmptyString
385
genNameNE = genName >>= mkNonEmpty
386

Iustin Pop's avatar
Iustin Pop committed
387
388
389
390
-- | Gets a list of names (non-fqdn) in non-empty type.
genNamesNE :: Gen [NonEmptyString]
genNamesNE = resize maxNodes (listOf genNameNE)

391
392
-- | Returns a list of non-empty fields.
genFieldsNE :: Gen [NonEmptyString]
393
genFieldsNE = genFields >>= mapM mkNonEmpty
394

395
396
397
398
399
400
-- | Generate a 3-byte MAC prefix.
genMacPrefix :: Gen NonEmptyString
genMacPrefix = do
  octets <- vectorOf 3 $ choose (0::Int, 255)
  mkNonEmpty . intercalate ":" $ map (printf "%02x") octets

401
402
403
404
-- | Generate a non empty string
genStringNE :: Gen NonEmptyString
genStringNE = genName >>= mkNonEmpty

405
406
407
-- | Arbitrary instance for MetaOpCode, defined here due to TH ordering.
$(genArbitrary ''OpCodes.MetaOpCode)

408
409
410
411
412
-- | Small helper to check for a failed JSON deserialisation
isJsonError :: J.Result a -> Bool
isJsonError (J.Error _) = True
isJsonError _           = False

413
414
415
-- * Test cases

-- | Check that opcode serialization is idempotent.
416
prop_serialization :: OpCodes.OpCode -> Property
417
prop_serialization = testSerialisation
418
419

-- | Check that Python and Haskell defined the same opcode list.
420
421
case_AllDefined :: HUnit.Assertion
case_AllDefined = do
422
423
424
  let py_ops = sort C.opcodesOpIds
      hs_ops = sort OpCodes.allOpIDs
      extra_py = py_ops \\ hs_ops
425
      extra_hs = hs_ops \\ py_ops
426
427
  HUnit.assertBool ("Missing OpCodes from the Haskell code:\n" ++
                    unlines extra_py) (null extra_py)
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
  HUnit.assertBool ("Extra OpCodes in the Haskell code code:\n" ++
                    unlines extra_hs) (null extra_hs)

-- | Custom HUnit test case that forks a Python process and checks
-- correspondence between Haskell-generated OpCodes and their Python
-- decoded, validated and re-encoded version.
--
-- Note that we have a strange beast here: since launching Python is
-- expensive, we don't do this via a usual QuickProperty, since that's
-- slow (I've tested it, and it's indeed quite slow). Rather, we use a
-- single HUnit assertion, and in it we manually use QuickCheck to
-- generate 500 opcodes times the number of defined opcodes, which
-- then we pass in bulk to Python. The drawbacks to this method are
-- two fold: we cannot control the number of generated opcodes, since
-- HUnit assertions don't get access to the test options, and for the
-- same reason we can't run a repeatable seed. We should probably find
-- a better way to do this, for example by having a
-- separately-launched Python process (if not running the tests would
-- be skipped).
447
448
case_py_compat_types :: HUnit.Assertion
case_py_compat_types = do
449
  let num_opcodes = length OpCodes.allOpIDs * 100
450
451
452
  opcodes <- genSample (vectorOf num_opcodes
                                   (arbitrary::Gen OpCodes.MetaOpCode))
  let with_sum = map (\o -> (OpCodes.opSummary $
Iustin Pop's avatar
Iustin Pop committed
453
                             OpCodes.metaOpCode o, o)) opcodes
454
      serialized = J.encode opcodes
455
456
457
458
459
  -- check for non-ASCII fields, usually due to 'arbitrary :: String'
  mapM_ (\op -> when (any (not . isAscii) (J.encode op)) .
                HUnit.assertFailure $
                  "OpCode has non-ASCII fields: " ++ show op
        ) opcodes
460
461
462
463
464
465
466
467
  py_stdout <-
     runPython "from ganeti import opcodes\n\
               \import sys\n\
               \from ganeti import serializer\n\
               \op_data = serializer.Load(sys.stdin.read())\n\
               \decoded = [opcodes.OpCode.LoadOpCode(o) for o in op_data]\n\
               \for op in decoded:\n\
               \  op.Validate(True)\n\
Iustin Pop's avatar
Iustin Pop committed
468
469
               \encoded = [(op.Summary(), op.__getstate__())\n\
               \           for op in decoded]\n\
470
471
               \print serializer.Dump(encoded)" serialized
     >>= checkPythonResult
Iustin Pop's avatar
Iustin Pop committed
472
473
  let deserialised =
        J.decode py_stdout::J.Result [(String, OpCodes.MetaOpCode)]
474
475
476
477
478
479
480
481
  decoded <- case deserialised of
               J.Ok ops -> return ops
               J.Error msg ->
                 HUnit.assertFailure ("Unable to decode opcodes: " ++ msg)
                 -- this already raised an expection, but we need it
                 -- for proper types
                 >> fail "Unable to decode opcodes"
  HUnit.assertEqual "Mismatch in number of returned opcodes"
Iustin Pop's avatar
Iustin Pop committed
482
    (length decoded) (length with_sum)
483
  mapM_ (uncurry (HUnit.assertEqual "Different result after encoding/decoding")
Iustin Pop's avatar
Iustin Pop committed
484
        ) $ zip decoded with_sum
485

486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
-- | Custom HUnit test case that forks a Python process and checks
-- correspondence between Haskell OpCodes fields and their Python
-- equivalent.
case_py_compat_fields :: HUnit.Assertion
case_py_compat_fields = do
  let hs_fields = sort $ map (\op_id -> (op_id, OpCodes.allOpFields op_id))
                         OpCodes.allOpIDs
  py_stdout <-
     runPython "from ganeti import opcodes\n\
               \import sys\n\
               \from ganeti import serializer\n\
               \fields = [(k, sorted([p[0] for p in v.OP_PARAMS]))\n\
               \           for k, v in opcodes.OP_MAPPING.items()]\n\
               \print serializer.Dump(fields)" ""
     >>= checkPythonResult
  let deserialised = J.decode py_stdout::J.Result [(String, [String])]
  py_fields <- case deserialised of
                 J.Ok v -> return $ sort v
                 J.Error msg ->
                   HUnit.assertFailure ("Unable to decode op fields: " ++ msg)
                   -- this already raised an expection, but we need it
                   -- for proper types
                   >> fail "Unable to decode op fields"
  HUnit.assertEqual "Mismatch in number of returned opcodes"
    (length hs_fields) (length py_fields)
  HUnit.assertEqual "Mismatch in defined OP_IDs"
    (map fst hs_fields) (map fst py_fields)
  mapM_ (\((py_id, py_flds), (hs_id, hs_flds)) -> do
           HUnit.assertEqual "Mismatch in OP_ID" py_id hs_id
           HUnit.assertEqual ("Mismatch in fields for " ++ hs_id)
             py_flds hs_flds
        ) $ zip py_fields hs_fields

519
520
521
522
523
524
-- | Checks that setOpComment works correctly.
prop_setOpComment :: OpCodes.MetaOpCode -> String -> Property
prop_setOpComment op comment =
  let (OpCodes.MetaOpCode common _) = OpCodes.setOpComment comment op
  in OpCodes.opComment common ==? Just comment

525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
-- | Tests wrong tag object building (cluster takes only jsnull, the
-- other take a string, so we test the opposites).
case_TagObject_fail :: Assertion
case_TagObject_fail =
  mapM_ (\(t, j) -> assertEqual (show t ++ "/" ++ J.encode j) Nothing $
                    tagObjectFrom t j)
    [ (TagTypeCluster,  J.showJSON "abc")
    , (TagTypeInstance, J.JSNull)
    , (TagTypeNode,     J.JSNull)
    , (TagTypeGroup,    J.JSNull)
    ]

-- | Tests wrong (negative) disk index.
prop_mkDiskIndex_fail :: QuickCheck.Positive Int -> Property
prop_mkDiskIndex_fail (Positive i) =
  case mkDiskIndex (negate i) of
    Bad msg -> printTestCase "error message " $
               "Invalid value" `isPrefixOf` msg
    Ok v -> failTest $ "Succeeded to build disk index '" ++ show v ++
                       "' from negative value " ++ show (negate i)

-- | Tests a few invalid 'readRecreateDisks' cases.
case_readRecreateDisks_fail :: Assertion
case_readRecreateDisks_fail = do
  assertBool "null" $
    isJsonError (J.readJSON J.JSNull::J.Result RecreateDisksInfo)
  assertBool "string" $
    isJsonError (J.readJSON (J.showJSON "abc")::J.Result RecreateDisksInfo)

-- | Tests a few invalid 'readDdmOldChanges' cases.
case_readDdmOldChanges_fail :: Assertion
case_readDdmOldChanges_fail = do
  assertBool "null" $
    isJsonError (J.readJSON J.JSNull::J.Result DdmOldChanges)
  assertBool "string" $
    isJsonError (J.readJSON (J.showJSON "abc")::J.Result DdmOldChanges)

-- | Tests a few invalid 'readExportTarget' cases.
case_readExportTarget_fail :: Assertion
case_readExportTarget_fail = do
  assertBool "null" $
    isJsonError (J.readJSON J.JSNull::J.Result ExportTarget)
  assertBool "int" $
    isJsonError (J.readJSON (J.showJSON (5::Int))::J.Result ExportTarget)

570
testSuite "OpCodes"
571
572
            [ 'prop_serialization
            , 'case_AllDefined
573
574
            , 'case_py_compat_types
            , 'case_py_compat_fields
575
            , 'prop_setOpComment
576
577
578
579
580
            , 'case_TagObject_fail
            , 'prop_mkDiskIndex_fail
            , 'case_readRecreateDisks_fail
            , 'case_readDdmOldChanges_fail
            , 'case_readExportTarget_fail
581
            ]