blob: 11d9c9ce8b8c1a4c60250f57226d1d19f38eca33 [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 ])
Ezio Melottif27b9a72014-02-01 21:21:01 +0200154 # add the [] as a workaround to avoid buffering (see #20288)
155 self._run_check(["<div>&#bad;</div>"], [
156 ("starttag", "div", []),
157 ("data", "&#bad;"),
158 ("endtag", "div"),
159 ])
Victor Stinnere021f4b2010-05-24 21:46:25 +0000160
Fred Drake073148c2001-12-03 16:44:09 +0000161 def test_unclosed_entityref(self):
162 self._run_check("&entityref foo", [
163 ("entityref", "entityref"),
164 ("data", " foo"),
165 ])
166
Fred Drake84bb9d82001-08-03 19:53:01 +0000167 def test_bad_nesting(self):
168 # Strangely, this *is* supposed to test that overlapping
169 # elements are allowed. HTMLParser is more geared toward
170 # lexing the input that parsing the structure.
Fred Drakebd3090d2001-05-18 15:32:59 +0000171 self._run_check("<a><b></a></b>", [
172 ("starttag", "a", []),
173 ("starttag", "b", []),
174 ("endtag", "a"),
175 ("endtag", "b"),
176 ])
177
Fred Drake029acfb2001-08-20 21:24:19 +0000178 def test_bare_ampersands(self):
179 self._run_check("this text & contains & ampersands &", [
180 ("data", "this text & contains & ampersands &"),
181 ])
182
183 def test_bare_pointy_brackets(self):
184 self._run_check("this < text > contains < bare>pointy< brackets", [
185 ("data", "this < text > contains < bare>pointy< brackets"),
186 ])
187
Fred Drakec20a6982001-09-04 15:13:04 +0000188 def test_illegal_declarations(self):
Fred Drake7cf613d2001-09-04 16:26:03 +0000189 self._parse_error('<!spacer type="block" height="25">')
Fred Drakec20a6982001-09-04 15:13:04 +0000190
Fred Drake84bb9d82001-08-03 19:53:01 +0000191 def test_starttag_end_boundary(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000192 self._run_check("""<a b='<'>""", [("starttag", "a", [("b", "<")])])
193 self._run_check("""<a b='>'>""", [("starttag", "a", [("b", ">")])])
194
Fred Drake84bb9d82001-08-03 19:53:01 +0000195 def test_buffer_artefacts(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000196 output = [("starttag", "a", [("b", "<")])]
197 self._run_check(["<a b='<'>"], output)
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
204 output = [("starttag", "a", [("b", ">")])]
205 self._run_check(["<a b='>'>"], output)
206 self._run_check(["<a ", "b='>'>"], output)
207 self._run_check(["<a b", "='>'>"], output)
208 self._run_check(["<a b=", "'>'>"], output)
209 self._run_check(["<a b='>", "'>"], output)
210 self._run_check(["<a b='>'", ">"], output)
211
Fred Drake75d9a622004-09-08 22:57:01 +0000212 output = [("comment", "abc")]
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 self._run_check(["<!--", "abc-->"], output)
218 self._run_check(["<!--a", "bc-->"], output)
219 self._run_check(["<!--ab", "c-->"], output)
220 self._run_check(["<!--abc", "-->"], output)
221 self._run_check(["<!--abc-", "->"], output)
222 self._run_check(["<!--abc--", ">"], output)
223 self._run_check(["<!--abc-->", ""], output)
224
Fred Drake84bb9d82001-08-03 19:53:01 +0000225 def test_starttag_junk_chars(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000226 self._parse_error("</>")
227 self._parse_error("</$>")
228 self._parse_error("</")
229 self._parse_error("</a")
Fred Drakebd3090d2001-05-18 15:32:59 +0000230 self._parse_error("<a<a>")
231 self._parse_error("</a<a>")
Fred Drakebd3090d2001-05-18 15:32:59 +0000232 self._parse_error("<!")
Fred Drakebd3090d2001-05-18 15:32:59 +0000233 self._parse_error("<a")
234 self._parse_error("<a foo='bar'")
235 self._parse_error("<a foo='bar")
236 self._parse_error("<a foo='>'")
237 self._parse_error("<a foo='>")
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200238 self._parse_error("<a$>")
239 self._parse_error("<a$b>")
240 self._parse_error("<a$b/>")
241 self._parse_error("<a$b >")
242 self._parse_error("<a$b />")
Fred Drakebd3090d2001-05-18 15:32:59 +0000243
Ezio Melottif4ab4912012-02-13 15:50:37 +0200244 def test_valid_doctypes(self):
245 # from http://www.w3.org/QA/2002/04/valid-dtd-list.html
246 dtds = ['HTML', # HTML5 doctype
247 ('HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
248 '"http://www.w3.org/TR/html4/strict.dtd"'),
249 ('HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" '
250 '"http://www.w3.org/TR/html4/loose.dtd"'),
251 ('html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" '
252 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"'),
253 ('html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" '
254 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"'),
255 ('math PUBLIC "-//W3C//DTD MathML 2.0//EN" '
256 '"http://www.w3.org/Math/DTD/mathml2/mathml2.dtd"'),
257 ('html PUBLIC "-//W3C//DTD '
258 'XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" '
259 '"http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd"'),
260 ('svg PUBLIC "-//W3C//DTD SVG 1.1//EN" '
261 '"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"'),
262 'html PUBLIC "-//IETF//DTD HTML 2.0//EN"',
263 'html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"']
264 for dtd in dtds:
265 self._run_check("<!DOCTYPE %s>" % dtd,
266 [('decl', 'DOCTYPE ' + dtd)])
267
Fred Drake84bb9d82001-08-03 19:53:01 +0000268 def test_declaration_junk_chars(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000269 self._parse_error("<!DOCTYPE foo $ >")
270
Fred Drake84bb9d82001-08-03 19:53:01 +0000271 def test_startendtag(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000272 self._run_check("<p/>", [
273 ("startendtag", "p", []),
274 ])
275 self._run_check("<p></p>", [
276 ("starttag", "p", []),
277 ("endtag", "p"),
278 ])
279 self._run_check("<p><img src='foo' /></p>", [
280 ("starttag", "p", []),
281 ("startendtag", "img", [("src", "foo")]),
282 ("endtag", "p"),
283 ])
284
Fred Drake84bb9d82001-08-03 19:53:01 +0000285 def test_get_starttag_text(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000286 s = """<foo:bar \n one="1"\ttwo=2 >"""
287 self._run_check_extra(s, [
288 ("starttag", "foo:bar", [("one", "1"), ("two", "2")]),
289 ("starttag_text", s)])
290
Fred Drake84bb9d82001-08-03 19:53:01 +0000291 def test_cdata_content(self):
Ezio Melotti7de56f62011-11-01 14:12:22 +0200292 contents = [
293 '<!-- not a comment --> &not-an-entity-ref;',
294 "<not a='start tag'>",
295 '<a href="" /> <p> <span></span>',
296 'foo = "</scr" + "ipt>";',
297 'foo = "</SCRIPT" + ">";',
298 'foo = <\n/script> ',
299 '<!-- document.write("</scr" + "ipt>"); -->',
300 ('\n//<![CDATA[\n'
301 'document.write(\'<s\'+\'cript type="text/javascript" '
302 'src="http://www.example.org/r=\'+new '
303 'Date().getTime()+\'"><\\/s\'+\'cript>\');\n//]]>'),
304 '\n<!-- //\nvar foo = 3.14;\n// -->\n',
305 'foo = "</sty" + "le>";',
306 '<!-- \u2603 -->',
307 # these two should be invalid according to the HTML 5 spec,
308 # section 8.1.2.2
309 #'foo = </\nscript>',
310 #'foo = </ script>',
311 ]
312 elements = ['script', 'style', 'SCRIPT', 'STYLE', 'Script', 'Style']
313 for content in contents:
314 for element in elements:
315 element_lower = element.lower()
316 s = '<{element}>{content}</{element}>'.format(element=element,
317 content=content)
318 self._run_check(s, [("starttag", element_lower, []),
319 ("data", content),
320 ("endtag", element_lower)])
321
Ezio Melotti15cb4892011-11-18 18:01:49 +0200322 def test_cdata_with_closing_tags(self):
323 # see issue #13358
324 # make sure that HTMLParser calls handle_data only once for each CDATA.
325 # The normal event collector normalizes the events in get_events,
326 # so we override it to return the original list of events.
327 class Collector(EventCollector):
328 def get_events(self):
329 return self.events
Fred Drakebd3090d2001-05-18 15:32:59 +0000330
Ezio Melotti15cb4892011-11-18 18:01:49 +0200331 content = """<!-- not a comment --> &not-an-entity-ref;
332 <a href="" /> </p><p> <span></span></style>
333 '</script' + '>'"""
334 for element in [' script', 'script ', ' script ',
335 '\nscript', 'script\n', '\nscript\n']:
336 element_lower = element.lower().strip()
337 s = '<script>{content}</{element}>'.format(element=element,
338 content=content)
339 self._run_check(s, [("starttag", element_lower, []),
340 ("data", content),
341 ("endtag", element_lower)],
342 collector=Collector())
Fred Drakebd3090d2001-05-18 15:32:59 +0000343
Ezio Melottifa3702d2012-02-10 10:45:44 +0200344 def test_comments(self):
345 html = ("<!-- I'm a valid comment -->"
346 '<!--me too!-->'
347 '<!------>'
348 '<!---->'
349 '<!----I have many hyphens---->'
350 '<!-- I have a > in the middle -->'
351 '<!-- and I have -- in the middle! -->')
352 expected = [('comment', " I'm a valid comment "),
353 ('comment', 'me too!'),
354 ('comment', '--'),
355 ('comment', ''),
356 ('comment', '--I have many hyphens--'),
357 ('comment', ' I have a > in the middle '),
358 ('comment', ' and I have -- in the middle! ')]
359 self._run_check(html, expected)
360
Ezio Melotti62f3d032011-12-19 07:29:03 +0200361 def test_condcoms(self):
362 html = ('<!--[if IE & !(lte IE 8)]>aren\'t<![endif]-->'
363 '<!--[if IE 8]>condcoms<![endif]-->'
364 '<!--[if lte IE 7]>pretty?<![endif]-->')
365 expected = [('comment', "[if IE & !(lte IE 8)]>aren't<![endif]"),
366 ('comment', '[if IE 8]>condcoms<![endif]'),
367 ('comment', '[if lte IE 7]>pretty?<![endif]')]
368 self._run_check(html, expected)
369
370
Ezio Melottic1e73c32011-11-01 18:57:15 +0200371class HTMLParserTolerantTestCase(HTMLParserStrictTestCase):
R. David Murrayb579dba2010-12-03 04:06:39 +0000372
Ezio Melottib9a48f72011-11-01 15:00:59 +0200373 def get_collector(self):
374 return EventCollector(strict=False)
R. David Murrayb579dba2010-12-03 04:06:39 +0000375
376 def test_tolerant_parsing(self):
377 self._run_check('<html <html>te>>xt&a<<bc</a></html>\n'
378 '<img src="URL><//img></html</html>', [
Ezio Melottic2fe5772011-11-14 18:53:33 +0200379 ('starttag', 'html', [('<html', None)]),
380 ('data', 'te>>xt'),
381 ('entityref', 'a'),
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200382 ('data', '<'),
383 ('starttag', 'bc<', [('a', None)]),
Ezio Melottic2fe5772011-11-14 18:53:33 +0200384 ('endtag', 'html'),
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200385 ('data', '\n<img src="URL>'),
386 ('comment', '/img'),
387 ('endtag', 'html<')])
R. David Murrayb579dba2010-12-03 04:06:39 +0000388
Ezio Melotti86f67122012-02-13 14:11:27 +0200389 def test_starttag_junk_chars(self):
390 self._run_check("</>", [])
391 self._run_check("</$>", [('comment', '$')])
392 self._run_check("</", [('data', '</')])
393 self._run_check("</a", [('data', '</a')])
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200394 self._run_check("<a<a>", [('starttag', 'a<a', [])])
Ezio Melotti86f67122012-02-13 14:11:27 +0200395 self._run_check("</a<a>", [('endtag', 'a<a')])
396 self._run_check("<!", [('data', '<!')])
397 self._run_check("<a", [('data', '<a')])
398 self._run_check("<a foo='bar'", [('data', "<a foo='bar'")])
399 self._run_check("<a foo='bar", [('data', "<a foo='bar")])
400 self._run_check("<a foo='>'", [('data', "<a foo='>'")])
401 self._run_check("<a foo='>", [('data', "<a foo='>")])
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200402 self._run_check("<a$>", [('starttag', 'a$', [])])
403 self._run_check("<a$b>", [('starttag', 'a$b', [])])
404 self._run_check("<a$b/>", [('startendtag', 'a$b', [])])
405 self._run_check("<a$b >", [('starttag', 'a$b', [])])
406 self._run_check("<a$b />", [('startendtag', 'a$b', [])])
Ezio Melotti86f67122012-02-13 14:11:27 +0200407
Ezio Melotti29877e82012-02-21 09:25:00 +0200408 def test_slashes_in_starttag(self):
409 self._run_check('<a foo="var"/>', [('startendtag', 'a', [('foo', 'var')])])
410 html = ('<img width=902 height=250px '
411 'src="/sites/default/files/images/homepage/foo.jpg" '
412 '/*what am I doing here*/ />')
413 expected = [(
414 'startendtag', 'img',
415 [('width', '902'), ('height', '250px'),
416 ('src', '/sites/default/files/images/homepage/foo.jpg'),
417 ('*what', None), ('am', None), ('i', None),
418 ('doing', None), ('here*', None)]
419 )]
420 self._run_check(html, expected)
421 html = ('<a / /foo/ / /=/ / /bar/ / />'
422 '<a / /foo/ / /=/ / /bar/ / >')
423 expected = [
424 ('startendtag', 'a', [('foo', None), ('=', None), ('bar', None)]),
425 ('starttag', 'a', [('foo', None), ('=', None), ('bar', None)])
426 ]
427 self._run_check(html, expected)
Ezio Melotti0780b6b2012-04-18 19:18:22 -0600428 #see issue #14538
429 html = ('<meta><meta / ><meta // ><meta / / >'
430 '<meta/><meta /><meta //><meta//>')
431 expected = [
432 ('starttag', 'meta', []), ('starttag', 'meta', []),
433 ('starttag', 'meta', []), ('starttag', 'meta', []),
434 ('startendtag', 'meta', []), ('startendtag', 'meta', []),
435 ('startendtag', 'meta', []), ('startendtag', 'meta', []),
436 ]
437 self._run_check(html, expected)
Ezio Melotti29877e82012-02-21 09:25:00 +0200438
Ezio Melotti86f67122012-02-13 14:11:27 +0200439 def test_declaration_junk_chars(self):
Ezio Melottif4ab4912012-02-13 15:50:37 +0200440 self._run_check("<!DOCTYPE foo $ >", [('decl', 'DOCTYPE foo $ ')])
Ezio Melotti86f67122012-02-13 14:11:27 +0200441
442 def test_illegal_declarations(self):
Ezio Melotti86f67122012-02-13 14:11:27 +0200443 self._run_check('<!spacer type="block" height="25">',
444 [('comment', 'spacer type="block" height="25"')])
445
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200446 def test_with_unquoted_attributes(self):
Ezio Melottib9a48f72011-11-01 15:00:59 +0200447 # see #12008
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200448 html = ("<html><body bgcolor=d0ca90 text='181008'>"
449 "<table cellspacing=0 cellpadding=1 width=100% ><tr>"
450 "<td align=left><font size=-1>"
451 "- <a href=/rabota/><span class=en> software-and-i</span></a>"
452 "- <a href='/1/'><span class=en> library</span></a></table>")
453 expected = [
454 ('starttag', 'html', []),
455 ('starttag', 'body', [('bgcolor', 'd0ca90'), ('text', '181008')]),
456 ('starttag', 'table',
457 [('cellspacing', '0'), ('cellpadding', '1'), ('width', '100%')]),
458 ('starttag', 'tr', []),
459 ('starttag', 'td', [('align', 'left')]),
460 ('starttag', 'font', [('size', '-1')]),
461 ('data', '- '), ('starttag', 'a', [('href', '/rabota/')]),
462 ('starttag', 'span', [('class', 'en')]), ('data', ' software-and-i'),
463 ('endtag', 'span'), ('endtag', 'a'),
464 ('data', '- '), ('starttag', 'a', [('href', '/1/')]),
465 ('starttag', 'span', [('class', 'en')]), ('data', ' library'),
466 ('endtag', 'span'), ('endtag', 'a'), ('endtag', 'table')
467 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200468 self._run_check(html, expected)
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200469
R. David Murrayb579dba2010-12-03 04:06:39 +0000470 def test_comma_between_attributes(self):
471 self._run_check('<form action="/xxx.php?a=1&amp;b=2&amp", '
472 'method="post">', [
473 ('starttag', 'form',
Ezio Melotti46495182012-06-24 22:02:56 +0200474 [('action', '/xxx.php?a=1&b=2&'),
Ezio Melottic2fe5772011-11-14 18:53:33 +0200475 (',', None), ('method', 'post')])])
R. David Murrayb579dba2010-12-03 04:06:39 +0000476
477 def test_weird_chars_in_unquoted_attribute_values(self):
478 self._run_check('<form action=bogus|&#()value>', [
479 ('starttag', 'form',
Ezio Melottic1e73c32011-11-01 18:57:15 +0200480 [('action', 'bogus|&#()value')])])
R. David Murrayb579dba2010-12-03 04:06:39 +0000481
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200482 def test_invalid_end_tags(self):
483 # A collection of broken end tags. <br> is used as separator.
484 # see http://www.w3.org/TR/html5/tokenization.html#end-tag-open-state
485 # and #13993
486 html = ('<br></label</p><br></div end tmAd-leaderBoard><br></<h4><br>'
487 '</li class="unit"><br></li\r\n\t\t\t\t\t\t</ul><br></><br>')
488 expected = [('starttag', 'br', []),
489 # < is part of the name, / is discarded, p is an attribute
490 ('endtag', 'label<'),
491 ('starttag', 'br', []),
492 # text and attributes are discarded
493 ('endtag', 'div'),
494 ('starttag', 'br', []),
495 # comment because the first char after </ is not a-zA-Z
496 ('comment', '<h4'),
497 ('starttag', 'br', []),
498 # attributes are discarded
499 ('endtag', 'li'),
500 ('starttag', 'br', []),
501 # everything till ul (included) is discarded
502 ('endtag', 'li'),
503 ('starttag', 'br', []),
504 # </> is ignored
505 ('starttag', 'br', [])]
506 self._run_check(html, expected)
507
508 def test_broken_invalid_end_tag(self):
509 # This is technically wrong (the "> shouldn't be included in the 'data')
510 # but is probably not worth fixing it (in addition to all the cases of
511 # the previous test, it would require a full attribute parsing).
512 # see #13993
513 html = '<b>This</b attr=">"> confuses the parser'
514 expected = [('starttag', 'b', []),
515 ('data', 'This'),
516 ('endtag', 'b'),
517 ('data', '"> confuses the parser')]
518 self._run_check(html, expected)
519
Ezio Melottib9a48f72011-11-01 15:00:59 +0200520 def test_correct_detection_of_start_tags(self):
521 # see #13273
Ezio Melottif50ffa92011-10-28 13:21:09 +0300522 html = ('<div style="" ><b>The <a href="some_url">rain</a> '
523 '<br /> in <span>Spain</span></b></div>')
524 expected = [
525 ('starttag', 'div', [('style', '')]),
526 ('starttag', 'b', []),
527 ('data', 'The '),
528 ('starttag', 'a', [('href', 'some_url')]),
529 ('data', 'rain'),
530 ('endtag', 'a'),
531 ('data', ' '),
532 ('startendtag', 'br', []),
533 ('data', ' in '),
534 ('starttag', 'span', []),
535 ('data', 'Spain'),
536 ('endtag', 'span'),
537 ('endtag', 'b'),
538 ('endtag', 'div')
539 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200540 self._run_check(html, expected)
Ezio Melottif50ffa92011-10-28 13:21:09 +0300541
Ezio Melottif50ffa92011-10-28 13:21:09 +0300542 html = '<div style="", foo = "bar" ><b>The <a href="some_url">rain</a>'
543 expected = [
Ezio Melottic2fe5772011-11-14 18:53:33 +0200544 ('starttag', 'div', [('style', ''), (',', None), ('foo', 'bar')]),
Ezio Melottif50ffa92011-10-28 13:21:09 +0300545 ('starttag', 'b', []),
546 ('data', 'The '),
547 ('starttag', 'a', [('href', 'some_url')]),
548 ('data', 'rain'),
549 ('endtag', 'a'),
550 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200551 self._run_check(html, expected)
Ezio Melottif50ffa92011-10-28 13:21:09 +0300552
Ezio Melotti8e596a72013-05-01 16:18:25 +0300553 def test_EOF_in_charref(self):
554 # see #17802
555 # This test checks that the UnboundLocalError reported in the issue
556 # is not raised, however I'm not sure the returned values are correct.
557 # Maybe HTMLParser should use self.unescape for these
558 data = [
559 ('a&', [('data', 'a&')]),
560 ('a&b', [('data', 'ab')]),
561 ('a&b ', [('data', 'a'), ('entityref', 'b'), ('data', ' ')]),
562 ('a&b;', [('data', 'a'), ('entityref', 'b')]),
563 ]
564 for html, expected in data:
565 self._run_check(html, expected)
566
Senthil Kumaran164540f2010-12-28 15:55:16 +0000567 def test_unescape_function(self):
Ezio Melotti86f67122012-02-13 14:11:27 +0200568 p = self.get_collector()
Senthil Kumaran164540f2010-12-28 15:55:16 +0000569 self.assertEqual(p.unescape('&#bad;'),'&#bad;')
570 self.assertEqual(p.unescape('&#0038;'),'&')
Ezio Melottid9e0b062011-09-05 17:11:06 +0300571 # see #12888
572 self.assertEqual(p.unescape('&#123; ' * 1050), '{ ' * 1050)
Ezio Melotti46495182012-06-24 22:02:56 +0200573 # see #15156
574 self.assertEqual(p.unescape('&Eacuteric&Eacute;ric'
575 '&alphacentauri&alpha;centauri'),
576 'ÉricÉric&alphacentauriαcentauri')
577 self.assertEqual(p.unescape('&co;'), '&co;')
R. David Murrayb579dba2010-12-03 04:06:39 +0000578
Ezio Melottifa3702d2012-02-10 10:45:44 +0200579 def test_broken_comments(self):
580 html = ('<! not really a comment >'
581 '<! not a comment either -->'
582 '<! -- close enough -->'
Ezio Melottif4ab4912012-02-13 15:50:37 +0200583 '<!><!<-- this was an empty comment>'
Ezio Melottifa3702d2012-02-10 10:45:44 +0200584 '<!!! another bogus comment !!!>')
585 expected = [
586 ('comment', ' not really a comment '),
587 ('comment', ' not a comment either --'),
588 ('comment', ' -- close enough --'),
Ezio Melottif4ab4912012-02-13 15:50:37 +0200589 ('comment', ''),
590 ('comment', '<-- this was an empty comment'),
Ezio Melottifa3702d2012-02-10 10:45:44 +0200591 ('comment', '!! another bogus comment !!!'),
592 ]
593 self._run_check(html, expected)
594
Ezio Melotti62f3d032011-12-19 07:29:03 +0200595 def test_broken_condcoms(self):
596 # these condcoms are missing the '--' after '<!' and before the '>'
597 html = ('<![if !(IE)]>broken condcom<![endif]>'
598 '<![if ! IE]><link href="favicon.tiff"/><![endif]>'
599 '<![if !IE 6]><img src="firefox.png" /><![endif]>'
600 '<![if !ie 6]><b>foo</b><![endif]>'
601 '<![if (!IE)|(lt IE 9)]><img src="mammoth.bmp" /><![endif]>')
602 # According to the HTML5 specs sections "8.2.4.44 Bogus comment state"
603 # and "8.2.4.45 Markup declaration open state", comment tokens should
604 # be emitted instead of 'unknown decl', but calling unknown_decl
605 # provides more flexibility.
606 # See also Lib/_markupbase.py:parse_declaration
607 expected = [
608 ('unknown decl', 'if !(IE)'),
609 ('data', 'broken condcom'),
610 ('unknown decl', 'endif'),
611 ('unknown decl', 'if ! IE'),
612 ('startendtag', 'link', [('href', 'favicon.tiff')]),
613 ('unknown decl', 'endif'),
614 ('unknown decl', 'if !IE 6'),
615 ('startendtag', 'img', [('src', 'firefox.png')]),
616 ('unknown decl', 'endif'),
617 ('unknown decl', 'if !ie 6'),
618 ('starttag', 'b', []),
619 ('data', 'foo'),
620 ('endtag', 'b'),
621 ('unknown decl', 'endif'),
622 ('unknown decl', 'if (!IE)|(lt IE 9)'),
623 ('startendtag', 'img', [('src', 'mammoth.bmp')]),
624 ('unknown decl', 'endif')
625 ]
626 self._run_check(html, expected)
627
Ezio Melottic1e73c32011-11-01 18:57:15 +0200628
Ezio Melottib245ed12011-11-14 18:13:22 +0200629class AttributesStrictTestCase(TestCaseBase):
630
631 def get_collector(self):
Ezio Melotti3861d8b2012-06-23 15:27:51 +0200632 with support.check_warnings(("", DeprecationWarning), quite=False):
633 return EventCollector(strict=True)
Ezio Melottib245ed12011-11-14 18:13:22 +0200634
635 def test_attr_syntax(self):
636 output = [
637 ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", None)])
638 ]
639 self._run_check("""<a b='v' c="v" d=v e>""", output)
640 self._run_check("""<a b = 'v' c = "v" d = v e>""", output)
641 self._run_check("""<a\nb\n=\n'v'\nc\n=\n"v"\nd\n=\nv\ne>""", output)
642 self._run_check("""<a\tb\t=\t'v'\tc\t=\t"v"\td\t=\tv\te>""", output)
643
644 def test_attr_values(self):
645 self._run_check("""<a b='xxx\n\txxx' c="yyy\t\nyyy" d='\txyz\n'>""",
646 [("starttag", "a", [("b", "xxx\n\txxx"),
647 ("c", "yyy\t\nyyy"),
648 ("d", "\txyz\n")])])
649 self._run_check("""<a b='' c="">""",
650 [("starttag", "a", [("b", ""), ("c", "")])])
651 # Regression test for SF patch #669683.
652 self._run_check("<e a=rgb(1,2,3)>",
653 [("starttag", "e", [("a", "rgb(1,2,3)")])])
654 # Regression test for SF bug #921657.
655 self._run_check(
656 "<a href=mailto:xyz@example.com>",
657 [("starttag", "a", [("href", "mailto:xyz@example.com")])])
658
659 def test_attr_nonascii(self):
660 # see issue 7311
661 self._run_check(
662 "<img src=/foo/bar.png alt=\u4e2d\u6587>",
663 [("starttag", "img", [("src", "/foo/bar.png"),
664 ("alt", "\u4e2d\u6587")])])
665 self._run_check(
666 "<a title='\u30c6\u30b9\u30c8' href='\u30c6\u30b9\u30c8.html'>",
667 [("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
668 ("href", "\u30c6\u30b9\u30c8.html")])])
669 self._run_check(
670 '<a title="\u30c6\u30b9\u30c8" href="\u30c6\u30b9\u30c8.html">',
671 [("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
672 ("href", "\u30c6\u30b9\u30c8.html")])])
673
674 def test_attr_entity_replacement(self):
675 self._run_check(
676 "<a b='&amp;&gt;&lt;&quot;&apos;'>",
677 [("starttag", "a", [("b", "&><\"'")])])
678
679 def test_attr_funky_names(self):
680 self._run_check(
681 "<a a.b='v' c:d=v e-f=v>",
682 [("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")])])
683
684 def test_entityrefs_in_attributes(self):
685 self._run_check(
686 "<html foo='&euro;&amp;&#97;&#x61;&unsupported;'>",
687 [("starttag", "html", [("foo", "\u20AC&aa&unsupported;")])])
688
689
Ezio Melottic2fe5772011-11-14 18:53:33 +0200690
691class AttributesTolerantTestCase(AttributesStrictTestCase):
692
693 def get_collector(self):
694 return EventCollector(strict=False)
695
696 def test_attr_funky_names2(self):
697 self._run_check(
698 "<a $><b $=%><c \=/>",
699 [("starttag", "a", [("$", None)]),
700 ("starttag", "b", [("$", "%")]),
701 ("starttag", "c", [("\\", "/")])])
702
703 def test_entities_in_attribute_value(self):
704 # see #1200313
705 for entity in ['&', '&amp;', '&#38;', '&#x26;']:
706 self._run_check('<a href="%s">' % entity,
707 [("starttag", "a", [("href", "&")])])
708 self._run_check("<a href='%s'>" % entity,
709 [("starttag", "a", [("href", "&")])])
710 self._run_check("<a href=%s>" % entity,
711 [("starttag", "a", [("href", "&")])])
712
713 def test_malformed_attributes(self):
714 # see #13357
715 html = (
716 "<a href=test'style='color:red;bad1'>test - bad1</a>"
717 "<a href=test'+style='color:red;ba2'>test - bad2</a>"
718 "<a href=test'&nbsp;style='color:red;bad3'>test - bad3</a>"
719 "<a href = test'&nbsp;style='color:red;bad4' >test - bad4</a>"
720 )
721 expected = [
722 ('starttag', 'a', [('href', "test'style='color:red;bad1'")]),
723 ('data', 'test - bad1'), ('endtag', 'a'),
724 ('starttag', 'a', [('href', "test'+style='color:red;ba2'")]),
725 ('data', 'test - bad2'), ('endtag', 'a'),
726 ('starttag', 'a', [('href', "test'\xa0style='color:red;bad3'")]),
727 ('data', 'test - bad3'), ('endtag', 'a'),
728 ('starttag', 'a', [('href', "test'\xa0style='color:red;bad4'")]),
729 ('data', 'test - bad4'), ('endtag', 'a')
730 ]
731 self._run_check(html, expected)
732
733 def test_malformed_adjacent_attributes(self):
734 # see #12629
735 self._run_check('<x><y z=""o"" /></x>',
736 [('starttag', 'x', []),
737 ('startendtag', 'y', [('z', ''), ('o""', None)]),
738 ('endtag', 'x')])
739 self._run_check('<x><y z="""" /></x>',
740 [('starttag', 'x', []),
741 ('startendtag', 'y', [('z', ''), ('""', None)]),
742 ('endtag', 'x')])
743
744 # see #755670 for the following 3 tests
745 def test_adjacent_attributes(self):
746 self._run_check('<a width="100%"cellspacing=0>',
747 [("starttag", "a",
748 [("width", "100%"), ("cellspacing","0")])])
749
750 self._run_check('<a id="foo"class="bar">',
751 [("starttag", "a",
752 [("id", "foo"), ("class","bar")])])
753
754 def test_missing_attribute_value(self):
755 self._run_check('<a v=>',
756 [("starttag", "a", [("v", "")])])
757
758 def test_javascript_attribute_value(self):
759 self._run_check("<a href=javascript:popup('/popup/help.html')>",
760 [("starttag", "a",
761 [("href", "javascript:popup('/popup/help.html')")])])
762
763 def test_end_tag_in_attribute_value(self):
764 # see #1745761
765 self._run_check("<a href='http://www.example.org/\">;'>spam</a>",
766 [("starttag", "a",
767 [("href", "http://www.example.org/\">;")]),
768 ("data", "spam"), ("endtag", "a")])
769
770
Fred Drakee8220492001-09-24 20:19:08 +0000771if __name__ == "__main__":
Ezio Melotti5028f4d2013-11-02 17:49:08 +0200772 unittest.main()