示例#1
0
    def _get_xsd_import_name(self):
        """Returns the name of the documents xsd for building the correct
        schemaLocation statement
        """
        gen = XSDGenerator()
        tmp_dir_name = tempfile.mkdtemp()
        file_name = gen.write_model_xsd_file(self.instance.__class__, tmp_dir_name)
        shutil.rmtree(tmp_dir_name)

        return os.path.basename(file_name)
示例#2
0
 def __init__(self, model, custom_ns_map=None):
     self.model = model
     self.custom_ns_map = custom_ns_map
     self.xsd_gen = XSDGenerator(self.custom_ns_map)
     self.xsd_list = None
示例#3
0
class ModelOpener(object):
    """Simple Interface for simple XML and XSD generation"""

    def __init__(self, model, custom_ns_map=None):
        self.model = model
        self.custom_ns_map = custom_ns_map
        self.xsd_gen = XSDGenerator(self.custom_ns_map)
        self.xsd_list = None

    def validate_instance(self, instance):
        # 1) Generate the schemas, due to the possibility that there may be more than one xsd involved will need to write these to a temp file
        # -> check to see if the files have already been written, if not write them to a temp location

        xsd_dir = None
        temp_used = False
        if not self.xsd_list:
            temp_used = True
            xsd_dir = tempfile.mkdtemp()
            self.write_schemas(xsd_dir)
        else:
            xsd_dir = os.path.dirname(self.xsd_list[0])

        xsd_full_path = self.xsd_gen.write_model_xsd_file(self.model, xsd_dir)

        with open(xsd_full_path) as file_handler:
            schema_doc = etree.parse(file_handler)

        model_xsd = etree.XMLSchema(schema_doc)

#        xsd_name = self.xsd_gen.__get_xsd_file_name(self.model, None)
#        xsd_full_path = os.path.join(xsd_dir, xsd_name)

        # 2) Build a lxml XML Schema.
#        model_xsd = self.get_schema_etree()


        # 3) Write the instance XML to a stream and then parse that into an lxml etree
        doc = etree.parse(StringIO(self.get_instance_xml(instance)))
        # 4) Run lxml assertValid. If it is invalid the capture the log

        valid = model_xsd.validate(doc)
        if temp_used:
            shutil.rmtree(xsd_dir)

        # 5) Return a tuple containing the validation state and the log.
        return valid, model_xsd.error_log
    

    def __instance_of_model(self, instance):
        """Validates that the instance is indeed and instance of the Model
        class passed in the init method
        """
        if not isinstance(instance, self.model):
            msg = """Expected instance of {0:>s} but the instance belongs to
            the class {1:>s}""".format(
                self.model.__name__,
                instance.__class__.__name__)

            raise TypeError(msg)


    def __get_instance_converter(self, instance):
        """Generates an instance of util.model_utils.ClassModelConverter for
        the given instance.
        """

        self.__instance_of_model(instance)
        return ClassModelConverter(instance, custom_nsmap=self.custom_ns_map)

    def get_instance_xml(self, instance):
        """Returns a xml string for the given model instance
        """

        return self.__get_instance_converter(instance).to_xml()

    def get_instance_etree(self, instance):
        """Returns a lxml.etre._Element instance for the given model instance.
        """

        return self.__get_instance_converter(instance).to_etree()

    def write_instance_xml(self, instance, destination_file):
        """ Writes an xml file to the given destination for the given model
        instance
        """

        return self.__get_instance_converter(
            instance).to_file(destination_file
            )

    def get_schema_xml(self):
        """Returns a string representation of an XSD for the specified model.
        """
        return self.xsd_gen.get_model_xsd(self.model)

    def get_schema_etree(self):
        xsd_string = StringIO(self.get_schema_xml())
        xsd_doc = etree.parse(xsd_string)

        return etree.XMLSchema(xsd_doc)

    def write_schemas(self, folder_path):
        """Writes the XML Schema for the model.
        
        This method also generates all schemas that the model may be importing.

        @param folder_path:  The destination path for the XML Schemas
        """
        self.xsd_list = self.xsd_gen.write_all_models(self.model, folder_path)
        return self.xsd_list
示例#4
0
 def setUp(self):
     self.xsd_gen = XSDGenerator()
     self.xsd_gen.model_schema_nsmap[
         "DoubleNestedModel"] = "DoubleNestedModel"
     self.xsd_gen.model_schema_nsmap["NestedModel"] = "NestedModel"
     self.xsd_gen.model_schema_nsmap["SimpleModel"] = "SimpleModel"
