def xtestObjectReplacementHack(self): buildTestFile = True fs = FileSystem(".") converter = oooConverter() fromBookFile = noMathtype toBookFile = "testData/testObjectReplacementHackResult.odt" fs.delete(toBookFile) self.assertFalse(fs.isFile(toBookFile)) docs = [ (sample_mathtype, ""), (noMathtype, ""), \ (sample_mathtypeAndNoMathType, ""), (linkfile, "") ] try: # build test infomation converter.buildBook(fromBookFile, docs, toBookFile, baseUrl="http://localhost:8000", title=None) self.assertTrue(fs.isFile(toBookFile)) xmlString = """<root xmlns:draw='urn:oasis:names:tc:opendocument:xmlns:drawing:1.0' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:text='urn:oasis:names:tc:opendocument:xmlns:text:1.0' xmlns:svg='urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0'>""" # now assert the the toBookFile contains all the orginal enbedded objects. tempFs = fs.unzipToTempDirectory(toBookFile) xml = IceCommon.Xml(tempFs.absolutePath("content.xml"), nsList) nodes = xml.getNodes("//draw:frame") if buildTestFile == True: print "Building expectedxmlString.xml" for node in nodes: xmlString += str(node) xmlString += "</root>" fs.writeFile("testData/expectedxmlString.xml", xmlString) else: #Compare current Book xml with the expected xml result xmlExpected = IceCommon.Xml("testData/expectedxmlString.xml", nsList) expectedNodes = xmlExpected.getNodes("//draw:frame") for node, expectedNode in zip(nodes, expectedNodes): #Hack: for now just remove namespaces for testing nodeStr = str(node).replace(":", "_") expectedNodeStr = str(expectedNode).replace(":", "_") self.assertSameXml(nodeStr, expectedNodeStr, \ "Nodes are not the same!") xmlExpected.close() finally: xml.close() tempFs.delete()
def test_getPreviousItem(): print "test_getPreviousItem()" mockOrg = mockOrganization() xml = IceCommon.Xml(nestedItemTestXml) nestedItemTestNode = xml.getRootNode() item = imsItem(mockOrg, itemXmlNode=nestedItemTestNode) mockOrg.addItem(item) xml.close() print "====" print mockOrg.__class__.__name__ print mockOrg.parentItem print mockOrg print "====" aItem = item.getNextItem().getNextItem() print "aItem=", aItem.title prevItem = aItem.getPreviousItem() print "prevItem=", prevItem.title assert prevItem.title == "Module 1 About Stuff" prevItem = prevItem.getPreviousItem() print "prevItem=", prevItem.title assert prevItem.title == "Study Guide" print "---" print prevItem.__class__.__name__ print prevItem.parentItem print "---" prevItem = prevItem.getPreviousItem() print prevItem print "-----"
def xtestExternalLinkReport(self): manifestItem = {"/": ["Package Title", 1, 0], "one.odt": ["One Title", 0, "one.htm"]} rep = MockRep(self.iceContext, {"/one.htm":""}, {"/one.htm":{"http://www.python.org":"linkText"}}, manifest=manifestItem) checker = CourseLinkCheck(self.iceContext) report = checker.report("/") # print report # print "----" dom = IceCommon.Xml(report) try: h1 = dom.getNode("//h1[1]") h1msg = h1.getNextSibling().content self.assertEqual(h1msg, "\nNo invalid internal links\n") h1 = dom.getNode("//h1[2]") #print str(h1) nextSibling = h1.getNextSibling() if nextSibling.getType()=="text": nextSibling = nextSibling.getNextSibling() listItem = nextSibling.getNode("li[1]") #print str(listItem) self.assertEqual(len(listItem.getNodes("a")), 1) self.assertEqual(listItem.getNode("a/@href").content, "/one.htm") #print h1msg #self.assertEqual(h1msg, "No external links found") finally: dom.close()
def testAssertSameXml(self): xmlStr1 = "<root><item a='2' b='1'/></root>" xmlStr2 = "<root><item b=\"1\" a='2'></item></root>" xmlStr3 = "<root><item a='2' b='11'/></root>" t = self.test # should assert to being the same t.assertSameXml("<root/>", "<root></root>") t.assertSameXml(xmlStr1, xmlStr2) xml = IceCommon.Xml(xmlStr1) t.assertSameXml(xml, xmlStr1) t.assertSameXml(xml, xmlStr2) t.assertSameXml(xmlStr2, xml) xml.close() # should raise an AssertionError msg = self.__expectAssertionError(None, None) expectedMsg = 'Xml not the same!\n\t(not XML data) actual==None and expected==None!' self.assertEqual(msg, expectedMsg) #print repr(msg) msg = self.__expectAssertionError("", "") expectedMsg = 'Xml not the same!\n\tActual is not well-formed XML! (or is not an xmlString or dom/node)' self.assertEqual(msg, expectedMsg) #print repr(msg) msg = self.__expectAssertionError(None, "<root/>") expectedMsg = 'Xml not the same!\n\tactual==None and actual!=expected!' self.assertEqual(msg, expectedMsg) #print repr(msg) msg = self.__expectAssertionError(xmlStr1, xmlStr3) expectedMsg = 'Xml not the same!\n\t <root>\n\n- <item a="2" b="1"></item>\n\n+ <item a="2" b="11"></item>\n\n? +\n\n </root>\n\nactual = \'<root>\n <item a="2" b="1"></item>\n</root>\'\nexpected = \'<root>\n <item a="2" b="11"></item>\n</root>\'' self.assertEqual(msg, expectedMsg)
def test_load(): print "test_load()" item = imsItem(mockOrg) xml = IceCommon.Xml(simpleItemTestXml) simpleItemTestNode = xml.getRootNode() item.load(simpleItemTestNode) assertSameXml(str(item), str(simpleItemTestNode)) xml.close() xml = IceCommon.Xml(nestedItemTestXml) nestedItemTestNode = xml.getRootNode() item.load(nestedItemTestNode) assertSameXml(str(item), str(nestedItemTestNode)) xml.close()
def test_serialize(): print "test_serialize()" xml = IceCommon.Xml(simpleItemTestXml) simpleItemTestNode = xml.getRootNode() item = imsItem(mockOrg, itemXmlNode=simpleItemTestNode) node = item.serialize(xml) assertSameXml(str(node), simpleItemTestXml) xml.close()
def getTestOrg(): parent = mockParent() org = imsOrganization(parent) xml = IceCommon.Xml(organizationXmlStr) node = xml.getRootNode() org.load(node) xml.close() return org
def test_serialize(): # serialize(xml) - (overriden) org = getTestOrg() xml = IceCommon.Xml("<root/>") orgNode = org.serialize(xml) assertSameXml(str(orgNode), organizationXmlStr) xml.close()
def processTest(name, xsltSrc, xmlSrc, expectedXml): print "--- Test: '%s' ---" % name xslt = xslt_util.xslt(xsltSrc) r = "<root" for ns in nsList: r += " xmlns:" + ns[0] + '="' + ns[1] + '"\n' r += ">\n" r += xmlSrc + "\n</root>" xml = IceCommon.Xml(r, nsList) newXml = xml.applyXslt(xslt) xslt.close() xml.close() expected = expectedXml.replace("utfx:expected", "body").replace(' validate="no"', "") html = """<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"></meta> <title> Untitled </title> <style type="text/css" xml:space="preserve">table {border-spacing: 0;empty-cells: show;} </style> </head> <body> </body> </html>""" xml = IceCommon.Xml(expected, nsList) import diff_util same = diff_util.sameXml(newXml.getNode("//body"), xml.getNode("//body"), False) print "Same=", same if same is False: for node in newXml.getNode("//body").getChildren(): if node.getType() != "text": print node print for node in xml.getNode("//body").getChildren(): if node.getType() != "text": print node newXml.close() xml.close() print "--- Done ---\n"
def test_title(): print "test_title" item = imsItem(mockOrg) xml = IceCommon.Xml(simpleItemTestXml) simpleItemTestNode = xml.getRootNode() assert item.title == "" item.load(simpleItemTestNode) assert item.title == "Introduction" item.title = "test" assert item.title == "test" xml.close()
def formatPart(xmlStr, match, format=True): xml = IceCommon.Xml(xmlStr, [("", "http://www.w3.org/1999/xhtml"), ("html", "http://www.w3.org/1999/xhtml")]) matchContent = xml.getNode(match) s = str(matchContent) if format: pr = prettyPrint(s) pr = pr[pr.find("\n") + 1:] else: pr = s xml.close() return pr
def test_load_serialize(): parent = mockParent() orgs = imsOrganizations(parent) xml = IceCommon.Xml(orgsXmlTestStr) orgs.load(xml.getRootNode()) orgsNode = orgs.serialize(xml) expected = """<organizations default="default"><mockOrganization identifier="default"/><mockOrganization identifier="test-id"/></organizations>""" assertSameXml(orgsNode, expected) xml.close()
def test_getItem(): print "test_getItem()" xml = IceCommon.Xml(nestedItemTestXml) nestedItemTestNode = xml.getRootNode() item = imsItem(mockOrg, itemXmlNode=nestedItemTestNode) childItems = item.getAllChildItems() for childItem in childItems: i = item.getItem(childItem.identifier) assert i is childItem xml.close() assert item.getItem(item.identifier) is item
def test_resource(): print "test_resource" item = imsItem(mockOrg) xml = IceCommon.Xml(simpleItemTestXml) simpleItemTestNode = xml.getRootNode() item.load(simpleItemTestNode) id = simpleItemTestNode.getAttribute("identifierref") resource = item.resource res = mockOrg.resources[id] assert resource is res xml.close()
def test_isWordDoc(): print "test_isWordDoc" item = imsItem(mockOrg) xml = IceCommon.Xml(simpleItemTestXml) simpleItemTestNode = xml.getRootNode() item.load(simpleItemTestNode) assert item.isWordDoc == False item.resource.isWordDoc = True assert item.isWordDoc == True xml.close()
def test_getItemByIdRef(): # NOTE: returns the first item found with this idRef print "test_getItemByIdRef()" xml = IceCommon.Xml(nestedItemTestXml) nestedItemTestNode = xml.getRootNode() item = imsItem(mockOrg, itemXmlNode=nestedItemTestNode) childItems = item.getAllChildItems() for childItem in childItems: i = item.getItemByIdRef(childItem.identifierRef) assert i is childItem xml.close() assert item.getItemByIdRef(item.identifierRef) is item
def read(self): file = self.relPath data = None if file.endswith("/manifest.xml"): dom = IceCommon.Xml("<dummy xmlns='http://www.imsglobal.org/xsd/imscp_v1p1'/>", \ [("x", "http://www.imsglobal.org/xsd/imscp_v1p1")]) rNode = dom.getRootNode() resNode = dom.createElement("resource") rNode.addChild(resNode) for name in self.contents.keys(): fNode = dom.createElement("file", href=name) resNode.addChild(fNode) data = str(dom) dom.close() return data
def xtestImageObject(self): fs = FileSystem(".") fromBookFile = noMathtype tempFs = fs.unzipToTempDirectory(fromBookFile) xml = IceCommon.Xml(tempFs.absolutePath("content.xml"), nsList) nodes = xml.getNodes("//draw:frame") #nodes = xml.getNodes("//draw:frame[draw:object-ole]") for node in nodes: objectOleNode = node.getNode("*[local-name()='object-ole']") self.assertFalse(objectOleNode == None, "Only Image File not Object") xml.close()
def test_addItemBefore(): print "test_addItemBefore()" item1 = imsItem(mockOrg) item1.title = "One" item2 = imsItem(mockOrg) item2.title = "Two" item3 = imsItem(item2) item3.title = "Three" item1.addItem(item2) item1.addItemBeforeItem(item3, item2) xml = IceCommon.Xml("<root/>") xml.addChild(item1.serialize(xml)) assert xml.getContent("/item/title") == "One" assert xml.getContent("/item/item/title") == "Three" assert xml.getContent("/item/item[2]/title") == "Two" xml.close()
def xtestEmptyReport(self): rep = MockRep(self.iceContext) checker = CourseLinkCheck(self.iceContext) report = checker.report("/") dom = IceCommon.Xml(report) try: h1 = dom.getNode("//h1[1]") h1msg = h1.getNextSibling().content #print h1msg self.assertEqual(h1msg, "\nNo invalid internal links\n") h1 = dom.getNode("//h1[2]") h1msg = h1.getNextSibling().content #print h1msg self.assertEqual(h1msg, "\nNo external links found\n") finally: dom.close()
def test_itemInit(): print "test_itemInit()" item = imsItem(mockOrg) xmlStr = str(item) assert xmlStr == """<item identifierref="" identifier="" isvisible="True"><title></title></item>""" xml = IceCommon.Xml(simpleItemTestXml) simpleItemTestNode = xml.getRootNode() item = imsItem(mockOrg, itemXmlNode=simpleItemTestNode) assertSameXml(str(item), str(simpleItemTestNode)) resource = mockOrg.resources.testGetResource(0) item = imsItem(mockOrg, resource=resource) expected = """<item identifierref="61259e595362bef92c48bbc3a018263c" identifier="mock-61259e595362bef92c48bbc3a018263c-1" isvisible="True"><title>/test/intro/introduction.htm-title</title></item>""" print (str(item)) assertSameXml(str(item), expected) xml.close()
def test_load_serialize(): parent = mockParent() ress = ImsResources(parent) xml = IceCommon.Xml(resourcesXmlStr) ress.load(xml.getRootNode()) href = "intro/assessment.htm" id = "1d8994d66d3f5774b5d92b143bfd2daa" assert ress.containsResource(href) assert ress.getResourceByHref(href) is not None assert ress[id] is not None ressXmlStr = """<resources><resource href="intro/assessment.htm" identifier="1d8994d66d3f5774b5d92b143bfd2daa" mock="True"/></resources>""" assert str(ress) == ressXmlStr ressNode = ress.serialize(xml) assertSameXml(ressNode, ressXmlStr) xml.close()
def read(self, file): if file.endswith("/manifest.xml"): dom = IceCommon.Xml("<dummy xmlns='http://www.imsglobal.org/xsd/imscp_v1p1'/>", \ [("x", "http://www.imsglobal.org/xsd/imscp_v1p1")]) #hrefs = dom.getContents("//x:resource/x:file/@href") rNode = dom.getRootNode() resNode = dom.createElement("resource") rNode.addChild(resNode) for name in self.contents.keys(): fNode = dom.createElement("file", href=name) resNode.addChild(fNode) data = str(dom) #print data dom.close() return data else: return self.contents.get(file)
def test_isVisible(): print "test_isVisible" item = imsItem(mockOrg) xml = IceCommon.Xml(simpleItemTestXml) simpleItemTestNode = xml.getRootNode() item.load(simpleItemTestNode) assert item.isVisible == True simpleItemTestNode.setAttribute("isvisible", "False") item.load(simpleItemTestNode) assert item.isVisible == False item.isVisible = True assert item.isVisible == True item.isVisible = False assert item.isVisible == False xml.close()
def test_setAsDefaultItem(): print "test_setAsDefaultItem()" mockOrg = mockOrganization() xml = IceCommon.Xml(nestedItemTestXml) nestedItemTestNode = xml.getRootNode() item = imsItem(mockOrg, itemXmlNode=nestedItemTestNode) mockOrg.addItem(item) xml.close() children = item.getAllChildItems() child = children[3] item.setAsDefaultItem() assert item.isDefaultItem child.setAsDefaultItem() assert child.isDefaultItem assert item.isDefaultItem==False item.setAsDefaultItem() assert child.isDefaultItem==False
def test_getNextItem(): print "test_getNextItem()" #lookDown=True mockOrg = mockOrganization() xml = IceCommon.Xml(nestedItemTestXml) nestedItemTestNode = xml.getRootNode() item = imsItem(mockOrg, itemXmlNode=nestedItemTestNode) mockOrg.addItem(item) xml.close() nextItem = item.getNextItem() assert nextItem.title=="Module 1 About Stuff" nextItem = nextItem.getNextItem() assert nextItem.title=="Module 2 More about stuff" nextItem = nextItem.getNextItem() assert nextItem.title=="Module 3 Even more about stuff" nextItem = nextItem.getNextItem() assert nextItem is None nextItem = item.getNextItem(lookDown=False) assert nextItem is None
def processFiles(testName): items = [] files = getTestFiles() for file in files: #print "file = ", file xml = IceCommon.Xml(file, [("utfx", "http://utfx.org/test-definition")]) nodes = xml.getNodes("//utfx:name") for node in nodes: name = node.getContent() if name.startswith(testName): #utfx:stylesheet src="ooo2xhtml.xsl" xsltSrc = xml.getNode("*/utfx:stylesheet").getAttribute("src") pNode = node.getParent() source = pNode.getNode("*/*[local-name()='source']") expected = pNode.getNode("*/*[local-name()='expected']") n = xml.createElement("office:body") n.addChildren(source.getChildren()) source = str(n) n.delete() expected = str(expected) items.append((xsltSrc, source, expected, name)) xml.close() return items
def testAll(display=10, testName=None): print testCount = 0 failedCount = 0 skipedCount = 0 testFiles = getListOfTestFiles() #print testFiles print testFiles for testFile in testFiles: print "TestFile - '%s'" % testFile xml = IceCommon.Xml(testFile, [("x", "http://www.w3.org/1999/xhtml")]) tests = xml.getNodes("/testData/tests/test") for test in tests: name = test.getAttribute("name") if testName != None and not name.startswith(testName): continue skip = test.getAttribute("skip") format = test.getAttribute("normalize-white-spaces") format = format.lower() format = format == "true" if skip is not None and skip.lower() == "true": print " Name = '%s' --- Skiped ---" % name skipedCount += 1 testCount += 1 continue testCount += 1 source = test.getNode("source") expected = test.getNode("expected") match = expected.getAttribute("match") if match is None: match = "/" expected = test.getNode("expected/*") source = str(source) source = source.replace("<source>", "<source%s>" % nsStr) #print str(source) #print " Name = '%s' (match='%s')" % (name, match) sio = StringIO() stdout = sys.stdout sys.stdout = sio o = ooo2xhtml.Ooo2xhtml(IceCommon.IceContext) o.resetIDCount() o.process(source) #result = str(o) result = o.serialize() sys.stdout = stdout result = result[result.find("<html"):] result = formatPart(result, match, format) expected = formatPart(str(expected), "/*", format) r = testForDiff(name, result, expected, sio, display) if r == False: if display > 0: display -= 1 failedCount += 1 if False: xsltR = xsltResult(source) print xsltR xml.close() if failedCount == 0 and skipedCount == 0: print "Total: %s Tests and all passed OK (%s skipped)" % (testCount, skipedCount) else: print "Total: %s Tests, %s passed, %s failed, %s skipped" % ( testCount, testCount - failedCount - skipedCount, failedCount, skipedCount)
def testLinkReport(self): # contents links manifestItem = {"/": ["Package Title", 1, 0], "one.odt": ["One Title", 0, "one.htm"] } rep = MockRep(self.iceContext, {"/one.htm":""}, {"/one.htm": { "/one.htm":"localOK", "/bad.htm":"localBad", # Bad "one.htm":"relativeLocalOK", "bad.htm":"relativeLocalBad", # Bad "news://somewhere.com":"newLink", #External "mailto:[email protected]":"mailtoLink", #External "http://www.python.org":"pythonLink", #External } }, manifest=manifestItem) checker = CourseLinkCheck(self.iceContext) report = checker.report("/") # print "report='%s'" % report dom = IceCommon.Xml(report) try: h1 = dom.getNode("//h1[1]") nextSibling = h1.getNextSibling() if nextSibling.getType()=="text": nextSibling = nextSibling.getNextSibling() listItems = nextSibling.getNodes("li") #print str(h1) #print str(nextSibling) #print nextSibling.content #for listItem in listItems: # print "-" # print str(listItem) #print "---\n" self.assertEqual(h1.content, "Invalid internal links") self.assertEqual(len(listItems), 2) self.assertEqual(listItems[0].content, '/bad.htm in these pages: one.htm with the link text "relativeLocalBad". ') self.assertEqual(listItems[1].content, '/bad.htm in these pages: one.htm with the link text "localBad". ') h1 = dom.getNode("//h1[2]") nextSibling = h1.getNextSibling() if nextSibling.getType()=="text": nextSibling = nextSibling.getNextSibling() listItems = nextSibling.getNodes("li") #print str(h1) #print str(nextSibling) #print nextSibling.content #for listItem in listItems: # print "-" # print str(listItem) #print "---\n" self.assertEqual(h1.content, "External links") self.assertEqual(len(listItems), 3) self.assertEqual(listItems[0].content, 'news://somewhere.com in these pages: one.htm with the link text "newLink". ') self.assertEqual(listItems[1].content, 'mailto:[email protected] in these pages: one.htm with the link text "mailtoLink". ') self.assertEqual(listItems[2].content, '/one.htm in these pages: one.htm with the link text "pythonLink". ') finally: dom.close()