diff --git a/lib/utils/algo.py b/lib/utils/algo.py index 0a12ba4c787ed9927a67c0206e6b4fd9b74b6c79..0655290c0accdaceaf1579ab8aca938f665fdbd5 100644 --- a/lib/utils/algo.py +++ b/lib/utils/algo.py @@ -148,6 +148,27 @@ def InvertDict(dict_in): return dict(zip(dict_in.values(), dict_in.keys())) +def InsertAtPos(src, pos, other): + """Inserts C{other} at given C{pos} into C{src}. + + @note: This function does not modify C{src} in place but returns a new copy + + @type src: list + @param src: The source list in which we want insert elements + @type pos: int + @param pos: The position where we want to start insert C{other} + @type other: list + @param other: The other list to insert into C{src} + @return: A copy of C{src} with C{other} inserted at C{pos} + + """ + new = src[:pos] + new.extend(other) + new.extend(src[pos:]) + + return new + + class RunningTimeout(object): """Class to calculate remaining timeout when doing several operations. diff --git a/test/ganeti.utils.algo_unittest.py b/test/ganeti.utils.algo_unittest.py index 6a3b6d6d536d7bd41e155483148b5af09b879ba9..89a9f32884418b724811f262bc6c0c06ee6179b8 100755 --- a/test/ganeti.utils.algo_unittest.py +++ b/test/ganeti.utils.algo_unittest.py @@ -236,6 +236,16 @@ class TestInvertDict(unittest.TestCase): { 1: "foo", 2: "bar", 5: "baz"}) +class TestInsertAtPos(unittest.TestCase): + def test(self): + a = [1, 5, 6] + b = [2, 3, 4] + self.assertEqual(algo.InsertAtPos(a, 1, b), [1, 2, 3, 4, 5, 6]) + self.assertEqual(algo.InsertAtPos(a, 0, b), b + a) + self.assertEqual(algo.InsertAtPos(a, len(a), b), a + b) + self.assertEqual(algo.InsertAtPos(a, 2, b), [1, 5, 2, 3, 4, 6]) + + class TimeMock: def __init__(self, values): self.values = values