Revision cdf71b12
b/lib/utils/algo.py | ||
---|---|---|
46 | 46 |
return [i for i in seq if i not in seen and not seen.add(i)] |
47 | 47 |
|
48 | 48 |
|
49 |
def JoinDisjointDicts(dict_a, dict_b): |
|
50 |
"""Joins dictionaries with no conflicting keys. |
|
51 |
|
|
52 |
Enforces the constraint that the two key sets must be disjoint, and then |
|
53 |
merges the two dictionaries in a new dictionary that is returned to the |
|
54 |
caller. |
|
55 |
|
|
56 |
@type dict_a: dict |
|
57 |
@param dict_a: the first dictionary |
|
58 |
@type dict_b: dict |
|
59 |
@param dict_b: the second dictionary |
|
60 |
@rtype: dict |
|
61 |
@return: a new dictionary containing all the key/value pairs contained in the |
|
62 |
two dictionaries. |
|
63 |
|
|
64 |
""" |
|
65 |
assert not (set(dict_a) & set(dict_b)), ("Duplicate keys found while joining" |
|
66 |
" %s and %s" % (dict_a, dict_b)) |
|
67 |
result = dict_a.copy() |
|
68 |
result.update(dict_b) |
|
69 |
return result |
|
70 |
|
|
71 |
|
|
49 | 72 |
def FindDuplicates(seq): |
50 | 73 |
"""Identifies duplicates in a list. |
51 | 74 |
|
b/test/ganeti.utils.algo_unittest.py | ||
---|---|---|
272 | 272 |
self.assertRaises(ValueError, algo.RunningTimeout, -1.0, True) |
273 | 273 |
|
274 | 274 |
|
275 |
class TestJoinDisjointDicts(unittest.TestCase): |
|
276 |
def setUp(self): |
|
277 |
self.non_empty_dict = {"a": 1, "b": 2} |
|
278 |
self.empty_dict = dict() |
|
279 |
|
|
280 |
def testWithEmptyDicts(self): |
|
281 |
self.assertEqual(self.empty_dict, algo.JoinDisjointDicts(self.empty_dict, |
|
282 |
self.empty_dict)) |
|
283 |
self.assertEqual(self.non_empty_dict, algo.JoinDisjointDicts( |
|
284 |
self.empty_dict, self.non_empty_dict)) |
|
285 |
self.assertEqual(self.non_empty_dict, algo.JoinDisjointDicts( |
|
286 |
self.non_empty_dict, self.empty_dict)) |
|
287 |
|
|
288 |
def testNonDisjoint(self): |
|
289 |
self.assertRaises(AssertionError, algo.JoinDisjointDicts, |
|
290 |
self.non_empty_dict, self.non_empty_dict) |
|
291 |
|
|
292 |
def testCommonCase(self): |
|
293 |
dict_a = {"TEST1": 1, "TEST2": 2} |
|
294 |
dict_b = {"TEST3": 3, "TEST4": 4} |
|
295 |
|
|
296 |
result = dict_a.copy() |
|
297 |
result.update(dict_b) |
|
298 |
|
|
299 |
self.assertEqual(result, algo.JoinDisjointDicts(dict_a, dict_b)) |
|
300 |
self.assertEqual(result, algo.JoinDisjointDicts(dict_b, dict_a)) |
|
301 |
|
|
302 |
|
|
275 | 303 |
if __name__ == "__main__": |
276 | 304 |
testutils.GanetiTestProgram() |
Also available in: Unified diff