blob: b85beab333fd7b460ee53a95ebfcdae2481027c1 [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):
Ezio Melotti7de56f62011-11-01 14:12:22 +0200324 contents = [
325 '<!-- not a comment --> &not-an-entity-ref;',
326 "<not a='start tag'>",
327 '<a href="" /> <p> <span></span>',
328 'foo = "</scr" + "ipt>";',
329 'foo = "</SCRIPT" + ">";',
330 'foo = <\n/script> ',
331 '<!-- document.write("</scr" + "ipt>"); -->',
332 ('\n//<![CDATA[\n'
333 'document.write(\'<s\'+\'cript type="text/javascript" '
334 'src="http://www.example.org/r=\'+new '
335 'Date().getTime()+\'"><\\/s\'+\'cript>\');\n//]]>'),
336 '\n<!-- //\nvar foo = 3.14;\n// -->\n',
337 'foo = "</sty" + "le>";',
338 '<!-- \u2603 -->',
339 # these two should be invalid according to the HTML 5 spec,
340 # section 8.1.2.2
341 #'foo = </\nscript>',
342 #'foo = </ script>',
343 ]
344 elements = ['script', 'style', 'SCRIPT', 'STYLE', 'Script', 'Style']
345 for content in contents:
346 for element in elements:
347 element_lower = element.lower()
348 s = '<{element}>{content}</{element}>'.format(element=element,
349 content=content)
350 self._run_check(s, [("starttag", element_lower, []),
351 ("data", content),
352 ("endtag", element_lower)])
353
Fred Drakebd3090d2001-05-18 15:32:59 +0000354
Guido van Rossumd8faa362007-04-27 19:54:29 +0000355 def test_entityrefs_in_attributes(self):
356 self._run_check("<html foo='&euro;&amp;&#97;&#x61;&unsupported;'>", [
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000357 ("starttag", "html", [("foo", "\u20AC&aa&unsupported;")])
Guido van Rossumd8faa362007-04-27 19:54:29 +0000358 ])
359
Fred Drakebd3090d2001-05-18 15:32:59 +0000360
R. David Murrayb579dba2010-12-03 04:06:39 +0000361class HTMLParserTolerantTestCase(TestCaseBase):
362
363 def setUp(self):
364 self.collector = EventCollector(strict=False)
365
366 def test_tolerant_parsing(self):
367 self._run_check('<html <html>te>>xt&a<<bc</a></html>\n'
368 '<img src="URL><//img></html</html>', [
369 ('data', '<html '),
370 ('starttag', 'html', []),
371 ('data', 'te>>xt'),
372 ('entityref', 'a'),
373 ('data', '<<bc'),
374 ('endtag', 'a'),
375 ('endtag', 'html'),
376 ('data', '\n<img src="URL><//img></html'),
377 ('endtag', 'html')],
378 collector = self.collector)
379
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200380 def test_with_unquoted_attributes(self):
381 html = ("<html><body bgcolor=d0ca90 text='181008'>"
382 "<table cellspacing=0 cellpadding=1 width=100% ><tr>"
383 "<td align=left><font size=-1>"
384 "- <a href=/rabota/><span class=en> software-and-i</span></a>"
385 "- <a href='/1/'><span class=en> library</span></a></table>")
386 expected = [
387 ('starttag', 'html', []),
388 ('starttag', 'body', [('bgcolor', 'd0ca90'), ('text', '181008')]),
389 ('starttag', 'table',
390 [('cellspacing', '0'), ('cellpadding', '1'), ('width', '100%')]),
391 ('starttag', 'tr', []),
392 ('starttag', 'td', [('align', 'left')]),
393 ('starttag', 'font', [('size', '-1')]),
394 ('data', '- '), ('starttag', 'a', [('href', '/rabota/')]),
395 ('starttag', 'span', [('class', 'en')]), ('data', ' software-and-i'),
396 ('endtag', 'span'), ('endtag', 'a'),
397 ('data', '- '), ('starttag', 'a', [('href', '/1/')]),
398 ('starttag', 'span', [('class', 'en')]), ('data', ' library'),
399 ('endtag', 'span'), ('endtag', 'a'), ('endtag', 'table')
400 ]
401
402 self._run_check(html, expected, collector=self.collector)
403
R. David Murrayb579dba2010-12-03 04:06:39 +0000404 def test_comma_between_attributes(self):
405 self._run_check('<form action="/xxx.php?a=1&amp;b=2&amp", '
406 'method="post">', [
407 ('starttag', 'form',
408 [('action', '/xxx.php?a=1&b=2&amp'),
409 ('method', 'post')])],
410 collector = self.collector)
411
412 def test_weird_chars_in_unquoted_attribute_values(self):
413 self._run_check('<form action=bogus|&#()value>', [
414 ('starttag', 'form',
415 [('action', 'bogus|&#()value')])],
416 collector = self.collector)
417
Ezio Melottif50ffa92011-10-28 13:21:09 +0300418 def test_issue13273(self):
419 html = ('<div style="" ><b>The <a href="some_url">rain</a> '
420 '<br /> in <span>Spain</span></b></div>')
421 expected = [
422 ('starttag', 'div', [('style', '')]),
423 ('starttag', 'b', []),
424 ('data', 'The '),
425 ('starttag', 'a', [('href', 'some_url')]),
426 ('data', 'rain'),
427 ('endtag', 'a'),
428 ('data', ' '),
429 ('startendtag', 'br', []),
430 ('data', ' in '),
431 ('starttag', 'span', []),
432 ('data', 'Spain'),
433 ('endtag', 'span'),
434 ('endtag', 'b'),
435 ('endtag', 'div')
436 ]
437 self._run_check(html, expected, collector=self.collector)
438
439 def test_issue13273_2(self):
440 html = '<div style="", foo = "bar" ><b>The <a href="some_url">rain</a>'
441 expected = [
442 ('starttag', 'div', [('style', ''), ('foo', 'bar')]),
443 ('starttag', 'b', []),
444 ('data', 'The '),
445 ('starttag', 'a', [('href', 'some_url')]),
446 ('data', 'rain'),
447 ('endtag', 'a'),
448 ]
449 self._run_check(html, expected, collector=self.collector)
450
Senthil Kumaran164540f2010-12-28 15:55:16 +0000451 def test_unescape_function(self):
452 p = html.parser.HTMLParser()
453 self.assertEqual(p.unescape('&#bad;'),'&#bad;')
454 self.assertEqual(p.unescape('&#0038;'),'&')
Ezio Melottid9e0b062011-09-05 17:11:06 +0300455 # see #12888
456 self.assertEqual(p.unescape('&#123; ' * 1050), '{ ' * 1050)
R. David Murrayb579dba2010-12-03 04:06:39 +0000457
Fred Drakee8220492001-09-24 20:19:08 +0000458def test_main():
R. David Murrayb579dba2010-12-03 04:06:39 +0000459 support.run_unittest(HTMLParserTestCase, HTMLParserTolerantTestCase)
Fred Drakee8220492001-09-24 20:19:08 +0000460
461
462if __name__ == "__main__":
463 test_main()