Debian Codegraph @

test/hs/Test/Ganeti/Query/Query.hs

raw
1 {-# LANGUAGE TemplateHaskell, BangPatterns #-}
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 All rights reserved.
12
13 Redistribution and use in source and binary forms, with or without
14 modification, are permitted provided that the following conditions are
15 met:
16
17 1. Redistributions of source code must retain the above copyright notice,
18 this list of conditions and the following disclaimer.
19
20 2. Redistributions in binary form must reproduce the above copyright
21 notice, this list of conditions and the following disclaimer in the
22 documentation and/or other materials provided with the distribution.
23
24 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
25 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
26 TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
27 PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
28 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
30 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
31 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
32 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
33 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
34 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35
36 -}
37
38 module Test.Ganeti.Query.Query (testQuery_Query) where
39
40 import Test.HUnit (Assertion, assertEqual)
41 import Test.QuickCheck hiding (Result)
42 import Test.QuickCheck.Monadic
43
44 import Data.Function (on)
45 import Data.List
46 import qualified Data.Map as Map
47 import Data.Maybe
48 import qualified Data.Set as Set
49 import Text.JSON (JSValue(..), showJSON)
50
51 import Test.Ganeti.TestHelper
52 import Test.Ganeti.TestCommon
53 import Test.Ganeti.Objects (genEmptyCluster)
54
55 import Ganeti.BasicTypes
56 import Ganeti.Errors
57 import Ganeti.JSON
58 import Ganeti.Objects
59 import Ganeti.Query.Filter
60 import qualified Ganeti.Query.Group as Group
61 import Ganeti.Query.Language
62 import qualified Ganeti.Query.Node as Node
63 import Ganeti.Query.Query
64 import qualified Ganeti.Query.Job as Job
65 import Ganeti.Utils (sepSplit)
66
67 {-# ANN module "HLint: ignore Use camelCase" #-}
68
69 -- * Helpers
70
71 -- | Checks if a list of field definitions contains unknown fields.
72 hasUnknownFields :: [FieldDefinition] -> Bool
73 hasUnknownFields = (QFTUnknown `notElem`) . map fdefKind
74
75 -- * Test cases
76
77 -- ** Node queries
78
79 -- | Tests that querying any existing fields, via either query or
80 -- queryFields, will not return unknown fields.
81 prop_queryNode_noUnknown :: Property
82 prop_queryNode_noUnknown =
83 forAll (choose (0, maxNodes) >>= genEmptyCluster) $ \cluster ->
84 forAll (elements (Map.keys Node.fieldsMap)) $ \field -> monadicIO $ do
85 QueryResult fdefs fdata <-
86 run (query cluster False (Query (ItemTypeOpCode QRNode)
87 [field] EmptyFilter)) >>= resultProp
88 QueryFieldsResult fdefs' <-
89 resultProp $ queryFields (QueryFields (ItemTypeOpCode QRNode) [field])
90 _ <- stop $ conjoin
91 [ counterexample ("Got unknown fields via query (" ++
92 show fdefs ++ ")") (hasUnknownFields fdefs)
93 , counterexample ("Got unknown result status via query (" ++
94 show fdata ++ ")")
95 (all (all ((/= RSUnknown) . rentryStatus)) fdata)
96 , counterexample ("Got unknown fields via query fields (" ++
97 show fdefs'++ ")") (hasUnknownFields fdefs')
98 ]
99 return ()
100
101 -- | Tests that an unknown field is returned as such.
102 prop_queryNode_Unknown :: Property
103 prop_queryNode_Unknown =
104 forAll (choose (0, maxNodes) >>= genEmptyCluster) $ \cluster ->
105 forAll (arbitrary `suchThat` (`notElem` Map.keys Node.fieldsMap))
106 $ \field -> monadicIO $ do
107 QueryResult fdefs fdata <-
108 run (query cluster False (Query (ItemTypeOpCode QRNode)
109 [field] EmptyFilter)) >>= resultProp
110 QueryFieldsResult fdefs' <-
111 resultProp $ queryFields (QueryFields (ItemTypeOpCode QRNode) [field])
112 _ <- stop $ conjoin
113 [ counterexample ("Got known fields via query (" ++ show fdefs ++ ")")
114 (not $ hasUnknownFields fdefs)
115 , counterexample ("Got /= ResultUnknown result status via query (" ++
116 show fdata ++ ")")
117 (all (all ((== RSUnknown) . rentryStatus)) fdata)
118 , counterexample ("Got a Just in a result value (" ++
119 show fdata ++ ")")
120 (all (all (isNothing . rentryValue)) fdata)
121 , counterexample ("Got known fields via query fields (" ++ show fdefs'
122 ++ ")") (not $ hasUnknownFields fdefs')
123 ]
124 return ()
125
126 -- | Checks that a result type is conforming to a field definition.
127 checkResultType :: FieldDefinition -> ResultEntry -> Property
128 checkResultType _ (ResultEntry RSNormal Nothing) =
129 failTest "Nothing result in RSNormal field"
130 checkResultType _ (ResultEntry _ Nothing) = passTest
131 checkResultType fdef (ResultEntry RSNormal (Just v)) =
132 case (fdefKind fdef, v) of
133 (QFTText , JSString {}) -> passTest
134 (QFTBool , JSBool {}) -> passTest
135 (QFTNumber , JSRational {}) -> passTest
136 (QFTNumberFloat , JSRational {}) -> passTest
137 (QFTTimestamp , JSRational {}) -> passTest
138 (QFTUnit , JSRational {}) -> passTest
139 (QFTOther , _) -> passTest -- meh, QFT not precise...
140 (kind, _) -> failTest $ "Type mismatch, field definition says " ++
141 show kind ++ " but returned value is " ++ show v ++
142 " for field '" ++ fdefName fdef ++ "'"
143 checkResultType _ (ResultEntry r (Just _)) =
144 failTest $ "Just result in " ++ show r ++ " field"
145
146 -- | Tests that querying any existing fields, the following three
147 -- properties hold: RSNormal corresponds to a Just value, any other
148 -- value corresponds to Nothing, and for a RSNormal and value field,
149 -- the type of the value corresponds to the type of the field as
150 -- declared in the FieldDefinition.
151 prop_queryNode_types :: Property
152 prop_queryNode_types =
153 forAll (choose (0, maxNodes)) $ \numnodes ->
154 forAll (genEmptyCluster numnodes) $ \cfg ->
155 forAll (elements (Map.keys Node.fieldsMap)) $ \field -> monadicIO $ do
156 QueryResult fdefs fdata <-
157 run (query cfg False (Query (ItemTypeOpCode QRNode)
158 [field] EmptyFilter)) >>= resultProp
159 _ <- stop $ conjoin
160 [ counterexample ("Inconsistent result entries (" ++ show fdata ++ ")")
161 (conjoin $ map (conjoin . zipWith checkResultType fdefs) fdata)
162 , counterexample "Wrong field definitions length"
163 (length fdefs ==? 1)
164 , counterexample "Wrong field result rows length"
165 (all ((== 1) . length) fdata)
166 , counterexample "Wrong number of result rows"
167 (length fdata ==? numnodes)
168 ]
169 return ()
170
171 -- | Test that queryFields with empty fields list returns all node fields.
172 case_queryNode_allfields :: Assertion
173 case_queryNode_allfields = do
174 fdefs <- case queryFields (QueryFields (ItemTypeOpCode QRNode) []) of
175 Bad msg -> fail $ "Error in query all fields: " ++
176 formatError msg
177 Ok (QueryFieldsResult v) -> return v
178 let field_sort = compare `on` fdefName
179 assertEqual "Mismatch in all fields list"
180 (sortBy field_sort . map (\(f, _, _) -> f) $ Map.elems Node.fieldsMap)
181 (sortBy field_sort fdefs)
182
183 -- | Check if cluster node names are unique (first elems).
184 areNodeNamesSane :: ConfigData -> Bool
185 areNodeNamesSane cfg =
186 let fqdns = map nodeName . Map.elems . fromContainer $ configNodes cfg
187 names = map (head . sepSplit '.') fqdns
188 in length names == length (nub names)
189
190 -- | Check that the nodes reported by a name filter are sane.
191 prop_queryNode_filter :: Property
192 prop_queryNode_filter =
193 forAll (choose (1, maxNodes)) $ \nodes ->
194 forAll (genEmptyCluster nodes `suchThat`
195 areNodeNamesSane) $ \cluster -> monadicIO $ do
196 let node_list = map nodeName . Map.elems . fromContainer $
197 configNodes cluster
198 count <- pick $ choose (1, nodes)
199 fqdn_set <- pick . genSetHelper node_list $ Just count
200 let fqdns = Set.elems fqdn_set
201 names = map (head . sepSplit '.') fqdns
202 flt = makeSimpleFilter "name" $ map Left names
203 QueryResult _ fdata <-
204 run (query cluster False (Query (ItemTypeOpCode QRNode)
205 ["name"] flt)) >>= resultProp
206 _ <- stop $ conjoin
207 [ counterexample "Invalid node names" $
208 map (map rentryValue) fdata ==? map (\f -> [Just (showJSON f)]) fqdns
209 ]
210 return ()
211
212 -- ** Group queries
213
214 prop_queryGroup_noUnknown :: Property
215 prop_queryGroup_noUnknown =
216 forAll (choose (0, maxNodes) >>= genEmptyCluster) $ \cluster ->
217 forAll (elements (Map.keys Group.fieldsMap)) $ \field -> monadicIO $ do
218 QueryResult fdefs fdata <-
219 run (query cluster False (Query (ItemTypeOpCode QRGroup)
220 [field] EmptyFilter)) >>=
221 resultProp
222 QueryFieldsResult fdefs' <-
223 resultProp $ queryFields (QueryFields (ItemTypeOpCode QRGroup) [field])
224 _ <- stop $ conjoin
225 [ counterexample ("Got unknown fields via query (" ++ show fdefs ++ ")")
226 (hasUnknownFields fdefs)
227 , counterexample ("Got unknown result status via query (" ++
228 show fdata ++ ")")
229 (all (all ((/= RSUnknown) . rentryStatus)) fdata)
230 , counterexample ("Got unknown fields via query fields (" ++ show fdefs'
231 ++ ")") (hasUnknownFields fdefs')
232 ]
233 return ()
234
235 prop_queryGroup_Unknown :: Property
236 prop_queryGroup_Unknown =
237 forAll (choose (0, maxNodes) >>= genEmptyCluster) $ \cluster ->
238 forAll (arbitrary `suchThat` (`notElem` Map.keys Group.fieldsMap))
239 $ \field -> monadicIO $ do
240 QueryResult fdefs fdata <-
241 run (query cluster False (Query (ItemTypeOpCode QRGroup)
242 [field] EmptyFilter)) >>= resultProp
243 QueryFieldsResult fdefs' <-
244 resultProp $ queryFields (QueryFields (ItemTypeOpCode QRGroup) [field])
245 _ <- stop $ conjoin
246 [ counterexample ("Got known fields via query (" ++ show fdefs ++ ")")
247 (not $ hasUnknownFields fdefs)
248 , counterexample ("Got /= ResultUnknown result status via query (" ++
249 show fdata ++ ")")
250 (all (all ((== RSUnknown) . rentryStatus)) fdata)
251 , counterexample ("Got a Just in a result value (" ++
252 show fdata ++ ")")
253 (all (all (isNothing . rentryValue)) fdata)
254 , counterexample ("Got known fields via query fields (" ++ show fdefs'
255 ++ ")") (not $ hasUnknownFields fdefs')
256 ]
257 return ()
258
259 prop_queryGroup_types :: Property
260 prop_queryGroup_types =
261 forAll (choose (0, maxNodes)) $ \numnodes ->
262 forAll (genEmptyCluster numnodes) $ \cfg ->
263 forAll (elements (Map.keys Group.fieldsMap)) $ \field -> monadicIO $ do
264 QueryResult fdefs fdata <-
265 run (query cfg False (Query (ItemTypeOpCode QRGroup)
266 [field] EmptyFilter)) >>= resultProp
267 _ <- stop $ conjoin
268 [ counterexample ("Inconsistent result entries (" ++ show fdata ++ ")")
269 (conjoin $ map (conjoin . zipWith checkResultType fdefs) fdata)
270 , counterexample "Wrong field definitions length" (length fdefs ==? 1)
271 , counterexample "Wrong field result rows length"
272 (all ((== 1) . length) fdata)
273 ]
274 return ()
275
276 case_queryGroup_allfields :: Assertion
277 case_queryGroup_allfields = do
278 fdefs <- case queryFields (QueryFields (ItemTypeOpCode QRGroup) []) of
279 Bad msg -> fail $ "Error in query all fields: " ++
280 formatError msg
281 Ok (QueryFieldsResult v) -> return v
282 let field_sort = compare `on` fdefName
283 assertEqual "Mismatch in all fields list"
284 (sortBy field_sort . map (\(f, _, _) -> f) $ Map.elems Group.fieldsMap)
285 (sortBy field_sort fdefs)
286
287 -- | Check that the node count reported by a group list is sane.
288 --
289 -- FIXME: also verify the node list, etc.
290 prop_queryGroup_nodeCount :: Property
291 prop_queryGroup_nodeCount =
292 forAll (choose (0, maxNodes)) $ \nodes ->
293 forAll (genEmptyCluster nodes) $ \cluster -> monadicIO $
294 do
295 QueryResult _ fdata <-
296 run (query cluster False (Query (ItemTypeOpCode QRGroup)
297 ["node_cnt"] EmptyFilter)) >>= resultProp
298 _ <- stop $ conjoin
299 [ counterexample "Invalid node count" $
300 map (map rentryValue) fdata ==? [[Just (showJSON nodes)]]
301 ]
302 return ()
303
304 -- ** Job queries
305
306 -- | Tests that querying any existing fields, via either query or
307 -- queryFields, will not return unknown fields. This uses 'undefined'
308 -- for config, as job queries shouldn't use the configuration, and an
309 -- explicit filter as otherwise non-live queries wouldn't return any
310 -- result rows.
311 prop_queryJob_noUnknown :: Property
312 prop_queryJob_noUnknown =
313 forAll (listOf (arbitrary::Gen (Positive Integer))) $ \ids ->
314 forAll (elements (Map.keys Job.fieldsMap)) $ \field -> monadicIO $ do
315 let qtype = ItemTypeLuxi QRJob
316 flt = makeSimpleFilter (nameField qtype) $
317 map (\(Positive i) -> Right i) ids
318 QueryResult fdefs fdata <-
319 run (query undefined False (Query qtype [field] flt)) >>= resultProp
320 QueryFieldsResult fdefs' <-
321 resultProp $ queryFields (QueryFields qtype [field])
322 _ <- stop $ conjoin
323 [ counterexample ("Got unknown fields via query (" ++
324 show fdefs ++ ")") (hasUnknownFields fdefs)
325 , counterexample ("Got unknown result status via query (" ++
326 show fdata ++ ")")
327 (all (all ((/= RSUnknown) . rentryStatus)) fdata)
328 , counterexample ("Got unknown fields via query fields (" ++
329 show fdefs'++ ")") (hasUnknownFields fdefs')
330 ]
331 return ()
332
333 -- | Tests that an unknown field is returned as such.
334 prop_queryJob_Unknown :: Property
335 prop_queryJob_Unknown =
336 forAll (listOf (arbitrary::Gen (Positive Integer))) $ \ids ->
337 forAll (arbitrary `suchThat` (`notElem` Map.keys Job.fieldsMap))
338 $ \field -> monadicIO $ do
339 let qtype = ItemTypeLuxi QRJob
340 flt = makeSimpleFilter (nameField qtype) $
341 map (\(Positive i) -> Right i) ids
342 QueryResult fdefs fdata <-
343 run (query undefined False (Query qtype [field] flt)) >>= resultProp
344 QueryFieldsResult fdefs' <-
345 resultProp $ queryFields (QueryFields qtype [field])
346 _ <- stop $ conjoin
347 [ counterexample ("Got known fields via query (" ++ show fdefs ++ ")")
348 (not $ hasUnknownFields fdefs)
349 , counterexample ("Got /= ResultUnknown result status via query (" ++
350 show fdata ++ ")")
351 (all (all ((== RSUnknown) . rentryStatus)) fdata)
352 , counterexample ("Got a Just in a result value (" ++
353 show fdata ++ ")")
354 (all (all (isNothing . rentryValue)) fdata)
355 , counterexample ("Got known fields via query fields (" ++ show fdefs'
356 ++ ")") (not $ hasUnknownFields fdefs')
357 ]
358 return ()
359
360 -- ** Misc other tests
361
362 -- | Tests that requested names checking behaves as expected.
363 prop_getRequestedNames :: Property
364 prop_getRequestedNames =
365 forAll genName $ \node1 ->
366 let chk = getRequestedNames . Query (ItemTypeOpCode QRNode) []
367 q_node1 = QuotedString node1
368 eq_name = EQFilter "name"
369 eq_node1 = eq_name q_node1
370 in conjoin [ counterexample "empty filter" $ chk EmptyFilter ==? []
371 , counterexample "and filter" $ chk (AndFilter [eq_node1]) ==? []
372 , counterexample "simple equality" $ chk eq_node1 ==? [node1]
373 , counterexample "non-name field" $
374 chk (EQFilter "foo" q_node1) ==? []
375 , counterexample "non-simple filter" $
376 chk (OrFilter [ eq_node1 , LTFilter "foo" q_node1]) ==? []
377 ]
378
379 testSuite "Query/Query"
380 [ 'prop_queryNode_noUnknown
381 , 'prop_queryNode_Unknown
382 , 'prop_queryNode_types
383 , 'prop_queryNode_filter
384 , 'case_queryNode_allfields
385 , 'prop_queryGroup_noUnknown
386 , 'prop_queryGroup_Unknown
387 , 'prop_queryGroup_types
388 , 'case_queryGroup_allfields
389 , 'prop_queryGroup_nodeCount
390 , 'prop_queryJob_noUnknown
391 , 'prop_queryJob_Unknown
392 , 'prop_getRequestedNames
393 ]