class TestOWLExporter(PloneOntologyTestCase):
    """Test the OWL export."""

    def afterSetUp(self):
        self.setRoles(['Manager'])

        self.exporter = OWLExporter()

    def testOWLExportGenerateClassDefault(self):
        self.exporter.generateClass("foo")
        cl = self.exporter.getDOM().documentElement.lastChild

        self.assertEqual('foo', cl.getAttribute('rdf:ID'))

    def testOWLExportGenerateClassSuperClasses(self):
        self.exporter.generateClass("foo", superclasses = ["bar", "blaz"])
        cl = self.exporter.getDOM().documentElement.lastChild

        super = cl.getElementsByTagName('rdfs:subClassOf')
        names = [c.getAttribute('rdf:resource') for c in super]
        names.sort()

        self.assertEqual(['#bar', '#blaz'], names)

    def testOWLExportGenerateClassLabels(self):
        self.exporter.generateClass("foo", labels = [('de','Honig'), ('en','honey')])
        cl = self.exporter.getDOM().documentElement.lastChild

        labels = cl.getElementsByTagName('rdfs:label')
        res = []
        for l in labels:
            res.append((l.getAttribute('xml:lang'), l.firstChild.data))

        res.sort()

        self.assertEqual([('de','Honig'), ('en', 'honey')], res)

    def testOWLExportGenerateClassDCAttributes(self):
        self.exporter.generateClass("foo", labels=[('en',"bar")], descriptions=[('en',"blaz")])
        cl = self.exporter.getDOM().documentElement.lastChild

        title = cl.getElementsByTagName('rdfs:label')
        self.assertEqual(1, title.length)
        self.assertEqual("bar", title.item(0).firstChild.data)

        desc = cl.getElementsByTagName('dc:description')
        self.assertEqual(1, desc.length)
        self.assertEqual("blaz", desc.item(0).firstChild.data)

    def testOWLExportGenerateEquivalentClass(self):
        self.exporter.generateEquivalentClass("foo", "bar")
        cl = self.exporter.getDOM().documentElement.lastChild

        self.assertEqual("#foo", cl.getAttribute('rdf:about'))

        ecl = cl.getElementsByTagName('owl:equivalentClass')
        self.assertEqual(1, ecl.length)
        self.assertEqual("#bar", ecl.item(0).getAttribute('rdf:resource'))

    def testOWLExportEnsureEntities(self):
        self.exporter.ensureEntities()

        self.assert_(self.exporter.getEntities().has_key('owl'))
        self.assert_(self.exporter.getEntities().has_key('nip'))

    def testOWLExportGenerateObjectPropertyDefault(self):
        self.exporter.generateObjectProperty("foo")
        prop = self.exporter.getDOM().documentElement.lastChild

        self.assertEqual("foo", prop.getAttribute("rdf:ID"))

    def testOWLExportGenerateObjectPropertyTypes(self):
        self.exporter.generateObjectProperty("foo", types=["bar", "blaz"])
        prop = self.exporter.getDOM().documentElement.lastChild

        types = prop.getElementsByTagName('rdf:type')
        names = [x.getAttribute('rdf:resource') for x in types]
        names.sort()

        self.assertEqual(["bar", "blaz"], names)

    def testOWLExportGenerateObjectPropertyInverses(self):
        self.exporter.generateObjectProperty("foo", inverses=["bar", "blaz"])
        prop = self.exporter.getDOM().documentElement.lastChild

        types = prop.getElementsByTagName('owl:inverseOf')
        names = [x.getAttribute('rdf:resource') for x in types]
        names.sort()

        self.assertEqual(["#bar", "#blaz"], names)

    def testOWLExportGenerateObjectPropertyDomains(self):
        self.exporter.generateObjectProperty("foo", domains=["bar", "blaz"])
        prop = self.exporter.getDOM().documentElement.lastChild

        types = prop.getElementsByTagName('rdfs:domain')
        names = [x.getAttribute('rdf:resource') for x in types]
        names.sort()

        self.assertEqual(["bar", "blaz"], names)

    def testOWLExportGenerateObjectPropertyRange(self):
        self.exporter.generateObjectProperty("foo", ranges=["bar", "blaz"])
        prop = self.exporter.getDOM().documentElement.lastChild

        types = prop.getElementsByTagName('rdfs:range')
        names = [x.getAttribute('rdf:resource') for x in types]
        names.sort()

        self.assertEqual(["bar", "blaz"], names)

    def testOWLExportGenerateObjectPropertyLabels(self):
        self.exporter.generateObjectProperty("foo", labels = [('de','Honig'), ('en','honey')])
        prop = self.exporter.getDOM().documentElement.lastChild

        labels = prop.getElementsByTagName('rdfs:label')
        res = []
        for l in labels:
            res.append((l.getAttribute('xml:lang'), l.firstChild.data))

        res.sort()

        self.assertEqual([('de','Honig'), ('en', 'honey')], res)

    def testOWLExportGenerateObjectPropertyDCAttributes(self):
        self.exporter.generateObjectProperty("foo", labels=[('en',"bar")], descriptions=[('en',"blaz")])
        prop = self.exporter.getDOM().documentElement.lastChild

        title = prop.getElementsByTagName('rdfs:label')
        self.assertEqual(1, title.length)
        self.assertEqual("bar", title.item(0).firstChild.data)

        desc = prop.getElementsByTagName('dc:description')
        self.assertEqual(1, desc.length)
        self.assertEqual("blaz", desc.item(0).firstChild.data)
