blob: 3e2a59064e5bbf3e82b139048b895e1bfaa1a570 [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
Ezio Melottic1e73c32011-11-01 18:57:15 +020075 def get_collector(self):
76 raise NotImplementedError
77
R. David Murrayb579dba2010-12-03 04:06:39 +000078 def _run_check(self, source, expected_events, collector=None):
79 if collector is None:
Ezio Melottic1e73c32011-11-01 18:57:15 +020080 collector = self.get_collector()
R. David Murrayb579dba2010-12-03 04:06:39 +000081 parser = collector
Fred Drakebd3090d2001-05-18 15:32:59 +000082 for s in source:
83 parser.feed(s)
Fred Drakebd3090d2001-05-18 15:32:59 +000084 parser.close()
Fred Drake029acfb2001-08-20 21:24:19 +000085 events = parser.get_events()
Fred Drakec20a6982001-09-04 15:13:04 +000086 if events != expected_events:
87 self.fail("received events did not match expected events\n"
88 "Expected:\n" + pprint.pformat(expected_events) +
89 "\nReceived:\n" + pprint.pformat(events))
Fred Drakebd3090d2001-05-18 15:32:59 +000090
91 def _run_check_extra(self, source, events):
R. David Murrayb579dba2010-12-03 04:06:39 +000092 self._run_check(source, events, EventCollectorExtra())
Fred Drakebd3090d2001-05-18 15:32:59 +000093
94 def _parse_error(self, source):
95 def parse(source=source):
Ezio Melotti86f67122012-02-13 14:11:27 +020096 parser = self.get_collector()
Fred Drakebd3090d2001-05-18 15:32:59 +000097 parser.feed(source)
98 parser.close()
Mark Dickinsonf64dcf32008-05-21 13:51:18 +000099 self.assertRaises(html.parser.HTMLParseError, parse)
Fred Drakebd3090d2001-05-18 15:32:59 +0000100
101
Ezio Melottic1e73c32011-11-01 18:57:15 +0200102class HTMLParserStrictTestCase(TestCaseBase):
103
104 def get_collector(self):
105 return EventCollector(strict=True)
Fred Drakebd3090d2001-05-18 15:32:59 +0000106
Fred Drake84bb9d82001-08-03 19:53:01 +0000107 def test_processing_instruction_only(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000108 self._run_check("<?processing instruction>", [
109 ("pi", "processing instruction"),
110 ])
Fred Drakefafd56f2003-04-17 22:19:26 +0000111 self._run_check("<?processing instruction ?>", [
112 ("pi", "processing instruction ?"),
113 ])
Fred Drakebd3090d2001-05-18 15:32:59 +0000114
Fred Drake84bb9d82001-08-03 19:53:01 +0000115 def test_simple_html(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000116 self._run_check("""
117<!DOCTYPE html PUBLIC 'foo'>
118<HTML>&entity;&#32;
119<!--comment1a
120-></foo><bar>&lt;<?pi?></foo<bar
121comment1b-->
122<Img sRc='Bar' isMAP>sample
123text
Fred Drake84bb9d82001-08-03 19:53:01 +0000124&#x201C;
Ezio Melottif4ab4912012-02-13 15:50:37 +0200125<!--comment2a-- --comment2b-->
Fred Drakebd3090d2001-05-18 15:32:59 +0000126</Html>
127""", [
128 ("data", "\n"),
129 ("decl", "DOCTYPE html PUBLIC 'foo'"),
130 ("data", "\n"),
131 ("starttag", "html", []),
132 ("entityref", "entity"),
133 ("charref", "32"),
134 ("data", "\n"),
135 ("comment", "comment1a\n-></foo><bar>&lt;<?pi?></foo<bar\ncomment1b"),
136 ("data", "\n"),
137 ("starttag", "img", [("src", "Bar"), ("ismap", None)]),
138 ("data", "sample\ntext\n"),
Fred Drake84bb9d82001-08-03 19:53:01 +0000139 ("charref", "x201C"),
140 ("data", "\n"),
Fred Drakebd3090d2001-05-18 15:32:59 +0000141 ("comment", "comment2a-- --comment2b"),
142 ("data", "\n"),
143 ("endtag", "html"),
144 ("data", "\n"),
145 ])
146
Victor Stinnere021f4b2010-05-24 21:46:25 +0000147 def test_malformatted_charref(self):
148 self._run_check("<p>&#bad;</p>", [
149 ("starttag", "p", []),
150 ("data", "&#bad;"),
151 ("endtag", "p"),
152 ])
153
Fred Drake073148c2001-12-03 16:44:09 +0000154 def test_unclosed_entityref(self):
155 self._run_check("&entityref foo", [
156 ("entityref", "entityref"),
157 ("data", " foo"),
158 ])
159
Fred Drake84bb9d82001-08-03 19:53:01 +0000160 def test_bad_nesting(self):
161 # Strangely, this *is* supposed to test that overlapping
162 # elements are allowed. HTMLParser is more geared toward
163 # lexing the input that parsing the structure.
Fred Drakebd3090d2001-05-18 15:32:59 +0000164 self._run_check("<a><b></a></b>", [
165 ("starttag", "a", []),
166 ("starttag", "b", []),
167 ("endtag", "a"),
168 ("endtag", "b"),
169 ])
170
Fred Drake029acfb2001-08-20 21:24:19 +0000171 def test_bare_ampersands(self):
172 self._run_check("this text & contains & ampersands &", [
173 ("data", "this text & contains & ampersands &"),
174 ])
175
176 def test_bare_pointy_brackets(self):
177 self._run_check("this < text > contains < bare>pointy< brackets", [
178 ("data", "this < text > contains < bare>pointy< brackets"),
179 ])
180
Fred Drakec20a6982001-09-04 15:13:04 +0000181 def test_illegal_declarations(self):
Fred Drake7cf613d2001-09-04 16:26:03 +0000182 self._parse_error('<!spacer type="block" height="25">')
Fred Drakec20a6982001-09-04 15:13:04 +0000183
Fred Drake84bb9d82001-08-03 19:53:01 +0000184 def test_starttag_end_boundary(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000185 self._run_check("""<a b='<'>""", [("starttag", "a", [("b", "<")])])
186 self._run_check("""<a b='>'>""", [("starttag", "a", [("b", ">")])])
187
Fred Drake84bb9d82001-08-03 19:53:01 +0000188 def test_buffer_artefacts(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000189 output = [("starttag", "a", [("b", "<")])]
190 self._run_check(["<a b='<'>"], output)
191 self._run_check(["<a ", "b='<'>"], output)
192 self._run_check(["<a b", "='<'>"], output)
193 self._run_check(["<a b=", "'<'>"], output)
194 self._run_check(["<a b='<", "'>"], output)
195 self._run_check(["<a b='<'", ">"], output)
196
197 output = [("starttag", "a", [("b", ">")])]
198 self._run_check(["<a b='>'>"], output)
199 self._run_check(["<a ", "b='>'>"], output)
200 self._run_check(["<a b", "='>'>"], output)
201 self._run_check(["<a b=", "'>'>"], output)
202 self._run_check(["<a b='>", "'>"], output)
203 self._run_check(["<a b='>'", ">"], output)
204
Fred Drake75d9a622004-09-08 22:57:01 +0000205 output = [("comment", "abc")]
206 self._run_check(["", "<!--abc-->"], output)
207 self._run_check(["<", "!--abc-->"], output)
208 self._run_check(["<!", "--abc-->"], output)
209 self._run_check(["<!-", "-abc-->"], output)
210 self._run_check(["<!--", "abc-->"], output)
211 self._run_check(["<!--a", "bc-->"], output)
212 self._run_check(["<!--ab", "c-->"], output)
213 self._run_check(["<!--abc", "-->"], output)
214 self._run_check(["<!--abc-", "->"], output)
215 self._run_check(["<!--abc--", ">"], output)
216 self._run_check(["<!--abc-->", ""], output)
217
Fred Drake84bb9d82001-08-03 19:53:01 +0000218 def test_starttag_junk_chars(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000219 self._parse_error("</>")
220 self._parse_error("</$>")
221 self._parse_error("</")
222 self._parse_error("</a")
Fred Drakebd3090d2001-05-18 15:32:59 +0000223 self._parse_error("<a<a>")
224 self._parse_error("</a<a>")
Fred Drakebd3090d2001-05-18 15:32:59 +0000225 self._parse_error("<!")
Fred Drakebd3090d2001-05-18 15:32:59 +0000226 self._parse_error("<a")
227 self._parse_error("<a foo='bar'")
228 self._parse_error("<a foo='bar")
229 self._parse_error("<a foo='>'")
230 self._parse_error("<a foo='>")
Fred Drakebd3090d2001-05-18 15:32:59 +0000231
Ezio Melottif4ab4912012-02-13 15:50:37 +0200232 def test_valid_doctypes(self):
233 # from http://www.w3.org/QA/2002/04/valid-dtd-list.html
234 dtds = ['HTML', # HTML5 doctype
235 ('HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
236 '"http://www.w3.org/TR/html4/strict.dtd"'),
237 ('HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" '
238 '"http://www.w3.org/TR/html4/loose.dtd"'),
239 ('html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" '
240 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"'),
241 ('html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" '
242 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"'),
243 ('math PUBLIC "-//W3C//DTD MathML 2.0//EN" '
244 '"http://www.w3.org/Math/DTD/mathml2/mathml2.dtd"'),
245 ('html PUBLIC "-//W3C//DTD '
246 'XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" '
247 '"http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd"'),
248 ('svg PUBLIC "-//W3C//DTD SVG 1.1//EN" '
249 '"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"'),
250 'html PUBLIC "-//IETF//DTD HTML 2.0//EN"',
251 'html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"']
252 for dtd in dtds:
253 self._run_check("<!DOCTYPE %s>" % dtd,
254 [('decl', 'DOCTYPE ' + dtd)])
255
Fred Drake84bb9d82001-08-03 19:53:01 +0000256 def test_declaration_junk_chars(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000257 self._parse_error("<!DOCTYPE foo $ >")
258
Fred Drake84bb9d82001-08-03 19:53:01 +0000259 def test_startendtag(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000260 self._run_check("<p/>", [
261 ("startendtag", "p", []),
262 ])
263 self._run_check("<p></p>", [
264 ("starttag", "p", []),
265 ("endtag", "p"),
266 ])
267 self._run_check("<p><img src='foo' /></p>", [
268 ("starttag", "p", []),
269 ("startendtag", "img", [("src", "foo")]),
270 ("endtag", "p"),
271 ])
272
Fred Drake84bb9d82001-08-03 19:53:01 +0000273 def test_get_starttag_text(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000274 s = """<foo:bar \n one="1"\ttwo=2 >"""
275 self._run_check_extra(s, [
276 ("starttag", "foo:bar", [("one", "1"), ("two", "2")]),
277 ("starttag_text", s)])
278
Fred Drake84bb9d82001-08-03 19:53:01 +0000279 def test_cdata_content(self):
Ezio Melotti7de56f62011-11-01 14:12:22 +0200280 contents = [
281 '<!-- not a comment --> &not-an-entity-ref;',
282 "<not a='start tag'>",
283 '<a href="" /> <p> <span></span>',
284 'foo = "</scr" + "ipt>";',
285 'foo = "</SCRIPT" + ">";',
286 'foo = <\n/script> ',
287 '<!-- document.write("</scr" + "ipt>"); -->',
288 ('\n//<![CDATA[\n'
289 'document.write(\'<s\'+\'cript type="text/javascript" '
290 'src="http://www.example.org/r=\'+new '
291 'Date().getTime()+\'"><\\/s\'+\'cript>\');\n//]]>'),
292 '\n<!-- //\nvar foo = 3.14;\n// -->\n',
293 'foo = "</sty" + "le>";',
294 '<!-- \u2603 -->',
295 # these two should be invalid according to the HTML 5 spec,
296 # section 8.1.2.2
297 #'foo = </\nscript>',
298 #'foo = </ script>',
299 ]
300 elements = ['script', 'style', 'SCRIPT', 'STYLE', 'Script', 'Style']
301 for content in contents:
302 for element in elements:
303 element_lower = element.lower()
304 s = '<{element}>{content}</{element}>'.format(element=element,
305 content=content)
306 self._run_check(s, [("starttag", element_lower, []),
307 ("data", content),
308 ("endtag", element_lower)])
309
Ezio Melotti15cb4892011-11-18 18:01:49 +0200310 def test_cdata_with_closing_tags(self):
311 # see issue #13358
312 # make sure that HTMLParser calls handle_data only once for each CDATA.
313 # The normal event collector normalizes the events in get_events,
314 # so we override it to return the original list of events.
315 class Collector(EventCollector):
316 def get_events(self):
317 return self.events
Fred Drakebd3090d2001-05-18 15:32:59 +0000318
Ezio Melotti15cb4892011-11-18 18:01:49 +0200319 content = """<!-- not a comment --> &not-an-entity-ref;
320 <a href="" /> </p><p> <span></span></style>
321 '</script' + '>'"""
322 for element in [' script', 'script ', ' script ',
323 '\nscript', 'script\n', '\nscript\n']:
324 element_lower = element.lower().strip()
325 s = '<script>{content}</{element}>'.format(element=element,
326 content=content)
327 self._run_check(s, [("starttag", element_lower, []),
328 ("data", content),
329 ("endtag", element_lower)],
330 collector=Collector())
Fred Drakebd3090d2001-05-18 15:32:59 +0000331
Ezio Melottifa3702d2012-02-10 10:45:44 +0200332 def test_comments(self):
333 html = ("<!-- I'm a valid comment -->"
334 '<!--me too!-->'
335 '<!------>'
336 '<!---->'
337 '<!----I have many hyphens---->'
338 '<!-- I have a > in the middle -->'
339 '<!-- and I have -- in the middle! -->')
340 expected = [('comment', " I'm a valid comment "),
341 ('comment', 'me too!'),
342 ('comment', '--'),
343 ('comment', ''),
344 ('comment', '--I have many hyphens--'),
345 ('comment', ' I have a > in the middle '),
346 ('comment', ' and I have -- in the middle! ')]
347 self._run_check(html, expected)
348
Ezio Melotti62f3d032011-12-19 07:29:03 +0200349 def test_condcoms(self):
350 html = ('<!--[if IE & !(lte IE 8)]>aren\'t<![endif]-->'
351 '<!--[if IE 8]>condcoms<![endif]-->'
352 '<!--[if lte IE 7]>pretty?<![endif]-->')
353 expected = [('comment', "[if IE & !(lte IE 8)]>aren't<![endif]"),
354 ('comment', '[if IE 8]>condcoms<![endif]'),
355 ('comment', '[if lte IE 7]>pretty?<![endif]')]
356 self._run_check(html, expected)
357
358
Ezio Melottic1e73c32011-11-01 18:57:15 +0200359class HTMLParserTolerantTestCase(HTMLParserStrictTestCase):
R. David Murrayb579dba2010-12-03 04:06:39 +0000360
Ezio Melottib9a48f72011-11-01 15:00:59 +0200361 def get_collector(self):
362 return EventCollector(strict=False)
R. David Murrayb579dba2010-12-03 04:06:39 +0000363
364 def test_tolerant_parsing(self):
365 self._run_check('<html <html>te>>xt&a<<bc</a></html>\n'
366 '<img src="URL><//img></html</html>', [
Ezio Melottic2fe5772011-11-14 18:53:33 +0200367 ('starttag', 'html', [('<html', None)]),
368 ('data', 'te>>xt'),
369 ('entityref', 'a'),
370 ('data', '<<bc'),
371 ('endtag', 'a'),
372 ('endtag', 'html'),
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200373 ('data', '\n<img src="URL>'),
374 ('comment', '/img'),
375 ('endtag', 'html<')])
R. David Murrayb579dba2010-12-03 04:06:39 +0000376
Ezio Melotti86f67122012-02-13 14:11:27 +0200377 def test_starttag_junk_chars(self):
378 self._run_check("</>", [])
379 self._run_check("</$>", [('comment', '$')])
380 self._run_check("</", [('data', '</')])
381 self._run_check("</a", [('data', '</a')])
382 # XXX this might be wrong
383 self._run_check("<a<a>", [('data', '<a'), ('starttag', 'a', [])])
384 self._run_check("</a<a>", [('endtag', 'a<a')])
385 self._run_check("<!", [('data', '<!')])
386 self._run_check("<a", [('data', '<a')])
387 self._run_check("<a foo='bar'", [('data', "<a foo='bar'")])
388 self._run_check("<a foo='bar", [('data', "<a foo='bar")])
389 self._run_check("<a foo='>'", [('data', "<a foo='>'")])
390 self._run_check("<a foo='>", [('data', "<a foo='>")])
391
Ezio Melotti29877e82012-02-21 09:25:00 +0200392 def test_slashes_in_starttag(self):
393 self._run_check('<a foo="var"/>', [('startendtag', 'a', [('foo', 'var')])])
394 html = ('<img width=902 height=250px '
395 'src="/sites/default/files/images/homepage/foo.jpg" '
396 '/*what am I doing here*/ />')
397 expected = [(
398 'startendtag', 'img',
399 [('width', '902'), ('height', '250px'),
400 ('src', '/sites/default/files/images/homepage/foo.jpg'),
401 ('*what', None), ('am', None), ('i', None),
402 ('doing', None), ('here*', None)]
403 )]
404 self._run_check(html, expected)
405 html = ('<a / /foo/ / /=/ / /bar/ / />'
406 '<a / /foo/ / /=/ / /bar/ / >')
407 expected = [
408 ('startendtag', 'a', [('foo', None), ('=', None), ('bar', None)]),
409 ('starttag', 'a', [('foo', None), ('=', None), ('bar', None)])
410 ]
411 self._run_check(html, expected)
412
Ezio Melotti86f67122012-02-13 14:11:27 +0200413 def test_declaration_junk_chars(self):
Ezio Melottif4ab4912012-02-13 15:50:37 +0200414 self._run_check("<!DOCTYPE foo $ >", [('decl', 'DOCTYPE foo $ ')])
Ezio Melotti86f67122012-02-13 14:11:27 +0200415
416 def test_illegal_declarations(self):
Ezio Melotti86f67122012-02-13 14:11:27 +0200417 self._run_check('<!spacer type="block" height="25">',
418 [('comment', 'spacer type="block" height="25"')])
419
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200420 def test_with_unquoted_attributes(self):
Ezio Melottib9a48f72011-11-01 15:00:59 +0200421 # see #12008
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200422 html = ("<html><body bgcolor=d0ca90 text='181008'>"
423 "<table cellspacing=0 cellpadding=1 width=100% ><tr>"
424 "<td align=left><font size=-1>"
425 "- <a href=/rabota/><span class=en> software-and-i</span></a>"
426 "- <a href='/1/'><span class=en> library</span></a></table>")
427 expected = [
428 ('starttag', 'html', []),
429 ('starttag', 'body', [('bgcolor', 'd0ca90'), ('text', '181008')]),
430 ('starttag', 'table',
431 [('cellspacing', '0'), ('cellpadding', '1'), ('width', '100%')]),
432 ('starttag', 'tr', []),
433 ('starttag', 'td', [('align', 'left')]),
434 ('starttag', 'font', [('size', '-1')]),
435 ('data', '- '), ('starttag', 'a', [('href', '/rabota/')]),
436 ('starttag', 'span', [('class', 'en')]), ('data', ' software-and-i'),
437 ('endtag', 'span'), ('endtag', 'a'),
438 ('data', '- '), ('starttag', 'a', [('href', '/1/')]),
439 ('starttag', 'span', [('class', 'en')]), ('data', ' library'),
440 ('endtag', 'span'), ('endtag', 'a'), ('endtag', 'table')
441 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200442 self._run_check(html, expected)
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200443
R. David Murrayb579dba2010-12-03 04:06:39 +0000444 def test_comma_between_attributes(self):
445 self._run_check('<form action="/xxx.php?a=1&amp;b=2&amp", '
446 'method="post">', [
447 ('starttag', 'form',
448 [('action', '/xxx.php?a=1&b=2&amp'),
Ezio Melottic2fe5772011-11-14 18:53:33 +0200449 (',', None), ('method', 'post')])])
R. David Murrayb579dba2010-12-03 04:06:39 +0000450
451 def test_weird_chars_in_unquoted_attribute_values(self):
452 self._run_check('<form action=bogus|&#()value>', [
453 ('starttag', 'form',
Ezio Melottic1e73c32011-11-01 18:57:15 +0200454 [('action', 'bogus|&#()value')])])
R. David Murrayb579dba2010-12-03 04:06:39 +0000455
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200456 def test_invalid_end_tags(self):
457 # A collection of broken end tags. <br> is used as separator.
458 # see http://www.w3.org/TR/html5/tokenization.html#end-tag-open-state
459 # and #13993
460 html = ('<br></label</p><br></div end tmAd-leaderBoard><br></<h4><br>'
461 '</li class="unit"><br></li\r\n\t\t\t\t\t\t</ul><br></><br>')
462 expected = [('starttag', 'br', []),
463 # < is part of the name, / is discarded, p is an attribute
464 ('endtag', 'label<'),
465 ('starttag', 'br', []),
466 # text and attributes are discarded
467 ('endtag', 'div'),
468 ('starttag', 'br', []),
469 # comment because the first char after </ is not a-zA-Z
470 ('comment', '<h4'),
471 ('starttag', 'br', []),
472 # attributes are discarded
473 ('endtag', 'li'),
474 ('starttag', 'br', []),
475 # everything till ul (included) is discarded
476 ('endtag', 'li'),
477 ('starttag', 'br', []),
478 # </> is ignored
479 ('starttag', 'br', [])]
480 self._run_check(html, expected)
481
482 def test_broken_invalid_end_tag(self):
483 # This is technically wrong (the "> shouldn't be included in the 'data')
484 # but is probably not worth fixing it (in addition to all the cases of
485 # the previous test, it would require a full attribute parsing).
486 # see #13993
487 html = '<b>This</b attr=">"> confuses the parser'
488 expected = [('starttag', 'b', []),
489 ('data', 'This'),
490 ('endtag', 'b'),
491 ('data', '"> confuses the parser')]
492 self._run_check(html, expected)
493
Ezio Melottib9a48f72011-11-01 15:00:59 +0200494 def test_correct_detection_of_start_tags(self):
495 # see #13273
Ezio Melottif50ffa92011-10-28 13:21:09 +0300496 html = ('<div style="" ><b>The <a href="some_url">rain</a> '
497 '<br /> in <span>Spain</span></b></div>')
498 expected = [
499 ('starttag', 'div', [('style', '')]),
500 ('starttag', 'b', []),
501 ('data', 'The '),
502 ('starttag', 'a', [('href', 'some_url')]),
503 ('data', 'rain'),
504 ('endtag', 'a'),
505 ('data', ' '),
506 ('startendtag', 'br', []),
507 ('data', ' in '),
508 ('starttag', 'span', []),
509 ('data', 'Spain'),
510 ('endtag', 'span'),
511 ('endtag', 'b'),
512 ('endtag', 'div')
513 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200514 self._run_check(html, expected)
Ezio Melottif50ffa92011-10-28 13:21:09 +0300515
Ezio Melottif50ffa92011-10-28 13:21:09 +0300516 html = '<div style="", foo = "bar" ><b>The <a href="some_url">rain</a>'
517 expected = [
Ezio Melottic2fe5772011-11-14 18:53:33 +0200518 ('starttag', 'div', [('style', ''), (',', None), ('foo', 'bar')]),
Ezio Melottif50ffa92011-10-28 13:21:09 +0300519 ('starttag', 'b', []),
520 ('data', 'The '),
521 ('starttag', 'a', [('href', 'some_url')]),
522 ('data', 'rain'),
523 ('endtag', 'a'),
524 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200525 self._run_check(html, expected)
Ezio Melottif50ffa92011-10-28 13:21:09 +0300526
Senthil Kumaran164540f2010-12-28 15:55:16 +0000527 def test_unescape_function(self):
Ezio Melotti86f67122012-02-13 14:11:27 +0200528 p = self.get_collector()
Senthil Kumaran164540f2010-12-28 15:55:16 +0000529 self.assertEqual(p.unescape('&#bad;'),'&#bad;')
530 self.assertEqual(p.unescape('&#0038;'),'&')
Ezio Melottid9e0b062011-09-05 17:11:06 +0300531 # see #12888
532 self.assertEqual(p.unescape('&#123; ' * 1050), '{ ' * 1050)
R. David Murrayb579dba2010-12-03 04:06:39 +0000533
Ezio Melottifa3702d2012-02-10 10:45:44 +0200534 def test_broken_comments(self):
535 html = ('<! not really a comment >'
536 '<! not a comment either -->'
537 '<! -- close enough -->'
Ezio Melottif4ab4912012-02-13 15:50:37 +0200538 '<!><!<-- this was an empty comment>'
Ezio Melottifa3702d2012-02-10 10:45:44 +0200539 '<!!! another bogus comment !!!>')
540 expected = [
541 ('comment', ' not really a comment '),
542 ('comment', ' not a comment either --'),
543 ('comment', ' -- close enough --'),
Ezio Melottif4ab4912012-02-13 15:50:37 +0200544 ('comment', ''),
545 ('comment', '<-- this was an empty comment'),
Ezio Melottifa3702d2012-02-10 10:45:44 +0200546 ('comment', '!! another bogus comment !!!'),
547 ]
548 self._run_check(html, expected)
549
Ezio Melotti62f3d032011-12-19 07:29:03 +0200550 def test_broken_condcoms(self):
551 # these condcoms are missing the '--' after '<!' and before the '>'
552 html = ('<![if !(IE)]>broken condcom<![endif]>'
553 '<![if ! IE]><link href="favicon.tiff"/><![endif]>'
554 '<![if !IE 6]><img src="firefox.png" /><![endif]>'
555 '<![if !ie 6]><b>foo</b><![endif]>'
556 '<![if (!IE)|(lt IE 9)]><img src="mammoth.bmp" /><![endif]>')
557 # According to the HTML5 specs sections "8.2.4.44 Bogus comment state"
558 # and "8.2.4.45 Markup declaration open state", comment tokens should
559 # be emitted instead of 'unknown decl', but calling unknown_decl
560 # provides more flexibility.
561 # See also Lib/_markupbase.py:parse_declaration
562 expected = [
563 ('unknown decl', 'if !(IE)'),
564 ('data', 'broken condcom'),
565 ('unknown decl', 'endif'),
566 ('unknown decl', 'if ! IE'),
567 ('startendtag', 'link', [('href', 'favicon.tiff')]),
568 ('unknown decl', 'endif'),
569 ('unknown decl', 'if !IE 6'),
570 ('startendtag', 'img', [('src', 'firefox.png')]),
571 ('unknown decl', 'endif'),
572 ('unknown decl', 'if !ie 6'),
573 ('starttag', 'b', []),
574 ('data', 'foo'),
575 ('endtag', 'b'),
576 ('unknown decl', 'endif'),
577 ('unknown decl', 'if (!IE)|(lt IE 9)'),
578 ('startendtag', 'img', [('src', 'mammoth.bmp')]),
579 ('unknown decl', 'endif')
580 ]
581 self._run_check(html, expected)
582
Ezio Melottic1e73c32011-11-01 18:57:15 +0200583
Ezio Melottib245ed12011-11-14 18:13:22 +0200584class AttributesStrictTestCase(TestCaseBase):
585
586 def get_collector(self):
587 return EventCollector(strict=True)
588
589 def test_attr_syntax(self):
590 output = [
591 ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", None)])
592 ]
593 self._run_check("""<a b='v' c="v" d=v e>""", output)
594 self._run_check("""<a b = 'v' c = "v" d = v e>""", output)
595 self._run_check("""<a\nb\n=\n'v'\nc\n=\n"v"\nd\n=\nv\ne>""", output)
596 self._run_check("""<a\tb\t=\t'v'\tc\t=\t"v"\td\t=\tv\te>""", output)
597
598 def test_attr_values(self):
599 self._run_check("""<a b='xxx\n\txxx' c="yyy\t\nyyy" d='\txyz\n'>""",
600 [("starttag", "a", [("b", "xxx\n\txxx"),
601 ("c", "yyy\t\nyyy"),
602 ("d", "\txyz\n")])])
603 self._run_check("""<a b='' c="">""",
604 [("starttag", "a", [("b", ""), ("c", "")])])
605 # Regression test for SF patch #669683.
606 self._run_check("<e a=rgb(1,2,3)>",
607 [("starttag", "e", [("a", "rgb(1,2,3)")])])
608 # Regression test for SF bug #921657.
609 self._run_check(
610 "<a href=mailto:xyz@example.com>",
611 [("starttag", "a", [("href", "mailto:xyz@example.com")])])
612
613 def test_attr_nonascii(self):
614 # see issue 7311
615 self._run_check(
616 "<img src=/foo/bar.png alt=\u4e2d\u6587>",
617 [("starttag", "img", [("src", "/foo/bar.png"),
618 ("alt", "\u4e2d\u6587")])])
619 self._run_check(
620 "<a title='\u30c6\u30b9\u30c8' href='\u30c6\u30b9\u30c8.html'>",
621 [("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
622 ("href", "\u30c6\u30b9\u30c8.html")])])
623 self._run_check(
624 '<a title="\u30c6\u30b9\u30c8" href="\u30c6\u30b9\u30c8.html">',
625 [("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
626 ("href", "\u30c6\u30b9\u30c8.html")])])
627
628 def test_attr_entity_replacement(self):
629 self._run_check(
630 "<a b='&amp;&gt;&lt;&quot;&apos;'>",
631 [("starttag", "a", [("b", "&><\"'")])])
632
633 def test_attr_funky_names(self):
634 self._run_check(
635 "<a a.b='v' c:d=v e-f=v>",
636 [("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")])])
637
638 def test_entityrefs_in_attributes(self):
639 self._run_check(
640 "<html foo='&euro;&amp;&#97;&#x61;&unsupported;'>",
641 [("starttag", "html", [("foo", "\u20AC&aa&unsupported;")])])
642
643
Ezio Melottic2fe5772011-11-14 18:53:33 +0200644
645class AttributesTolerantTestCase(AttributesStrictTestCase):
646
647 def get_collector(self):
648 return EventCollector(strict=False)
649
650 def test_attr_funky_names2(self):
651 self._run_check(
652 "<a $><b $=%><c \=/>",
653 [("starttag", "a", [("$", None)]),
654 ("starttag", "b", [("$", "%")]),
655 ("starttag", "c", [("\\", "/")])])
656
657 def test_entities_in_attribute_value(self):
658 # see #1200313
659 for entity in ['&', '&amp;', '&#38;', '&#x26;']:
660 self._run_check('<a href="%s">' % entity,
661 [("starttag", "a", [("href", "&")])])
662 self._run_check("<a href='%s'>" % entity,
663 [("starttag", "a", [("href", "&")])])
664 self._run_check("<a href=%s>" % entity,
665 [("starttag", "a", [("href", "&")])])
666
667 def test_malformed_attributes(self):
668 # see #13357
669 html = (
670 "<a href=test'style='color:red;bad1'>test - bad1</a>"
671 "<a href=test'+style='color:red;ba2'>test - bad2</a>"
672 "<a href=test'&nbsp;style='color:red;bad3'>test - bad3</a>"
673 "<a href = test'&nbsp;style='color:red;bad4' >test - bad4</a>"
674 )
675 expected = [
676 ('starttag', 'a', [('href', "test'style='color:red;bad1'")]),
677 ('data', 'test - bad1'), ('endtag', 'a'),
678 ('starttag', 'a', [('href', "test'+style='color:red;ba2'")]),
679 ('data', 'test - bad2'), ('endtag', 'a'),
680 ('starttag', 'a', [('href', "test'\xa0style='color:red;bad3'")]),
681 ('data', 'test - bad3'), ('endtag', 'a'),
682 ('starttag', 'a', [('href', "test'\xa0style='color:red;bad4'")]),
683 ('data', 'test - bad4'), ('endtag', 'a')
684 ]
685 self._run_check(html, expected)
686
687 def test_malformed_adjacent_attributes(self):
688 # see #12629
689 self._run_check('<x><y z=""o"" /></x>',
690 [('starttag', 'x', []),
691 ('startendtag', 'y', [('z', ''), ('o""', None)]),
692 ('endtag', 'x')])
693 self._run_check('<x><y z="""" /></x>',
694 [('starttag', 'x', []),
695 ('startendtag', 'y', [('z', ''), ('""', None)]),
696 ('endtag', 'x')])
697
698 # see #755670 for the following 3 tests
699 def test_adjacent_attributes(self):
700 self._run_check('<a width="100%"cellspacing=0>',
701 [("starttag", "a",
702 [("width", "100%"), ("cellspacing","0")])])
703
704 self._run_check('<a id="foo"class="bar">',
705 [("starttag", "a",
706 [("id", "foo"), ("class","bar")])])
707
708 def test_missing_attribute_value(self):
709 self._run_check('<a v=>',
710 [("starttag", "a", [("v", "")])])
711
712 def test_javascript_attribute_value(self):
713 self._run_check("<a href=javascript:popup('/popup/help.html')>",
714 [("starttag", "a",
715 [("href", "javascript:popup('/popup/help.html')")])])
716
717 def test_end_tag_in_attribute_value(self):
718 # see #1745761
719 self._run_check("<a href='http://www.example.org/\">;'>spam</a>",
720 [("starttag", "a",
721 [("href", "http://www.example.org/\">;")]),
722 ("data", "spam"), ("endtag", "a")])
723
724
725
Fred Drakee8220492001-09-24 20:19:08 +0000726def test_main():
Ezio Melottib245ed12011-11-14 18:13:22 +0200727 support.run_unittest(HTMLParserStrictTestCase, HTMLParserTolerantTestCase,
Ezio Melottic2fe5772011-11-14 18:53:33 +0200728 AttributesStrictTestCase, AttributesTolerantTestCase)
Fred Drakee8220492001-09-24 20:19:08 +0000729
730
731if __name__ == "__main__":
732 test_main()