baserlib.FillOpCode: Allow parameter rename
authorMichael Hanselmann <hansmi@google.com>
Mon, 14 Feb 2011 16:20:33 +0000 (17:20 +0100)
committerMichael Hanselmann <hansmi@google.com>
Tue, 15 Feb 2011 11:09:37 +0000 (12:09 +0100)
Some RAPI parameters don't match the name of the underlying
opcode. With this patch they can be renamed while filling
the opcode.

Signed-off-by: Michael Hanselmann <hansmi@google.com>
Reviewed-by: RenĂ© Nussbaumer <rn@google.com>

lib/rapi/baserlib.py
test/ganeti.rapi.baserlib_unittest.py

index 83dc059..66f69b2 100644 (file)
@@ -170,7 +170,7 @@ def MakeParamsDict(opts, params):
   return result
 
 
-def FillOpcode(opcls, body, static):
+def FillOpcode(opcls, body, static, rename=None):
   """Fills an opcode with body parameters.
 
   Parameter types are checked.
@@ -181,21 +181,32 @@ def FillOpcode(opcls, body, static):
   @param body: Body parameters as received from client
   @type static: dict
   @param static: Static parameters which can't be modified by client
+  @type rename: dict
+  @param rename: Renamed parameters, key as old name, value as new name
   @return: Opcode object
 
   """
   CheckType(body, dict, "Body contents")
 
+  # Make copy to be modified
+  params = body.copy()
+
+  if rename:
+    for old, new in rename.items():
+      if new in params and old in params:
+        raise http.HttpBadRequest("Parameter '%s' was renamed to '%s', but"
+                                  " both are specified" %
+                                  (old, new))
+      if old in params:
+        assert new not in params
+        params[new] = params.pop(old)
+
   if static:
-    overwritten = set(body.keys()) & set(static.keys())
+    overwritten = set(params.keys()) & set(static.keys())
     if overwritten:
       raise http.HttpBadRequest("Can't overwrite static parameters %r" %
                                 overwritten)
 
-  # Combine parameters
-  params = body.copy()
-
-  if static:
     params.update(static)
 
   # Convert keys to strings (simplejson decodes them as unicode)
index b3b6f1c..fc29cce 100755 (executable)
@@ -80,6 +80,22 @@ class TestFillOpcode(unittest.TestCase):
     self.assertRaises(http.HttpBadRequest, baserlib.FillOpcode,
                       self.OpTest, range(10), None)
 
+  def testRenameBothSpecified(self):
+    self.assertRaises(http.HttpBadRequest, baserlib.FillOpcode,
+                      self.OpTest, { "old": 123, "new": 999, }, None,
+                      rename={ "old": "new", })
+
+  def testRename(self):
+    value = "Hello World"
+    op = baserlib.FillOpcode(self.OpTest, { "data": value, }, None,
+                             rename={ "data": "test", })
+    self.assertEqual(op.test, value)
+
+  def testRenameStatic(self):
+    self.assertRaises(http.HttpBadRequest, baserlib.FillOpcode,
+                      self.OpTest, { "data": 0, }, { "test": None, },
+                      rename={ "data": "test", })
+
 
 if __name__ == "__main__":
   testutils.GanetiTestProgram()