class TestOWLImporter(PloneOntologyTestCase):
    """Test the OWL import."""

    def afterSetUp(self):
        self.setRoles(["Manager"])

        self.ct = self.portal.portal_classification

        self.exporter = OWLExporter()
        self.importer = OWLImporter(self.portal)

    def testOWLImporterObjectProperty(self):
        owl = self.exporter.getEntities()["owl"]

        self.exporter.generateObjectProperty(
            "synonymOf",
            types=[owl + "TransitiveProperty", owl + "SymmetricProperty"],
            inverses=["foo"],
            domains=[owl + "Class"],
            ranges=[owl + "Class"],
            labels=[("en", "footitle")],
            comments=[("de", "Honig"), ("en", "honey")],
            descriptions=[("en", "foodescription")],
            propertyproperties=[("nip:weight", "0.7")],
        )

        prop = self.exporter.getDOM().documentElement.lastChild

        self.importer.importObjectProperty(prop)

        try:
            rel = self.ct.getRelation("synonymOf")
        except NotFound:
            self.fail("Necessary relation not created on import.")

        self.assert_("transitive" in self.ct.getTypes("synonymOf"))
        self.assert_("symmetric" in self.ct.getTypes("synonymOf"))
        self.assertEqual(["foo"], self.ct.getInverses("synonymOf"))
        self.assertAlmostEqual(0.7, self.ct.getWeight("synonymOf"))
        # titles are used as names, labels are ignored, see owl.py
        self.assertEqual("synonymOf", rel.Title())
        self.assertEqual("foodescription", rel.Description())

    def testOWLImporterObjectPropertyIgnoreNonOWLClassDomain(self):
        owl = self.exporter.getEntities()["owl"]
        self.exporter.generateObjectProperty("foo1", domains=[owl + "Instance"], ranges=[owl + "Class"])
        prop = self.exporter.getDOM().documentElement.lastChild
        self.importer.importObjectProperty(prop)
        self.assertRaises(NotFound, self.ct.getRelation, "foo1")

    def testOWLImporterObjectPropertyIgnoreNonOWLClassRange(self):
        owl = self.exporter.getEntities()["owl"]
        self.exporter.generateObjectProperty("foo1", ranges=[owl + "Instance"], domains=[owl + "Class"])
        prop = self.exporter.getDOM().documentElement.lastChild
        self.importer.importObjectProperty(prop)
        self.assertRaises(NotFound, self.ct.getRelation, "foo1")

    def testOWLImporterObjectPropertyAccumulateNonBuiltins(self):
        owl = self.exporter.getEntities()["owl"]
        self.exporter.generateObjectProperty("authorOf", ranges=[owl + "Class"], domains=[owl + "Class"])
        prop = self.exporter.getDOM().documentElement.lastChild
        self.importer.importObjectProperty(prop)

        self.assertEquals(["authorOf"], self.importer.objectProperties())

        self.exporter.generateObjectProperty("publisher", ranges=[owl + "Class"], domains=[owl + "Class"])
        prop = self.exporter.getDOM().documentElement.lastChild
        self.importer.importObjectProperty(prop)

        props = self.importer.objectProperties()
        props.sort()

        self.assertEquals(["authorOf", "publisher"], self.importer.objectProperties())

    def testOWLImporterBuiltinProperties(self):
        try:
            self.ct.getRelation("childOf")
            self.ct.getRelation("parentOf")
            self.ct.getRelation("synonymOf")
        except NotFound:
            self.fail("At least one builtin relation is missing after creation of an importer")

    def testOWLImporterClass(self):
        self.ct.addRelation("authorOf")
        self.ct.addRelation("publisher")
        self.importer._props = ["authorOf", "publisher"]
        self.exporter.generateClass(
            "Foo",
            superclasses=["Bar", "Blaz"],
            labels=[("en", "footitle")],
            comments=[("de", "Honig"), ("en", "honey")],
            descriptions=[("en", "foodescription")],
            classproperties=[("authorOf", "Bonk"), ("publisher", "Gargle")],
        )
        cl = self.exporter.getDOM().documentElement.lastChild
        self.importer.importClass(cl)

        try:
            kw = self.ct.getKeyword("Foo")
        except NotFound:
            self.fail("Necessary keyword not created on import.")

        self.assertEqual("footitle", kw.Title())
        self.assertEqual("foodescription", kw.getKwDescription())

        try:
            self.ct.getKeyword("Bar")
            self.ct.getKeyword("Blaz")
        except NotFound:
            self.fail("Necessary keyword not created on import (superclasses).")

        super = kw.getReferences("childOf")
        super = [x.getName() for x in super]
        super.sort()

        self.assertEqual(["Bar", "Blaz"], super)

        try:
            self.ct.getKeyword("Bonk")
            self.ct.getKeyword("Gargle")
        except NotFound:
            self.fail("Necessary keyword not created on import (properties).")

        syn = kw.getReferences("authorOf")
        syn = [x.getName() for x in syn]

        self.assertEqual(["Bonk"], syn)

        syn = kw.getReferences("publisher")
        syn = [x.getName() for x in syn]

        self.assertEqual(["Gargle"], syn)

    def testOWLImporterClassEquivalentClass(self):
        foo = self.ct.addKeyword("Foo")
        bar = self.ct.addKeyword("Bar")
        self.exporter.generateEquivalentClass("Foo", "Bar")
        cl = self.exporter.getDOM().documentElement.lastChild
        self.importer.importClass(cl)

        self.assertEquals(["Bar"], [x.getName() for x in foo.getReferences("synonymOf")])