blob: 637ab01f126223db1274547ba79b1969ccfa2478 [file] [log] [blame]
Fred Drakebd3090d2001-05-18 15:32:59 +00001"""Tests for HTMLParser.py."""
2
Mark Dickinsonf64dcf32008-05-21 13:51:18 +00003import html.parser
Fred Drake029acfb2001-08-20 21:24:19 +00004import pprint
Fred Drakebd3090d2001-05-18 15:32:59 +00005import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00006from test import support
Fred Drakebd3090d2001-05-18 15:32:59 +00007
8
Mark Dickinsonf64dcf32008-05-21 13:51:18 +00009class EventCollector(html.parser.HTMLParser):
Fred Drakebd3090d2001-05-18 15:32:59 +000010
R. David Murrayb579dba2010-12-03 04:06:39 +000011 def __init__(self, *args, **kw):
Fred Drakebd3090d2001-05-18 15:32:59 +000012 self.events = []
13 self.append = self.events.append
R. David Murrayb579dba2010-12-03 04:06:39 +000014 html.parser.HTMLParser.__init__(self, *args, **kw)
Fred Drakebd3090d2001-05-18 15:32:59 +000015
16 def get_events(self):
17 # Normalize the list of events so that buffer artefacts don't
18 # separate runs of contiguous characters.
19 L = []
20 prevtype = None
21 for event in self.events:
22 type = event[0]
23 if type == prevtype == "data":
24 L[-1] = ("data", L[-1][1] + event[1])
25 else:
26 L.append(event)
27 prevtype = type
28 self.events = L
29 return L
30
31 # structure markup
32
33 def handle_starttag(self, tag, attrs):
34 self.append(("starttag", tag, attrs))
35
36 def handle_startendtag(self, tag, attrs):
37 self.append(("startendtag", tag, attrs))
38
39 def handle_endtag(self, tag):
40 self.append(("endtag", tag))
41
42 # all other markup
43
44 def handle_comment(self, data):
45 self.append(("comment", data))
46
47 def handle_charref(self, data):
48 self.append(("charref", data))
49
50 def handle_data(self, data):
51 self.append(("data", data))
52
53 def handle_decl(self, data):
54 self.append(("decl", data))
55
56 def handle_entityref(self, data):
57 self.append(("entityref", data))
58
59 def handle_pi(self, data):
60 self.append(("pi", data))
61
Fred Drakec20a6982001-09-04 15:13:04 +000062 def unknown_decl(self, decl):
63 self.append(("unknown decl", decl))
64
Fred Drakebd3090d2001-05-18 15:32:59 +000065
66class EventCollectorExtra(EventCollector):
67
68 def handle_starttag(self, tag, attrs):
69 EventCollector.handle_starttag(self, tag, attrs)
70 self.append(("starttag_text", self.get_starttag_text()))
71
72
73class TestCaseBase(unittest.TestCase):
74
R. David Murrayb579dba2010-12-03 04:06:39 +000075 def _run_check(self, source, expected_events, collector=None):
76 if collector is None:
77 collector = EventCollector()
78 parser = collector
Fred Drakebd3090d2001-05-18 15:32:59 +000079 for s in source:
80 parser.feed(s)
Fred Drakebd3090d2001-05-18 15:32:59 +000081 parser.close()
Fred Drake029acfb2001-08-20 21:24:19 +000082 events = parser.get_events()
Fred Drakec20a6982001-09-04 15:13:04 +000083 if events != expected_events:
84 self.fail("received events did not match expected events\n"
85 "Expected:\n" + pprint.pformat(expected_events) +
86 "\nReceived:\n" + pprint.pformat(events))
Fred Drakebd3090d2001-05-18 15:32:59 +000087
88 def _run_check_extra(self, source, events):
R. David Murrayb579dba2010-12-03 04:06:39 +000089 self._run_check(source, events, EventCollectorExtra())
Fred Drakebd3090d2001-05-18 15:32:59 +000090
91 def _parse_error(self, source):
92 def parse(source=source):
Mark Dickinsonf64dcf32008-05-21 13:51:18 +000093 parser = html.parser.HTMLParser()
Fred Drakebd3090d2001-05-18 15:32:59 +000094 parser.feed(source)
95 parser.close()
Mark Dickinsonf64dcf32008-05-21 13:51:18 +000096 self.assertRaises(html.parser.HTMLParseError, parse)
Fred Drakebd3090d2001-05-18 15:32:59 +000097
98
99class HTMLParserTestCase(TestCaseBase):
100
Fred Drake84bb9d82001-08-03 19:53:01 +0000101 def test_processing_instruction_only(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000102 self._run_check("<?processing instruction>", [
103 ("pi", "processing instruction"),
104 ])
Fred Drakefafd56f2003-04-17 22:19:26 +0000105 self._run_check("<?processing instruction ?>", [
106 ("pi", "processing instruction ?"),
107 ])
Fred Drakebd3090d2001-05-18 15:32:59 +0000108
Fred Drake84bb9d82001-08-03 19:53:01 +0000109 def test_simple_html(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000110 self._run_check("""
111<!DOCTYPE html PUBLIC 'foo'>
112<HTML>&entity;&#32;
113<!--comment1a
114-></foo><bar>&lt;<?pi?></foo<bar
115comment1b-->
116<Img sRc='Bar' isMAP>sample
117text
Fred Drake84bb9d82001-08-03 19:53:01 +0000118&#x201C;
Georg Brandld09def32006-03-09 13:27:14 +0000119<!--comment2a-- --comment2b--><!>
Fred Drakebd3090d2001-05-18 15:32:59 +0000120</Html>
121""", [
122 ("data", "\n"),
123 ("decl", "DOCTYPE html PUBLIC 'foo'"),
124 ("data", "\n"),
125 ("starttag", "html", []),
126 ("entityref", "entity"),
127 ("charref", "32"),
128 ("data", "\n"),
129 ("comment", "comment1a\n-></foo><bar>&lt;<?pi?></foo<bar\ncomment1b"),
130 ("data", "\n"),
131 ("starttag", "img", [("src", "Bar"), ("ismap", None)]),
132 ("data", "sample\ntext\n"),
Fred Drake84bb9d82001-08-03 19:53:01 +0000133 ("charref", "x201C"),
134 ("data", "\n"),
Fred Drakebd3090d2001-05-18 15:32:59 +0000135 ("comment", "comment2a-- --comment2b"),
136 ("data", "\n"),
137 ("endtag", "html"),
138 ("data", "\n"),
139 ])
140
Victor Stinnere021f4b2010-05-24 21:46:25 +0000141 def test_malformatted_charref(self):
142 self._run_check("<p>&#bad;</p>", [
143 ("starttag", "p", []),
144 ("data", "&#bad;"),
145 ("endtag", "p"),
146 ])
147
Fred Drake073148c2001-12-03 16:44:09 +0000148 def test_unclosed_entityref(self):
149 self._run_check("&entityref foo", [
150 ("entityref", "entityref"),
151 ("data", " foo"),
152 ])
153
Fred Drake029acfb2001-08-20 21:24:19 +0000154 def test_doctype_decl(self):
155 inside = """\
156DOCTYPE html [
157 <!ELEMENT html - O EMPTY>
158 <!ATTLIST html
Fred Drakec20a6982001-09-04 15:13:04 +0000159 version CDATA #IMPLIED
160 profile CDATA 'DublinCore'>
161 <!NOTATION datatype SYSTEM 'http://xml.python.org/notations/python-module'>
162 <!ENTITY myEntity 'internal parsed entity'>
163 <!ENTITY anEntity SYSTEM 'http://xml.python.org/entities/something.xml'>
164 <!ENTITY % paramEntity 'name|name|name'>
165 %paramEntity;
Fred Drake029acfb2001-08-20 21:24:19 +0000166 <!-- comment -->
167]"""
168 self._run_check("<!%s>" % inside, [
169 ("decl", inside),
170 ])
171
Fred Drake84bb9d82001-08-03 19:53:01 +0000172 def test_bad_nesting(self):
173 # Strangely, this *is* supposed to test that overlapping
174 # elements are allowed. HTMLParser is more geared toward
175 # lexing the input that parsing the structure.
Fred Drakebd3090d2001-05-18 15:32:59 +0000176 self._run_check("<a><b></a></b>", [
177 ("starttag", "a", []),
178 ("starttag", "b", []),
179 ("endtag", "a"),
180 ("endtag", "b"),
181 ])
182
Fred Drake029acfb2001-08-20 21:24:19 +0000183 def test_bare_ampersands(self):
184 self._run_check("this text & contains & ampersands &", [
185 ("data", "this text & contains & ampersands &"),
186 ])
187
188 def test_bare_pointy_brackets(self):
189 self._run_check("this < text > contains < bare>pointy< brackets", [
190 ("data", "this < text > contains < bare>pointy< brackets"),
191 ])
192
Fred Drake84bb9d82001-08-03 19:53:01 +0000193 def test_attr_syntax(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000194 output = [
195 ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", None)])
196 ]
197 self._run_check("""<a b='v' c="v" d=v e>""", output)
198 self._run_check("""<a b = 'v' c = "v" d = v e>""", output)
199 self._run_check("""<a\nb\n=\n'v'\nc\n=\n"v"\nd\n=\nv\ne>""", output)
200 self._run_check("""<a\tb\t=\t'v'\tc\t=\t"v"\td\t=\tv\te>""", output)
201
Fred Drake84bb9d82001-08-03 19:53:01 +0000202 def test_attr_values(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000203 self._run_check("""<a b='xxx\n\txxx' c="yyy\t\nyyy" d='\txyz\n'>""",
204 [("starttag", "a", [("b", "xxx\n\txxx"),
205 ("c", "yyy\t\nyyy"),
206 ("d", "\txyz\n")])
207 ])
208 self._run_check("""<a b='' c="">""", [
209 ("starttag", "a", [("b", ""), ("c", "")]),
210 ])
Fred Drake0834d772003-03-14 16:21:57 +0000211 # Regression test for SF patch #669683.
212 self._run_check("<e a=rgb(1,2,3)>", [
213 ("starttag", "e", [("a", "rgb(1,2,3)")]),
214 ])
Tim Peters27f88362004-07-08 04:22:35 +0000215 # Regression test for SF bug #921657.
Andrew M. Kuchlingb7d8ce02004-06-05 15:31:45 +0000216 self._run_check("<a href=mailto:xyz@example.com>", [
217 ("starttag", "a", [("href", "mailto:xyz@example.com")]),
218 ])
Fred Drakebd3090d2001-05-18 15:32:59 +0000219
Ezio Melotti2e3607c2011-04-07 22:03:31 +0300220 def test_attr_nonascii(self):
221 # see issue 7311
222 self._run_check("<img src=/foo/bar.png alt=\u4e2d\u6587>", [
223 ("starttag", "img", [("src", "/foo/bar.png"),
224 ("alt", "\u4e2d\u6587")]),
225 ])
226 self._run_check("<a title='\u30c6\u30b9\u30c8' "
227 "href='\u30c6\u30b9\u30c8.html'>", [
228 ("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
229 ("href", "\u30c6\u30b9\u30c8.html")]),
230 ])
231 self._run_check('<a title="\u30c6\u30b9\u30c8" '
232 'href="\u30c6\u30b9\u30c8.html">', [
233 ("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
234 ("href", "\u30c6\u30b9\u30c8.html")]),
235 ])
236
Fred Drake84bb9d82001-08-03 19:53:01 +0000237 def test_attr_entity_replacement(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000238 self._run_check("""<a b='&amp;&gt;&lt;&quot;&apos;'>""", [
239 ("starttag", "a", [("b", "&><\"'")]),
240 ])
241
Fred Drake84bb9d82001-08-03 19:53:01 +0000242 def test_attr_funky_names(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000243 self._run_check("""<a a.b='v' c:d=v e-f=v>""", [
244 ("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")]),
245 ])
246
Fred Drakec20a6982001-09-04 15:13:04 +0000247 def test_illegal_declarations(self):
Fred Drake7cf613d2001-09-04 16:26:03 +0000248 self._parse_error('<!spacer type="block" height="25">')
Fred Drakec20a6982001-09-04 15:13:04 +0000249
Fred Drake84bb9d82001-08-03 19:53:01 +0000250 def test_starttag_end_boundary(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000251 self._run_check("""<a b='<'>""", [("starttag", "a", [("b", "<")])])
252 self._run_check("""<a b='>'>""", [("starttag", "a", [("b", ">")])])
253
Fred Drake84bb9d82001-08-03 19:53:01 +0000254 def test_buffer_artefacts(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000255 output = [("starttag", "a", [("b", "<")])]
256 self._run_check(["<a b='<'>"], output)
257 self._run_check(["<a ", "b='<'>"], output)
258 self._run_check(["<a b", "='<'>"], output)
259 self._run_check(["<a b=", "'<'>"], output)
260 self._run_check(["<a b='<", "'>"], output)
261 self._run_check(["<a b='<'", ">"], output)
262
263 output = [("starttag", "a", [("b", ">")])]
264 self._run_check(["<a b='>'>"], output)
265 self._run_check(["<a ", "b='>'>"], output)
266 self._run_check(["<a b", "='>'>"], output)
267 self._run_check(["<a b=", "'>'>"], output)
268 self._run_check(["<a b='>", "'>"], output)
269 self._run_check(["<a b='>'", ">"], output)
270
Fred Drake75d9a622004-09-08 22:57:01 +0000271 output = [("comment", "abc")]
272 self._run_check(["", "<!--abc-->"], output)
273 self._run_check(["<", "!--abc-->"], output)
274 self._run_check(["<!", "--abc-->"], output)
275 self._run_check(["<!-", "-abc-->"], output)
276 self._run_check(["<!--", "abc-->"], output)
277 self._run_check(["<!--a", "bc-->"], output)
278 self._run_check(["<!--ab", "c-->"], output)
279 self._run_check(["<!--abc", "-->"], output)
280 self._run_check(["<!--abc-", "->"], output)
281 self._run_check(["<!--abc--", ">"], output)
282 self._run_check(["<!--abc-->", ""], output)
283
Fred Drake84bb9d82001-08-03 19:53:01 +0000284 def test_starttag_junk_chars(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000285 self._parse_error("</>")
286 self._parse_error("</$>")
287 self._parse_error("</")
288 self._parse_error("</a")
Fred Drakebd3090d2001-05-18 15:32:59 +0000289 self._parse_error("<a<a>")
290 self._parse_error("</a<a>")
Fred Drakebd3090d2001-05-18 15:32:59 +0000291 self._parse_error("<!")
292 self._parse_error("<a $>")
293 self._parse_error("<a")
294 self._parse_error("<a foo='bar'")
295 self._parse_error("<a foo='bar")
296 self._parse_error("<a foo='>'")
297 self._parse_error("<a foo='>")
298 self._parse_error("<a foo=>")
299
Fred Drake84bb9d82001-08-03 19:53:01 +0000300 def test_declaration_junk_chars(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000301 self._parse_error("<!DOCTYPE foo $ >")
302
Fred Drake84bb9d82001-08-03 19:53:01 +0000303 def test_startendtag(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000304 self._run_check("<p/>", [
305 ("startendtag", "p", []),
306 ])
307 self._run_check("<p></p>", [
308 ("starttag", "p", []),
309 ("endtag", "p"),
310 ])
311 self._run_check("<p><img src='foo' /></p>", [
312 ("starttag", "p", []),
313 ("startendtag", "img", [("src", "foo")]),
314 ("endtag", "p"),
315 ])
316
Fred Drake84bb9d82001-08-03 19:53:01 +0000317 def test_get_starttag_text(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000318 s = """<foo:bar \n one="1"\ttwo=2 >"""
319 self._run_check_extra(s, [
320 ("starttag", "foo:bar", [("one", "1"), ("two", "2")]),
321 ("starttag_text", s)])
322
Fred Drake84bb9d82001-08-03 19:53:01 +0000323 def test_cdata_content(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000324 s = """<script> <!-- not a comment --> &not-an-entity-ref; </script>"""
325 self._run_check(s, [
326 ("starttag", "script", []),
327 ("data", " <!-- not a comment --> &not-an-entity-ref; "),
328 ("endtag", "script"),
329 ])
330 s = """<script> <not a='start tag'> </script>"""
331 self._run_check(s, [
332 ("starttag", "script", []),
333 ("data", " <not a='start tag'> "),
334 ("endtag", "script"),
335 ])
336
Guido van Rossumd8faa362007-04-27 19:54:29 +0000337 def test_entityrefs_in_attributes(self):
338 self._run_check("<html foo='&euro;&amp;&#97;&#x61;&unsupported;'>", [
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000339 ("starttag", "html", [("foo", "\u20AC&aa&unsupported;")])
Guido van Rossumd8faa362007-04-27 19:54:29 +0000340 ])
341
Fred Drakebd3090d2001-05-18 15:32:59 +0000342
R. David Murrayb579dba2010-12-03 04:06:39 +0000343class HTMLParserTolerantTestCase(TestCaseBase):
344
345 def setUp(self):
346 self.collector = EventCollector(strict=False)
347
348 def test_tolerant_parsing(self):
349 self._run_check('<html <html>te>>xt&a<<bc</a></html>\n'
350 '<img src="URL><//img></html</html>', [
351 ('data', '<html '),
352 ('starttag', 'html', []),
353 ('data', 'te>>xt'),
354 ('entityref', 'a'),
355 ('data', '<<bc'),
356 ('endtag', 'a'),
357 ('endtag', 'html'),
358 ('data', '\n<img src="URL><//img></html'),
359 ('endtag', 'html')],
360 collector = self.collector)
361
362 def test_comma_between_attributes(self):
363 self._run_check('<form action="/xxx.php?a=1&amp;b=2&amp", '
364 'method="post">', [
365 ('starttag', 'form',
366 [('action', '/xxx.php?a=1&b=2&amp'),
367 ('method', 'post')])],
368 collector = self.collector)
369
370 def test_weird_chars_in_unquoted_attribute_values(self):
371 self._run_check('<form action=bogus|&#()value>', [
372 ('starttag', 'form',
373 [('action', 'bogus|&#()value')])],
374 collector = self.collector)
375
Senthil Kumaran164540f2010-12-28 15:55:16 +0000376 def test_unescape_function(self):
377 p = html.parser.HTMLParser()
378 self.assertEqual(p.unescape('&#bad;'),'&#bad;')
379 self.assertEqual(p.unescape('&#0038;'),'&')
380
R. David Murrayb579dba2010-12-03 04:06:39 +0000381
Fred Drakee8220492001-09-24 20:19:08 +0000382def test_main():
R. David Murrayb579dba2010-12-03 04:06:39 +0000383 support.run_unittest(HTMLParserTestCase, HTMLParserTolerantTestCase)
Fred Drakee8220492001-09-24 20:19:08 +0000384
385
386if __name__ == "__main__":
387 test_main()