示例#5
0
class TestXsdGen(unittest.TestCase):
    def setUp(self):
        self.xsd_gen = XSDGenerator()
        self.xsd_gen.model_schema_nsmap[
            "DoubleNestedModel"] = "DoubleNestedModel"
        self.xsd_gen.model_schema_nsmap["NestedModel"] = "NestedModel"
        self.xsd_gen.model_schema_nsmap["SimpleModel"] = "SimpleModel"

    def tearDown(self):
        for f in glob('*.xsd'):
            os.unlink(f)

    def named_element_check(self, element):
        name_found = False
        for el in element.iter():
            if el.tag.find('element') != -1 and el.attrib['name'] == 'text':
                name_found = True
                break

        return name_found

    def test_simple_xsd(self):
        simple_xsd = self.xsd_gen.get_model_xsd(SimpleModel, pretty_print=True)

        self.xsd_gen.write_model_xsd_file(SimpleModel, ".")

        xsd_element = etree.XML(simple_xsd)

        self.assertEquals(xsd_element.attrib['targetNamespace'],
                          SimpleModel.get_namespace())

        name_found = self.named_element_check(xsd_element)

        self.assertTrue(name_found)

    def test_nested_xsd(self):
        nested_xsd = self.xsd_gen.get_model_xsd(NestedModel,
                                                pretty_print=False)

        tree = etree.XML(nested_xsd)

        self.assertEquals(tree.attrib['targetNamespace'],
                          NestedModel.get_namespace())

    def test_double_nested_xsd(self):
        double_xsd = self.xsd_gen.get_model_xsd(DoubleNestedModel,
                                                pretty_print=True)

        tree = etree.XML(double_xsd)

        self.assertEquals(tree.attrib['targetNamespace'],
                          DoubleNestedModel.get_namespace())

    def test_customized_xms(self):
        class Complex(ClassModel):
            simple = SimpleModel.customize(min_occurs=11,
                                           max_occurs="unbounded",
                                           nillable=False)
            bobby = Integer(nillable=False, min_occurs=10, max_occurs=20002)

        class ExtraComplex(ClassModel):
            cp = Complex.customize(min_occurs=8,
                                   max_occurs=1010,
                                   nillable=False,
                                   foo="bar")

        xsd = self.xsd_gen.get_model_xsd(ExtraComplex, pretty_print=True)
        assert xsd

    def test_xsd_file(self):
        file_name = self.xsd_gen.write_model_xsd_file(SimpleModel, '.')
        self.assertTrue(os.path.isfile(file_name))

    def test_get_all_models(self):
        ret_list = self.xsd_gen.get_all_models_xsd(DoubleNestedModel,
                                                   pretty_print=True)

        self.assertEquals(len(ret_list), 3)

    def test_write_all_models(self):
        ret_list = self.xsd_gen.write_all_models(DoubleNestedModel, '.')
        self.assertEquals(len(ret_list), 3)
        for file in ret_list:
            self.assertTrue(os.path.isfile(file))
示例#6
0
 def setUp(self):
     self.xsd_gen = XSDGenerator()
     self.xsd_gen.model_schema_nsmap[
         "DoubleNestedModel"] = "DoubleNestedModel"
     self.xsd_gen.model_schema_nsmap["NestedModel"] = "NestedModel"
     self.xsd_gen.model_schema_nsmap["SimpleModel"] = "SimpleModel"
示例#7
0
class TestXsdGen(unittest.TestCase):
    def setUp(self):
        self.xsd_gen = XSDGenerator()
        self.xsd_gen.model_schema_nsmap[
            "DoubleNestedModel"] = "DoubleNestedModel"
        self.xsd_gen.model_schema_nsmap["NestedModel"] = "NestedModel"
        self.xsd_gen.model_schema_nsmap["SimpleModel"] = "SimpleModel"

    def tearDown(self):
        for f in glob('*.xsd'):
            os.unlink(f)

    def named_element_check(self, element):
        name_found = False
        for el in element.iter():
            if el.tag.find('element') != -1 and el.attrib['name'] == 'text':
                name_found = True
                break

        return name_found

    def test_simple_xsd(self):
        simple_xsd = self.xsd_gen.get_model_xsd(SimpleModel, pretty_print=True)

        self.xsd_gen.write_model_xsd_file(SimpleModel, ".")

        xsd_element = etree.XML(simple_xsd)

        self.assertEquals(xsd_element.attrib['targetNamespace'],
                          SimpleModel.get_namespace())

        name_found = self.named_element_check(xsd_element)

        self.assertTrue(name_found)

    def test_nested_xsd(self):
        nested_xsd = self.xsd_gen.get_model_xsd(
            NestedModel, pretty_print=False)

        tree = etree.XML(nested_xsd)

        self.assertEquals(tree.attrib['targetNamespace'],
                          NestedModel.get_namespace())

    def test_double_nested_xsd(self):
        double_xsd = self.xsd_gen.get_model_xsd(
            DoubleNestedModel, pretty_print=True)

        tree = etree.XML(double_xsd)

        self.assertEquals(tree.attrib['targetNamespace'],
                          DoubleNestedModel.get_namespace())

    def test_customized_xms(self):
        class Complex(ClassModel):
            simple = SimpleModel.customize(
                min_occurs=11, max_occurs="unbounded", nillable=False)
            bobby = Integer(nillable=False, min_occurs=10, max_occurs=20002)

        class ExtraComplex(ClassModel):
            cp = Complex.customize(
                min_occurs=8, max_occurs=1010, nillable=False, foo="bar")

        xsd = self.xsd_gen.get_model_xsd(ExtraComplex, pretty_print=True)
        assert xsd

    def test_xsd_file(self):
        file_name = self.xsd_gen.write_model_xsd_file(SimpleModel, '.')
        self.assertTrue(os.path.isfile(file_name))

    def test_get_all_models(self):
        ret_list = self.xsd_gen.get_all_models_xsd(
            DoubleNestedModel, pretty_print=True)

        self.assertEquals(len(ret_list), 3)

    def test_write_all_models(self):
        ret_list = self.xsd_gen.write_all_models(DoubleNestedModel, '.')
        self.assertEquals(len(ret_list), 3)
        for file in ret_list:
            self.assertTrue(os.path.isfile(file))
 def setUp(self):
     self.xsd_gen = XSDGenerator()
