Statistics
| Branch: | Tag: | Revision:

root / test / hs / Test / Ganeti / Utils.hs @ 72747d91

History | View | Annotate | Download (12.2 kB)

1
{-# LANGUAGE TemplateHaskell, CPP #-}
2
{-# OPTIONS_GHC -fno-warn-orphans #-}
3

    
4
{-| Unittests for ganeti-htools.
5

    
6
-}
7

    
8
{-
9

    
10
Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc.
11

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

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

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

    
27
-}
28

    
29
module Test.Ganeti.Utils (testUtils) where
30

    
31
import Test.QuickCheck hiding (Result)
32
import Test.HUnit
33

    
34
import Data.Char (isSpace)
35
import Data.List
36
import System.Time
37
import qualified Text.JSON as J
38
#ifndef NO_REGEX_PCRE
39
import Text.Regex.PCRE
40
#endif
41

    
42
import Test.Ganeti.TestHelper
43
import Test.Ganeti.TestCommon
44

    
45
import Ganeti.BasicTypes
46
import qualified Ganeti.Constants as C
47
import qualified Ganeti.JSON as JSON
48
import Ganeti.Utils
49

    
50
-- | Helper to generate a small string that doesn't contain commas.
51
genNonCommaString :: Gen String
52
genNonCommaString = do
53
  size <- choose (0, 20) -- arbitrary max size
54
  vectorOf size (arbitrary `suchThat` (/=) ',')
55

    
56
-- | If the list is not just an empty element, and if the elements do
57
-- not contain commas, then join+split should be idempotent.
58
prop_commaJoinSplit :: Property
59
prop_commaJoinSplit =
60
  forAll (choose (0, 20)) $ \llen ->
61
  forAll (vectorOf llen genNonCommaString `suchThat` (/=) [""]) $ \lst ->
62
  sepSplit ',' (commaJoin lst) ==? lst
63

    
64
-- | Split and join should always be idempotent.
65
prop_commaSplitJoin :: String -> Property
66
prop_commaSplitJoin s =
67
  commaJoin (sepSplit ',' s) ==? s
68

    
69
-- | fromObjWithDefault, we test using the Maybe monad and an integer
70
-- value.
71
prop_fromObjWithDefault :: Integer -> String -> Bool
72
prop_fromObjWithDefault def_value random_key =
73
  -- a missing key will be returned with the default
74
  JSON.fromObjWithDefault [] random_key def_value == Just def_value &&
75
  -- a found key will be returned as is, not with default
76
  JSON.fromObjWithDefault [(random_key, J.showJSON def_value)]
77
       random_key (def_value+1) == Just def_value
78

    
79
-- | Test that functional if' behaves like the syntactic sugar if.
80
prop_if'if :: Bool -> Int -> Int -> Gen Prop
81
prop_if'if cnd a b =
82
  if' cnd a b ==? if cnd then a else b
83

    
84
-- | Test basic select functionality
85
prop_select :: Int      -- ^ Default result
86
            -> [Int]    -- ^ List of False values
87
            -> [Int]    -- ^ List of True values
88
            -> Gen Prop -- ^ Test result
89
prop_select def lst1 lst2 =
90
  select def (flist ++ tlist) ==? expectedresult
91
    where expectedresult = defaultHead def lst2
92
          flist = zip (repeat False) lst1
93
          tlist = zip (repeat True)  lst2
94

    
95
{-# ANN prop_select_undefd "HLint: ignore Use alternative" #-}
96
-- | Test basic select functionality with undefined default
97
prop_select_undefd :: [Int]            -- ^ List of False values
98
                   -> NonEmptyList Int -- ^ List of True values
99
                   -> Gen Prop         -- ^ Test result
100
prop_select_undefd lst1 (NonEmpty lst2) =
101
  -- head is fine as NonEmpty "guarantees" a non-empty list, but not
102
  -- via types
103
  select undefined (flist ++ tlist) ==? head lst2
104
    where flist = zip (repeat False) lst1
105
          tlist = zip (repeat True)  lst2
106

    
107
{-# ANN prop_select_undefv "HLint: ignore Use alternative" #-}
108
-- | Test basic select functionality with undefined list values
109
prop_select_undefv :: [Int]            -- ^ List of False values
110
                   -> NonEmptyList Int -- ^ List of True values
111
                   -> Gen Prop         -- ^ Test result
112
prop_select_undefv lst1 (NonEmpty lst2) =
113
  -- head is fine as NonEmpty "guarantees" a non-empty list, but not
114
  -- via types
115
  select undefined cndlist ==? head lst2
116
    where flist = zip (repeat False) lst1
117
          tlist = zip (repeat True)  lst2
118
          cndlist = flist ++ tlist ++ [undefined]
119

    
120
prop_parseUnit :: NonNegative Int -> Property
121
prop_parseUnit (NonNegative n) =
122
  conjoin
123
  [ parseUnit (show n) ==? (Ok n::Result Int)
124
  , parseUnit (show n ++ "m") ==? (Ok n::Result Int)
125
  , parseUnit (show n ++ "M") ==? (Ok (truncate n_mb)::Result Int)
126
  , parseUnit (show n ++ "g") ==? (Ok (n*1024)::Result Int)
127
  , parseUnit (show n ++ "G") ==? (Ok (truncate n_gb)::Result Int)
128
  , parseUnit (show n ++ "t") ==? (Ok (n*1048576)::Result Int)
129
  , parseUnit (show n ++ "T") ==? (Ok (truncate n_tb)::Result Int)
130
  , printTestCase "Internal error/overflow?"
131
    (n_mb >=0 && n_gb >= 0 && n_tb >= 0)
132
  , property (isBad (parseUnit (show n ++ "x")::Result Int))
133
  ]
134
  where n_mb = (fromIntegral n::Rational) * 1000 * 1000 / 1024 / 1024
135
        n_gb = n_mb * 1000
136
        n_tb = n_gb * 1000
137

    
138
{-# ANN case_niceSort_static "HLint: ignore Use camelCase" #-}
139

    
140
case_niceSort_static :: Assertion
141
case_niceSort_static = do
142
  assertEqual "empty list" [] $ niceSort []
143
  assertEqual "punctuation" [",", "."] $ niceSort [",", "."]
144
  assertEqual "decimal numbers" ["0.1", "0.2"] $ niceSort ["0.1", "0.2"]
145
  assertEqual "various numbers" ["0,099", "0.1", "0.2", "0;099"] $
146
              niceSort ["0;099", "0,099", "0.1", "0.2"]
147

    
148
  assertEqual "simple concat" ["0000", "a0", "a1", "a2", "a20", "a99",
149
                               "b00", "b10", "b70"] $
150
    niceSort ["a0", "a1", "a99", "a20", "a2", "b10", "b70", "b00", "0000"]
151

    
152
  assertEqual "ranges" ["A", "Z", "a0-0", "a0-4", "a1-0", "a9-1", "a09-2",
153
                      "a20-3", "a99-3", "a99-10", "b"] $
154
    niceSort ["a0-0", "a1-0", "a99-10", "a20-3", "a0-4", "a99-3", "a09-2",
155
              "Z", "a9-1", "A", "b"]
156

    
157
  assertEqual "large"
158
    ["3jTwJPtrXOY22bwL2YoW", "Eegah9ei", "KOt7vn1dWXi",
159
     "KVQqLPDjcPjf8T3oyzjcOsfkb", "WvNJd91OoXvLzdEiEXa6",
160
     "Z8Ljf1Pf5eBfNg171wJR", "a07h8feON165N67PIE", "bH4Q7aCu3PUPjK3JtH",
161
     "cPRi0lM7HLnSuWA2G9", "guKJkXnkULealVC8CyF1xefym",
162
     "pqF8dkU5B1cMnyZuREaSOADYx", "uHXAyYYftCSG1o7qcCqe",
163
     "xij88brTulHYAv8IEOyU", "xpIUJeVT1Rp"] $
164
    niceSort ["Eegah9ei", "xij88brTulHYAv8IEOyU", "3jTwJPtrXOY22bwL2YoW",
165
             "Z8Ljf1Pf5eBfNg171wJR", "WvNJd91OoXvLzdEiEXa6",
166
             "uHXAyYYftCSG1o7qcCqe", "xpIUJeVT1Rp", "KOt7vn1dWXi",
167
             "a07h8feON165N67PIE", "bH4Q7aCu3PUPjK3JtH",
168
             "cPRi0lM7HLnSuWA2G9", "KVQqLPDjcPjf8T3oyzjcOsfkb",
169
             "guKJkXnkULealVC8CyF1xefym", "pqF8dkU5B1cMnyZuREaSOADYx"]
170

    
171
-- | Tests single-string behaviour of 'niceSort'.
172
prop_niceSort_single :: Property
173
prop_niceSort_single =
174
  forAll genName $ \name ->
175
  conjoin
176
  [ printTestCase "single string" $ [name] ==? niceSort [name]
177
  , printTestCase "single plus empty" $ ["", name] ==? niceSort [name, ""]
178
  ]
179

    
180
-- | Tests some generic 'niceSort' properties. Note that the last test
181
-- must add a non-digit prefix; a digit one might change ordering.
182
prop_niceSort_generic :: Property
183
prop_niceSort_generic =
184
  forAll (resize 20 arbitrary) $ \names ->
185
  let n_sorted = niceSort names in
186
  conjoin [ printTestCase "length" $ length names ==? length n_sorted
187
          , printTestCase "same strings" $ sort names ==? sort n_sorted
188
          , printTestCase "idempotence" $ n_sorted ==? niceSort n_sorted
189
          , printTestCase "static prefix" $ n_sorted ==?
190
              map tail (niceSort $ map (" "++) names)
191
          ]
192

    
193
-- | Tests that niceSorting numbers is identical to actual sorting
194
-- them (in numeric form).
195
prop_niceSort_numbers :: Property
196
prop_niceSort_numbers =
197
  forAll (listOf (arbitrary::Gen (NonNegative Int))) $ \numbers ->
198
  map show (sort numbers) ==? niceSort (map show numbers)
199

    
200
-- | Tests that 'niceSort' and 'niceSortKey' are equivalent.
201
prop_niceSortKey_equiv :: Property
202
prop_niceSortKey_equiv =
203
  forAll (resize 20 arbitrary) $ \names ->
204
  forAll (vectorOf (length names) (arbitrary::Gen Int)) $ \numbers ->
205
  let n_sorted = niceSort names in
206
  conjoin
207
  [ printTestCase "key id" $ n_sorted ==? niceSortKey id names
208
  , printTestCase "key rev" $ niceSort (map reverse names) ==?
209
                              map reverse (niceSortKey reverse names)
210
  , printTestCase "key snd" $ n_sorted ==? map snd (niceSortKey snd $
211
                                                    zip numbers names)
212
  ]
213

    
214
-- | Tests 'rStripSpace'.
215
prop_rStripSpace :: NonEmptyList Char -> Property
216
prop_rStripSpace (NonEmpty str) =
217
  forAll (resize 50 $ listOf1 (arbitrary `suchThat` isSpace)) $ \whitespace ->
218
  conjoin [ printTestCase "arb. string last char is not space" $
219
              case rStripSpace str of
220
                [] -> True
221
                xs -> not . isSpace $ last xs
222
          , printTestCase "whitespace suffix is stripped" $
223
              rStripSpace str ==? rStripSpace (str ++ whitespace)
224
          , printTestCase "whitespace reduced to null" $
225
              rStripSpace whitespace ==? ""
226
          , printTestCase "idempotent on empty strings" $
227
              rStripSpace "" ==? ""
228
          ]
229

    
230
#ifndef NO_REGEX_PCRE
231
{-# ANN case_new_uuid "HLint: ignore Use camelCase" #-}
232

    
233
-- | Tests that the newUUID function produces valid UUIDs.
234
case_new_uuid :: Assertion
235
case_new_uuid = do
236
  uuid <- newUUID
237
  assertBool "newUUID" $ uuid =~ C.uuidRegex
238
#endif
239

    
240
prop_clockTimeToString :: Integer -> Integer -> Property
241
prop_clockTimeToString ts pico =
242
  clockTimeToString (TOD ts pico) ==? show ts
243

    
244
-- | Test normal operation for 'chompPrefix'.
245
--
246
-- Any random prefix of a string must be stripped correctly, including the empty
247
-- prefix, and the whole string.
248
prop_chompPrefix_normal :: String -> Property
249
prop_chompPrefix_normal str =
250
  forAll (choose (0, length str)) $ \size ->
251
  chompPrefix (take size str) str ==? (Just $ drop size str)
252

    
253
-- | Test that 'chompPrefix' correctly allows the last char (the separator) to
254
-- be absent if the string terminates there.
255
prop_chompPrefix_last :: Property
256
prop_chompPrefix_last =
257
  forAll (choose (1, 20)) $ \len ->
258
  forAll (vectorOf len arbitrary) $ \pfx ->
259
  chompPrefix pfx pfx ==? Just "" .&&.
260
  chompPrefix pfx (init pfx) ==? Just ""
261

    
262
-- | Test that chompPrefix on the empty string always returns Nothing for
263
-- prefixes of length 2 or more.
264
prop_chompPrefix_empty_string :: Property
265
prop_chompPrefix_empty_string =
266
  forAll (choose (2, 20)) $ \len ->
267
  forAll (vectorOf len arbitrary) $ \pfx ->
268
  chompPrefix pfx "" ==? Nothing
269

    
270
-- | Test 'chompPrefix' returns Nothing when the prefix doesn't match.
271
prop_chompPrefix_nothing :: Property
272
prop_chompPrefix_nothing =
273
  forAll (choose (1, 20)) $ \len ->
274
  forAll (vectorOf len arbitrary) $ \pfx ->
275
  forAll (arbitrary `suchThat`
276
          (\s -> not (pfx `isPrefixOf` s) && s /= init pfx)) $ \str ->
277
  chompPrefix pfx str ==? Nothing
278

    
279
-- | Tests 'trim'.
280
prop_trim :: NonEmptyList Char -> Property
281
prop_trim (NonEmpty str) =
282
  forAll (listOf1 $ elements " \t\n\r\f") $ \whitespace ->
283
  forAll (choose (0, length whitespace)) $ \n ->
284
  let (preWS, postWS) = splitAt n whitespace in
285
  conjoin [ printTestCase "arb. string first and last char are not space" $
286
              case trim str of
287
                [] -> True
288
                xs -> (not . isSpace . head) xs && (not . isSpace . last) xs
289
          , printTestCase "whitespace is striped" $
290
              trim str ==? trim (preWS ++ str ++ postWS)
291
          , printTestCase "whitespace reduced to null" $
292
              trim whitespace ==? ""
293
          , printTestCase "idempotent on empty strings" $
294
              trim "" ==? ""
295
          ]
296

    
297
-- | Test list for the Utils module.
298
testSuite "Utils"
299
            [ 'prop_commaJoinSplit
300
            , 'prop_commaSplitJoin
301
            , 'prop_fromObjWithDefault
302
            , 'prop_if'if
303
            , 'prop_select
304
            , 'prop_select_undefd
305
            , 'prop_select_undefv
306
            , 'prop_parseUnit
307
            , 'case_niceSort_static
308
            , 'prop_niceSort_single
309
            , 'prop_niceSort_generic
310
            , 'prop_niceSort_numbers
311
            , 'prop_niceSortKey_equiv
312
            , 'prop_rStripSpace
313
            , 'prop_trim
314
#ifndef NO_REGEX_PCRE
315
            , 'case_new_uuid
316
#endif
317
            , 'prop_clockTimeToString
318
            , 'prop_chompPrefix_normal
319
            , 'prop_chompPrefix_last
320
            , 'prop_chompPrefix_empty_string
321
            , 'prop_chompPrefix_nothing
322
            ]