blob: 192a34193547d19400eecc65027723f4c7ca8dff [file] [log] [blame]
Fred Drakebd3090d2001-05-18 15:32:59 +00001"""Tests for HTMLParser.py."""
2
Georg Brandlbcdafa42008-05-20 07:58:42 +00003import HTMLParser
Fred Drake029acfb2001-08-20 21:24:19 +00004import pprint
Fred Drakebd3090d2001-05-18 15:32:59 +00005import unittest
Barry Warsaw04f357c2002-07-23 19:04:11 +00006from test import test_support
Fred Drakebd3090d2001-05-18 15:32:59 +00007
8
Georg Brandlbcdafa42008-05-20 07:58:42 +00009class EventCollector(HTMLParser.HTMLParser):
Fred Drakebd3090d2001-05-18 15:32:59 +000010
11 def __init__(self):
12 self.events = []
13 self.append = self.events.append
Georg Brandlbcdafa42008-05-20 07:58:42 +000014 HTMLParser.HTMLParser.__init__(self)
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
Fred Drakec20a6982001-09-04 15:13:04 +000075 def _run_check(self, source, expected_events, collector=EventCollector):
Fred Drakebd3090d2001-05-18 15:32:59 +000076 parser = collector()
Fred Drakebd3090d2001-05-18 15:32:59 +000077 for s in source:
78 parser.feed(s)
Fred Drakebd3090d2001-05-18 15:32:59 +000079 parser.close()
Fred Drake029acfb2001-08-20 21:24:19 +000080 events = parser.get_events()
Fred Drakec20a6982001-09-04 15:13:04 +000081 if events != expected_events:
82 self.fail("received events did not match expected events\n"
83 "Expected:\n" + pprint.pformat(expected_events) +
84 "\nReceived:\n" + pprint.pformat(events))
Fred Drakebd3090d2001-05-18 15:32:59 +000085
86 def _run_check_extra(self, source, events):
87 self._run_check(source, events, EventCollectorExtra)
88
89 def _parse_error(self, source):
90 def parse(source=source):
Georg Brandlbcdafa42008-05-20 07:58:42 +000091 parser = HTMLParser.HTMLParser()
Fred Drakebd3090d2001-05-18 15:32:59 +000092 parser.feed(source)
93 parser.close()
Georg Brandlbcdafa42008-05-20 07:58:42 +000094 self.assertRaises(HTMLParser.HTMLParseError, parse)
Fred Drakebd3090d2001-05-18 15:32:59 +000095
96
97class HTMLParserTestCase(TestCaseBase):
98
Fred Drake84bb9d82001-08-03 19:53:01 +000099 def test_processing_instruction_only(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000100 self._run_check("<?processing instruction>", [
101 ("pi", "processing instruction"),
102 ])
Fred Drakefafd56f2003-04-17 22:19:26 +0000103 self._run_check("<?processing instruction ?>", [
104 ("pi", "processing instruction ?"),
105 ])
Fred Drakebd3090d2001-05-18 15:32:59 +0000106
Fred Drake84bb9d82001-08-03 19:53:01 +0000107 def test_simple_html(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000108 self._run_check("""
109<!DOCTYPE html PUBLIC 'foo'>
110<HTML>&entity;&#32;
111<!--comment1a
112-></foo><bar>&lt;<?pi?></foo<bar
113comment1b-->
114<Img sRc='Bar' isMAP>sample
115text
Fred Drake84bb9d82001-08-03 19:53:01 +0000116&#x201C;
Georg Brandld09def32006-03-09 13:27:14 +0000117<!--comment2a-- --comment2b--><!>
Fred Drakebd3090d2001-05-18 15:32:59 +0000118</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>&lt;<?pi?></foo<bar\ncomment1b"),
128 ("data", "\n"),
129 ("starttag", "img", [("src", "Bar"), ("ismap", None)]),
130 ("data", "sample\ntext\n"),
Fred Drake84bb9d82001-08-03 19:53:01 +0000131 ("charref", "x201C"),
132 ("data", "\n"),
Fred Drakebd3090d2001-05-18 15:32:59 +0000133 ("comment", "comment2a-- --comment2b"),
134 ("data", "\n"),
135 ("endtag", "html"),
136 ("data", "\n"),
137 ])
138
Fred Drake073148c2001-12-03 16:44:09 +0000139 def test_unclosed_entityref(self):
140 self._run_check("&entityref foo", [
141 ("entityref", "entityref"),
142 ("data", " foo"),
143 ])
144
Fred Drake029acfb2001-08-20 21:24:19 +0000145 def test_doctype_decl(self):
146 inside = """\
147DOCTYPE html [
148 <!ELEMENT html - O EMPTY>
149 <!ATTLIST html
Fred Drakec20a6982001-09-04 15:13:04 +0000150 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;
Fred Drake029acfb2001-08-20 21:24:19 +0000157 <!-- comment -->
158]"""
159 self._run_check("<!%s>" % inside, [
160 ("decl", inside),
161 ])
162
Fred Drake84bb9d82001-08-03 19:53:01 +0000163 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.
Fred Drakebd3090d2001-05-18 15:32:59 +0000167 self._run_check("<a><b></a></b>", [
168 ("starttag", "a", []),
169 ("starttag", "b", []),
170 ("endtag", "a"),
171 ("endtag", "b"),
172 ])
173
Fred Drake029acfb2001-08-20 21:24:19 +0000174 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
Fred Drakec20a6982001-09-04 15:13:04 +0000184 def test_illegal_declarations(self):
Fred Drake7cf613d2001-09-04 16:26:03 +0000185 self._parse_error('<!spacer type="block" height="25">')
Fred Drakec20a6982001-09-04 15:13:04 +0000186
Fred Drake84bb9d82001-08-03 19:53:01 +0000187 def test_starttag_end_boundary(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000188 self._run_check("""<a b='<'>""", [("starttag", "a", [("b", "<")])])
189 self._run_check("""<a b='>'>""", [("starttag", "a", [("b", ">")])])
190
Fred Drake84bb9d82001-08-03 19:53:01 +0000191 def test_buffer_artefacts(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000192 output = [("starttag", "a", [("b", "<")])]
193 self._run_check(["<a b='<'>"], output)
194 self._run_check(["<a ", "b='<'>"], output)
195 self._run_check(["<a b", "='<'>"], output)
196 self._run_check(["<a b=", "'<'>"], output)
197 self._run_check(["<a b='<", "'>"], output)
198 self._run_check(["<a b='<'", ">"], output)
199
200 output = [("starttag", "a", [("b", ">")])]
201 self._run_check(["<a b='>'>"], output)
202 self._run_check(["<a ", "b='>'>"], output)
203 self._run_check(["<a b", "='>'>"], output)
204 self._run_check(["<a b=", "'>'>"], output)
205 self._run_check(["<a b='>", "'>"], output)
206 self._run_check(["<a b='>'", ">"], output)
207
Fred Drake75d9a622004-09-08 22:57:01 +0000208 output = [("comment", "abc")]
209 self._run_check(["", "<!--abc-->"], output)
210 self._run_check(["<", "!--abc-->"], output)
211 self._run_check(["<!", "--abc-->"], output)
212 self._run_check(["<!-", "-abc-->"], output)
213 self._run_check(["<!--", "abc-->"], output)
214 self._run_check(["<!--a", "bc-->"], output)
215 self._run_check(["<!--ab", "c-->"], output)
216 self._run_check(["<!--abc", "-->"], output)
217 self._run_check(["<!--abc-", "->"], output)
218 self._run_check(["<!--abc--", ">"], output)
219 self._run_check(["<!--abc-->", ""], output)
220
Fred Drake84bb9d82001-08-03 19:53:01 +0000221 def test_starttag_junk_chars(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000222 self._parse_error("</>")
223 self._parse_error("</$>")
224 self._parse_error("</")
225 self._parse_error("</a")
Fred Drakebd3090d2001-05-18 15:32:59 +0000226 self._parse_error("<a<a>")
227 self._parse_error("</a<a>")
Fred Drakebd3090d2001-05-18 15:32:59 +0000228 self._parse_error("<!")
229 self._parse_error("<a $>")
230 self._parse_error("<a")
231 self._parse_error("<a foo='bar'")
232 self._parse_error("<a foo='bar")
233 self._parse_error("<a foo='>'")
234 self._parse_error("<a foo='>")
235 self._parse_error("<a foo=>")
236
Fred Drake84bb9d82001-08-03 19:53:01 +0000237 def test_declaration_junk_chars(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000238 self._parse_error("<!DOCTYPE foo $ >")
239
Fred Drake84bb9d82001-08-03 19:53:01 +0000240 def test_startendtag(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000241 self._run_check("<p/>", [
242 ("startendtag", "p", []),
243 ])
244 self._run_check("<p></p>", [
245 ("starttag", "p", []),
246 ("endtag", "p"),
247 ])
248 self._run_check("<p><img src='foo' /></p>", [
249 ("starttag", "p", []),
250 ("startendtag", "img", [("src", "foo")]),
251 ("endtag", "p"),
252 ])
253
Fred Drake84bb9d82001-08-03 19:53:01 +0000254 def test_get_starttag_text(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000255 s = """<foo:bar \n one="1"\ttwo=2 >"""
256 self._run_check_extra(s, [
257 ("starttag", "foo:bar", [("one", "1"), ("two", "2")]),
258 ("starttag_text", s)])
259
Fred Drake84bb9d82001-08-03 19:53:01 +0000260 def test_cdata_content(self):
Ezio Melotti7e82b272011-11-01 14:09:56 +0200261 contents = [
262 '<!-- not a comment --> &not-an-entity-ref;',
263 "<not a='start tag'>",
264 '<a href="" /> <p> <span></span>',
265 'foo = "</scr" + "ipt>";',
266 'foo = "</SCRIPT" + ">";',
267 'foo = <\n/script> ',
268 '<!-- document.write("</scr" + "ipt>"); -->',
269 ('\n//<![CDATA[\n'
270 'document.write(\'<s\'+\'cript type="text/javascript" '
271 'src="http://www.example.org/r=\'+new '
272 'Date().getTime()+\'"><\\/s\'+\'cript>\');\n//]]>'),
273 '\n<!-- //\nvar foo = 3.14;\n// -->\n',
274 'foo = "</sty" + "le>";',
275 u'<!-- \u2603 -->',
276 # these two should be invalid according to the HTML 5 spec,
277 # section 8.1.2.2
278 #'foo = </\nscript>',
279 #'foo = </ script>',
280 ]
281 elements = ['script', 'style', 'SCRIPT', 'STYLE', 'Script', 'Style']
282 for content in contents:
283 for element in elements:
284 element_lower = element.lower()
285 s = u'<{element}>{content}</{element}>'.format(element=element,
286 content=content)
287 self._run_check(s, [("starttag", element_lower, []),
288 ("data", content),
289 ("endtag", element_lower)])
290
Victor Stinner554a3b82010-05-24 21:33:24 +0000291 def test_malformatted_charref(self):
292 self._run_check("<p>&#bad;</p>", [
293 ("starttag", "p", []),
294 ("data", "&#bad;"),
295 ("endtag", "p"),
296 ])
297
Senthil Kumaran3f60f092010-12-28 16:05:07 +0000298 def test_unescape_function(self):
299 parser = HTMLParser.HTMLParser()
300 self.assertEqual(parser.unescape('&#bad;'),'&#bad;')
301 self.assertEqual(parser.unescape('&#0038;'),'&')
302
Fred Drakebd3090d2001-05-18 15:32:59 +0000303
Ezio Melotti74592912011-11-08 02:07:18 +0200304
305class AttributesTestCase(TestCaseBase):
306
307 def test_attr_syntax(self):
308 output = [
309 ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", None)])
310 ]
311 self._run_check("""<a b='v' c="v" d=v e>""", output)
312 self._run_check("""<a b = 'v' c = "v" d = v e>""", output)
313 self._run_check("""<a\nb\n=\n'v'\nc\n=\n"v"\nd\n=\nv\ne>""", output)
314 self._run_check("""<a\tb\t=\t'v'\tc\t=\t"v"\td\t=\tv\te>""", output)
315
316 def test_attr_values(self):
317 self._run_check("""<a b='xxx\n\txxx' c="yyy\t\nyyy" d='\txyz\n'>""",
318 [("starttag", "a", [("b", "xxx\n\txxx"),
319 ("c", "yyy\t\nyyy"),
320 ("d", "\txyz\n")])])
321 self._run_check("""<a b='' c="">""",
322 [("starttag", "a", [("b", ""), ("c", "")])])
323 # Regression test for SF patch #669683.
324 self._run_check("<e a=rgb(1,2,3)>",
325 [("starttag", "e", [("a", "rgb(1,2,3)")])])
326 # Regression test for SF bug #921657.
327 self._run_check(
328 "<a href=mailto:xyz@example.com>",
329 [("starttag", "a", [("href", "mailto:xyz@example.com")])])
330
331 def test_attr_nonascii(self):
332 # see issue 7311
333 self._run_check(
334 u"<img src=/foo/bar.png alt=\u4e2d\u6587>",
335 [("starttag", "img", [("src", "/foo/bar.png"),
336 ("alt", u"\u4e2d\u6587")])])
337 self._run_check(
338 u"<a title='\u30c6\u30b9\u30c8' href='\u30c6\u30b9\u30c8.html'>",
339 [("starttag", "a", [("title", u"\u30c6\u30b9\u30c8"),
340 ("href", u"\u30c6\u30b9\u30c8.html")])])
341 self._run_check(
342 u'<a title="\u30c6\u30b9\u30c8" href="\u30c6\u30b9\u30c8.html">',
343 [("starttag", "a", [("title", u"\u30c6\u30b9\u30c8"),
344 ("href", u"\u30c6\u30b9\u30c8.html")])])
345
346 def test_attr_entity_replacement(self):
347 self._run_check(
348 "<a b='&amp;&gt;&lt;&quot;&apos;'>",
349 [("starttag", "a", [("b", "&><\"'")])])
350
351 def test_attr_funky_names(self):
352 self._run_check(
353 "<a a.b='v' c:d=v e-f=v>",
354 [("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")])])
355
356
357 def test_entityrefs_in_attributes(self):
358 self._run_check(
359 "<html foo='&euro;&amp;&#97;&#x61;&unsupported;'>",
360 [("starttag", "html", [("foo", u"\u20AC&aa&unsupported;")])])
361
Fred Drakee8220492001-09-24 20:19:08 +0000362def test_main():
Ezio Melotti74592912011-11-08 02:07:18 +0200363 test_support.run_unittest(HTMLParserTestCase, AttributesTestCase)
Fred Drakee8220492001-09-24 20:19:08 +0000364
365
366if __name__ == "__main__":
367 test_main()