blob: de8f3e80d4b7bfba2b3c922ca3c6678d10408351 [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
Ezio Melotti95401c52013-11-23 19:52:05 +020073class EventCollectorCharrefs(EventCollector):
74
75 def get_events(self):
76 return self.events
77
78 def handle_charref(self, data):
79 self.fail('This should never be called with convert_charrefs=True')
80
81 def handle_entityref(self, data):
82 self.fail('This should never be called with convert_charrefs=True')
83
84
Fred Drakebd3090d2001-05-18 15:32:59 +000085class TestCaseBase(unittest.TestCase):
86
Ezio Melottic1e73c32011-11-01 18:57:15 +020087 def get_collector(self):
Ezio Melotti73a43592014-08-02 14:10:30 +030088 return EventCollector(convert_charrefs=False)
Ezio Melottic1e73c32011-11-01 18:57:15 +020089
R. David Murrayb579dba2010-12-03 04:06:39 +000090 def _run_check(self, source, expected_events, collector=None):
91 if collector is None:
Ezio Melottic1e73c32011-11-01 18:57:15 +020092 collector = self.get_collector()
R. David Murrayb579dba2010-12-03 04:06:39 +000093 parser = collector
Fred Drakebd3090d2001-05-18 15:32:59 +000094 for s in source:
95 parser.feed(s)
Fred Drakebd3090d2001-05-18 15:32:59 +000096 parser.close()
Fred Drake029acfb2001-08-20 21:24:19 +000097 events = parser.get_events()
Fred Drakec20a6982001-09-04 15:13:04 +000098 if events != expected_events:
Ezio Melotti95401c52013-11-23 19:52:05 +020099 self.fail("received events did not match expected events" +
100 "\nSource:\n" + repr(source) +
101 "\nExpected:\n" + pprint.pformat(expected_events) +
Fred Drakec20a6982001-09-04 15:13:04 +0000102 "\nReceived:\n" + pprint.pformat(events))
Fred Drakebd3090d2001-05-18 15:32:59 +0000103
104 def _run_check_extra(self, source, events):
Ezio Melotti95401c52013-11-23 19:52:05 +0200105 self._run_check(source, events,
106 EventCollectorExtra(convert_charrefs=False))
Fred Drakebd3090d2001-05-18 15:32:59 +0000107
Fred Drakebd3090d2001-05-18 15:32:59 +0000108
Ezio Melotti73a43592014-08-02 14:10:30 +0300109class HTMLParserTestCase(TestCaseBase):
Fred Drakebd3090d2001-05-18 15:32:59 +0000110
Fred Drake84bb9d82001-08-03 19:53:01 +0000111 def test_processing_instruction_only(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000112 self._run_check("<?processing instruction>", [
113 ("pi", "processing instruction"),
114 ])
Fred Drakefafd56f2003-04-17 22:19:26 +0000115 self._run_check("<?processing instruction ?>", [
116 ("pi", "processing instruction ?"),
117 ])
Fred Drakebd3090d2001-05-18 15:32:59 +0000118
Fred Drake84bb9d82001-08-03 19:53:01 +0000119 def test_simple_html(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000120 self._run_check("""
121<!DOCTYPE html PUBLIC 'foo'>
122<HTML>&entity;&#32;
123<!--comment1a
124-></foo><bar>&lt;<?pi?></foo<bar
125comment1b-->
126<Img sRc='Bar' isMAP>sample
127text
Fred Drake84bb9d82001-08-03 19:53:01 +0000128&#x201C;
Ezio Melottif4ab4912012-02-13 15:50:37 +0200129<!--comment2a-- --comment2b-->
Fred Drakebd3090d2001-05-18 15:32:59 +0000130</Html>
131""", [
132 ("data", "\n"),
133 ("decl", "DOCTYPE html PUBLIC 'foo'"),
134 ("data", "\n"),
135 ("starttag", "html", []),
136 ("entityref", "entity"),
137 ("charref", "32"),
138 ("data", "\n"),
139 ("comment", "comment1a\n-></foo><bar>&lt;<?pi?></foo<bar\ncomment1b"),
140 ("data", "\n"),
141 ("starttag", "img", [("src", "Bar"), ("ismap", None)]),
142 ("data", "sample\ntext\n"),
Fred Drake84bb9d82001-08-03 19:53:01 +0000143 ("charref", "x201C"),
144 ("data", "\n"),
Fred Drakebd3090d2001-05-18 15:32:59 +0000145 ("comment", "comment2a-- --comment2b"),
146 ("data", "\n"),
147 ("endtag", "html"),
148 ("data", "\n"),
149 ])
150
Victor Stinnere021f4b2010-05-24 21:46:25 +0000151 def test_malformatted_charref(self):
152 self._run_check("<p>&#bad;</p>", [
153 ("starttag", "p", []),
154 ("data", "&#bad;"),
155 ("endtag", "p"),
156 ])
Ezio Melottif27b9a72014-02-01 21:21:01 +0200157 # add the [] as a workaround to avoid buffering (see #20288)
158 self._run_check(["<div>&#bad;</div>"], [
159 ("starttag", "div", []),
160 ("data", "&#bad;"),
161 ("endtag", "div"),
162 ])
Victor Stinnere021f4b2010-05-24 21:46:25 +0000163
Fred Drake073148c2001-12-03 16:44:09 +0000164 def test_unclosed_entityref(self):
165 self._run_check("&entityref foo", [
166 ("entityref", "entityref"),
167 ("data", " foo"),
168 ])
169
Fred Drake84bb9d82001-08-03 19:53:01 +0000170 def test_bad_nesting(self):
171 # Strangely, this *is* supposed to test that overlapping
172 # elements are allowed. HTMLParser is more geared toward
173 # lexing the input that parsing the structure.
Fred Drakebd3090d2001-05-18 15:32:59 +0000174 self._run_check("<a><b></a></b>", [
175 ("starttag", "a", []),
176 ("starttag", "b", []),
177 ("endtag", "a"),
178 ("endtag", "b"),
179 ])
180
Fred Drake029acfb2001-08-20 21:24:19 +0000181 def test_bare_ampersands(self):
182 self._run_check("this text & contains & ampersands &", [
183 ("data", "this text & contains & ampersands &"),
184 ])
185
186 def test_bare_pointy_brackets(self):
187 self._run_check("this < text > contains < bare>pointy< brackets", [
188 ("data", "this < text > contains < bare>pointy< brackets"),
189 ])
190
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
Ezio Melottif4ab4912012-02-13 15:50:37 +0200225 def test_valid_doctypes(self):
226 # from http://www.w3.org/QA/2002/04/valid-dtd-list.html
227 dtds = ['HTML', # HTML5 doctype
228 ('HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
229 '"http://www.w3.org/TR/html4/strict.dtd"'),
230 ('HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" '
231 '"http://www.w3.org/TR/html4/loose.dtd"'),
232 ('html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" '
233 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"'),
234 ('html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" '
235 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"'),
236 ('math PUBLIC "-//W3C//DTD MathML 2.0//EN" '
237 '"http://www.w3.org/Math/DTD/mathml2/mathml2.dtd"'),
238 ('html PUBLIC "-//W3C//DTD '
239 'XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" '
240 '"http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd"'),
241 ('svg PUBLIC "-//W3C//DTD SVG 1.1//EN" '
242 '"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"'),
243 'html PUBLIC "-//IETF//DTD HTML 2.0//EN"',
244 'html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"']
245 for dtd in dtds:
246 self._run_check("<!DOCTYPE %s>" % dtd,
247 [('decl', 'DOCTYPE ' + dtd)])
248
Fred Drake84bb9d82001-08-03 19:53:01 +0000249 def test_startendtag(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000250 self._run_check("<p/>", [
251 ("startendtag", "p", []),
252 ])
253 self._run_check("<p></p>", [
254 ("starttag", "p", []),
255 ("endtag", "p"),
256 ])
257 self._run_check("<p><img src='foo' /></p>", [
258 ("starttag", "p", []),
259 ("startendtag", "img", [("src", "foo")]),
260 ("endtag", "p"),
261 ])
262
Fred Drake84bb9d82001-08-03 19:53:01 +0000263 def test_get_starttag_text(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000264 s = """<foo:bar \n one="1"\ttwo=2 >"""
265 self._run_check_extra(s, [
266 ("starttag", "foo:bar", [("one", "1"), ("two", "2")]),
267 ("starttag_text", s)])
268
Fred Drake84bb9d82001-08-03 19:53:01 +0000269 def test_cdata_content(self):
Ezio Melotti7de56f62011-11-01 14:12:22 +0200270 contents = [
271 '<!-- not a comment --> &not-an-entity-ref;',
272 "<not a='start tag'>",
273 '<a href="" /> <p> <span></span>',
274 'foo = "</scr" + "ipt>";',
275 'foo = "</SCRIPT" + ">";',
276 'foo = <\n/script> ',
277 '<!-- document.write("</scr" + "ipt>"); -->',
278 ('\n//<![CDATA[\n'
279 'document.write(\'<s\'+\'cript type="text/javascript" '
280 'src="http://www.example.org/r=\'+new '
281 'Date().getTime()+\'"><\\/s\'+\'cript>\');\n//]]>'),
282 '\n<!-- //\nvar foo = 3.14;\n// -->\n',
283 'foo = "</sty" + "le>";',
284 '<!-- \u2603 -->',
285 # these two should be invalid according to the HTML 5 spec,
286 # section 8.1.2.2
287 #'foo = </\nscript>',
288 #'foo = </ script>',
289 ]
290 elements = ['script', 'style', 'SCRIPT', 'STYLE', 'Script', 'Style']
291 for content in contents:
292 for element in elements:
293 element_lower = element.lower()
294 s = '<{element}>{content}</{element}>'.format(element=element,
295 content=content)
296 self._run_check(s, [("starttag", element_lower, []),
297 ("data", content),
298 ("endtag", element_lower)])
299
Ezio Melotti15cb4892011-11-18 18:01:49 +0200300 def test_cdata_with_closing_tags(self):
301 # see issue #13358
302 # make sure that HTMLParser calls handle_data only once for each CDATA.
303 # The normal event collector normalizes the events in get_events,
304 # so we override it to return the original list of events.
305 class Collector(EventCollector):
306 def get_events(self):
307 return self.events
Fred Drakebd3090d2001-05-18 15:32:59 +0000308
Ezio Melotti15cb4892011-11-18 18:01:49 +0200309 content = """<!-- not a comment --> &not-an-entity-ref;
310 <a href="" /> </p><p> <span></span></style>
311 '</script' + '>'"""
312 for element in [' script', 'script ', ' script ',
313 '\nscript', 'script\n', '\nscript\n']:
314 element_lower = element.lower().strip()
315 s = '<script>{content}</{element}>'.format(element=element,
316 content=content)
317 self._run_check(s, [("starttag", element_lower, []),
318 ("data", content),
319 ("endtag", element_lower)],
Ezio Melotti95401c52013-11-23 19:52:05 +0200320 collector=Collector(convert_charrefs=False))
Fred Drakebd3090d2001-05-18 15:32:59 +0000321
Ezio Melottifa3702d2012-02-10 10:45:44 +0200322 def test_comments(self):
323 html = ("<!-- I'm a valid comment -->"
324 '<!--me too!-->'
325 '<!------>'
326 '<!---->'
327 '<!----I have many hyphens---->'
328 '<!-- I have a > in the middle -->'
329 '<!-- and I have -- in the middle! -->')
330 expected = [('comment', " I'm a valid comment "),
331 ('comment', 'me too!'),
332 ('comment', '--'),
333 ('comment', ''),
334 ('comment', '--I have many hyphens--'),
335 ('comment', ' I have a > in the middle '),
336 ('comment', ' and I have -- in the middle! ')]
337 self._run_check(html, expected)
338
Ezio Melotti62f3d032011-12-19 07:29:03 +0200339 def test_condcoms(self):
340 html = ('<!--[if IE & !(lte IE 8)]>aren\'t<![endif]-->'
341 '<!--[if IE 8]>condcoms<![endif]-->'
342 '<!--[if lte IE 7]>pretty?<![endif]-->')
343 expected = [('comment', "[if IE & !(lte IE 8)]>aren't<![endif]"),
344 ('comment', '[if IE 8]>condcoms<![endif]'),
345 ('comment', '[if lte IE 7]>pretty?<![endif]')]
346 self._run_check(html, expected)
347
Ezio Melotti95401c52013-11-23 19:52:05 +0200348 def test_convert_charrefs(self):
Ezio Melotti6fc16d82014-08-02 18:36:12 +0300349 # default value for convert_charrefs is now True
350 collector = lambda: EventCollectorCharrefs()
Ezio Melotti95401c52013-11-23 19:52:05 +0200351 self.assertTrue(collector().convert_charrefs)
352 charrefs = ['&quot;', '&#34;', '&#x22;', '&quot', '&#34', '&#x22']
353 # check charrefs in the middle of the text/attributes
354 expected = [('starttag', 'a', [('href', 'foo"zar')]),
355 ('data', 'a"z'), ('endtag', 'a')]
356 for charref in charrefs:
357 self._run_check('<a href="foo{0}zar">a{0}z</a>'.format(charref),
358 expected, collector=collector())
359 # check charrefs at the beginning/end of the text/attributes
360 expected = [('data', '"'),
361 ('starttag', 'a', [('x', '"'), ('y', '"X'), ('z', 'X"')]),
362 ('data', '"'), ('endtag', 'a'), ('data', '"')]
363 for charref in charrefs:
364 self._run_check('{0}<a x="{0}" y="{0}X" z="X{0}">'
365 '{0}</a>{0}'.format(charref),
366 expected, collector=collector())
367 # check charrefs in <script>/<style> elements
368 for charref in charrefs:
369 text = 'X'.join([charref]*3)
370 expected = [('data', '"'),
371 ('starttag', 'script', []), ('data', text),
372 ('endtag', 'script'), ('data', '"'),
373 ('starttag', 'style', []), ('data', text),
374 ('endtag', 'style'), ('data', '"')]
375 self._run_check('{1}<script>{0}</script>{1}'
376 '<style>{0}</style>{1}'.format(text, charref),
377 expected, collector=collector())
378 # check truncated charrefs at the end of the file
379 html = '&quo &# &#x'
380 for x in range(1, len(html)):
381 self._run_check(html[:x], [('data', html[:x])],
382 collector=collector())
383 # check a string with no charrefs
384 self._run_check('no charrefs here', [('data', 'no charrefs here')],
385 collector=collector())
386
Ezio Melotti73a43592014-08-02 14:10:30 +0300387 # the remaining tests were for the "tolerant" parser (which is now
388 # the default), and check various kind of broken markup
R. David Murrayb579dba2010-12-03 04:06:39 +0000389 def test_tolerant_parsing(self):
390 self._run_check('<html <html>te>>xt&a<<bc</a></html>\n'
391 '<img src="URL><//img></html</html>', [
Ezio Melottic2fe5772011-11-14 18:53:33 +0200392 ('starttag', 'html', [('<html', None)]),
393 ('data', 'te>>xt'),
394 ('entityref', 'a'),
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200395 ('data', '<'),
396 ('starttag', 'bc<', [('a', None)]),
Ezio Melottic2fe5772011-11-14 18:53:33 +0200397 ('endtag', 'html'),
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200398 ('data', '\n<img src="URL>'),
399 ('comment', '/img'),
400 ('endtag', 'html<')])
R. David Murrayb579dba2010-12-03 04:06:39 +0000401
Ezio Melotti86f67122012-02-13 14:11:27 +0200402 def test_starttag_junk_chars(self):
403 self._run_check("</>", [])
404 self._run_check("</$>", [('comment', '$')])
405 self._run_check("</", [('data', '</')])
406 self._run_check("</a", [('data', '</a')])
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200407 self._run_check("<a<a>", [('starttag', 'a<a', [])])
Ezio Melotti86f67122012-02-13 14:11:27 +0200408 self._run_check("</a<a>", [('endtag', 'a<a')])
409 self._run_check("<!", [('data', '<!')])
410 self._run_check("<a", [('data', '<a')])
411 self._run_check("<a foo='bar'", [('data', "<a foo='bar'")])
412 self._run_check("<a foo='bar", [('data', "<a foo='bar")])
413 self._run_check("<a foo='>'", [('data', "<a foo='>'")])
414 self._run_check("<a foo='>", [('data', "<a foo='>")])
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200415 self._run_check("<a$>", [('starttag', 'a$', [])])
416 self._run_check("<a$b>", [('starttag', 'a$b', [])])
417 self._run_check("<a$b/>", [('startendtag', 'a$b', [])])
418 self._run_check("<a$b >", [('starttag', 'a$b', [])])
419 self._run_check("<a$b />", [('startendtag', 'a$b', [])])
Ezio Melotti86f67122012-02-13 14:11:27 +0200420
Ezio Melotti29877e82012-02-21 09:25:00 +0200421 def test_slashes_in_starttag(self):
422 self._run_check('<a foo="var"/>', [('startendtag', 'a', [('foo', 'var')])])
423 html = ('<img width=902 height=250px '
424 'src="/sites/default/files/images/homepage/foo.jpg" '
425 '/*what am I doing here*/ />')
426 expected = [(
427 'startendtag', 'img',
428 [('width', '902'), ('height', '250px'),
429 ('src', '/sites/default/files/images/homepage/foo.jpg'),
430 ('*what', None), ('am', None), ('i', None),
431 ('doing', None), ('here*', None)]
432 )]
433 self._run_check(html, expected)
434 html = ('<a / /foo/ / /=/ / /bar/ / />'
435 '<a / /foo/ / /=/ / /bar/ / >')
436 expected = [
437 ('startendtag', 'a', [('foo', None), ('=', None), ('bar', None)]),
438 ('starttag', 'a', [('foo', None), ('=', None), ('bar', None)])
439 ]
440 self._run_check(html, expected)
Ezio Melotti0780b6b2012-04-18 19:18:22 -0600441 #see issue #14538
442 html = ('<meta><meta / ><meta // ><meta / / >'
443 '<meta/><meta /><meta //><meta//>')
444 expected = [
445 ('starttag', 'meta', []), ('starttag', 'meta', []),
446 ('starttag', 'meta', []), ('starttag', 'meta', []),
447 ('startendtag', 'meta', []), ('startendtag', 'meta', []),
448 ('startendtag', 'meta', []), ('startendtag', 'meta', []),
449 ]
450 self._run_check(html, expected)
Ezio Melotti29877e82012-02-21 09:25:00 +0200451
Ezio Melotti86f67122012-02-13 14:11:27 +0200452 def test_declaration_junk_chars(self):
Ezio Melottif4ab4912012-02-13 15:50:37 +0200453 self._run_check("<!DOCTYPE foo $ >", [('decl', 'DOCTYPE foo $ ')])
Ezio Melotti86f67122012-02-13 14:11:27 +0200454
455 def test_illegal_declarations(self):
Ezio Melotti86f67122012-02-13 14:11:27 +0200456 self._run_check('<!spacer type="block" height="25">',
457 [('comment', 'spacer type="block" height="25"')])
458
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200459 def test_with_unquoted_attributes(self):
Ezio Melottib9a48f72011-11-01 15:00:59 +0200460 # see #12008
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200461 html = ("<html><body bgcolor=d0ca90 text='181008'>"
462 "<table cellspacing=0 cellpadding=1 width=100% ><tr>"
463 "<td align=left><font size=-1>"
464 "- <a href=/rabota/><span class=en> software-and-i</span></a>"
465 "- <a href='/1/'><span class=en> library</span></a></table>")
466 expected = [
467 ('starttag', 'html', []),
468 ('starttag', 'body', [('bgcolor', 'd0ca90'), ('text', '181008')]),
469 ('starttag', 'table',
470 [('cellspacing', '0'), ('cellpadding', '1'), ('width', '100%')]),
471 ('starttag', 'tr', []),
472 ('starttag', 'td', [('align', 'left')]),
473 ('starttag', 'font', [('size', '-1')]),
474 ('data', '- '), ('starttag', 'a', [('href', '/rabota/')]),
475 ('starttag', 'span', [('class', 'en')]), ('data', ' software-and-i'),
476 ('endtag', 'span'), ('endtag', 'a'),
477 ('data', '- '), ('starttag', 'a', [('href', '/1/')]),
478 ('starttag', 'span', [('class', 'en')]), ('data', ' library'),
479 ('endtag', 'span'), ('endtag', 'a'), ('endtag', 'table')
480 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200481 self._run_check(html, expected)
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200482
R. David Murrayb579dba2010-12-03 04:06:39 +0000483 def test_comma_between_attributes(self):
484 self._run_check('<form action="/xxx.php?a=1&amp;b=2&amp", '
485 'method="post">', [
486 ('starttag', 'form',
Ezio Melotti46495182012-06-24 22:02:56 +0200487 [('action', '/xxx.php?a=1&b=2&'),
Ezio Melottic2fe5772011-11-14 18:53:33 +0200488 (',', None), ('method', 'post')])])
R. David Murrayb579dba2010-12-03 04:06:39 +0000489
490 def test_weird_chars_in_unquoted_attribute_values(self):
491 self._run_check('<form action=bogus|&#()value>', [
492 ('starttag', 'form',
Ezio Melottic1e73c32011-11-01 18:57:15 +0200493 [('action', 'bogus|&#()value')])])
R. David Murrayb579dba2010-12-03 04:06:39 +0000494
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200495 def test_invalid_end_tags(self):
496 # A collection of broken end tags. <br> is used as separator.
497 # see http://www.w3.org/TR/html5/tokenization.html#end-tag-open-state
498 # and #13993
499 html = ('<br></label</p><br></div end tmAd-leaderBoard><br></<h4><br>'
500 '</li class="unit"><br></li\r\n\t\t\t\t\t\t</ul><br></><br>')
501 expected = [('starttag', 'br', []),
502 # < is part of the name, / is discarded, p is an attribute
503 ('endtag', 'label<'),
504 ('starttag', 'br', []),
505 # text and attributes are discarded
506 ('endtag', 'div'),
507 ('starttag', 'br', []),
508 # comment because the first char after </ is not a-zA-Z
509 ('comment', '<h4'),
510 ('starttag', 'br', []),
511 # attributes are discarded
512 ('endtag', 'li'),
513 ('starttag', 'br', []),
514 # everything till ul (included) is discarded
515 ('endtag', 'li'),
516 ('starttag', 'br', []),
517 # </> is ignored
518 ('starttag', 'br', [])]
519 self._run_check(html, expected)
520
521 def test_broken_invalid_end_tag(self):
522 # This is technically wrong (the "> shouldn't be included in the 'data')
523 # but is probably not worth fixing it (in addition to all the cases of
524 # the previous test, it would require a full attribute parsing).
525 # see #13993
526 html = '<b>This</b attr=">"> confuses the parser'
527 expected = [('starttag', 'b', []),
528 ('data', 'This'),
529 ('endtag', 'b'),
530 ('data', '"> confuses the parser')]
531 self._run_check(html, expected)
532
Ezio Melottib9a48f72011-11-01 15:00:59 +0200533 def test_correct_detection_of_start_tags(self):
534 # see #13273
Ezio Melottif50ffa92011-10-28 13:21:09 +0300535 html = ('<div style="" ><b>The <a href="some_url">rain</a> '
536 '<br /> in <span>Spain</span></b></div>')
537 expected = [
538 ('starttag', 'div', [('style', '')]),
539 ('starttag', 'b', []),
540 ('data', 'The '),
541 ('starttag', 'a', [('href', 'some_url')]),
542 ('data', 'rain'),
543 ('endtag', 'a'),
544 ('data', ' '),
545 ('startendtag', 'br', []),
546 ('data', ' in '),
547 ('starttag', 'span', []),
548 ('data', 'Spain'),
549 ('endtag', 'span'),
550 ('endtag', 'b'),
551 ('endtag', 'div')
552 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200553 self._run_check(html, expected)
Ezio Melottif50ffa92011-10-28 13:21:09 +0300554
Ezio Melottif50ffa92011-10-28 13:21:09 +0300555 html = '<div style="", foo = "bar" ><b>The <a href="some_url">rain</a>'
556 expected = [
Ezio Melottic2fe5772011-11-14 18:53:33 +0200557 ('starttag', 'div', [('style', ''), (',', None), ('foo', 'bar')]),
Ezio Melottif50ffa92011-10-28 13:21:09 +0300558 ('starttag', 'b', []),
559 ('data', 'The '),
560 ('starttag', 'a', [('href', 'some_url')]),
561 ('data', 'rain'),
562 ('endtag', 'a'),
563 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200564 self._run_check(html, expected)
Ezio Melottif50ffa92011-10-28 13:21:09 +0300565
Ezio Melotti8e596a72013-05-01 16:18:25 +0300566 def test_EOF_in_charref(self):
567 # see #17802
568 # This test checks that the UnboundLocalError reported in the issue
569 # is not raised, however I'm not sure the returned values are correct.
570 # Maybe HTMLParser should use self.unescape for these
571 data = [
572 ('a&', [('data', 'a&')]),
573 ('a&b', [('data', 'ab')]),
574 ('a&b ', [('data', 'a'), ('entityref', 'b'), ('data', ' ')]),
575 ('a&b;', [('data', 'a'), ('entityref', 'b')]),
576 ]
577 for html, expected in data:
578 self._run_check(html, expected)
579
Ezio Melottif6de9eb2013-11-22 05:49:29 +0200580 def test_unescape_method(self):
581 from html import unescape
582 p = self.get_collector()
583 with self.assertWarns(DeprecationWarning):
584 s = '&quot;&#34;&#x22;&quot&#34&#x22&#bad;'
585 self.assertEqual(p.unescape(s), unescape(s))
586
Ezio Melottifa3702d2012-02-10 10:45:44 +0200587 def test_broken_comments(self):
588 html = ('<! not really a comment >'
589 '<! not a comment either -->'
590 '<! -- close enough -->'
Ezio Melottif4ab4912012-02-13 15:50:37 +0200591 '<!><!<-- this was an empty comment>'
Ezio Melottifa3702d2012-02-10 10:45:44 +0200592 '<!!! another bogus comment !!!>')
593 expected = [
594 ('comment', ' not really a comment '),
595 ('comment', ' not a comment either --'),
596 ('comment', ' -- close enough --'),
Ezio Melottif4ab4912012-02-13 15:50:37 +0200597 ('comment', ''),
598 ('comment', '<-- this was an empty comment'),
Ezio Melottifa3702d2012-02-10 10:45:44 +0200599 ('comment', '!! another bogus comment !!!'),
600 ]
601 self._run_check(html, expected)
602
Ezio Melotti62f3d032011-12-19 07:29:03 +0200603 def test_broken_condcoms(self):
604 # these condcoms are missing the '--' after '<!' and before the '>'
605 html = ('<![if !(IE)]>broken condcom<![endif]>'
606 '<![if ! IE]><link href="favicon.tiff"/><![endif]>'
607 '<![if !IE 6]><img src="firefox.png" /><![endif]>'
608 '<![if !ie 6]><b>foo</b><![endif]>'
609 '<![if (!IE)|(lt IE 9)]><img src="mammoth.bmp" /><![endif]>')
610 # According to the HTML5 specs sections "8.2.4.44 Bogus comment state"
611 # and "8.2.4.45 Markup declaration open state", comment tokens should
612 # be emitted instead of 'unknown decl', but calling unknown_decl
613 # provides more flexibility.
614 # See also Lib/_markupbase.py:parse_declaration
615 expected = [
616 ('unknown decl', 'if !(IE)'),
617 ('data', 'broken condcom'),
618 ('unknown decl', 'endif'),
619 ('unknown decl', 'if ! IE'),
620 ('startendtag', 'link', [('href', 'favicon.tiff')]),
621 ('unknown decl', 'endif'),
622 ('unknown decl', 'if !IE 6'),
623 ('startendtag', 'img', [('src', 'firefox.png')]),
624 ('unknown decl', 'endif'),
625 ('unknown decl', 'if !ie 6'),
626 ('starttag', 'b', []),
627 ('data', 'foo'),
628 ('endtag', 'b'),
629 ('unknown decl', 'endif'),
630 ('unknown decl', 'if (!IE)|(lt IE 9)'),
631 ('startendtag', 'img', [('src', 'mammoth.bmp')]),
632 ('unknown decl', 'endif')
633 ]
634 self._run_check(html, expected)
635
Ezio Melottic1e73c32011-11-01 18:57:15 +0200636
Ezio Melotti73a43592014-08-02 14:10:30 +0300637class AttributesTestCase(TestCaseBase):
Ezio Melottib245ed12011-11-14 18:13:22 +0200638
639 def test_attr_syntax(self):
640 output = [
641 ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", None)])
642 ]
643 self._run_check("""<a b='v' c="v" d=v e>""", output)
644 self._run_check("""<a b = 'v' c = "v" d = v e>""", output)
645 self._run_check("""<a\nb\n=\n'v'\nc\n=\n"v"\nd\n=\nv\ne>""", output)
646 self._run_check("""<a\tb\t=\t'v'\tc\t=\t"v"\td\t=\tv\te>""", output)
647
648 def test_attr_values(self):
649 self._run_check("""<a b='xxx\n\txxx' c="yyy\t\nyyy" d='\txyz\n'>""",
650 [("starttag", "a", [("b", "xxx\n\txxx"),
651 ("c", "yyy\t\nyyy"),
652 ("d", "\txyz\n")])])
653 self._run_check("""<a b='' c="">""",
654 [("starttag", "a", [("b", ""), ("c", "")])])
655 # Regression test for SF patch #669683.
656 self._run_check("<e a=rgb(1,2,3)>",
657 [("starttag", "e", [("a", "rgb(1,2,3)")])])
658 # Regression test for SF bug #921657.
659 self._run_check(
660 "<a href=mailto:xyz@example.com>",
661 [("starttag", "a", [("href", "mailto:xyz@example.com")])])
662
663 def test_attr_nonascii(self):
664 # see issue 7311
665 self._run_check(
666 "<img src=/foo/bar.png alt=\u4e2d\u6587>",
667 [("starttag", "img", [("src", "/foo/bar.png"),
668 ("alt", "\u4e2d\u6587")])])
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 self._run_check(
674 '<a title="\u30c6\u30b9\u30c8" href="\u30c6\u30b9\u30c8.html">',
675 [("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
676 ("href", "\u30c6\u30b9\u30c8.html")])])
677
678 def test_attr_entity_replacement(self):
679 self._run_check(
680 "<a b='&amp;&gt;&lt;&quot;&apos;'>",
681 [("starttag", "a", [("b", "&><\"'")])])
682
683 def test_attr_funky_names(self):
684 self._run_check(
685 "<a a.b='v' c:d=v e-f=v>",
686 [("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")])])
687
688 def test_entityrefs_in_attributes(self):
689 self._run_check(
690 "<html foo='&euro;&amp;&#97;&#x61;&unsupported;'>",
691 [("starttag", "html", [("foo", "\u20AC&aa&unsupported;")])])
692
693
Ezio Melottic2fe5772011-11-14 18:53:33 +0200694 def test_attr_funky_names2(self):
695 self._run_check(
696 "<a $><b $=%><c \=/>",
697 [("starttag", "a", [("$", None)]),
698 ("starttag", "b", [("$", "%")]),
699 ("starttag", "c", [("\\", "/")])])
700
701 def test_entities_in_attribute_value(self):
702 # see #1200313
703 for entity in ['&', '&amp;', '&#38;', '&#x26;']:
704 self._run_check('<a href="%s">' % entity,
705 [("starttag", "a", [("href", "&")])])
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
711 def test_malformed_attributes(self):
712 # see #13357
713 html = (
714 "<a href=test'style='color:red;bad1'>test - bad1</a>"
715 "<a href=test'+style='color:red;ba2'>test - bad2</a>"
716 "<a href=test'&nbsp;style='color:red;bad3'>test - bad3</a>"
717 "<a href = test'&nbsp;style='color:red;bad4' >test - bad4</a>"
718 )
719 expected = [
720 ('starttag', 'a', [('href', "test'style='color:red;bad1'")]),
721 ('data', 'test - bad1'), ('endtag', 'a'),
722 ('starttag', 'a', [('href', "test'+style='color:red;ba2'")]),
723 ('data', 'test - bad2'), ('endtag', 'a'),
724 ('starttag', 'a', [('href', "test'\xa0style='color:red;bad3'")]),
725 ('data', 'test - bad3'), ('endtag', 'a'),
726 ('starttag', 'a', [('href', "test'\xa0style='color:red;bad4'")]),
727 ('data', 'test - bad4'), ('endtag', 'a')
728 ]
729 self._run_check(html, expected)
730
731 def test_malformed_adjacent_attributes(self):
732 # see #12629
733 self._run_check('<x><y z=""o"" /></x>',
734 [('starttag', 'x', []),
735 ('startendtag', 'y', [('z', ''), ('o""', None)]),
736 ('endtag', 'x')])
737 self._run_check('<x><y z="""" /></x>',
738 [('starttag', 'x', []),
739 ('startendtag', 'y', [('z', ''), ('""', None)]),
740 ('endtag', 'x')])
741
742 # see #755670 for the following 3 tests
743 def test_adjacent_attributes(self):
744 self._run_check('<a width="100%"cellspacing=0>',
745 [("starttag", "a",
746 [("width", "100%"), ("cellspacing","0")])])
747
748 self._run_check('<a id="foo"class="bar">',
749 [("starttag", "a",
750 [("id", "foo"), ("class","bar")])])
751
752 def test_missing_attribute_value(self):
753 self._run_check('<a v=>',
754 [("starttag", "a", [("v", "")])])
755
756 def test_javascript_attribute_value(self):
757 self._run_check("<a href=javascript:popup('/popup/help.html')>",
758 [("starttag", "a",
759 [("href", "javascript:popup('/popup/help.html')")])])
760
761 def test_end_tag_in_attribute_value(self):
762 # see #1745761
763 self._run_check("<a href='http://www.example.org/\">;'>spam</a>",
764 [("starttag", "a",
765 [("href", "http://www.example.org/\">;")]),
766 ("data", "spam"), ("endtag", "a")])
767
768
Fred Drakee8220492001-09-24 20:19:08 +0000769if __name__ == "__main__":
Ezio Melotti5028f4d2013-11-02 17:49:08 +0200770 unittest.main()