From d60946d9fa5afccee0784c527eb3caacdac29162 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Nussbaumer?= <rn@google.com> Date: Wed, 2 Nov 2011 16:06:10 +0100 Subject: [PATCH] utils.algo: Add a function to insert a list into a list MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: RenΓ© Nussbaumer <rn@google.com> Reviewed-by: Michael Hanselmann <hansmi@google.com> --- lib/utils/algo.py | 21 +++++++++++++++++++++ test/ganeti.utils.algo_unittest.py | 10 ++++++++++ 2 files changed, 31 insertions(+) diff --git a/lib/utils/algo.py b/lib/utils/algo.py index 0a12ba4c7..0655290c0 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 6a3b6d6d5..89a9f3288 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 -- GitLab