示例#9
0
 def setUp(self):
     self.xsd_gen = XSDGenerator()
示例#10
0
class TestXsdGen(unittest.TestCase):
    def setUp(self):
        self.xsd_gen = XSDGenerator()

    def tearDown(self):
        for f in glob('*.xsd'):
            os.unlink(f)

    def named_element_check(self, element):
        name_found = False
        for el in element.iter():
            if el.tag.find('element') != -1 and el.attrib['name'] == 'text':
                name_found = True
                break

        return name_found

    def test_simple_xsd(self):
        simple_xsd = self.xsd_gen.get_model_xsd(SimpleModel,
                                                pretty_print=False)

        xsd_element = etree.XML(simple_xsd)

        self.assertEquals(xsd_element.attrib['targetNamespace'],
                          SimpleModel.get_namespace())

        name_found = self.named_element_check(xsd_element)

        self.assertTrue(name_found)

    def test_nested_xsd(self):
        nested_xsd = self.xsd_gen.get_model_xsd(NestedModel,
                                                pretty_print=False)

        tree = etree.XML(nested_xsd)

        self.assertEquals(tree.attrib['targetNamespace'],
                          NestedModel.get_namespace())

    def test_double_nested_xsd(self):
        double_xsd = self.xsd_gen.get_model_xsd(DoubleNestedModel,
                                                pretty_print=False)

        tree = etree.XML(double_xsd)

        self.assertEquals(tree.attrib['targetNamespace'],
                          DoubleNestedModel.get_namespace())

    def test_xsd_file(self):
        file_name = self.xsd_gen.write_model_xsd_file(SimpleModel, '.')
        self.assertTrue(os.path.isfile(file_name))

    def test_get_all_models(self):
        ret_list = self.xsd_gen.get_all_models_xsd(DoubleNestedModel,
                                                   pretty_print=True)

        self.assertEquals(len(ret_list), 3)

    def test_write_all_models(self):
        ret_list = self.xsd_gen.write_all_models(DoubleNestedModel, '.')
        self.assertEquals(len(ret_list), 3)
        for file in ret_list:
            self.assertTrue(os.path.isfile(file))
示例#11
0
class TestXsdGen(unittest.TestCase):
    def setUp(self):
        self.xsd_gen = XSDGenerator()

    def tearDown(self):
        for f in glob('*.xsd'):
            os.unlink(f)

    def named_element_check(self, element):
        name_found = False
        for el in element.iter():
            if el.tag.find('element') != -1 and el.attrib['name'] == 'text':
                name_found = True
                break

        return name_found

    def test_simple_xsd(self):
        simple_xsd = self.xsd_gen.get_model_xsd(
            SimpleModel,
            pretty_print=False
        )

        xsd_element = etree.XML(simple_xsd)

        self.assertEquals(xsd_element.attrib['targetNamespace'],
            SimpleModel.get_namespace()
        )

        name_found = self.named_element_check(xsd_element)

        self.assertTrue(name_found)

    def test_nested_xsd(self):
        nested_xsd = self.xsd_gen.get_model_xsd(
            NestedModel,
            pretty_print=False
        )

        tree = etree.XML(nested_xsd)

        self.assertEquals(
            tree.attrib['targetNamespace'],
            NestedModel.get_namespace()
        )

    def test_double_nested_xsd(self):
        double_xsd = self.xsd_gen.get_model_xsd(
                DoubleNestedModel,
                pretty_print=False
        )

        tree = etree.XML(double_xsd)

        self.assertEquals(
            tree.attrib['targetNamespace'],
            DoubleNestedModel.get_namespace()
        )

    def test_xsd_file(self):
        file_name = self.xsd_gen.write_model_xsd_file(SimpleModel, '.')
        self.assertTrue(os.path.isfile(file_name))

    def test_get_all_models(self):
        ret_list = self.xsd_gen.get_all_models_xsd(DoubleNestedModel, pretty_print=True)

        self.assertEquals(len(ret_list), 3)

    def test_write_all_models(self):
        ret_list = self.xsd_gen.write_all_models(DoubleNestedModel, '.')
        self.assertEquals(len(ret_list), 3)
        for file in ret_list:
            self.assertTrue(os.path.isfile(file))