1
2
3 """
4 Test cases related to DTD parsing and validation
5 """
6
7 import unittest
8
9 from common_imports import etree, StringIO, doctest
10 from common_imports import HelperTestCase, fileInTestDir
11
15
23
25 root = etree.XML("<b/>")
26 dtd = etree.DTD(StringIO("<!ELEMENT b EMPTY>"))
27 self.assert_(dtd.validate(root))
28
30 root = etree.XML("<b><a/></b>")
31 dtd = etree.DTD(StringIO("<!ELEMENT b EMPTY>"))
32 self.assertRaises(etree.DocumentInvalid, dtd.assertValid, root)
33
35 root = etree.XML("<b><a/></b>")
36 dtd = etree.DTD(StringIO("<!ELEMENT b (a)><!ELEMENT a EMPTY>"))
37 dtd.assertValid(root)
38
40 root = etree.XML('''
41 <!DOCTYPE b SYSTEM "none" [
42 <!ELEMENT b (a)>
43 <!ELEMENT a EMPTY>
44 ]>
45 <b><a/></b>
46 ''')
47 dtd = etree.ElementTree(root).docinfo.internalDTD
48 self.assert_(dtd)
49 dtd.assertValid(root)
50
52 root = etree.XML('''
53 <!DOCTYPE b SYSTEM "none" [
54 <!ELEMENT b (a)>
55 <!ELEMENT a (c)>
56 <!ELEMENT c EMPTY>
57 ]>
58 <b><a/></b>
59 ''')
60 dtd = etree.ElementTree(root).docinfo.internalDTD
61 self.assert_(dtd)
62 self.assertFalse(dtd.validate(root))
63
65 self.assertRaises(etree.DTDParseError, etree.DTD,
66 StringIO("<!ELEMENT b HONKEY>"))
67
69 parser = etree.XMLParser(attribute_defaults=True)
70
71 tree = etree.parse(fileInTestDir('test.xml'), parser)
72 root = tree.getroot()
73
74 self.assertEquals(
75 "valueA",
76 root.get("default"))
77 self.assertEquals(
78 "valueB",
79 root[0].get("default"))
80
82 iterparse = etree.iterparse
83 iterator = iterparse(fileInTestDir("test.xml"), events=("start",),
84 attribute_defaults=True)
85 attributes = [ element.get("default")
86 for event, element in iterator ]
87 self.assertEquals(
88 ["valueA", "valueB"],
89 attributes)
90
91
93 suite = unittest.TestSuite()
94 suite.addTests([unittest.makeSuite(ETreeDtdTestCase)])
95 suite.addTests(
96 [doctest.DocFileSuite('../../../doc/validation.txt')])
97 return suite
98
99 if __name__ == '__main__':
100 unittest.main()
101