home *** CD-ROM | disk | FTP | other *** search
/ Komputer for Alle 2004 #2 / K-CD-2-2004.ISO / OpenOffice Sv / f_0397 / python-core-2.2.2 / lib / test / test_htmlparser.py < prev    next >
Encoding:
Python Source  |  2003-07-18  |  9.1 KB  |  295 lines

  1. """Tests for HTMLParser.py."""
  2.  
  3. import HTMLParser
  4. import pprint
  5. import sys
  6. import test_support
  7. import unittest
  8.  
  9.  
  10. class EventCollector(HTMLParser.HTMLParser):
  11.  
  12.     def __init__(self):
  13.         self.events = []
  14.         self.append = self.events.append
  15.         HTMLParser.HTMLParser.__init__(self)
  16.  
  17.     def get_events(self):
  18.         # Normalize the list of events so that buffer artefacts don't
  19.         # separate runs of contiguous characters.
  20.         L = []
  21.         prevtype = None
  22.         for event in self.events:
  23.             type = event[0]
  24.             if type == prevtype == "data":
  25.                 L[-1] = ("data", L[-1][1] + event[1])
  26.             else:
  27.                 L.append(event)
  28.             prevtype = type
  29.         self.events = L
  30.         return L
  31.  
  32.     # structure markup
  33.  
  34.     def handle_starttag(self, tag, attrs):
  35.         self.append(("starttag", tag, attrs))
  36.  
  37.     def handle_startendtag(self, tag, attrs):
  38.         self.append(("startendtag", tag, attrs))
  39.  
  40.     def handle_endtag(self, tag):
  41.         self.append(("endtag", tag))
  42.  
  43.     # all other markup
  44.  
  45.     def handle_comment(self, data):
  46.         self.append(("comment", data))
  47.  
  48.     def handle_charref(self, data):
  49.         self.append(("charref", data))
  50.  
  51.     def handle_data(self, data):
  52.         self.append(("data", data))
  53.  
  54.     def handle_decl(self, data):
  55.         self.append(("decl", data))
  56.  
  57.     def handle_entityref(self, data):
  58.         self.append(("entityref", data))
  59.  
  60.     def handle_pi(self, data):
  61.         self.append(("pi", data))
  62.  
  63.     def unknown_decl(self, decl):
  64.         self.append(("unknown decl", decl))
  65.  
  66.  
  67. class EventCollectorExtra(EventCollector):
  68.  
  69.     def handle_starttag(self, tag, attrs):
  70.         EventCollector.handle_starttag(self, tag, attrs)
  71.         self.append(("starttag_text", self.get_starttag_text()))
  72.  
  73.  
  74. class TestCaseBase(unittest.TestCase):
  75.  
  76.     def _run_check(self, source, expected_events, collector=EventCollector):
  77.         parser = collector()
  78.         for s in source:
  79.             parser.feed(s)
  80.         parser.close()
  81.         events = parser.get_events()
  82.         if events != expected_events:
  83.             self.fail("received events did not match expected events\n"
  84.                       "Expected:\n" + pprint.pformat(expected_events) +
  85.                       "\nReceived:\n" + pprint.pformat(events))
  86.  
  87.     def _run_check_extra(self, source, events):
  88.         self._run_check(source, events, EventCollectorExtra)
  89.  
  90.     def _parse_error(self, source):
  91.         def parse(source=source):
  92.             parser = HTMLParser.HTMLParser()
  93.             parser.feed(source)
  94.             parser.close()
  95.         self.assertRaises(HTMLParser.HTMLParseError, parse)
  96.  
  97.  
  98. class HTMLParserTestCase(TestCaseBase):
  99.  
  100.     def test_processing_instruction_only(self):
  101.         self._run_check("<?processing instruction>", [
  102.             ("pi", "processing instruction"),
  103.             ])
  104.  
  105.     def test_simple_html(self):
  106.         self._run_check("""
  107. <!DOCTYPE html PUBLIC 'foo'>
  108. <HTML>&entity;
  109. <!--comment1a
  110. -></foo><bar><<?pi?></foo<bar
  111. comment1b-->
  112. <Img sRc='Bar' isMAP>sample
  113. text
  114. <!--comment2a-- --comment2b-->
  115. </Html>
  116. """, [
  117.     ("data", "\n"),
  118.     ("decl", "DOCTYPE html PUBLIC 'foo'"),
  119.     ("data", "\n"),
  120.     ("starttag", "html", []),
  121.     ("entityref", "entity"),
  122.     ("charref", "32"),
  123.     ("data", "\n"),
  124.     ("comment", "comment1a\n-></foo><bar><<?pi?></foo<bar\ncomment1b"),
  125.     ("data", "\n"),
  126.     ("starttag", "img", [("src", "Bar"), ("ismap", None)]),
  127.     ("data", "sample\ntext\n"),
  128.     ("charref", "x201C"),
  129.     ("data", "\n"),
  130.     ("comment", "comment2a-- --comment2b"),
  131.     ("data", "\n"),
  132.     ("endtag", "html"),
  133.     ("data", "\n"),
  134.     ])
  135.  
  136.     def test_unclosed_entityref(self):
  137.         self._run_check("&entityref foo", [
  138.             ("entityref", "entityref"),
  139.             ("data", " foo"),
  140.             ])
  141.  
  142.     def test_doctype_decl(self):
  143.         inside = """\
  144. DOCTYPE html [
  145.   <!ELEMENT html - O EMPTY>
  146.   <!ATTLIST html
  147.       version CDATA #IMPLIED
  148.       profile CDATA 'DublinCore'>
  149.   <!NOTATION datatype SYSTEM 'http://xml.python.org/notations/python-module'>
  150.   <!ENTITY myEntity 'internal parsed entity'>
  151.   <!ENTITY anEntity SYSTEM 'http://xml.python.org/entities/something.xml'>
  152.   <!ENTITY % paramEntity 'name|name|name'>
  153.   %paramEntity;
  154.   <!-- comment -->
  155. ]"""
  156.         self._run_check("<!%s>" % inside, [
  157.             ("decl", inside),
  158.             ])
  159.  
  160.     def test_bad_nesting(self):
  161.         # Strangely, this *is* supposed to test that overlapping
  162.         # elements are allowed.  HTMLParser is more geared toward
  163.         # lexing the input that parsing the structure.
  164.         self._run_check("<a><b></a></b>", [
  165.             ("starttag", "a", []),
  166.             ("starttag", "b", []),
  167.             ("endtag", "a"),
  168.             ("endtag", "b"),
  169.             ])
  170.  
  171.     def test_bare_ampersands(self):
  172.         self._run_check("this text & contains & ampersands &", [
  173.             ("data", "this text & contains & ampersands &"),
  174.             ])
  175.  
  176.     def test_bare_pointy_brackets(self):
  177.         self._run_check("this < text > contains < bare>pointy< brackets", [
  178.             ("data", "this < text > contains < bare>pointy< brackets"),
  179.             ])
  180.  
  181.     def test_attr_syntax(self):
  182.         output = [
  183.           ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", None)])
  184.           ]
  185.         self._run_check("""<a b='v' c="v" d=v e>""", output)
  186.         self._run_check("""<a  b = 'v' c = "v" d = v e>""", output)
  187.         self._run_check("""<a\nb\n=\n'v'\nc\n=\n"v"\nd\n=\nv\ne>""", output)
  188.         self._run_check("""<a\tb\t=\t'v'\tc\t=\t"v"\td\t=\tv\te>""", output)
  189.  
  190.     def test_attr_values(self):
  191.         self._run_check("""<a b='xxx\n\txxx' c="yyy\t\nyyy" d='\txyz\n'>""",
  192.                         [("starttag", "a", [("b", "xxx\n\txxx"),
  193.                                             ("c", "yyy\t\nyyy"),
  194.                                             ("d", "\txyz\n")])
  195.                          ])
  196.         self._run_check("""<a b='' c="">""", [
  197.             ("starttag", "a", [("b", ""), ("c", "")]),
  198.             ])
  199.  
  200.     def test_attr_entity_replacement(self):
  201.         self._run_check("""<a b='&><"''>""", [
  202.             ("starttag", "a", [("b", "&><\"'")]),
  203.             ])
  204.  
  205.     def test_attr_funky_names(self):
  206.         self._run_check("""<a a.b='v' c:d=v e-f=v>""", [
  207.             ("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")]),
  208.             ])
  209.  
  210.     def test_illegal_declarations(self):
  211.         self._parse_error('<!spacer type="block" height="25">')
  212.  
  213.     def test_starttag_end_boundary(self):
  214.         self._run_check("""<a b='<'>""", [("starttag", "a", [("b", "<")])])
  215.         self._run_check("""<a b='>'>""", [("starttag", "a", [("b", ">")])])
  216.  
  217.     def test_buffer_artefacts(self):
  218.         output = [("starttag", "a", [("b", "<")])]
  219.         self._run_check(["<a b='<'>"], output)
  220.         self._run_check(["<a ", "b='<'>"], output)
  221.         self._run_check(["<a b", "='<'>"], output)
  222.         self._run_check(["<a b=", "'<'>"], output)
  223.         self._run_check(["<a b='<", "'>"], output)
  224.         self._run_check(["<a b='<'", ">"], output)
  225.  
  226.         output = [("starttag", "a", [("b", ">")])]
  227.         self._run_check(["<a b='>'>"], output)
  228.         self._run_check(["<a ", "b='>'>"], output)
  229.         self._run_check(["<a b", "='>'>"], output)
  230.         self._run_check(["<a b=", "'>'>"], output)
  231.         self._run_check(["<a b='>", "'>"], output)
  232.         self._run_check(["<a b='>'", ">"], output)
  233.  
  234.     def test_starttag_junk_chars(self):
  235.         self._parse_error("</>")
  236.         self._parse_error("</$>")
  237.         self._parse_error("</")
  238.         self._parse_error("</a")
  239.         self._parse_error("<a<a>")
  240.         self._parse_error("</a<a>")
  241.         self._parse_error("<!")
  242.         self._parse_error("<a $>")
  243.         self._parse_error("<a")
  244.         self._parse_error("<a foo='bar'")
  245.         self._parse_error("<a foo='bar")
  246.         self._parse_error("<a foo='>'")
  247.         self._parse_error("<a foo='>")
  248.         self._parse_error("<a foo=>")
  249.  
  250.     def test_declaration_junk_chars(self):
  251.         self._parse_error("<!DOCTYPE foo $ >")
  252.  
  253.     def test_startendtag(self):
  254.         self._run_check("<p/>", [
  255.             ("startendtag", "p", []),
  256.             ])
  257.         self._run_check("<p></p>", [
  258.             ("starttag", "p", []),
  259.             ("endtag", "p"),
  260.             ])
  261.         self._run_check("<p><img src='foo' /></p>", [
  262.             ("starttag", "p", []),
  263.             ("startendtag", "img", [("src", "foo")]),
  264.             ("endtag", "p"),
  265.             ])
  266.  
  267.     def test_get_starttag_text(self):
  268.         s = """<foo:bar   \n   one="1"\ttwo=2   >"""
  269.         self._run_check_extra(s, [
  270.             ("starttag", "foo:bar", [("one", "1"), ("two", "2")]),
  271.             ("starttag_text", s)])
  272.  
  273.     def test_cdata_content(self):
  274.         s = """<script> <!-- not a comment --> ¬-an-entity-ref; </script>"""
  275.         self._run_check(s, [
  276.             ("starttag", "script", []),
  277.             ("data", " <!-- not a comment --> ¬-an-entity-ref; "),
  278.             ("endtag", "script"),
  279.             ])
  280.         s = """<script> <not a='start tag'> </script>"""
  281.         self._run_check(s, [
  282.             ("starttag", "script", []),
  283.             ("data", " <not a='start tag'> "),
  284.             ("endtag", "script"),
  285.             ])
  286.  
  287.  
  288. def test_main():
  289.     test_support.run_unittest(HTMLParserTestCase)
  290.  
  291.  
  292. if __name__ == "__main__":
  293.     test_main()
  294.