Add utility to format dictionary as key=value strings
authorMichael Hanselmann <hansmi@google.com>
Thu, 20 Dec 2012 14:40:47 +0000 (15:40 +0100)
committerGuido Trotter <ultrotter@google.com>
Wed, 9 Jan 2013 15:57:24 +0000 (16:57 +0100)
This will be used in QA to format network interface parameters.

This is a cherry-pick of master commit eac9b7b8

Signed-off-by: Michael Hanselmann <hansmi@google.com>
Reviewed-by: Guido Trotter <ultrotter@google.com>

lib/utils/text.py
test/ganeti.utils.text_unittest.py

index e16a861..e21de4b 100644 (file)
@@ -588,3 +588,15 @@ def Truncate(text, length):
     return text
   else:
     return text[:length - len(_ASCII_ELLIPSIS)] + _ASCII_ELLIPSIS
+
+
+def FormatKeyValue(data):
+  """Formats a dictionary as "key=value" parameters.
+
+  The keys are sorted to have a stable order.
+
+  @type data: dict
+  @rtype: list of string
+
+  """
+  return ["%s=%s" % (key, value) for (key, value) in sorted(data.items())]
index b787dc8..affa126 100755 (executable)
@@ -576,5 +576,16 @@ class TestTruncate(unittest.TestCase):
       self.assertRaises(AssertionError, utils.Truncate, "", i)
 
 
+class TestFormatKeyValue(unittest.TestCase):
+  def test(self):
+    self.assertEqual(utils.FormatKeyValue({}), [])
+    self.assertEqual(utils.FormatKeyValue({1: 2}), ["1=2"])
+    self.assertEqual(utils.FormatKeyValue({
+      "zzz": "0",
+      "aaa": "1",
+      }),
+      ["aaa=1", "zzz=0"])
+
+
 if __name__ == "__main__":
   testutils.GanetiTestProgram()