Back to index

python3.2  3.2.2
test_sax.py
Go to the documentation of this file.
00001 # regression test for SAX 2.0
00002 # $Id$
00003 
00004 from xml.sax import make_parser, ContentHandler, \
00005                     SAXException, SAXReaderNotAvailable, SAXParseException
00006 try:
00007     make_parser()
00008 except SAXReaderNotAvailable:
00009     # don't try to test this module if we cannot create a parser
00010     raise ImportError("no XML parsers available")
00011 from xml.sax.saxutils import XMLGenerator, escape, unescape, quoteattr, \
00012                              XMLFilterBase
00013 from xml.sax.expatreader import create_parser
00014 from xml.sax.handler import feature_namespaces
00015 from xml.sax.xmlreader import InputSource, AttributesImpl, AttributesNSImpl
00016 from io import StringIO
00017 from test.support import findfile, run_unittest
00018 import unittest
00019 
00020 TEST_XMLFILE = findfile("test.xml", subdir="xmltestdata")
00021 TEST_XMLFILE_OUT = findfile("test.xml.out", subdir="xmltestdata")
00022 try:
00023     TEST_XMLFILE.encode("utf8")
00024     TEST_XMLFILE_OUT.encode("utf8")
00025 except UnicodeEncodeError:
00026     raise unittest.SkipTest("filename is not encodable to utf8")
00027 
00028 ns_uri = "http://www.python.org/xml-ns/saxtest/"
00029 
00030 class XmlTestBase(unittest.TestCase):
00031     def verify_empty_attrs(self, attrs):
00032         self.assertRaises(KeyError, attrs.getValue, "attr")
00033         self.assertRaises(KeyError, attrs.getValueByQName, "attr")
00034         self.assertRaises(KeyError, attrs.getNameByQName, "attr")
00035         self.assertRaises(KeyError, attrs.getQNameByName, "attr")
00036         self.assertRaises(KeyError, attrs.__getitem__, "attr")
00037         self.assertEqual(attrs.getLength(), 0)
00038         self.assertEqual(attrs.getNames(), [])
00039         self.assertEqual(attrs.getQNames(), [])
00040         self.assertEqual(len(attrs), 0)
00041         self.assertNotIn("attr", attrs)
00042         self.assertEqual(list(attrs.keys()), [])
00043         self.assertEqual(attrs.get("attrs"), None)
00044         self.assertEqual(attrs.get("attrs", 25), 25)
00045         self.assertEqual(list(attrs.items()), [])
00046         self.assertEqual(list(attrs.values()), [])
00047 
00048     def verify_empty_nsattrs(self, attrs):
00049         self.assertRaises(KeyError, attrs.getValue, (ns_uri, "attr"))
00050         self.assertRaises(KeyError, attrs.getValueByQName, "ns:attr")
00051         self.assertRaises(KeyError, attrs.getNameByQName, "ns:attr")
00052         self.assertRaises(KeyError, attrs.getQNameByName, (ns_uri, "attr"))
00053         self.assertRaises(KeyError, attrs.__getitem__, (ns_uri, "attr"))
00054         self.assertEqual(attrs.getLength(), 0)
00055         self.assertEqual(attrs.getNames(), [])
00056         self.assertEqual(attrs.getQNames(), [])
00057         self.assertEqual(len(attrs), 0)
00058         self.assertNotIn((ns_uri, "attr"), attrs)
00059         self.assertEqual(list(attrs.keys()), [])
00060         self.assertEqual(attrs.get((ns_uri, "attr")), None)
00061         self.assertEqual(attrs.get((ns_uri, "attr"), 25), 25)
00062         self.assertEqual(list(attrs.items()), [])
00063         self.assertEqual(list(attrs.values()), [])
00064 
00065     def verify_attrs_wattr(self, attrs):
00066         self.assertEqual(attrs.getLength(), 1)
00067         self.assertEqual(attrs.getNames(), ["attr"])
00068         self.assertEqual(attrs.getQNames(), ["attr"])
00069         self.assertEqual(len(attrs), 1)
00070         self.assertIn("attr", attrs)
00071         self.assertEqual(list(attrs.keys()), ["attr"])
00072         self.assertEqual(attrs.get("attr"), "val")
00073         self.assertEqual(attrs.get("attr", 25), "val")
00074         self.assertEqual(list(attrs.items()), [("attr", "val")])
00075         self.assertEqual(list(attrs.values()), ["val"])
00076         self.assertEqual(attrs.getValue("attr"), "val")
00077         self.assertEqual(attrs.getValueByQName("attr"), "val")
00078         self.assertEqual(attrs.getNameByQName("attr"), "attr")
00079         self.assertEqual(attrs["attr"], "val")
00080         self.assertEqual(attrs.getQNameByName("attr"), "attr")
00081 
00082 class MakeParserTest(unittest.TestCase):
00083     def test_make_parser2(self):
00084         # Creating parsers several times in a row should succeed.
00085         # Testing this because there have been failures of this kind
00086         # before.
00087         from xml.sax import make_parser
00088         p = make_parser()
00089         from xml.sax import make_parser
00090         p = make_parser()
00091         from xml.sax import make_parser
00092         p = make_parser()
00093         from xml.sax import make_parser
00094         p = make_parser()
00095         from xml.sax import make_parser
00096         p = make_parser()
00097         from xml.sax import make_parser
00098         p = make_parser()
00099 
00100 
00101 # ===========================================================================
00102 #
00103 #   saxutils tests
00104 #
00105 # ===========================================================================
00106 
00107 class SaxutilsTest(unittest.TestCase):
00108     # ===== escape
00109     def test_escape_basic(self):
00110         self.assertEqual(escape("Donald Duck & Co"), "Donald Duck & Co")
00111 
00112     def test_escape_all(self):
00113         self.assertEqual(escape("<Donald Duck & Co>"),
00114                          "&lt;Donald Duck &amp; Co&gt;")
00115 
00116     def test_escape_extra(self):
00117         self.assertEqual(escape("Hei på deg", {"å" : "&aring;"}),
00118                          "Hei p&aring; deg")
00119 
00120     # ===== unescape
00121     def test_unescape_basic(self):
00122         self.assertEqual(unescape("Donald Duck &amp; Co"), "Donald Duck & Co")
00123 
00124     def test_unescape_all(self):
00125         self.assertEqual(unescape("&lt;Donald Duck &amp; Co&gt;"),
00126                          "<Donald Duck & Co>")
00127 
00128     def test_unescape_extra(self):
00129         self.assertEqual(unescape("Hei på deg", {"å" : "&aring;"}),
00130                          "Hei p&aring; deg")
00131 
00132     def test_unescape_amp_extra(self):
00133         self.assertEqual(unescape("&amp;foo;", {"&foo;": "splat"}), "&foo;")
00134 
00135     # ===== quoteattr
00136     def test_quoteattr_basic(self):
00137         self.assertEqual(quoteattr("Donald Duck & Co"),
00138                          '"Donald Duck &amp; Co"')
00139 
00140     def test_single_quoteattr(self):
00141         self.assertEqual(quoteattr('Includes "double" quotes'),
00142                          '\'Includes "double" quotes\'')
00143 
00144     def test_double_quoteattr(self):
00145         self.assertEqual(quoteattr("Includes 'single' quotes"),
00146                          "\"Includes 'single' quotes\"")
00147 
00148     def test_single_double_quoteattr(self):
00149         self.assertEqual(quoteattr("Includes 'single' and \"double\" quotes"),
00150                          "\"Includes 'single' and &quot;double&quot; quotes\"")
00151 
00152     # ===== make_parser
00153     def test_make_parser(self):
00154         # Creating a parser should succeed - it should fall back
00155         # to the expatreader
00156         p = make_parser(['xml.parsers.no_such_parser'])
00157 
00158 
00159 # ===== XMLGenerator
00160 
00161 start = '<?xml version="1.0" encoding="iso-8859-1"?>\n'
00162 
00163 class XmlgenTest(unittest.TestCase):
00164     def test_xmlgen_basic(self):
00165         result = StringIO()
00166         gen = XMLGenerator(result)
00167         gen.startDocument()
00168         gen.startElement("doc", {})
00169         gen.endElement("doc")
00170         gen.endDocument()
00171 
00172         self.assertEqual(result.getvalue(), start + "<doc></doc>")
00173 
00174     def test_xmlgen_basic_empty(self):
00175         result = StringIO()
00176         gen = XMLGenerator(result, short_empty_elements=True)
00177         gen.startDocument()
00178         gen.startElement("doc", {})
00179         gen.endElement("doc")
00180         gen.endDocument()
00181 
00182         self.assertEqual(result.getvalue(), start + "<doc/>")
00183 
00184     def test_xmlgen_content(self):
00185         result = StringIO()
00186         gen = XMLGenerator(result)
00187 
00188         gen.startDocument()
00189         gen.startElement("doc", {})
00190         gen.characters("huhei")
00191         gen.endElement("doc")
00192         gen.endDocument()
00193 
00194         self.assertEqual(result.getvalue(), start + "<doc>huhei</doc>")
00195 
00196     def test_xmlgen_content_empty(self):
00197         result = StringIO()
00198         gen = XMLGenerator(result, short_empty_elements=True)
00199 
00200         gen.startDocument()
00201         gen.startElement("doc", {})
00202         gen.characters("huhei")
00203         gen.endElement("doc")
00204         gen.endDocument()
00205 
00206         self.assertEqual(result.getvalue(), start + "<doc>huhei</doc>")
00207 
00208     def test_xmlgen_pi(self):
00209         result = StringIO()
00210         gen = XMLGenerator(result)
00211 
00212         gen.startDocument()
00213         gen.processingInstruction("test", "data")
00214         gen.startElement("doc", {})
00215         gen.endElement("doc")
00216         gen.endDocument()
00217 
00218         self.assertEqual(result.getvalue(), start + "<?test data?><doc></doc>")
00219 
00220     def test_xmlgen_content_escape(self):
00221         result = StringIO()
00222         gen = XMLGenerator(result)
00223 
00224         gen.startDocument()
00225         gen.startElement("doc", {})
00226         gen.characters("<huhei&")
00227         gen.endElement("doc")
00228         gen.endDocument()
00229 
00230         self.assertEqual(result.getvalue(),
00231             start + "<doc>&lt;huhei&amp;</doc>")
00232 
00233     def test_xmlgen_attr_escape(self):
00234         result = StringIO()
00235         gen = XMLGenerator(result)
00236 
00237         gen.startDocument()
00238         gen.startElement("doc", {"a": '"'})
00239         gen.startElement("e", {"a": "'"})
00240         gen.endElement("e")
00241         gen.startElement("e", {"a": "'\""})
00242         gen.endElement("e")
00243         gen.startElement("e", {"a": "\n\r\t"})
00244         gen.endElement("e")
00245         gen.endElement("doc")
00246         gen.endDocument()
00247 
00248         self.assertEqual(result.getvalue(), start +
00249             ("<doc a='\"'><e a=\"'\"></e>"
00250              "<e a=\"'&quot;\"></e>"
00251              "<e a=\"&#10;&#13;&#9;\"></e></doc>"))
00252 
00253     def test_xmlgen_ignorable(self):
00254         result = StringIO()
00255         gen = XMLGenerator(result)
00256 
00257         gen.startDocument()
00258         gen.startElement("doc", {})
00259         gen.ignorableWhitespace(" ")
00260         gen.endElement("doc")
00261         gen.endDocument()
00262 
00263         self.assertEqual(result.getvalue(), start + "<doc> </doc>")
00264 
00265     def test_xmlgen_ignorable_empty(self):
00266         result = StringIO()
00267         gen = XMLGenerator(result, short_empty_elements=True)
00268 
00269         gen.startDocument()
00270         gen.startElement("doc", {})
00271         gen.ignorableWhitespace(" ")
00272         gen.endElement("doc")
00273         gen.endDocument()
00274 
00275         self.assertEqual(result.getvalue(), start + "<doc> </doc>")
00276 
00277     def test_xmlgen_ns(self):
00278         result = StringIO()
00279         gen = XMLGenerator(result)
00280 
00281         gen.startDocument()
00282         gen.startPrefixMapping("ns1", ns_uri)
00283         gen.startElementNS((ns_uri, "doc"), "ns1:doc", {})
00284         # add an unqualified name
00285         gen.startElementNS((None, "udoc"), None, {})
00286         gen.endElementNS((None, "udoc"), None)
00287         gen.endElementNS((ns_uri, "doc"), "ns1:doc")
00288         gen.endPrefixMapping("ns1")
00289         gen.endDocument()
00290 
00291         self.assertEqual(result.getvalue(), start + \
00292            ('<ns1:doc xmlns:ns1="%s"><udoc></udoc></ns1:doc>' %
00293                                          ns_uri))
00294 
00295     def test_xmlgen_ns_empty(self):
00296         result = StringIO()
00297         gen = XMLGenerator(result, short_empty_elements=True)
00298 
00299         gen.startDocument()
00300         gen.startPrefixMapping("ns1", ns_uri)
00301         gen.startElementNS((ns_uri, "doc"), "ns1:doc", {})
00302         # add an unqualified name
00303         gen.startElementNS((None, "udoc"), None, {})
00304         gen.endElementNS((None, "udoc"), None)
00305         gen.endElementNS((ns_uri, "doc"), "ns1:doc")
00306         gen.endPrefixMapping("ns1")
00307         gen.endDocument()
00308 
00309         self.assertEqual(result.getvalue(), start + \
00310            ('<ns1:doc xmlns:ns1="%s"><udoc/></ns1:doc>' %
00311                                          ns_uri))
00312 
00313     def test_1463026_1(self):
00314         result = StringIO()
00315         gen = XMLGenerator(result)
00316 
00317         gen.startDocument()
00318         gen.startElementNS((None, 'a'), 'a', {(None, 'b'):'c'})
00319         gen.endElementNS((None, 'a'), 'a')
00320         gen.endDocument()
00321 
00322         self.assertEqual(result.getvalue(), start+'<a b="c"></a>')
00323 
00324     def test_1463026_1_empty(self):
00325         result = StringIO()
00326         gen = XMLGenerator(result, short_empty_elements=True)
00327 
00328         gen.startDocument()
00329         gen.startElementNS((None, 'a'), 'a', {(None, 'b'):'c'})
00330         gen.endElementNS((None, 'a'), 'a')
00331         gen.endDocument()
00332 
00333         self.assertEqual(result.getvalue(), start+'<a b="c"/>')
00334 
00335     def test_1463026_2(self):
00336         result = StringIO()
00337         gen = XMLGenerator(result)
00338 
00339         gen.startDocument()
00340         gen.startPrefixMapping(None, 'qux')
00341         gen.startElementNS(('qux', 'a'), 'a', {})
00342         gen.endElementNS(('qux', 'a'), 'a')
00343         gen.endPrefixMapping(None)
00344         gen.endDocument()
00345 
00346         self.assertEqual(result.getvalue(), start+'<a xmlns="qux"></a>')
00347 
00348     def test_1463026_2_empty(self):
00349         result = StringIO()
00350         gen = XMLGenerator(result, short_empty_elements=True)
00351 
00352         gen.startDocument()
00353         gen.startPrefixMapping(None, 'qux')
00354         gen.startElementNS(('qux', 'a'), 'a', {})
00355         gen.endElementNS(('qux', 'a'), 'a')
00356         gen.endPrefixMapping(None)
00357         gen.endDocument()
00358 
00359         self.assertEqual(result.getvalue(), start+'<a xmlns="qux"/>')
00360 
00361     def test_1463026_3(self):
00362         result = StringIO()
00363         gen = XMLGenerator(result)
00364 
00365         gen.startDocument()
00366         gen.startPrefixMapping('my', 'qux')
00367         gen.startElementNS(('qux', 'a'), 'a', {(None, 'b'):'c'})
00368         gen.endElementNS(('qux', 'a'), 'a')
00369         gen.endPrefixMapping('my')
00370         gen.endDocument()
00371 
00372         self.assertEqual(result.getvalue(),
00373             start+'<my:a xmlns:my="qux" b="c"></my:a>')
00374 
00375     def test_1463026_3_empty(self):
00376         result = StringIO()
00377         gen = XMLGenerator(result, short_empty_elements=True)
00378 
00379         gen.startDocument()
00380         gen.startPrefixMapping('my', 'qux')
00381         gen.startElementNS(('qux', 'a'), 'a', {(None, 'b'):'c'})
00382         gen.endElementNS(('qux', 'a'), 'a')
00383         gen.endPrefixMapping('my')
00384         gen.endDocument()
00385 
00386         self.assertEqual(result.getvalue(),
00387             start+'<my:a xmlns:my="qux" b="c"/>')
00388 
00389     def test_5027_1(self):
00390         # The xml prefix (as in xml:lang below) is reserved and bound by
00391         # definition to http://www.w3.org/XML/1998/namespace.  XMLGenerator had
00392         # a bug whereby a KeyError is thrown because this namespace is missing
00393         # from a dictionary.
00394         #
00395         # This test demonstrates the bug by parsing a document.
00396         test_xml = StringIO(
00397             '<?xml version="1.0"?>'
00398             '<a:g1 xmlns:a="http://example.com/ns">'
00399              '<a:g2 xml:lang="en">Hello</a:g2>'
00400             '</a:g1>')
00401 
00402         parser = make_parser()
00403         parser.setFeature(feature_namespaces, True)
00404         result = StringIO()
00405         gen = XMLGenerator(result)
00406         parser.setContentHandler(gen)
00407         parser.parse(test_xml)
00408 
00409         self.assertEqual(result.getvalue(),
00410                          start + (
00411                          '<a:g1 xmlns:a="http://example.com/ns">'
00412                           '<a:g2 xml:lang="en">Hello</a:g2>'
00413                          '</a:g1>'))
00414 
00415     def test_5027_2(self):
00416         # The xml prefix (as in xml:lang below) is reserved and bound by
00417         # definition to http://www.w3.org/XML/1998/namespace.  XMLGenerator had
00418         # a bug whereby a KeyError is thrown because this namespace is missing
00419         # from a dictionary.
00420         #
00421         # This test demonstrates the bug by direct manipulation of the
00422         # XMLGenerator.
00423         result = StringIO()
00424         gen = XMLGenerator(result)
00425 
00426         gen.startDocument()
00427         gen.startPrefixMapping('a', 'http://example.com/ns')
00428         gen.startElementNS(('http://example.com/ns', 'g1'), 'g1', {})
00429         lang_attr = {('http://www.w3.org/XML/1998/namespace', 'lang'): 'en'}
00430         gen.startElementNS(('http://example.com/ns', 'g2'), 'g2', lang_attr)
00431         gen.characters('Hello')
00432         gen.endElementNS(('http://example.com/ns', 'g2'), 'g2')
00433         gen.endElementNS(('http://example.com/ns', 'g1'), 'g1')
00434         gen.endPrefixMapping('a')
00435         gen.endDocument()
00436 
00437         self.assertEqual(result.getvalue(),
00438                          start + (
00439                          '<a:g1 xmlns:a="http://example.com/ns">'
00440                           '<a:g2 xml:lang="en">Hello</a:g2>'
00441                          '</a:g1>'))
00442 
00443 
00444 class XMLFilterBaseTest(unittest.TestCase):
00445     def test_filter_basic(self):
00446         result = StringIO()
00447         gen = XMLGenerator(result)
00448         filter = XMLFilterBase()
00449         filter.setContentHandler(gen)
00450 
00451         filter.startDocument()
00452         filter.startElement("doc", {})
00453         filter.characters("content")
00454         filter.ignorableWhitespace(" ")
00455         filter.endElement("doc")
00456         filter.endDocument()
00457 
00458         self.assertEqual(result.getvalue(), start + "<doc>content </doc>")
00459 
00460 # ===========================================================================
00461 #
00462 #   expatreader tests
00463 #
00464 # ===========================================================================
00465 
00466 with open(TEST_XMLFILE_OUT) as f:
00467     xml_test_out = f.read()
00468 
00469 class ExpatReaderTest(XmlTestBase):
00470 
00471     # ===== XMLReader support
00472 
00473     def test_expat_file(self):
00474         parser = create_parser()
00475         result = StringIO()
00476         xmlgen = XMLGenerator(result)
00477 
00478         parser.setContentHandler(xmlgen)
00479         with open(TEST_XMLFILE) as f:
00480             parser.parse(f)
00481 
00482         self.assertEqual(result.getvalue(), xml_test_out)
00483 
00484     # ===== DTDHandler support
00485 
00486     class TestDTDHandler:
00487 
00488         def __init__(self):
00489             self._notations = []
00490             self._entities  = []
00491 
00492         def notationDecl(self, name, publicId, systemId):
00493             self._notations.append((name, publicId, systemId))
00494 
00495         def unparsedEntityDecl(self, name, publicId, systemId, ndata):
00496             self._entities.append((name, publicId, systemId, ndata))
00497 
00498     def test_expat_dtdhandler(self):
00499         parser = create_parser()
00500         handler = self.TestDTDHandler()
00501         parser.setDTDHandler(handler)
00502 
00503         parser.feed('<!DOCTYPE doc [\n')
00504         parser.feed('  <!ENTITY img SYSTEM "expat.gif" NDATA GIF>\n')
00505         parser.feed('  <!NOTATION GIF PUBLIC "-//CompuServe//NOTATION Graphics Interchange Format 89a//EN">\n')
00506         parser.feed(']>\n')
00507         parser.feed('<doc></doc>')
00508         parser.close()
00509 
00510         self.assertEqual(handler._notations,
00511             [("GIF", "-//CompuServe//NOTATION Graphics Interchange Format 89a//EN", None)])
00512         self.assertEqual(handler._entities, [("img", None, "expat.gif", "GIF")])
00513 
00514     # ===== EntityResolver support
00515 
00516     class TestEntityResolver:
00517 
00518         def resolveEntity(self, publicId, systemId):
00519             inpsrc = InputSource()
00520             inpsrc.setByteStream(StringIO("<entity/>"))
00521             return inpsrc
00522 
00523     def test_expat_entityresolver(self):
00524         parser = create_parser()
00525         parser.setEntityResolver(self.TestEntityResolver())
00526         result = StringIO()
00527         parser.setContentHandler(XMLGenerator(result))
00528 
00529         parser.feed('<!DOCTYPE doc [\n')
00530         parser.feed('  <!ENTITY test SYSTEM "whatever">\n')
00531         parser.feed(']>\n')
00532         parser.feed('<doc>&test;</doc>')
00533         parser.close()
00534 
00535         self.assertEqual(result.getvalue(), start +
00536                          "<doc><entity></entity></doc>")
00537 
00538     # ===== Attributes support
00539 
00540     class AttrGatherer(ContentHandler):
00541 
00542         def startElement(self, name, attrs):
00543             self._attrs = attrs
00544 
00545         def startElementNS(self, name, qname, attrs):
00546             self._attrs = attrs
00547 
00548     def test_expat_attrs_empty(self):
00549         parser = create_parser()
00550         gather = self.AttrGatherer()
00551         parser.setContentHandler(gather)
00552 
00553         parser.feed("<doc/>")
00554         parser.close()
00555 
00556         self.verify_empty_attrs(gather._attrs)
00557 
00558     def test_expat_attrs_wattr(self):
00559         parser = create_parser()
00560         gather = self.AttrGatherer()
00561         parser.setContentHandler(gather)
00562 
00563         parser.feed("<doc attr='val'/>")
00564         parser.close()
00565 
00566         self.verify_attrs_wattr(gather._attrs)
00567 
00568     def test_expat_nsattrs_empty(self):
00569         parser = create_parser(1)
00570         gather = self.AttrGatherer()
00571         parser.setContentHandler(gather)
00572 
00573         parser.feed("<doc/>")
00574         parser.close()
00575 
00576         self.verify_empty_nsattrs(gather._attrs)
00577 
00578     def test_expat_nsattrs_wattr(self):
00579         parser = create_parser(1)
00580         gather = self.AttrGatherer()
00581         parser.setContentHandler(gather)
00582 
00583         parser.feed("<doc xmlns:ns='%s' ns:attr='val'/>" % ns_uri)
00584         parser.close()
00585 
00586         attrs = gather._attrs
00587 
00588         self.assertEqual(attrs.getLength(), 1)
00589         self.assertEqual(attrs.getNames(), [(ns_uri, "attr")])
00590         self.assertTrue((attrs.getQNames() == [] or
00591                          attrs.getQNames() == ["ns:attr"]))
00592         self.assertEqual(len(attrs), 1)
00593         self.assertIn((ns_uri, "attr"), attrs)
00594         self.assertEqual(attrs.get((ns_uri, "attr")), "val")
00595         self.assertEqual(attrs.get((ns_uri, "attr"), 25), "val")
00596         self.assertEqual(list(attrs.items()), [((ns_uri, "attr"), "val")])
00597         self.assertEqual(list(attrs.values()), ["val"])
00598         self.assertEqual(attrs.getValue((ns_uri, "attr")), "val")
00599         self.assertEqual(attrs[(ns_uri, "attr")], "val")
00600 
00601     # ===== InputSource support
00602 
00603     def test_expat_inpsource_filename(self):
00604         parser = create_parser()
00605         result = StringIO()
00606         xmlgen = XMLGenerator(result)
00607 
00608         parser.setContentHandler(xmlgen)
00609         parser.parse(TEST_XMLFILE)
00610 
00611         self.assertEqual(result.getvalue(), xml_test_out)
00612 
00613     def test_expat_inpsource_sysid(self):
00614         parser = create_parser()
00615         result = StringIO()
00616         xmlgen = XMLGenerator(result)
00617 
00618         parser.setContentHandler(xmlgen)
00619         parser.parse(InputSource(TEST_XMLFILE))
00620 
00621         self.assertEqual(result.getvalue(), xml_test_out)
00622 
00623     def test_expat_inpsource_stream(self):
00624         parser = create_parser()
00625         result = StringIO()
00626         xmlgen = XMLGenerator(result)
00627 
00628         parser.setContentHandler(xmlgen)
00629         inpsrc = InputSource()
00630         with open(TEST_XMLFILE) as f:
00631             inpsrc.setByteStream(f)
00632             parser.parse(inpsrc)
00633 
00634         self.assertEqual(result.getvalue(), xml_test_out)
00635 
00636     # ===== IncrementalParser support
00637 
00638     def test_expat_incremental(self):
00639         result = StringIO()
00640         xmlgen = XMLGenerator(result)
00641         parser = create_parser()
00642         parser.setContentHandler(xmlgen)
00643 
00644         parser.feed("<doc>")
00645         parser.feed("</doc>")
00646         parser.close()
00647 
00648         self.assertEqual(result.getvalue(), start + "<doc></doc>")
00649 
00650     def test_expat_incremental_reset(self):
00651         result = StringIO()
00652         xmlgen = XMLGenerator(result)
00653         parser = create_parser()
00654         parser.setContentHandler(xmlgen)
00655 
00656         parser.feed("<doc>")
00657         parser.feed("text")
00658 
00659         result = StringIO()
00660         xmlgen = XMLGenerator(result)
00661         parser.setContentHandler(xmlgen)
00662         parser.reset()
00663 
00664         parser.feed("<doc>")
00665         parser.feed("text")
00666         parser.feed("</doc>")
00667         parser.close()
00668 
00669         self.assertEqual(result.getvalue(), start + "<doc>text</doc>")
00670 
00671     # ===== Locator support
00672 
00673     def test_expat_locator_noinfo(self):
00674         result = StringIO()
00675         xmlgen = XMLGenerator(result)
00676         parser = create_parser()
00677         parser.setContentHandler(xmlgen)
00678 
00679         parser.feed("<doc>")
00680         parser.feed("</doc>")
00681         parser.close()
00682 
00683         self.assertEqual(parser.getSystemId(), None)
00684         self.assertEqual(parser.getPublicId(), None)
00685         self.assertEqual(parser.getLineNumber(), 1)
00686 
00687     def test_expat_locator_withinfo(self):
00688         result = StringIO()
00689         xmlgen = XMLGenerator(result)
00690         parser = create_parser()
00691         parser.setContentHandler(xmlgen)
00692         parser.parse(TEST_XMLFILE)
00693 
00694         self.assertEqual(parser.getSystemId(), TEST_XMLFILE)
00695         self.assertEqual(parser.getPublicId(), None)
00696 
00697 
00698 # ===========================================================================
00699 #
00700 #   error reporting
00701 #
00702 # ===========================================================================
00703 
00704 class ErrorReportingTest(unittest.TestCase):
00705     def test_expat_inpsource_location(self):
00706         parser = create_parser()
00707         parser.setContentHandler(ContentHandler()) # do nothing
00708         source = InputSource()
00709         source.setByteStream(StringIO("<foo bar foobar>"))   #ill-formed
00710         name = "a file name"
00711         source.setSystemId(name)
00712         try:
00713             parser.parse(source)
00714             self.fail()
00715         except SAXException as e:
00716             self.assertEqual(e.getSystemId(), name)
00717 
00718     def test_expat_incomplete(self):
00719         parser = create_parser()
00720         parser.setContentHandler(ContentHandler()) # do nothing
00721         self.assertRaises(SAXParseException, parser.parse, StringIO("<foo>"))
00722 
00723     def test_sax_parse_exception_str(self):
00724         # pass various values from a locator to the SAXParseException to
00725         # make sure that the __str__() doesn't fall apart when None is
00726         # passed instead of an integer line and column number
00727         #
00728         # use "normal" values for the locator:
00729         str(SAXParseException("message", None,
00730                               self.DummyLocator(1, 1)))
00731         # use None for the line number:
00732         str(SAXParseException("message", None,
00733                               self.DummyLocator(None, 1)))
00734         # use None for the column number:
00735         str(SAXParseException("message", None,
00736                               self.DummyLocator(1, None)))
00737         # use None for both:
00738         str(SAXParseException("message", None,
00739                               self.DummyLocator(None, None)))
00740 
00741     class DummyLocator:
00742         def __init__(self, lineno, colno):
00743             self._lineno = lineno
00744             self._colno = colno
00745 
00746         def getPublicId(self):
00747             return "pubid"
00748 
00749         def getSystemId(self):
00750             return "sysid"
00751 
00752         def getLineNumber(self):
00753             return self._lineno
00754 
00755         def getColumnNumber(self):
00756             return self._colno
00757 
00758 # ===========================================================================
00759 #
00760 #   xmlreader tests
00761 #
00762 # ===========================================================================
00763 
00764 class XmlReaderTest(XmlTestBase):
00765 
00766     # ===== AttributesImpl
00767     def test_attrs_empty(self):
00768         self.verify_empty_attrs(AttributesImpl({}))
00769 
00770     def test_attrs_wattr(self):
00771         self.verify_attrs_wattr(AttributesImpl({"attr" : "val"}))
00772 
00773     def test_nsattrs_empty(self):
00774         self.verify_empty_nsattrs(AttributesNSImpl({}, {}))
00775 
00776     def test_nsattrs_wattr(self):
00777         attrs = AttributesNSImpl({(ns_uri, "attr") : "val"},
00778                                  {(ns_uri, "attr") : "ns:attr"})
00779 
00780         self.assertEqual(attrs.getLength(), 1)
00781         self.assertEqual(attrs.getNames(), [(ns_uri, "attr")])
00782         self.assertEqual(attrs.getQNames(), ["ns:attr"])
00783         self.assertEqual(len(attrs), 1)
00784         self.assertIn((ns_uri, "attr"), attrs)
00785         self.assertEqual(list(attrs.keys()), [(ns_uri, "attr")])
00786         self.assertEqual(attrs.get((ns_uri, "attr")), "val")
00787         self.assertEqual(attrs.get((ns_uri, "attr"), 25), "val")
00788         self.assertEqual(list(attrs.items()), [((ns_uri, "attr"), "val")])
00789         self.assertEqual(list(attrs.values()), ["val"])
00790         self.assertEqual(attrs.getValue((ns_uri, "attr")), "val")
00791         self.assertEqual(attrs.getValueByQName("ns:attr"), "val")
00792         self.assertEqual(attrs.getNameByQName("ns:attr"), (ns_uri, "attr"))
00793         self.assertEqual(attrs[(ns_uri, "attr")], "val")
00794         self.assertEqual(attrs.getQNameByName((ns_uri, "attr")), "ns:attr")
00795 
00796 
00797 def test_main():
00798     run_unittest(MakeParserTest,
00799                  SaxutilsTest,
00800                  XmlgenTest,
00801                  ExpatReaderTest,
00802                  ErrorReportingTest,
00803                  XmlReaderTest)
00804 
00805 if __name__ == "__main__":
00806     test_main()