Revision 31e22135
b/lib/utils.py | ||
---|---|---|
373 | 373 |
return ret |
374 | 374 |
|
375 | 375 |
|
376 |
def CheckDict(target, template, logname=None): |
|
377 |
"""Ensure a dictionary has a required set of keys. |
|
378 |
|
|
379 |
For the given dictionaries I{target} and I{template}, ensure |
|
380 |
I{target} has all the keys from I{template}. Missing keys are added |
|
381 |
with values from template. |
|
382 |
|
|
383 |
@type target: dict |
|
384 |
@param target: the dictionary to update |
|
385 |
@type template: dict |
|
386 |
@param template: the dictionary holding the default values |
|
387 |
@type logname: str or None |
|
388 |
@param logname: if not None, causes the missing keys to be |
|
389 |
logged with this name |
|
390 |
|
|
391 |
""" |
|
392 |
missing = [] |
|
393 |
for k in template: |
|
394 |
if k not in target: |
|
395 |
missing.append(k) |
|
396 |
target[k] = template[k] |
|
397 |
|
|
398 |
if missing and logname: |
|
399 |
logging.warning('%s missing keys %s', logname, ', '.join(missing)) |
|
400 |
|
|
401 |
|
|
402 | 376 |
def ForceDictType(target, key_types, allowed_values=None): |
403 | 377 |
"""Force the values of a dict to have certain types. |
404 | 378 |
|
b/test/ganeti.utils_unittest.py | ||
---|---|---|
40 | 40 |
from ganeti import utils |
41 | 41 |
from ganeti import errors |
42 | 42 |
from ganeti.utils import IsProcessAlive, RunCmd, \ |
43 |
RemoveFile, CheckDict, MatchNameComponent, FormatUnit, \
|
|
43 |
RemoveFile, MatchNameComponent, FormatUnit, \ |
|
44 | 44 |
ParseUnit, AddAuthorizedKey, RemoveAuthorizedKey, \ |
45 | 45 |
ShellQuote, ShellQuoteArgs, TcpPing, ListVisibleFiles, \ |
46 | 46 |
SetEtcHostsEntry, RemoveEtcHostsEntry, FirstFree, OwnIpAddress, \ |
... | ... | |
306 | 306 |
mkdir=True) |
307 | 307 |
|
308 | 308 |
|
309 |
class TestCheckdict(unittest.TestCase): |
|
310 |
"""Test case for the CheckDict function""" |
|
311 |
|
|
312 |
def testAdd(self): |
|
313 |
"""Test that CheckDict adds a missing key with the correct value""" |
|
314 |
|
|
315 |
tgt = {'a':1} |
|
316 |
tmpl = {'b': 2} |
|
317 |
CheckDict(tgt, tmpl) |
|
318 |
if 'b' not in tgt or tgt['b'] != 2: |
|
319 |
self.fail("Failed to update dict") |
|
320 |
|
|
321 |
|
|
322 |
def testNoUpdate(self): |
|
323 |
"""Test that CheckDict does not overwrite an existing key""" |
|
324 |
tgt = {'a':1, 'b': 3} |
|
325 |
tmpl = {'b': 2} |
|
326 |
CheckDict(tgt, tmpl) |
|
327 |
self.failUnlessEqual(tgt['b'], 3) |
|
328 |
|
|
329 |
|
|
330 | 309 |
class TestMatchNameComponent(unittest.TestCase): |
331 | 310 |
"""Test case for the MatchNameComponent function""" |
332 | 311 |
|
Also available in: Unified diff