diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0d20b64 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.pyc diff --git a/schema.py b/schema.py new file mode 100644 index 0000000..7535ad4 --- /dev/null +++ b/schema.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python +# coding: utf-8 + +import xmltodict +from StringIO import StringIO +from lxml import etree + + +class Schema: + + def __init__(self, xsd_input=None): + """ + Parse the XSD and attribute + """ + if xsd_input: + xmlschema_doc = etree.parse(StringIO(xsd_input)) + self.xmlschema = etree.XMLSchema(xmlschema_doc) + + def validate(self, xml_input): + """ + Validate XML + """ + parsed_xml = etree.parse(StringIO(xml_input)) + if self.xmlschema.validate(parsed_xml): + return True + else: + return False + + def deserialized(self, xml_input, *args, **kwargs): + """ + Convert XML to dict object + """ + if self.validate(xml_input): + return xmltodict.parse(xml_input, *args, **kwargs) + + def serialized(self, dict_input, **kwargs): + """ + Convert dict to XML + """ + return xmltodict.unparse(dict_input, **kwargs) diff --git a/test.py b/test.py new file mode 100644 index 0000000..faed448 --- /dev/null +++ b/test.py @@ -0,0 +1,45 @@ +# coding: utf-8 + +import unittest +import test_asserts +from schema import Schema + + +class SchemaTestCase(unittest.TestCase): + + def setUp(self): + + self.xsd_string = test_asserts.XSD + self.xml_string = test_asserts.XML + self.xml_string_invalid = test_asserts.XML_INVALID + + def test_instance(self): + sch = Schema(self.xsd_string) + self.assertIsInstance(sch, Schema) + + def test_validate(self): + sch = Schema(self.xsd_string) + validated = sch.validate(self.xml_string) + self.assertTrue(validated) + + def test_deserialized(self): + sch = Schema(self.xsd_string) + des = sch.deserialized(self.xml_string) + self.assertIsInstance(des, dict) + self.assertIn('wizard', des) + + def test_serialized(self): + sch = Schema() + ser = sch.serialized(test_asserts.DICT_OBJ) + self.assertEqual(ser, + '\n21') + + def test_invalid_xml(self): + sch = Schema(self.xsd_string) + invalid = sch.validate(self.xml_string_invalid) + self.assertFalse(invalid) + + def test_deserialized_invalid_xml(self): + sch = Schema(self.xsd_string) + des = sch.deserialized(self.xml_string_invalid) + self.assertNotIsInstance(des, dict) diff --git a/test_asserts.py b/test_asserts.py new file mode 100644 index 0000000..8069cb7 --- /dev/null +++ b/test_asserts.py @@ -0,0 +1,46 @@ +# coding: utf-8 + +DICT_OBJ = dict({'a': {'b': '1', 'c': '2'}}) + +XSD = ''' + + + + + + + + + + + + + + + + + ''' + + +XML = ''' + + start + My Example Setup + Welcome to this little demo application. + + Wizard Page One + + ''' + +XML_INVALID = ''' + + start + My Example Setup + Welcome to this little demo application. + + Wizard Page One + + '''