blob: 3d3f8593b556a6884d61297549e1d317b5f8908c [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;
Georg Brandld09def32006-03-09 13:27:14 +0000125<!--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 Drake029acfb2001-08-20 21:24:19 +0000160 def test_doctype_decl(self):
161 inside = """\
162DOCTYPE html [
163 <!ELEMENT html - O EMPTY>
164 <!ATTLIST html
Fred Drakec20a6982001-09-04 15:13:04 +0000165 version CDATA #IMPLIED
166 profile CDATA 'DublinCore'>
167 <!NOTATION datatype SYSTEM 'http://xml.python.org/notations/python-module'>
168 <!ENTITY myEntity 'internal parsed entity'>
169 <!ENTITY anEntity SYSTEM 'http://xml.python.org/entities/something.xml'>
170 <!ENTITY % paramEntity 'name|name|name'>
171 %paramEntity;
Fred Drake029acfb2001-08-20 21:24:19 +0000172 <!-- comment -->
173]"""
174 self._run_check("<!%s>" % inside, [
175 ("decl", inside),
176 ])
177
Fred Drake84bb9d82001-08-03 19:53:01 +0000178 def test_bad_nesting(self):
179 # Strangely, this *is* supposed to test that overlapping
180 # elements are allowed. HTMLParser is more geared toward
181 # lexing the input that parsing the structure.
Fred Drakebd3090d2001-05-18 15:32:59 +0000182 self._run_check("<a><b></a></b>", [
183 ("starttag", "a", []),
184 ("starttag", "b", []),
185 ("endtag", "a"),
186 ("endtag", "b"),
187 ])
188
Fred Drake029acfb2001-08-20 21:24:19 +0000189 def test_bare_ampersands(self):
190 self._run_check("this text & contains & ampersands &", [
191 ("data", "this text & contains & ampersands &"),
192 ])
193
194 def test_bare_pointy_brackets(self):
195 self._run_check("this < text > contains < bare>pointy< brackets", [
196 ("data", "this < text > contains < bare>pointy< brackets"),
197 ])
198
Fred Drakec20a6982001-09-04 15:13:04 +0000199 def test_illegal_declarations(self):
Fred Drake7cf613d2001-09-04 16:26:03 +0000200 self._parse_error('<!spacer type="block" height="25">')
Fred Drakec20a6982001-09-04 15:13:04 +0000201
Fred Drake84bb9d82001-08-03 19:53:01 +0000202 def test_starttag_end_boundary(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000203 self._run_check("""<a b='<'>""", [("starttag", "a", [("b", "<")])])
204 self._run_check("""<a b='>'>""", [("starttag", "a", [("b", ">")])])
205
Fred Drake84bb9d82001-08-03 19:53:01 +0000206 def test_buffer_artefacts(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000207 output = [("starttag", "a", [("b", "<")])]
208 self._run_check(["<a b='<'>"], output)
209 self._run_check(["<a ", "b='<'>"], output)
210 self._run_check(["<a b", "='<'>"], output)
211 self._run_check(["<a b=", "'<'>"], output)
212 self._run_check(["<a b='<", "'>"], output)
213 self._run_check(["<a b='<'", ">"], output)
214
215 output = [("starttag", "a", [("b", ">")])]
216 self._run_check(["<a b='>'>"], output)
217 self._run_check(["<a ", "b='>'>"], output)
218 self._run_check(["<a b", "='>'>"], output)
219 self._run_check(["<a b=", "'>'>"], output)
220 self._run_check(["<a b='>", "'>"], output)
221 self._run_check(["<a b='>'", ">"], output)
222
Fred Drake75d9a622004-09-08 22:57:01 +0000223 output = [("comment", "abc")]
224 self._run_check(["", "<!--abc-->"], output)
225 self._run_check(["<", "!--abc-->"], output)
226 self._run_check(["<!", "--abc-->"], output)
227 self._run_check(["<!-", "-abc-->"], output)
228 self._run_check(["<!--", "abc-->"], output)
229 self._run_check(["<!--a", "bc-->"], output)
230 self._run_check(["<!--ab", "c-->"], output)
231 self._run_check(["<!--abc", "-->"], output)
232 self._run_check(["<!--abc-", "->"], output)
233 self._run_check(["<!--abc--", ">"], output)
234 self._run_check(["<!--abc-->", ""], output)
235
Fred Drake84bb9d82001-08-03 19:53:01 +0000236 def test_starttag_junk_chars(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000237 self._parse_error("</>")
238 self._parse_error("</$>")
239 self._parse_error("</")
240 self._parse_error("</a")
Fred Drakebd3090d2001-05-18 15:32:59 +0000241 self._parse_error("<a<a>")
242 self._parse_error("</a<a>")
Fred Drakebd3090d2001-05-18 15:32:59 +0000243 self._parse_error("<!")
Fred Drakebd3090d2001-05-18 15:32:59 +0000244 self._parse_error("<a")
245 self._parse_error("<a foo='bar'")
246 self._parse_error("<a foo='bar")
247 self._parse_error("<a foo='>'")
248 self._parse_error("<a foo='>")
Fred Drakebd3090d2001-05-18 15:32:59 +0000249
Fred Drake84bb9d82001-08-03 19:53:01 +0000250 def test_declaration_junk_chars(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000251 self._parse_error("<!DOCTYPE foo $ >")
252
Fred Drake84bb9d82001-08-03 19:53:01 +0000253 def test_startendtag(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000254 self._run_check("<p/>", [
255 ("startendtag", "p", []),
256 ])
257 self._run_check("<p></p>", [
258 ("starttag", "p", []),
259 ("endtag", "p"),
260 ])
261 self._run_check("<p><img src='foo' /></p>", [
262 ("starttag", "p", []),
263 ("startendtag", "img", [("src", "foo")]),
264 ("endtag", "p"),
265 ])
266
Fred Drake84bb9d82001-08-03 19:53:01 +0000267 def test_get_starttag_text(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000268 s = """<foo:bar \n one="1"\ttwo=2 >"""
269 self._run_check_extra(s, [
270 ("starttag", "foo:bar", [("one", "1"), ("two", "2")]),
271 ("starttag_text", s)])
272
Fred Drake84bb9d82001-08-03 19:53:01 +0000273 def test_cdata_content(self):
Ezio Melotti7de56f62011-11-01 14:12:22 +0200274 contents = [
275 '<!-- not a comment --> &not-an-entity-ref;',
276 "<not a='start tag'>",
277 '<a href="" /> <p> <span></span>',
278 'foo = "</scr" + "ipt>";',
279 'foo = "</SCRIPT" + ">";',
280 'foo = <\n/script> ',
281 '<!-- document.write("</scr" + "ipt>"); -->',
282 ('\n//<![CDATA[\n'
283 'document.write(\'<s\'+\'cript type="text/javascript" '
284 'src="http://www.example.org/r=\'+new '
285 'Date().getTime()+\'"><\\/s\'+\'cript>\');\n//]]>'),
286 '\n<!-- //\nvar foo = 3.14;\n// -->\n',
287 'foo = "</sty" + "le>";',
288 '<!-- \u2603 -->',
289 # these two should be invalid according to the HTML 5 spec,
290 # section 8.1.2.2
291 #'foo = </\nscript>',
292 #'foo = </ script>',
293 ]
294 elements = ['script', 'style', 'SCRIPT', 'STYLE', 'Script', 'Style']
295 for content in contents:
296 for element in elements:
297 element_lower = element.lower()
298 s = '<{element}>{content}</{element}>'.format(element=element,
299 content=content)
300 self._run_check(s, [("starttag", element_lower, []),
301 ("data", content),
302 ("endtag", element_lower)])
303
Ezio Melotti15cb4892011-11-18 18:01:49 +0200304 def test_cdata_with_closing_tags(self):
305 # see issue #13358
306 # make sure that HTMLParser calls handle_data only once for each CDATA.
307 # The normal event collector normalizes the events in get_events,
308 # so we override it to return the original list of events.
309 class Collector(EventCollector):
310 def get_events(self):
311 return self.events
Fred Drakebd3090d2001-05-18 15:32:59 +0000312
Ezio Melotti15cb4892011-11-18 18:01:49 +0200313 content = """<!-- not a comment --> &not-an-entity-ref;
314 <a href="" /> </p><p> <span></span></style>
315 '</script' + '>'"""
316 for element in [' script', 'script ', ' script ',
317 '\nscript', 'script\n', '\nscript\n']:
318 element_lower = element.lower().strip()
319 s = '<script>{content}</{element}>'.format(element=element,
320 content=content)
321 self._run_check(s, [("starttag", element_lower, []),
322 ("data", content),
323 ("endtag", element_lower)],
324 collector=Collector())
Fred Drakebd3090d2001-05-18 15:32:59 +0000325
Ezio Melottifa3702d2012-02-10 10:45:44 +0200326 def test_comments(self):
327 html = ("<!-- I'm a valid comment -->"
328 '<!--me too!-->'
329 '<!------>'
330 '<!---->'
331 '<!----I have many hyphens---->'
332 '<!-- I have a > in the middle -->'
333 '<!-- and I have -- in the middle! -->')
334 expected = [('comment', " I'm a valid comment "),
335 ('comment', 'me too!'),
336 ('comment', '--'),
337 ('comment', ''),
338 ('comment', '--I have many hyphens--'),
339 ('comment', ' I have a > in the middle '),
340 ('comment', ' and I have -- in the middle! ')]
341 self._run_check(html, expected)
342
Ezio Melotti62f3d032011-12-19 07:29:03 +0200343 def test_condcoms(self):
344 html = ('<!--[if IE & !(lte IE 8)]>aren\'t<![endif]-->'
345 '<!--[if IE 8]>condcoms<![endif]-->'
346 '<!--[if lte IE 7]>pretty?<![endif]-->')
347 expected = [('comment', "[if IE & !(lte IE 8)]>aren't<![endif]"),
348 ('comment', '[if IE 8]>condcoms<![endif]'),
349 ('comment', '[if lte IE 7]>pretty?<![endif]')]
350 self._run_check(html, expected)
351
352
Ezio Melottic1e73c32011-11-01 18:57:15 +0200353class HTMLParserTolerantTestCase(HTMLParserStrictTestCase):
R. David Murrayb579dba2010-12-03 04:06:39 +0000354
Ezio Melottib9a48f72011-11-01 15:00:59 +0200355 def get_collector(self):
356 return EventCollector(strict=False)
R. David Murrayb579dba2010-12-03 04:06:39 +0000357
358 def test_tolerant_parsing(self):
359 self._run_check('<html <html>te>>xt&a<<bc</a></html>\n'
360 '<img src="URL><//img></html</html>', [
Ezio Melottic2fe5772011-11-14 18:53:33 +0200361 ('starttag', 'html', [('<html', None)]),
362 ('data', 'te>>xt'),
363 ('entityref', 'a'),
364 ('data', '<<bc'),
365 ('endtag', 'a'),
366 ('endtag', 'html'),
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200367 ('data', '\n<img src="URL>'),
368 ('comment', '/img'),
369 ('endtag', 'html<')])
R. David Murrayb579dba2010-12-03 04:06:39 +0000370
Ezio Melotti86f67122012-02-13 14:11:27 +0200371 def test_starttag_junk_chars(self):
372 self._run_check("</>", [])
373 self._run_check("</$>", [('comment', '$')])
374 self._run_check("</", [('data', '</')])
375 self._run_check("</a", [('data', '</a')])
376 # XXX this might be wrong
377 self._run_check("<a<a>", [('data', '<a'), ('starttag', 'a', [])])
378 self._run_check("</a<a>", [('endtag', 'a<a')])
379 self._run_check("<!", [('data', '<!')])
380 self._run_check("<a", [('data', '<a')])
381 self._run_check("<a foo='bar'", [('data', "<a foo='bar'")])
382 self._run_check("<a foo='bar", [('data', "<a foo='bar")])
383 self._run_check("<a foo='>'", [('data', "<a foo='>'")])
384 self._run_check("<a foo='>", [('data', "<a foo='>")])
385
386 def test_declaration_junk_chars(self):
387 # XXX this is wrong
388 self._run_check("<!DOCTYPE foo $ >", [('comment', 'DOCTYPE foo $ ')])
389
390 def test_illegal_declarations(self):
391 # XXX this might be wrong
392 self._run_check('<!spacer type="block" height="25">',
393 [('comment', 'spacer type="block" height="25"')])
394
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200395 def test_with_unquoted_attributes(self):
Ezio Melottib9a48f72011-11-01 15:00:59 +0200396 # see #12008
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200397 html = ("<html><body bgcolor=d0ca90 text='181008'>"
398 "<table cellspacing=0 cellpadding=1 width=100% ><tr>"
399 "<td align=left><font size=-1>"
400 "- <a href=/rabota/><span class=en> software-and-i</span></a>"
401 "- <a href='/1/'><span class=en> library</span></a></table>")
402 expected = [
403 ('starttag', 'html', []),
404 ('starttag', 'body', [('bgcolor', 'd0ca90'), ('text', '181008')]),
405 ('starttag', 'table',
406 [('cellspacing', '0'), ('cellpadding', '1'), ('width', '100%')]),
407 ('starttag', 'tr', []),
408 ('starttag', 'td', [('align', 'left')]),
409 ('starttag', 'font', [('size', '-1')]),
410 ('data', '- '), ('starttag', 'a', [('href', '/rabota/')]),
411 ('starttag', 'span', [('class', 'en')]), ('data', ' software-and-i'),
412 ('endtag', 'span'), ('endtag', 'a'),
413 ('data', '- '), ('starttag', 'a', [('href', '/1/')]),
414 ('starttag', 'span', [('class', 'en')]), ('data', ' library'),
415 ('endtag', 'span'), ('endtag', 'a'), ('endtag', 'table')
416 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200417 self._run_check(html, expected)
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200418
R. David Murrayb579dba2010-12-03 04:06:39 +0000419 def test_comma_between_attributes(self):
420 self._run_check('<form action="/xxx.php?a=1&amp;b=2&amp", '
421 'method="post">', [
422 ('starttag', 'form',
423 [('action', '/xxx.php?a=1&b=2&amp'),
Ezio Melottic2fe5772011-11-14 18:53:33 +0200424 (',', None), ('method', 'post')])])
R. David Murrayb579dba2010-12-03 04:06:39 +0000425
426 def test_weird_chars_in_unquoted_attribute_values(self):
427 self._run_check('<form action=bogus|&#()value>', [
428 ('starttag', 'form',
Ezio Melottic1e73c32011-11-01 18:57:15 +0200429 [('action', 'bogus|&#()value')])])
R. David Murrayb579dba2010-12-03 04:06:39 +0000430
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200431 def test_invalid_end_tags(self):
432 # A collection of broken end tags. <br> is used as separator.
433 # see http://www.w3.org/TR/html5/tokenization.html#end-tag-open-state
434 # and #13993
435 html = ('<br></label</p><br></div end tmAd-leaderBoard><br></<h4><br>'
436 '</li class="unit"><br></li\r\n\t\t\t\t\t\t</ul><br></><br>')
437 expected = [('starttag', 'br', []),
438 # < is part of the name, / is discarded, p is an attribute
439 ('endtag', 'label<'),
440 ('starttag', 'br', []),
441 # text and attributes are discarded
442 ('endtag', 'div'),
443 ('starttag', 'br', []),
444 # comment because the first char after </ is not a-zA-Z
445 ('comment', '<h4'),
446 ('starttag', 'br', []),
447 # attributes are discarded
448 ('endtag', 'li'),
449 ('starttag', 'br', []),
450 # everything till ul (included) is discarded
451 ('endtag', 'li'),
452 ('starttag', 'br', []),
453 # </> is ignored
454 ('starttag', 'br', [])]
455 self._run_check(html, expected)
456
457 def test_broken_invalid_end_tag(self):
458 # This is technically wrong (the "> shouldn't be included in the 'data')
459 # but is probably not worth fixing it (in addition to all the cases of
460 # the previous test, it would require a full attribute parsing).
461 # see #13993
462 html = '<b>This</b attr=">"> confuses the parser'
463 expected = [('starttag', 'b', []),
464 ('data', 'This'),
465 ('endtag', 'b'),
466 ('data', '"> confuses the parser')]
467 self._run_check(html, expected)
468
Ezio Melottib9a48f72011-11-01 15:00:59 +0200469 def test_correct_detection_of_start_tags(self):
470 # see #13273
Ezio Melottif50ffa92011-10-28 13:21:09 +0300471 html = ('<div style="" ><b>The <a href="some_url">rain</a> '
472 '<br /> in <span>Spain</span></b></div>')
473 expected = [
474 ('starttag', 'div', [('style', '')]),
475 ('starttag', 'b', []),
476 ('data', 'The '),
477 ('starttag', 'a', [('href', 'some_url')]),
478 ('data', 'rain'),
479 ('endtag', 'a'),
480 ('data', ' '),
481 ('startendtag', 'br', []),
482 ('data', ' in '),
483 ('starttag', 'span', []),
484 ('data', 'Spain'),
485 ('endtag', 'span'),
486 ('endtag', 'b'),
487 ('endtag', 'div')
488 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200489 self._run_check(html, expected)
Ezio Melottif50ffa92011-10-28 13:21:09 +0300490
Ezio Melottif50ffa92011-10-28 13:21:09 +0300491 html = '<div style="", foo = "bar" ><b>The <a href="some_url">rain</a>'
492 expected = [
Ezio Melottic2fe5772011-11-14 18:53:33 +0200493 ('starttag', 'div', [('style', ''), (',', None), ('foo', 'bar')]),
Ezio Melottif50ffa92011-10-28 13:21:09 +0300494 ('starttag', 'b', []),
495 ('data', 'The '),
496 ('starttag', 'a', [('href', 'some_url')]),
497 ('data', 'rain'),
498 ('endtag', 'a'),
499 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200500 self._run_check(html, expected)
Ezio Melottif50ffa92011-10-28 13:21:09 +0300501
Senthil Kumaran164540f2010-12-28 15:55:16 +0000502 def test_unescape_function(self):
Ezio Melotti86f67122012-02-13 14:11:27 +0200503 p = self.get_collector()
Senthil Kumaran164540f2010-12-28 15:55:16 +0000504 self.assertEqual(p.unescape('&#bad;'),'&#bad;')
505 self.assertEqual(p.unescape('&#0038;'),'&')
Ezio Melottid9e0b062011-09-05 17:11:06 +0300506 # see #12888
507 self.assertEqual(p.unescape('&#123; ' * 1050), '{ ' * 1050)
R. David Murrayb579dba2010-12-03 04:06:39 +0000508
Ezio Melottifa3702d2012-02-10 10:45:44 +0200509 def test_broken_comments(self):
510 html = ('<! not really a comment >'
511 '<! not a comment either -->'
512 '<! -- close enough -->'
513 '<!!! another bogus comment !!!>')
514 expected = [
515 ('comment', ' not really a comment '),
516 ('comment', ' not a comment either --'),
517 ('comment', ' -- close enough --'),
518 ('comment', '!! another bogus comment !!!'),
519 ]
520 self._run_check(html, expected)
521
Ezio Melotti62f3d032011-12-19 07:29:03 +0200522 def test_broken_condcoms(self):
523 # these condcoms are missing the '--' after '<!' and before the '>'
524 html = ('<![if !(IE)]>broken condcom<![endif]>'
525 '<![if ! IE]><link href="favicon.tiff"/><![endif]>'
526 '<![if !IE 6]><img src="firefox.png" /><![endif]>'
527 '<![if !ie 6]><b>foo</b><![endif]>'
528 '<![if (!IE)|(lt IE 9)]><img src="mammoth.bmp" /><![endif]>')
529 # According to the HTML5 specs sections "8.2.4.44 Bogus comment state"
530 # and "8.2.4.45 Markup declaration open state", comment tokens should
531 # be emitted instead of 'unknown decl', but calling unknown_decl
532 # provides more flexibility.
533 # See also Lib/_markupbase.py:parse_declaration
534 expected = [
535 ('unknown decl', 'if !(IE)'),
536 ('data', 'broken condcom'),
537 ('unknown decl', 'endif'),
538 ('unknown decl', 'if ! IE'),
539 ('startendtag', 'link', [('href', 'favicon.tiff')]),
540 ('unknown decl', 'endif'),
541 ('unknown decl', 'if !IE 6'),
542 ('startendtag', 'img', [('src', 'firefox.png')]),
543 ('unknown decl', 'endif'),
544 ('unknown decl', 'if !ie 6'),
545 ('starttag', 'b', []),
546 ('data', 'foo'),
547 ('endtag', 'b'),
548 ('unknown decl', 'endif'),
549 ('unknown decl', 'if (!IE)|(lt IE 9)'),
550 ('startendtag', 'img', [('src', 'mammoth.bmp')]),
551 ('unknown decl', 'endif')
552 ]
553 self._run_check(html, expected)
554
Ezio Melottic1e73c32011-11-01 18:57:15 +0200555
Ezio Melottib245ed12011-11-14 18:13:22 +0200556class AttributesStrictTestCase(TestCaseBase):
557
558 def get_collector(self):
559 return EventCollector(strict=True)
560
561 def test_attr_syntax(self):
562 output = [
563 ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", None)])
564 ]
565 self._run_check("""<a b='v' c="v" d=v e>""", output)
566 self._run_check("""<a b = 'v' c = "v" d = v e>""", output)
567 self._run_check("""<a\nb\n=\n'v'\nc\n=\n"v"\nd\n=\nv\ne>""", output)
568 self._run_check("""<a\tb\t=\t'v'\tc\t=\t"v"\td\t=\tv\te>""", output)
569
570 def test_attr_values(self):
571 self._run_check("""<a b='xxx\n\txxx' c="yyy\t\nyyy" d='\txyz\n'>""",
572 [("starttag", "a", [("b", "xxx\n\txxx"),
573 ("c", "yyy\t\nyyy"),
574 ("d", "\txyz\n")])])
575 self._run_check("""<a b='' c="">""",
576 [("starttag", "a", [("b", ""), ("c", "")])])
577 # Regression test for SF patch #669683.
578 self._run_check("<e a=rgb(1,2,3)>",
579 [("starttag", "e", [("a", "rgb(1,2,3)")])])
580 # Regression test for SF bug #921657.
581 self._run_check(
582 "<a href=mailto:xyz@example.com>",
583 [("starttag", "a", [("href", "mailto:xyz@example.com")])])
584
585 def test_attr_nonascii(self):
586 # see issue 7311
587 self._run_check(
588 "<img src=/foo/bar.png alt=\u4e2d\u6587>",
589 [("starttag", "img", [("src", "/foo/bar.png"),
590 ("alt", "\u4e2d\u6587")])])
591 self._run_check(
592 "<a title='\u30c6\u30b9\u30c8' href='\u30c6\u30b9\u30c8.html'>",
593 [("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
594 ("href", "\u30c6\u30b9\u30c8.html")])])
595 self._run_check(
596 '<a title="\u30c6\u30b9\u30c8" href="\u30c6\u30b9\u30c8.html">',
597 [("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
598 ("href", "\u30c6\u30b9\u30c8.html")])])
599
600 def test_attr_entity_replacement(self):
601 self._run_check(
602 "<a b='&amp;&gt;&lt;&quot;&apos;'>",
603 [("starttag", "a", [("b", "&><\"'")])])
604
605 def test_attr_funky_names(self):
606 self._run_check(
607 "<a a.b='v' c:d=v e-f=v>",
608 [("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")])])
609
610 def test_entityrefs_in_attributes(self):
611 self._run_check(
612 "<html foo='&euro;&amp;&#97;&#x61;&unsupported;'>",
613 [("starttag", "html", [("foo", "\u20AC&aa&unsupported;")])])
614
615
Ezio Melottic2fe5772011-11-14 18:53:33 +0200616
617class AttributesTolerantTestCase(AttributesStrictTestCase):
618
619 def get_collector(self):
620 return EventCollector(strict=False)
621
622 def test_attr_funky_names2(self):
623 self._run_check(
624 "<a $><b $=%><c \=/>",
625 [("starttag", "a", [("$", None)]),
626 ("starttag", "b", [("$", "%")]),
627 ("starttag", "c", [("\\", "/")])])
628
629 def test_entities_in_attribute_value(self):
630 # see #1200313
631 for entity in ['&', '&amp;', '&#38;', '&#x26;']:
632 self._run_check('<a href="%s">' % entity,
633 [("starttag", "a", [("href", "&")])])
634 self._run_check("<a href='%s'>" % entity,
635 [("starttag", "a", [("href", "&")])])
636 self._run_check("<a href=%s>" % entity,
637 [("starttag", "a", [("href", "&")])])
638
639 def test_malformed_attributes(self):
640 # see #13357
641 html = (
642 "<a href=test'style='color:red;bad1'>test - bad1</a>"
643 "<a href=test'+style='color:red;ba2'>test - bad2</a>"
644 "<a href=test'&nbsp;style='color:red;bad3'>test - bad3</a>"
645 "<a href = test'&nbsp;style='color:red;bad4' >test - bad4</a>"
646 )
647 expected = [
648 ('starttag', 'a', [('href', "test'style='color:red;bad1'")]),
649 ('data', 'test - bad1'), ('endtag', 'a'),
650 ('starttag', 'a', [('href', "test'+style='color:red;ba2'")]),
651 ('data', 'test - bad2'), ('endtag', 'a'),
652 ('starttag', 'a', [('href', "test'\xa0style='color:red;bad3'")]),
653 ('data', 'test - bad3'), ('endtag', 'a'),
654 ('starttag', 'a', [('href', "test'\xa0style='color:red;bad4'")]),
655 ('data', 'test - bad4'), ('endtag', 'a')
656 ]
657 self._run_check(html, expected)
658
659 def test_malformed_adjacent_attributes(self):
660 # see #12629
661 self._run_check('<x><y z=""o"" /></x>',
662 [('starttag', 'x', []),
663 ('startendtag', 'y', [('z', ''), ('o""', None)]),
664 ('endtag', 'x')])
665 self._run_check('<x><y z="""" /></x>',
666 [('starttag', 'x', []),
667 ('startendtag', 'y', [('z', ''), ('""', None)]),
668 ('endtag', 'x')])
669
670 # see #755670 for the following 3 tests
671 def test_adjacent_attributes(self):
672 self._run_check('<a width="100%"cellspacing=0>',
673 [("starttag", "a",
674 [("width", "100%"), ("cellspacing","0")])])
675
676 self._run_check('<a id="foo"class="bar">',
677 [("starttag", "a",
678 [("id", "foo"), ("class","bar")])])
679
680 def test_missing_attribute_value(self):
681 self._run_check('<a v=>',
682 [("starttag", "a", [("v", "")])])
683
684 def test_javascript_attribute_value(self):
685 self._run_check("<a href=javascript:popup('/popup/help.html')>",
686 [("starttag", "a",
687 [("href", "javascript:popup('/popup/help.html')")])])
688
689 def test_end_tag_in_attribute_value(self):
690 # see #1745761
691 self._run_check("<a href='http://www.example.org/\">;'>spam</a>",
692 [("starttag", "a",
693 [("href", "http://www.example.org/\">;")]),
694 ("data", "spam"), ("endtag", "a")])
695
696
697
Fred Drakee8220492001-09-24 20:19:08 +0000698def test_main():
Ezio Melottib245ed12011-11-14 18:13:22 +0200699 support.run_unittest(HTMLParserStrictTestCase, HTMLParserTolerantTestCase,
Ezio Melottic2fe5772011-11-14 18:53:33 +0200700 AttributesStrictTestCase, AttributesTolerantTestCase)
Fred Drakee8220492001-09-24 20:19:08 +0000701
702
703if __name__ == "__main__":
704 test_main()