blob: beaf6b63a239ca5892bd47b200ecab34ee8ef3a6 [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
Fred Drake84bb9d82001-08-03 19:53:01 +0000220 def test_attr_entity_replacement(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000221 self._run_check("""<a b='&amp;&gt;&lt;&quot;&apos;'>""", [
222 ("starttag", "a", [("b", "&><\"'")]),
223 ])
224
Fred Drake84bb9d82001-08-03 19:53:01 +0000225 def test_attr_funky_names(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000226 self._run_check("""<a a.b='v' c:d=v e-f=v>""", [
227 ("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")]),
228 ])
229
Fred Drakec20a6982001-09-04 15:13:04 +0000230 def test_illegal_declarations(self):
Fred Drake7cf613d2001-09-04 16:26:03 +0000231 self._parse_error('<!spacer type="block" height="25">')
Fred Drakec20a6982001-09-04 15:13:04 +0000232
Fred Drake84bb9d82001-08-03 19:53:01 +0000233 def test_starttag_end_boundary(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000234 self._run_check("""<a b='<'>""", [("starttag", "a", [("b", "<")])])
235 self._run_check("""<a b='>'>""", [("starttag", "a", [("b", ">")])])
236
Fred Drake84bb9d82001-08-03 19:53:01 +0000237 def test_buffer_artefacts(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000238 output = [("starttag", "a", [("b", "<")])]
239 self._run_check(["<a b='<'>"], output)
240 self._run_check(["<a ", "b='<'>"], output)
241 self._run_check(["<a b", "='<'>"], output)
242 self._run_check(["<a b=", "'<'>"], output)
243 self._run_check(["<a b='<", "'>"], output)
244 self._run_check(["<a b='<'", ">"], output)
245
246 output = [("starttag", "a", [("b", ">")])]
247 self._run_check(["<a b='>'>"], output)
248 self._run_check(["<a ", "b='>'>"], output)
249 self._run_check(["<a b", "='>'>"], output)
250 self._run_check(["<a b=", "'>'>"], output)
251 self._run_check(["<a b='>", "'>"], output)
252 self._run_check(["<a b='>'", ">"], output)
253
Fred Drake75d9a622004-09-08 22:57:01 +0000254 output = [("comment", "abc")]
255 self._run_check(["", "<!--abc-->"], output)
256 self._run_check(["<", "!--abc-->"], output)
257 self._run_check(["<!", "--abc-->"], output)
258 self._run_check(["<!-", "-abc-->"], output)
259 self._run_check(["<!--", "abc-->"], output)
260 self._run_check(["<!--a", "bc-->"], output)
261 self._run_check(["<!--ab", "c-->"], output)
262 self._run_check(["<!--abc", "-->"], output)
263 self._run_check(["<!--abc-", "->"], output)
264 self._run_check(["<!--abc--", ">"], output)
265 self._run_check(["<!--abc-->", ""], output)
266
Fred Drake84bb9d82001-08-03 19:53:01 +0000267 def test_starttag_junk_chars(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000268 self._parse_error("</>")
269 self._parse_error("</$>")
270 self._parse_error("</")
271 self._parse_error("</a")
Fred Drakebd3090d2001-05-18 15:32:59 +0000272 self._parse_error("<a<a>")
273 self._parse_error("</a<a>")
Fred Drakebd3090d2001-05-18 15:32:59 +0000274 self._parse_error("<!")
275 self._parse_error("<a $>")
276 self._parse_error("<a")
277 self._parse_error("<a foo='bar'")
278 self._parse_error("<a foo='bar")
279 self._parse_error("<a foo='>'")
280 self._parse_error("<a foo='>")
281 self._parse_error("<a foo=>")
282
Fred Drake84bb9d82001-08-03 19:53:01 +0000283 def test_declaration_junk_chars(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000284 self._parse_error("<!DOCTYPE foo $ >")
285
Fred Drake84bb9d82001-08-03 19:53:01 +0000286 def test_startendtag(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000287 self._run_check("<p/>", [
288 ("startendtag", "p", []),
289 ])
290 self._run_check("<p></p>", [
291 ("starttag", "p", []),
292 ("endtag", "p"),
293 ])
294 self._run_check("<p><img src='foo' /></p>", [
295 ("starttag", "p", []),
296 ("startendtag", "img", [("src", "foo")]),
297 ("endtag", "p"),
298 ])
299
Fred Drake84bb9d82001-08-03 19:53:01 +0000300 def test_get_starttag_text(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000301 s = """<foo:bar \n one="1"\ttwo=2 >"""
302 self._run_check_extra(s, [
303 ("starttag", "foo:bar", [("one", "1"), ("two", "2")]),
304 ("starttag_text", s)])
305
Fred Drake84bb9d82001-08-03 19:53:01 +0000306 def test_cdata_content(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000307 s = """<script> <!-- not a comment --> &not-an-entity-ref; </script>"""
308 self._run_check(s, [
309 ("starttag", "script", []),
310 ("data", " <!-- not a comment --> &not-an-entity-ref; "),
311 ("endtag", "script"),
312 ])
313 s = """<script> <not a='start tag'> </script>"""
314 self._run_check(s, [
315 ("starttag", "script", []),
316 ("data", " <not a='start tag'> "),
317 ("endtag", "script"),
318 ])
319
Guido van Rossumd8faa362007-04-27 19:54:29 +0000320 def test_entityrefs_in_attributes(self):
321 self._run_check("<html foo='&euro;&amp;&#97;&#x61;&unsupported;'>", [
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000322 ("starttag", "html", [("foo", "\u20AC&aa&unsupported;")])
Guido van Rossumd8faa362007-04-27 19:54:29 +0000323 ])
324
Fred Drakebd3090d2001-05-18 15:32:59 +0000325
R. David Murrayb579dba2010-12-03 04:06:39 +0000326class HTMLParserTolerantTestCase(TestCaseBase):
327
328 def setUp(self):
329 self.collector = EventCollector(strict=False)
330
331 def test_tolerant_parsing(self):
332 self._run_check('<html <html>te>>xt&a<<bc</a></html>\n'
333 '<img src="URL><//img></html</html>', [
334 ('data', '<html '),
335 ('starttag', 'html', []),
336 ('data', 'te>>xt'),
337 ('entityref', 'a'),
338 ('data', '<<bc'),
339 ('endtag', 'a'),
340 ('endtag', 'html'),
341 ('data', '\n<img src="URL><//img></html'),
342 ('endtag', 'html')],
343 collector = self.collector)
344
345 def test_comma_between_attributes(self):
346 self._run_check('<form action="/xxx.php?a=1&amp;b=2&amp", '
347 'method="post">', [
348 ('starttag', 'form',
349 [('action', '/xxx.php?a=1&b=2&amp'),
350 ('method', 'post')])],
351 collector = self.collector)
352
353 def test_weird_chars_in_unquoted_attribute_values(self):
354 self._run_check('<form action=bogus|&#()value>', [
355 ('starttag', 'form',
356 [('action', 'bogus|&#()value')])],
357 collector = self.collector)
358
359
Fred Drakee8220492001-09-24 20:19:08 +0000360def test_main():
R. David Murrayb579dba2010-12-03 04:06:39 +0000361 support.run_unittest(HTMLParserTestCase, HTMLParserTolerantTestCase)
Fred Drakee8220492001-09-24 20:19:08 +0000362
363
364if __name__ == "__main__":
365 test_main()