home *** CD-ROM | disk | FTP | other *** search
/ H4CK3R 14 / hacker14.iso / programacao / pythonwin / python.exe / TEST_HTMLPARSER.PY < prev    next >
Encoding:
Python Source  |  2003-04-18  |  9.7 KB  |  302 lines

  1. """Tests for HTMLParser.py."""
  2.  
  3. import HTMLParser
  4. import pprint
  5. import sys
  6. import unittest
  7. from test import test_support
  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.         self._run_check("<?processing instruction ?>", [
  105.             ("pi", "processing instruction ?"),
  106.             ])
  107.  
  108.     def test_simple_html(self):
  109.         self._run_check("""
  110. <!DOCTYPE html PUBLIC 'foo'>
  111. <HTML>&entity;
  112. <!--comment1a
  113. -></foo><bar><<?pi?></foo<bar
  114. comment1b-->
  115. <Img sRc='Bar' isMAP>sample
  116. text
  117. <!--comment2a-- --comment2b-->
  118. </Html>
  119. """, [
  120.     ("data", "\n"),
  121.     ("decl", "DOCTYPE html PUBLIC 'foo'"),
  122.     ("data", "\n"),
  123.     ("starttag", "html", []),
  124.     ("entityref", "entity"),
  125.     ("charref", "32"),
  126.     ("data", "\n"),
  127.     ("comment", "comment1a\n-></foo><bar><<?pi?></foo<bar\ncomment1b"),
  128.     ("data", "\n"),
  129.     ("starttag", "img", [("src", "Bar"), ("ismap", None)]),
  130.     ("data", "sample\ntext\n"),
  131.     ("charref", "x201C"),
  132.     ("data", "\n"),
  133.     ("comment", "comment2a-- --comment2b"),
  134.     ("data", "\n"),
  135.     ("endtag", "html"),
  136.     ("data", "\n"),
  137.     ])
  138.  
  139.     def test_unclosed_entityref(self):
  140.         self._run_check("&entityref foo", [
  141.             ("entityref", "entityref"),
  142.             ("data", " foo"),
  143.             ])
  144.  
  145.     def test_doctype_decl(self):
  146.         inside = """\
  147. DOCTYPE html [
  148.   <!ELEMENT html - O EMPTY>
  149.   <!ATTLIST html
  150.       version CDATA #IMPLIED
  151.       profile CDATA 'DublinCore'>
  152.   <!NOTATION datatype SYSTEM 'http://xml.python.org/notations/python-module'>
  153.   <!ENTITY myEntity 'internal parsed entity'>
  154.   <!ENTITY anEntity SYSTEM 'http://xml.python.org/entities/something.xml'>
  155.   <!ENTITY % paramEntity 'name|name|name'>
  156.   %paramEntity;
  157.   <!-- comment -->
  158. ]"""
  159.         self._run_check("<!%s>" % inside, [
  160.             ("decl", inside),
  161.             ])
  162.  
  163.     def test_bad_nesting(self):
  164.         # Strangely, this *is* supposed to test that overlapping
  165.         # elements are allowed.  HTMLParser is more geared toward
  166.         # lexing the input that parsing the structure.
  167.         self._run_check("<a><b></a></b>", [
  168.             ("starttag", "a", []),
  169.             ("starttag", "b", []),
  170.             ("endtag", "a"),
  171.             ("endtag", "b"),
  172.             ])
  173.  
  174.     def test_bare_ampersands(self):
  175.         self._run_check("this text & contains & ampersands &", [
  176.             ("data", "this text & contains & ampersands &"),
  177.             ])
  178.  
  179.     def test_bare_pointy_brackets(self):
  180.         self._run_check("this < text > contains < bare>pointy< brackets", [
  181.             ("data", "this < text > contains < bare>pointy< brackets"),
  182.             ])
  183.  
  184.     def test_attr_syntax(self):
  185.         output = [
  186.           ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", None)])
  187.           ]
  188.         self._run_check("""<a b='v' c="v" d=v e>""", output)
  189.         self._run_check("""<a  b = 'v' c = "v" d = v e>""", output)
  190.         self._run_check("""<a\nb\n=\n'v'\nc\n=\n"v"\nd\n=\nv\ne>""", output)
  191.         self._run_check("""<a\tb\t=\t'v'\tc\t=\t"v"\td\t=\tv\te>""", output)
  192.  
  193.     def test_attr_values(self):
  194.         self._run_check("""<a b='xxx\n\txxx' c="yyy\t\nyyy" d='\txyz\n'>""",
  195.                         [("starttag", "a", [("b", "xxx\n\txxx"),
  196.                                             ("c", "yyy\t\nyyy"),
  197.                                             ("d", "\txyz\n")])
  198.                          ])
  199.         self._run_check("""<a b='' c="">""", [
  200.             ("starttag", "a", [("b", ""), ("c", "")]),
  201.             ])
  202.         # Regression test for SF patch #669683.
  203.         self._run_check("<e a=rgb(1,2,3)>", [
  204.             ("starttag", "e", [("a", "rgb(1,2,3)")]),
  205.             ])
  206.  
  207.     def test_attr_entity_replacement(self):
  208.         self._run_check("""<a b='&><"''>""", [
  209.             ("starttag", "a", [("b", "&><\"'")]),
  210.             ])
  211.  
  212.     def test_attr_funky_names(self):
  213.         self._run_check("""<a a.b='v' c:d=v e-f=v>""", [
  214.             ("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")]),
  215.             ])
  216.  
  217.     def test_illegal_declarations(self):
  218.         self._parse_error('<!spacer type="block" height="25">')
  219.  
  220.     def test_starttag_end_boundary(self):
  221.         self._run_check("""<a b='<'>""", [("starttag", "a", [("b", "<")])])
  222.         self._run_check("""<a b='>'>""", [("starttag", "a", [("b", ">")])])
  223.  
  224.     def test_buffer_artefacts(self):
  225.         output = [("starttag", "a", [("b", "<")])]
  226.         self._run_check(["<a b='<'>"], output)
  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.  
  233.         output = [("starttag", "a", [("b", ">")])]
  234.         self._run_check(["<a b='>'>"], output)
  235.         self._run_check(["<a ", "b='>'>"], output)
  236.         self._run_check(["<a b", "='>'>"], output)
  237.         self._run_check(["<a b=", "'>'>"], output)
  238.         self._run_check(["<a b='>", "'>"], output)
  239.         self._run_check(["<a b='>'", ">"], output)
  240.  
  241.     def test_starttag_junk_chars(self):
  242.         self._parse_error("</>")
  243.         self._parse_error("</$>")
  244.         self._parse_error("</")
  245.         self._parse_error("</a")
  246.         self._parse_error("<a<a>")
  247.         self._parse_error("</a<a>")
  248.         self._parse_error("<!")
  249.         self._parse_error("<a $>")
  250.         self._parse_error("<a")
  251.         self._parse_error("<a foo='bar'")
  252.         self._parse_error("<a foo='bar")
  253.         self._parse_error("<a foo='>'")
  254.         self._parse_error("<a foo='>")
  255.         self._parse_error("<a foo=>")
  256.  
  257.     def test_declaration_junk_chars(self):
  258.         self._parse_error("<!DOCTYPE foo $ >")
  259.  
  260.     def test_startendtag(self):
  261.         self._run_check("<p/>", [
  262.             ("startendtag", "p", []),
  263.             ])
  264.         self._run_check("<p></p>", [
  265.             ("starttag", "p", []),
  266.             ("endtag", "p"),
  267.             ])
  268.         self._run_check("<p><img src='foo' /></p>", [
  269.             ("starttag", "p", []),
  270.             ("startendtag", "img", [("src", "foo")]),
  271.             ("endtag", "p"),
  272.             ])
  273.  
  274.     def test_get_starttag_text(self):
  275.         s = """<foo:bar   \n   one="1"\ttwo=2   >"""
  276.         self._run_check_extra(s, [
  277.             ("starttag", "foo:bar", [("one", "1"), ("two", "2")]),
  278.             ("starttag_text", s)])
  279.  
  280.     def test_cdata_content(self):
  281.         s = """<script> <!-- not a comment --> ¬-an-entity-ref; </script>"""
  282.         self._run_check(s, [
  283.             ("starttag", "script", []),
  284.             ("data", " <!-- not a comment --> ¬-an-entity-ref; "),
  285.             ("endtag", "script"),
  286.             ])
  287.         s = """<script> <not a='start tag'> </script>"""
  288.         self._run_check(s, [
  289.             ("starttag", "script", []),
  290.             ("data", " <not a='start tag'> "),
  291.             ("endtag", "script"),
  292.             ])
  293.  
  294.  
  295. def test_main():
  296.     test_support.run_unittest(HTMLParserTestCase)
  297.  
  298.  
  299. if __name__ == "__main__":
  300.     test_main()
  301.