Commit 5d630c22 authored by Michael Hanselmann's avatar Michael Hanselmann
Browse files

Factorize code to load and verify JSON

A new tool to configure the node daemon will also have to load and
verify JSON data.
Signed-off-by: default avatarMichael Hanselmann <>
Reviewed-by: default avatarGuido Trotter <>
parent 796b5152
......@@ -140,6 +140,28 @@ def LoadSignedJson(txt, key):
return LoadJson(msg), salt
def LoadAndVerifyJson(raw, verify_fn):
"""Parses and verifies JSON data.
@type raw: string
@param raw: Input data in JSON format
@type verify_fn: callable
@param verify_fn: Verification function, usually from L{ht}
@return: De-serialized data
data = LoadJson(raw)
except Exception, err:
raise errors.ParseError("Can't parse input data: %s" % err)
if not verify_fn(data):
raise errors.ParseError("Data does not match expected format: %s" %
return data
Dump = DumpJson
Load = LoadJson
DumpSigned = DumpSignedJson
......@@ -281,16 +281,7 @@ def LoadData(raw):
@rtype: dict
data = serializer.LoadJson(raw)
except Exception, err:
raise errors.ParseError("Can't parse input data: %s" % err)
if not _DATA_CHECK(data):
raise errors.ParseError("Input data does not match expected format: %s" %
return data
return serializer.LoadAndVerifyJson(raw, _DATA_CHECK)
def Main():
......@@ -26,6 +26,7 @@ import unittest
from ganeti import serializer
from ganeti import errors
from ganeti import ht
import testutils
......@@ -106,5 +107,29 @@ class TestSerializer(testutils.GanetiTestCase):
serializer.DumpJson(tdata), "mykey")
class TestLoadAndVerifyJson(unittest.TestCase):
def testNoJson(self):
self.assertRaises(errors.ParseError, serializer.LoadAndVerifyJson,
"", NotImplemented)
self.assertRaises(errors.ParseError, serializer.LoadAndVerifyJson,
"}", NotImplemented)
def testVerificationFails(self):
self.assertRaises(errors.ParseError, serializer.LoadAndVerifyJson,
"{}", lambda _: False)
verify_fn = ht.TListOf(ht.TNonEmptyString)
serializer.LoadAndVerifyJson("{}", verify_fn)
except errors.ParseError, err:
else:"Exception not raised")
def testSuccess(self):
self.assertEqual(serializer.LoadAndVerifyJson("{}", ht.TAny), {})
self.assertEqual(serializer.LoadAndVerifyJson("\"Foo\"", ht.TAny), "Foo")
if __name__ == "__main__":
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment