blob: c5d878dca597809e156b95d8316a71d6b4a68e9f [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):
Ezio Melotti3861d8b2012-06-23 15:27:51 +0200105 with support.check_warnings(("", DeprecationWarning), quite=False):
106 return EventCollector(strict=True)
Fred Drakebd3090d2001-05-18 15:32:59 +0000107
Fred Drake84bb9d82001-08-03 19:53:01 +0000108 def test_processing_instruction_only(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000109 self._run_check("<?processing instruction>", [
110 ("pi", "processing instruction"),
111 ])
Fred Drakefafd56f2003-04-17 22:19:26 +0000112 self._run_check("<?processing instruction ?>", [
113 ("pi", "processing instruction ?"),
114 ])
Fred Drakebd3090d2001-05-18 15:32:59 +0000115
Fred Drake84bb9d82001-08-03 19:53:01 +0000116 def test_simple_html(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000117 self._run_check("""
118<!DOCTYPE html PUBLIC 'foo'>
119<HTML>&entity;&#32;
120<!--comment1a
121-></foo><bar>&lt;<?pi?></foo<bar
122comment1b-->
123<Img sRc='Bar' isMAP>sample
124text
Fred Drake84bb9d82001-08-03 19:53:01 +0000125&#x201C;
Ezio Melottif4ab4912012-02-13 15:50:37 +0200126<!--comment2a-- --comment2b-->
Fred Drakebd3090d2001-05-18 15:32:59 +0000127</Html>
128""", [
129 ("data", "\n"),
130 ("decl", "DOCTYPE html PUBLIC 'foo'"),
131 ("data", "\n"),
132 ("starttag", "html", []),
133 ("entityref", "entity"),
134 ("charref", "32"),
135 ("data", "\n"),
136 ("comment", "comment1a\n-></foo><bar>&lt;<?pi?></foo<bar\ncomment1b"),
137 ("data", "\n"),
138 ("starttag", "img", [("src", "Bar"), ("ismap", None)]),
139 ("data", "sample\ntext\n"),
Fred Drake84bb9d82001-08-03 19:53:01 +0000140 ("charref", "x201C"),
141 ("data", "\n"),
Fred Drakebd3090d2001-05-18 15:32:59 +0000142 ("comment", "comment2a-- --comment2b"),
143 ("data", "\n"),
144 ("endtag", "html"),
145 ("data", "\n"),
146 ])
147
Victor Stinnere021f4b2010-05-24 21:46:25 +0000148 def test_malformatted_charref(self):
149 self._run_check("<p>&#bad;</p>", [
150 ("starttag", "p", []),
151 ("data", "&#bad;"),
152 ("endtag", "p"),
153 ])
154
Fred Drake073148c2001-12-03 16:44:09 +0000155 def test_unclosed_entityref(self):
156 self._run_check("&entityref foo", [
157 ("entityref", "entityref"),
158 ("data", " foo"),
159 ])
160
Fred Drake84bb9d82001-08-03 19:53:01 +0000161 def test_bad_nesting(self):
162 # Strangely, this *is* supposed to test that overlapping
163 # elements are allowed. HTMLParser is more geared toward
164 # lexing the input that parsing the structure.
Fred Drakebd3090d2001-05-18 15:32:59 +0000165 self._run_check("<a><b></a></b>", [
166 ("starttag", "a", []),
167 ("starttag", "b", []),
168 ("endtag", "a"),
169 ("endtag", "b"),
170 ])
171
Fred Drake029acfb2001-08-20 21:24:19 +0000172 def test_bare_ampersands(self):
173 self._run_check("this text & contains & ampersands &", [
174 ("data", "this text & contains & ampersands &"),
175 ])
176
177 def test_bare_pointy_brackets(self):
178 self._run_check("this < text > contains < bare>pointy< brackets", [
179 ("data", "this < text > contains < bare>pointy< brackets"),
180 ])
181
Fred Drakec20a6982001-09-04 15:13:04 +0000182 def test_illegal_declarations(self):
Fred Drake7cf613d2001-09-04 16:26:03 +0000183 self._parse_error('<!spacer type="block" height="25">')
Fred Drakec20a6982001-09-04 15:13:04 +0000184
Fred Drake84bb9d82001-08-03 19:53:01 +0000185 def test_starttag_end_boundary(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000186 self._run_check("""<a b='<'>""", [("starttag", "a", [("b", "<")])])
187 self._run_check("""<a b='>'>""", [("starttag", "a", [("b", ">")])])
188
Fred Drake84bb9d82001-08-03 19:53:01 +0000189 def test_buffer_artefacts(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000190 output = [("starttag", "a", [("b", "<")])]
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 self._run_check(["<a b='<'", ">"], output)
197
198 output = [("starttag", "a", [("b", ">")])]
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 self._run_check(["<a b='>'", ">"], output)
205
Fred Drake75d9a622004-09-08 22:57:01 +0000206 output = [("comment", "abc")]
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(["<!--", "abc-->"], output)
212 self._run_check(["<!--a", "bc-->"], output)
213 self._run_check(["<!--ab", "c-->"], output)
214 self._run_check(["<!--abc", "-->"], output)
215 self._run_check(["<!--abc-", "->"], output)
216 self._run_check(["<!--abc--", ">"], output)
217 self._run_check(["<!--abc-->", ""], output)
218
Fred Drake84bb9d82001-08-03 19:53:01 +0000219 def test_starttag_junk_chars(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000220 self._parse_error("</>")
221 self._parse_error("</$>")
222 self._parse_error("</")
223 self._parse_error("</a")
Fred Drakebd3090d2001-05-18 15:32:59 +0000224 self._parse_error("<a<a>")
225 self._parse_error("</a<a>")
Fred Drakebd3090d2001-05-18 15:32:59 +0000226 self._parse_error("<!")
Fred Drakebd3090d2001-05-18 15:32:59 +0000227 self._parse_error("<a")
228 self._parse_error("<a foo='bar'")
229 self._parse_error("<a foo='bar")
230 self._parse_error("<a foo='>'")
231 self._parse_error("<a foo='>")
Fred Drakebd3090d2001-05-18 15:32:59 +0000232
Ezio Melottif4ab4912012-02-13 15:50:37 +0200233 def test_valid_doctypes(self):
234 # from http://www.w3.org/QA/2002/04/valid-dtd-list.html
235 dtds = ['HTML', # HTML5 doctype
236 ('HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
237 '"http://www.w3.org/TR/html4/strict.dtd"'),
238 ('HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" '
239 '"http://www.w3.org/TR/html4/loose.dtd"'),
240 ('html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" '
241 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"'),
242 ('html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" '
243 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"'),
244 ('math PUBLIC "-//W3C//DTD MathML 2.0//EN" '
245 '"http://www.w3.org/Math/DTD/mathml2/mathml2.dtd"'),
246 ('html PUBLIC "-//W3C//DTD '
247 'XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" '
248 '"http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd"'),
249 ('svg PUBLIC "-//W3C//DTD SVG 1.1//EN" '
250 '"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"'),
251 'html PUBLIC "-//IETF//DTD HTML 2.0//EN"',
252 'html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"']
253 for dtd in dtds:
254 self._run_check("<!DOCTYPE %s>" % dtd,
255 [('decl', 'DOCTYPE ' + dtd)])
256
Fred Drake84bb9d82001-08-03 19:53:01 +0000257 def test_declaration_junk_chars(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000258 self._parse_error("<!DOCTYPE foo $ >")
259
Fred Drake84bb9d82001-08-03 19:53:01 +0000260 def test_startendtag(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000261 self._run_check("<p/>", [
262 ("startendtag", "p", []),
263 ])
264 self._run_check("<p></p>", [
265 ("starttag", "p", []),
266 ("endtag", "p"),
267 ])
268 self._run_check("<p><img src='foo' /></p>", [
269 ("starttag", "p", []),
270 ("startendtag", "img", [("src", "foo")]),
271 ("endtag", "p"),
272 ])
273
Fred Drake84bb9d82001-08-03 19:53:01 +0000274 def test_get_starttag_text(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000275 s = """<foo:bar \n one="1"\ttwo=2 >"""
276 self._run_check_extra(s, [
277 ("starttag", "foo:bar", [("one", "1"), ("two", "2")]),
278 ("starttag_text", s)])
279
Fred Drake84bb9d82001-08-03 19:53:01 +0000280 def test_cdata_content(self):
Ezio Melotti7de56f62011-11-01 14:12:22 +0200281 contents = [
282 '<!-- not a comment --> &not-an-entity-ref;',
283 "<not a='start tag'>",
284 '<a href="" /> <p> <span></span>',
285 'foo = "</scr" + "ipt>";',
286 'foo = "</SCRIPT" + ">";',
287 'foo = <\n/script> ',
288 '<!-- document.write("</scr" + "ipt>"); -->',
289 ('\n//<![CDATA[\n'
290 'document.write(\'<s\'+\'cript type="text/javascript" '
291 'src="http://www.example.org/r=\'+new '
292 'Date().getTime()+\'"><\\/s\'+\'cript>\');\n//]]>'),
293 '\n<!-- //\nvar foo = 3.14;\n// -->\n',
294 'foo = "</sty" + "le>";',
295 '<!-- \u2603 -->',
296 # these two should be invalid according to the HTML 5 spec,
297 # section 8.1.2.2
298 #'foo = </\nscript>',
299 #'foo = </ script>',
300 ]
301 elements = ['script', 'style', 'SCRIPT', 'STYLE', 'Script', 'Style']
302 for content in contents:
303 for element in elements:
304 element_lower = element.lower()
305 s = '<{element}>{content}</{element}>'.format(element=element,
306 content=content)
307 self._run_check(s, [("starttag", element_lower, []),
308 ("data", content),
309 ("endtag", element_lower)])
310
Ezio Melotti15cb4892011-11-18 18:01:49 +0200311 def test_cdata_with_closing_tags(self):
312 # see issue #13358
313 # make sure that HTMLParser calls handle_data only once for each CDATA.
314 # The normal event collector normalizes the events in get_events,
315 # so we override it to return the original list of events.
316 class Collector(EventCollector):
317 def get_events(self):
318 return self.events
Fred Drakebd3090d2001-05-18 15:32:59 +0000319
Ezio Melotti15cb4892011-11-18 18:01:49 +0200320 content = """<!-- not a comment --> &not-an-entity-ref;
321 <a href="" /> </p><p> <span></span></style>
322 '</script' + '>'"""
323 for element in [' script', 'script ', ' script ',
324 '\nscript', 'script\n', '\nscript\n']:
325 element_lower = element.lower().strip()
326 s = '<script>{content}</{element}>'.format(element=element,
327 content=content)
328 self._run_check(s, [("starttag", element_lower, []),
329 ("data", content),
330 ("endtag", element_lower)],
331 collector=Collector())
Fred Drakebd3090d2001-05-18 15:32:59 +0000332
Ezio Melottifa3702d2012-02-10 10:45:44 +0200333 def test_comments(self):
334 html = ("<!-- I'm a valid comment -->"
335 '<!--me too!-->'
336 '<!------>'
337 '<!---->'
338 '<!----I have many hyphens---->'
339 '<!-- I have a > in the middle -->'
340 '<!-- and I have -- in the middle! -->')
341 expected = [('comment', " I'm a valid comment "),
342 ('comment', 'me too!'),
343 ('comment', '--'),
344 ('comment', ''),
345 ('comment', '--I have many hyphens--'),
346 ('comment', ' I have a > in the middle '),
347 ('comment', ' and I have -- in the middle! ')]
348 self._run_check(html, expected)
349
Ezio Melotti62f3d032011-12-19 07:29:03 +0200350 def test_condcoms(self):
351 html = ('<!--[if IE & !(lte IE 8)]>aren\'t<![endif]-->'
352 '<!--[if IE 8]>condcoms<![endif]-->'
353 '<!--[if lte IE 7]>pretty?<![endif]-->')
354 expected = [('comment', "[if IE & !(lte IE 8)]>aren't<![endif]"),
355 ('comment', '[if IE 8]>condcoms<![endif]'),
356 ('comment', '[if lte IE 7]>pretty?<![endif]')]
357 self._run_check(html, expected)
358
359
Ezio Melottic1e73c32011-11-01 18:57:15 +0200360class HTMLParserTolerantTestCase(HTMLParserStrictTestCase):
R. David Murrayb579dba2010-12-03 04:06:39 +0000361
Ezio Melottib9a48f72011-11-01 15:00:59 +0200362 def get_collector(self):
363 return EventCollector(strict=False)
R. David Murrayb579dba2010-12-03 04:06:39 +0000364
365 def test_tolerant_parsing(self):
366 self._run_check('<html <html>te>>xt&a<<bc</a></html>\n'
367 '<img src="URL><//img></html</html>', [
Ezio Melottic2fe5772011-11-14 18:53:33 +0200368 ('starttag', 'html', [('<html', None)]),
369 ('data', 'te>>xt'),
370 ('entityref', 'a'),
371 ('data', '<<bc'),
372 ('endtag', 'a'),
373 ('endtag', 'html'),
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200374 ('data', '\n<img src="URL>'),
375 ('comment', '/img'),
376 ('endtag', 'html<')])
R. David Murrayb579dba2010-12-03 04:06:39 +0000377
Ezio Melotti86f67122012-02-13 14:11:27 +0200378 def test_starttag_junk_chars(self):
379 self._run_check("</>", [])
380 self._run_check("</$>", [('comment', '$')])
381 self._run_check("</", [('data', '</')])
382 self._run_check("</a", [('data', '</a')])
383 # XXX this might be wrong
384 self._run_check("<a<a>", [('data', '<a'), ('starttag', 'a', [])])
385 self._run_check("</a<a>", [('endtag', 'a<a')])
386 self._run_check("<!", [('data', '<!')])
387 self._run_check("<a", [('data', '<a')])
388 self._run_check("<a foo='bar'", [('data', "<a foo='bar'")])
389 self._run_check("<a foo='bar", [('data', "<a foo='bar")])
390 self._run_check("<a foo='>'", [('data', "<a foo='>'")])
391 self._run_check("<a foo='>", [('data', "<a foo='>")])
392
Ezio Melotti29877e82012-02-21 09:25:00 +0200393 def test_slashes_in_starttag(self):
394 self._run_check('<a foo="var"/>', [('startendtag', 'a', [('foo', 'var')])])
395 html = ('<img width=902 height=250px '
396 'src="/sites/default/files/images/homepage/foo.jpg" '
397 '/*what am I doing here*/ />')
398 expected = [(
399 'startendtag', 'img',
400 [('width', '902'), ('height', '250px'),
401 ('src', '/sites/default/files/images/homepage/foo.jpg'),
402 ('*what', None), ('am', None), ('i', None),
403 ('doing', None), ('here*', None)]
404 )]
405 self._run_check(html, expected)
406 html = ('<a / /foo/ / /=/ / /bar/ / />'
407 '<a / /foo/ / /=/ / /bar/ / >')
408 expected = [
409 ('startendtag', 'a', [('foo', None), ('=', None), ('bar', None)]),
410 ('starttag', 'a', [('foo', None), ('=', None), ('bar', None)])
411 ]
412 self._run_check(html, expected)
Ezio Melotti0780b6b2012-04-18 19:18:22 -0600413 #see issue #14538
414 html = ('<meta><meta / ><meta // ><meta / / >'
415 '<meta/><meta /><meta //><meta//>')
416 expected = [
417 ('starttag', 'meta', []), ('starttag', 'meta', []),
418 ('starttag', 'meta', []), ('starttag', 'meta', []),
419 ('startendtag', 'meta', []), ('startendtag', 'meta', []),
420 ('startendtag', 'meta', []), ('startendtag', 'meta', []),
421 ]
422 self._run_check(html, expected)
Ezio Melotti29877e82012-02-21 09:25:00 +0200423
Ezio Melotti86f67122012-02-13 14:11:27 +0200424 def test_declaration_junk_chars(self):
Ezio Melottif4ab4912012-02-13 15:50:37 +0200425 self._run_check("<!DOCTYPE foo $ >", [('decl', 'DOCTYPE foo $ ')])
Ezio Melotti86f67122012-02-13 14:11:27 +0200426
427 def test_illegal_declarations(self):
Ezio Melotti86f67122012-02-13 14:11:27 +0200428 self._run_check('<!spacer type="block" height="25">',
429 [('comment', 'spacer type="block" height="25"')])
430
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200431 def test_with_unquoted_attributes(self):
Ezio Melottib9a48f72011-11-01 15:00:59 +0200432 # see #12008
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200433 html = ("<html><body bgcolor=d0ca90 text='181008'>"
434 "<table cellspacing=0 cellpadding=1 width=100% ><tr>"
435 "<td align=left><font size=-1>"
436 "- <a href=/rabota/><span class=en> software-and-i</span></a>"
437 "- <a href='/1/'><span class=en> library</span></a></table>")
438 expected = [
439 ('starttag', 'html', []),
440 ('starttag', 'body', [('bgcolor', 'd0ca90'), ('text', '181008')]),
441 ('starttag', 'table',
442 [('cellspacing', '0'), ('cellpadding', '1'), ('width', '100%')]),
443 ('starttag', 'tr', []),
444 ('starttag', 'td', [('align', 'left')]),
445 ('starttag', 'font', [('size', '-1')]),
446 ('data', '- '), ('starttag', 'a', [('href', '/rabota/')]),
447 ('starttag', 'span', [('class', 'en')]), ('data', ' software-and-i'),
448 ('endtag', 'span'), ('endtag', 'a'),
449 ('data', '- '), ('starttag', 'a', [('href', '/1/')]),
450 ('starttag', 'span', [('class', 'en')]), ('data', ' library'),
451 ('endtag', 'span'), ('endtag', 'a'), ('endtag', 'table')
452 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200453 self._run_check(html, expected)
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200454
R. David Murrayb579dba2010-12-03 04:06:39 +0000455 def test_comma_between_attributes(self):
456 self._run_check('<form action="/xxx.php?a=1&amp;b=2&amp", '
457 'method="post">', [
458 ('starttag', 'form',
Ezio Melotti46495182012-06-24 22:02:56 +0200459 [('action', '/xxx.php?a=1&b=2&'),
Ezio Melottic2fe5772011-11-14 18:53:33 +0200460 (',', None), ('method', 'post')])])
R. David Murrayb579dba2010-12-03 04:06:39 +0000461
462 def test_weird_chars_in_unquoted_attribute_values(self):
463 self._run_check('<form action=bogus|&#()value>', [
464 ('starttag', 'form',
Ezio Melottic1e73c32011-11-01 18:57:15 +0200465 [('action', 'bogus|&#()value')])])
R. David Murrayb579dba2010-12-03 04:06:39 +0000466
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200467 def test_invalid_end_tags(self):
468 # A collection of broken end tags. <br> is used as separator.
469 # see http://www.w3.org/TR/html5/tokenization.html#end-tag-open-state
470 # and #13993
471 html = ('<br></label</p><br></div end tmAd-leaderBoard><br></<h4><br>'
472 '</li class="unit"><br></li\r\n\t\t\t\t\t\t</ul><br></><br>')
473 expected = [('starttag', 'br', []),
474 # < is part of the name, / is discarded, p is an attribute
475 ('endtag', 'label<'),
476 ('starttag', 'br', []),
477 # text and attributes are discarded
478 ('endtag', 'div'),
479 ('starttag', 'br', []),
480 # comment because the first char after </ is not a-zA-Z
481 ('comment', '<h4'),
482 ('starttag', 'br', []),
483 # attributes are discarded
484 ('endtag', 'li'),
485 ('starttag', 'br', []),
486 # everything till ul (included) is discarded
487 ('endtag', 'li'),
488 ('starttag', 'br', []),
489 # </> is ignored
490 ('starttag', 'br', [])]
491 self._run_check(html, expected)
492
493 def test_broken_invalid_end_tag(self):
494 # This is technically wrong (the "> shouldn't be included in the 'data')
495 # but is probably not worth fixing it (in addition to all the cases of
496 # the previous test, it would require a full attribute parsing).
497 # see #13993
498 html = '<b>This</b attr=">"> confuses the parser'
499 expected = [('starttag', 'b', []),
500 ('data', 'This'),
501 ('endtag', 'b'),
502 ('data', '"> confuses the parser')]
503 self._run_check(html, expected)
504
Ezio Melottib9a48f72011-11-01 15:00:59 +0200505 def test_correct_detection_of_start_tags(self):
506 # see #13273
Ezio Melottif50ffa92011-10-28 13:21:09 +0300507 html = ('<div style="" ><b>The <a href="some_url">rain</a> '
508 '<br /> in <span>Spain</span></b></div>')
509 expected = [
510 ('starttag', 'div', [('style', '')]),
511 ('starttag', 'b', []),
512 ('data', 'The '),
513 ('starttag', 'a', [('href', 'some_url')]),
514 ('data', 'rain'),
515 ('endtag', 'a'),
516 ('data', ' '),
517 ('startendtag', 'br', []),
518 ('data', ' in '),
519 ('starttag', 'span', []),
520 ('data', 'Spain'),
521 ('endtag', 'span'),
522 ('endtag', 'b'),
523 ('endtag', 'div')
524 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200525 self._run_check(html, expected)
Ezio Melottif50ffa92011-10-28 13:21:09 +0300526
Ezio Melottif50ffa92011-10-28 13:21:09 +0300527 html = '<div style="", foo = "bar" ><b>The <a href="some_url">rain</a>'
528 expected = [
Ezio Melottic2fe5772011-11-14 18:53:33 +0200529 ('starttag', 'div', [('style', ''), (',', None), ('foo', 'bar')]),
Ezio Melottif50ffa92011-10-28 13:21:09 +0300530 ('starttag', 'b', []),
531 ('data', 'The '),
532 ('starttag', 'a', [('href', 'some_url')]),
533 ('data', 'rain'),
534 ('endtag', 'a'),
535 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200536 self._run_check(html, expected)
Ezio Melottif50ffa92011-10-28 13:21:09 +0300537
Senthil Kumaran164540f2010-12-28 15:55:16 +0000538 def test_unescape_function(self):
Ezio Melotti86f67122012-02-13 14:11:27 +0200539 p = self.get_collector()
Senthil Kumaran164540f2010-12-28 15:55:16 +0000540 self.assertEqual(p.unescape('&#bad;'),'&#bad;')
541 self.assertEqual(p.unescape('&#0038;'),'&')
Ezio Melottid9e0b062011-09-05 17:11:06 +0300542 # see #12888
543 self.assertEqual(p.unescape('&#123; ' * 1050), '{ ' * 1050)
Ezio Melotti46495182012-06-24 22:02:56 +0200544 # see #15156
545 self.assertEqual(p.unescape('&Eacuteric&Eacute;ric'
546 '&alphacentauri&alpha;centauri'),
547 'ÉricÉric&alphacentauriαcentauri')
548 self.assertEqual(p.unescape('&co;'), '&co;')
R. David Murrayb579dba2010-12-03 04:06:39 +0000549
Ezio Melottifa3702d2012-02-10 10:45:44 +0200550 def test_broken_comments(self):
551 html = ('<! not really a comment >'
552 '<! not a comment either -->'
553 '<! -- close enough -->'
Ezio Melottif4ab4912012-02-13 15:50:37 +0200554 '<!><!<-- this was an empty comment>'
Ezio Melottifa3702d2012-02-10 10:45:44 +0200555 '<!!! another bogus comment !!!>')
556 expected = [
557 ('comment', ' not really a comment '),
558 ('comment', ' not a comment either --'),
559 ('comment', ' -- close enough --'),
Ezio Melottif4ab4912012-02-13 15:50:37 +0200560 ('comment', ''),
561 ('comment', '<-- this was an empty comment'),
Ezio Melottifa3702d2012-02-10 10:45:44 +0200562 ('comment', '!! another bogus comment !!!'),
563 ]
564 self._run_check(html, expected)
565
Ezio Melotti62f3d032011-12-19 07:29:03 +0200566 def test_broken_condcoms(self):
567 # these condcoms are missing the '--' after '<!' and before the '>'
568 html = ('<![if !(IE)]>broken condcom<![endif]>'
569 '<![if ! IE]><link href="favicon.tiff"/><![endif]>'
570 '<![if !IE 6]><img src="firefox.png" /><![endif]>'
571 '<![if !ie 6]><b>foo</b><![endif]>'
572 '<![if (!IE)|(lt IE 9)]><img src="mammoth.bmp" /><![endif]>')
573 # According to the HTML5 specs sections "8.2.4.44 Bogus comment state"
574 # and "8.2.4.45 Markup declaration open state", comment tokens should
575 # be emitted instead of 'unknown decl', but calling unknown_decl
576 # provides more flexibility.
577 # See also Lib/_markupbase.py:parse_declaration
578 expected = [
579 ('unknown decl', 'if !(IE)'),
580 ('data', 'broken condcom'),
581 ('unknown decl', 'endif'),
582 ('unknown decl', 'if ! IE'),
583 ('startendtag', 'link', [('href', 'favicon.tiff')]),
584 ('unknown decl', 'endif'),
585 ('unknown decl', 'if !IE 6'),
586 ('startendtag', 'img', [('src', 'firefox.png')]),
587 ('unknown decl', 'endif'),
588 ('unknown decl', 'if !ie 6'),
589 ('starttag', 'b', []),
590 ('data', 'foo'),
591 ('endtag', 'b'),
592 ('unknown decl', 'endif'),
593 ('unknown decl', 'if (!IE)|(lt IE 9)'),
594 ('startendtag', 'img', [('src', 'mammoth.bmp')]),
595 ('unknown decl', 'endif')
596 ]
597 self._run_check(html, expected)
598
Ezio Melottic1e73c32011-11-01 18:57:15 +0200599
Ezio Melottib245ed12011-11-14 18:13:22 +0200600class AttributesStrictTestCase(TestCaseBase):
601
602 def get_collector(self):
Ezio Melotti3861d8b2012-06-23 15:27:51 +0200603 with support.check_warnings(("", DeprecationWarning), quite=False):
604 return EventCollector(strict=True)
Ezio Melottib245ed12011-11-14 18:13:22 +0200605
606 def test_attr_syntax(self):
607 output = [
608 ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", None)])
609 ]
610 self._run_check("""<a b='v' c="v" d=v e>""", output)
611 self._run_check("""<a b = 'v' c = "v" d = v e>""", output)
612 self._run_check("""<a\nb\n=\n'v'\nc\n=\n"v"\nd\n=\nv\ne>""", output)
613 self._run_check("""<a\tb\t=\t'v'\tc\t=\t"v"\td\t=\tv\te>""", output)
614
615 def test_attr_values(self):
616 self._run_check("""<a b='xxx\n\txxx' c="yyy\t\nyyy" d='\txyz\n'>""",
617 [("starttag", "a", [("b", "xxx\n\txxx"),
618 ("c", "yyy\t\nyyy"),
619 ("d", "\txyz\n")])])
620 self._run_check("""<a b='' c="">""",
621 [("starttag", "a", [("b", ""), ("c", "")])])
622 # Regression test for SF patch #669683.
623 self._run_check("<e a=rgb(1,2,3)>",
624 [("starttag", "e", [("a", "rgb(1,2,3)")])])
625 # Regression test for SF bug #921657.
626 self._run_check(
627 "<a href=mailto:xyz@example.com>",
628 [("starttag", "a", [("href", "mailto:xyz@example.com")])])
629
630 def test_attr_nonascii(self):
631 # see issue 7311
632 self._run_check(
633 "<img src=/foo/bar.png alt=\u4e2d\u6587>",
634 [("starttag", "img", [("src", "/foo/bar.png"),
635 ("alt", "\u4e2d\u6587")])])
636 self._run_check(
637 "<a title='\u30c6\u30b9\u30c8' href='\u30c6\u30b9\u30c8.html'>",
638 [("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
639 ("href", "\u30c6\u30b9\u30c8.html")])])
640 self._run_check(
641 '<a title="\u30c6\u30b9\u30c8" href="\u30c6\u30b9\u30c8.html">',
642 [("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
643 ("href", "\u30c6\u30b9\u30c8.html")])])
644
645 def test_attr_entity_replacement(self):
646 self._run_check(
647 "<a b='&amp;&gt;&lt;&quot;&apos;'>",
648 [("starttag", "a", [("b", "&><\"'")])])
649
650 def test_attr_funky_names(self):
651 self._run_check(
652 "<a a.b='v' c:d=v e-f=v>",
653 [("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")])])
654
655 def test_entityrefs_in_attributes(self):
656 self._run_check(
657 "<html foo='&euro;&amp;&#97;&#x61;&unsupported;'>",
658 [("starttag", "html", [("foo", "\u20AC&aa&unsupported;")])])
659
660
Ezio Melottic2fe5772011-11-14 18:53:33 +0200661
662class AttributesTolerantTestCase(AttributesStrictTestCase):
663
664 def get_collector(self):
665 return EventCollector(strict=False)
666
667 def test_attr_funky_names2(self):
668 self._run_check(
669 "<a $><b $=%><c \=/>",
670 [("starttag", "a", [("$", None)]),
671 ("starttag", "b", [("$", "%")]),
672 ("starttag", "c", [("\\", "/")])])
673
674 def test_entities_in_attribute_value(self):
675 # see #1200313
676 for entity in ['&', '&amp;', '&#38;', '&#x26;']:
677 self._run_check('<a href="%s">' % entity,
678 [("starttag", "a", [("href", "&")])])
679 self._run_check("<a href='%s'>" % entity,
680 [("starttag", "a", [("href", "&")])])
681 self._run_check("<a href=%s>" % entity,
682 [("starttag", "a", [("href", "&")])])
683
684 def test_malformed_attributes(self):
685 # see #13357
686 html = (
687 "<a href=test'style='color:red;bad1'>test - bad1</a>"
688 "<a href=test'+style='color:red;ba2'>test - bad2</a>"
689 "<a href=test'&nbsp;style='color:red;bad3'>test - bad3</a>"
690 "<a href = test'&nbsp;style='color:red;bad4' >test - bad4</a>"
691 )
692 expected = [
693 ('starttag', 'a', [('href', "test'style='color:red;bad1'")]),
694 ('data', 'test - bad1'), ('endtag', 'a'),
695 ('starttag', 'a', [('href', "test'+style='color:red;ba2'")]),
696 ('data', 'test - bad2'), ('endtag', 'a'),
697 ('starttag', 'a', [('href', "test'\xa0style='color:red;bad3'")]),
698 ('data', 'test - bad3'), ('endtag', 'a'),
699 ('starttag', 'a', [('href', "test'\xa0style='color:red;bad4'")]),
700 ('data', 'test - bad4'), ('endtag', 'a')
701 ]
702 self._run_check(html, expected)
703
704 def test_malformed_adjacent_attributes(self):
705 # see #12629
706 self._run_check('<x><y z=""o"" /></x>',
707 [('starttag', 'x', []),
708 ('startendtag', 'y', [('z', ''), ('o""', None)]),
709 ('endtag', 'x')])
710 self._run_check('<x><y z="""" /></x>',
711 [('starttag', 'x', []),
712 ('startendtag', 'y', [('z', ''), ('""', None)]),
713 ('endtag', 'x')])
714
715 # see #755670 for the following 3 tests
716 def test_adjacent_attributes(self):
717 self._run_check('<a width="100%"cellspacing=0>',
718 [("starttag", "a",
719 [("width", "100%"), ("cellspacing","0")])])
720
721 self._run_check('<a id="foo"class="bar">',
722 [("starttag", "a",
723 [("id", "foo"), ("class","bar")])])
724
725 def test_missing_attribute_value(self):
726 self._run_check('<a v=>',
727 [("starttag", "a", [("v", "")])])
728
729 def test_javascript_attribute_value(self):
730 self._run_check("<a href=javascript:popup('/popup/help.html')>",
731 [("starttag", "a",
732 [("href", "javascript:popup('/popup/help.html')")])])
733
734 def test_end_tag_in_attribute_value(self):
735 # see #1745761
736 self._run_check("<a href='http://www.example.org/\">;'>spam</a>",
737 [("starttag", "a",
738 [("href", "http://www.example.org/\">;")]),
739 ("data", "spam"), ("endtag", "a")])
740
741
742
Fred Drakee8220492001-09-24 20:19:08 +0000743def test_main():
Ezio Melottib245ed12011-11-14 18:13:22 +0200744 support.run_unittest(HTMLParserStrictTestCase, HTMLParserTolerantTestCase,
Ezio Melottic2fe5772011-11-14 18:53:33 +0200745 AttributesStrictTestCase, AttributesTolerantTestCase)
Fred Drakee8220492001-09-24 20:19:08 +0000746
747
748if __name__ == "__main__":
749 test_main()