blob: 11420b2c8460cdd3764f0217290ec4a9aab943d2 [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
Ezio Melotti95401c52013-11-23 19:52:05 +020075 def handle_charref(self, data):
76 self.fail('This should never be called with convert_charrefs=True')
77
78 def handle_entityref(self, data):
79 self.fail('This should never be called with convert_charrefs=True')
80
81
Fred Drakebd3090d2001-05-18 15:32:59 +000082class TestCaseBase(unittest.TestCase):
83
Ezio Melottic1e73c32011-11-01 18:57:15 +020084 def get_collector(self):
Ezio Melotti73a43592014-08-02 14:10:30 +030085 return EventCollector(convert_charrefs=False)
Ezio Melottic1e73c32011-11-01 18:57:15 +020086
R. David Murrayb579dba2010-12-03 04:06:39 +000087 def _run_check(self, source, expected_events, collector=None):
88 if collector is None:
Ezio Melottic1e73c32011-11-01 18:57:15 +020089 collector = self.get_collector()
R. David Murrayb579dba2010-12-03 04:06:39 +000090 parser = collector
Fred Drakebd3090d2001-05-18 15:32:59 +000091 for s in source:
92 parser.feed(s)
Fred Drakebd3090d2001-05-18 15:32:59 +000093 parser.close()
Fred Drake029acfb2001-08-20 21:24:19 +000094 events = parser.get_events()
Fred Drakec20a6982001-09-04 15:13:04 +000095 if events != expected_events:
Ezio Melotti95401c52013-11-23 19:52:05 +020096 self.fail("received events did not match expected events" +
97 "\nSource:\n" + repr(source) +
98 "\nExpected:\n" + pprint.pformat(expected_events) +
Fred Drakec20a6982001-09-04 15:13:04 +000099 "\nReceived:\n" + pprint.pformat(events))
Fred Drakebd3090d2001-05-18 15:32:59 +0000100
101 def _run_check_extra(self, source, events):
Ezio Melotti95401c52013-11-23 19:52:05 +0200102 self._run_check(source, events,
103 EventCollectorExtra(convert_charrefs=False))
Fred Drakebd3090d2001-05-18 15:32:59 +0000104
Fred Drakebd3090d2001-05-18 15:32:59 +0000105
Ezio Melotti73a43592014-08-02 14:10:30 +0300106class HTMLParserTestCase(TestCaseBase):
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 Drake84bb9d82001-08-03 19:53:01 +0000188 def test_starttag_end_boundary(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000189 self._run_check("""<a b='<'>""", [("starttag", "a", [("b", "<")])])
190 self._run_check("""<a b='>'>""", [("starttag", "a", [("b", ">")])])
191
Fred Drake84bb9d82001-08-03 19:53:01 +0000192 def test_buffer_artefacts(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000193 output = [("starttag", "a", [("b", "<")])]
194 self._run_check(["<a b='<'>"], output)
195 self._run_check(["<a ", "b='<'>"], output)
196 self._run_check(["<a b", "='<'>"], output)
197 self._run_check(["<a b=", "'<'>"], output)
198 self._run_check(["<a b='<", "'>"], output)
199 self._run_check(["<a b='<'", ">"], output)
200
201 output = [("starttag", "a", [("b", ">")])]
202 self._run_check(["<a b='>'>"], output)
203 self._run_check(["<a ", "b='>'>"], output)
204 self._run_check(["<a b", "='>'>"], output)
205 self._run_check(["<a b=", "'>'>"], output)
206 self._run_check(["<a b='>", "'>"], output)
207 self._run_check(["<a b='>'", ">"], output)
208
Fred Drake75d9a622004-09-08 22:57:01 +0000209 output = [("comment", "abc")]
210 self._run_check(["", "<!--abc-->"], output)
211 self._run_check(["<", "!--abc-->"], output)
212 self._run_check(["<!", "--abc-->"], output)
213 self._run_check(["<!-", "-abc-->"], output)
214 self._run_check(["<!--", "abc-->"], output)
215 self._run_check(["<!--a", "bc-->"], output)
216 self._run_check(["<!--ab", "c-->"], output)
217 self._run_check(["<!--abc", "-->"], output)
218 self._run_check(["<!--abc-", "->"], output)
219 self._run_check(["<!--abc--", ">"], output)
220 self._run_check(["<!--abc-->", ""], output)
221
Ezio Melottif4ab4912012-02-13 15:50:37 +0200222 def test_valid_doctypes(self):
223 # from http://www.w3.org/QA/2002/04/valid-dtd-list.html
224 dtds = ['HTML', # HTML5 doctype
225 ('HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
226 '"http://www.w3.org/TR/html4/strict.dtd"'),
227 ('HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" '
228 '"http://www.w3.org/TR/html4/loose.dtd"'),
229 ('html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" '
230 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"'),
231 ('html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" '
232 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"'),
233 ('math PUBLIC "-//W3C//DTD MathML 2.0//EN" '
234 '"http://www.w3.org/Math/DTD/mathml2/mathml2.dtd"'),
235 ('html PUBLIC "-//W3C//DTD '
236 'XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" '
237 '"http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd"'),
238 ('svg PUBLIC "-//W3C//DTD SVG 1.1//EN" '
239 '"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"'),
240 'html PUBLIC "-//IETF//DTD HTML 2.0//EN"',
241 'html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"']
242 for dtd in dtds:
243 self._run_check("<!DOCTYPE %s>" % dtd,
244 [('decl', 'DOCTYPE ' + dtd)])
245
Fred Drake84bb9d82001-08-03 19:53:01 +0000246 def test_startendtag(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000247 self._run_check("<p/>", [
248 ("startendtag", "p", []),
249 ])
250 self._run_check("<p></p>", [
251 ("starttag", "p", []),
252 ("endtag", "p"),
253 ])
254 self._run_check("<p><img src='foo' /></p>", [
255 ("starttag", "p", []),
256 ("startendtag", "img", [("src", "foo")]),
257 ("endtag", "p"),
258 ])
259
Fred Drake84bb9d82001-08-03 19:53:01 +0000260 def test_get_starttag_text(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000261 s = """<foo:bar \n one="1"\ttwo=2 >"""
262 self._run_check_extra(s, [
263 ("starttag", "foo:bar", [("one", "1"), ("two", "2")]),
264 ("starttag_text", s)])
265
Fred Drake84bb9d82001-08-03 19:53:01 +0000266 def test_cdata_content(self):
Ezio Melotti7de56f62011-11-01 14:12:22 +0200267 contents = [
268 '<!-- not a comment --> &not-an-entity-ref;',
269 "<not a='start tag'>",
270 '<a href="" /> <p> <span></span>',
271 'foo = "</scr" + "ipt>";',
272 'foo = "</SCRIPT" + ">";',
273 'foo = <\n/script> ',
274 '<!-- document.write("</scr" + "ipt>"); -->',
275 ('\n//<![CDATA[\n'
276 'document.write(\'<s\'+\'cript type="text/javascript" '
277 'src="http://www.example.org/r=\'+new '
278 'Date().getTime()+\'"><\\/s\'+\'cript>\');\n//]]>'),
279 '\n<!-- //\nvar foo = 3.14;\n// -->\n',
280 'foo = "</sty" + "le>";',
281 '<!-- \u2603 -->',
282 # these two should be invalid according to the HTML 5 spec,
283 # section 8.1.2.2
284 #'foo = </\nscript>',
285 #'foo = </ script>',
286 ]
287 elements = ['script', 'style', 'SCRIPT', 'STYLE', 'Script', 'Style']
288 for content in contents:
289 for element in elements:
290 element_lower = element.lower()
291 s = '<{element}>{content}</{element}>'.format(element=element,
292 content=content)
293 self._run_check(s, [("starttag", element_lower, []),
294 ("data", content),
295 ("endtag", element_lower)])
296
Ezio Melotti15cb4892011-11-18 18:01:49 +0200297 def test_cdata_with_closing_tags(self):
298 # see issue #13358
299 # make sure that HTMLParser calls handle_data only once for each CDATA.
300 # The normal event collector normalizes the events in get_events,
301 # so we override it to return the original list of events.
302 class Collector(EventCollector):
303 def get_events(self):
304 return self.events
Fred Drakebd3090d2001-05-18 15:32:59 +0000305
Ezio Melotti15cb4892011-11-18 18:01:49 +0200306 content = """<!-- not a comment --> &not-an-entity-ref;
307 <a href="" /> </p><p> <span></span></style>
308 '</script' + '>'"""
309 for element in [' script', 'script ', ' script ',
310 '\nscript', 'script\n', '\nscript\n']:
311 element_lower = element.lower().strip()
312 s = '<script>{content}</{element}>'.format(element=element,
313 content=content)
314 self._run_check(s, [("starttag", element_lower, []),
315 ("data", content),
316 ("endtag", element_lower)],
Ezio Melotti95401c52013-11-23 19:52:05 +0200317 collector=Collector(convert_charrefs=False))
Fred Drakebd3090d2001-05-18 15:32:59 +0000318
Ezio Melottifa3702d2012-02-10 10:45:44 +0200319 def test_comments(self):
320 html = ("<!-- I'm a valid comment -->"
321 '<!--me too!-->'
322 '<!------>'
323 '<!---->'
324 '<!----I have many hyphens---->'
325 '<!-- I have a > in the middle -->'
326 '<!-- and I have -- in the middle! -->')
327 expected = [('comment', " I'm a valid comment "),
328 ('comment', 'me too!'),
329 ('comment', '--'),
330 ('comment', ''),
331 ('comment', '--I have many hyphens--'),
332 ('comment', ' I have a > in the middle '),
333 ('comment', ' and I have -- in the middle! ')]
334 self._run_check(html, expected)
335
Ezio Melotti62f3d032011-12-19 07:29:03 +0200336 def test_condcoms(self):
337 html = ('<!--[if IE & !(lte IE 8)]>aren\'t<![endif]-->'
338 '<!--[if IE 8]>condcoms<![endif]-->'
339 '<!--[if lte IE 7]>pretty?<![endif]-->')
340 expected = [('comment', "[if IE & !(lte IE 8)]>aren't<![endif]"),
341 ('comment', '[if IE 8]>condcoms<![endif]'),
342 ('comment', '[if lte IE 7]>pretty?<![endif]')]
343 self._run_check(html, expected)
344
Ezio Melotti95401c52013-11-23 19:52:05 +0200345 def test_convert_charrefs(self):
Ezio Melotti6fc16d82014-08-02 18:36:12 +0300346 # default value for convert_charrefs is now True
347 collector = lambda: EventCollectorCharrefs()
Ezio Melotti95401c52013-11-23 19:52:05 +0200348 self.assertTrue(collector().convert_charrefs)
349 charrefs = ['&quot;', '&#34;', '&#x22;', '&quot', '&#34', '&#x22']
350 # check charrefs in the middle of the text/attributes
351 expected = [('starttag', 'a', [('href', 'foo"zar')]),
352 ('data', 'a"z'), ('endtag', 'a')]
353 for charref in charrefs:
354 self._run_check('<a href="foo{0}zar">a{0}z</a>'.format(charref),
355 expected, collector=collector())
356 # check charrefs at the beginning/end of the text/attributes
357 expected = [('data', '"'),
358 ('starttag', 'a', [('x', '"'), ('y', '"X'), ('z', 'X"')]),
359 ('data', '"'), ('endtag', 'a'), ('data', '"')]
360 for charref in charrefs:
361 self._run_check('{0}<a x="{0}" y="{0}X" z="X{0}">'
362 '{0}</a>{0}'.format(charref),
363 expected, collector=collector())
364 # check charrefs in <script>/<style> elements
365 for charref in charrefs:
366 text = 'X'.join([charref]*3)
367 expected = [('data', '"'),
368 ('starttag', 'script', []), ('data', text),
369 ('endtag', 'script'), ('data', '"'),
370 ('starttag', 'style', []), ('data', text),
371 ('endtag', 'style'), ('data', '"')]
372 self._run_check('{1}<script>{0}</script>{1}'
373 '<style>{0}</style>{1}'.format(text, charref),
374 expected, collector=collector())
375 # check truncated charrefs at the end of the file
376 html = '&quo &# &#x'
377 for x in range(1, len(html)):
378 self._run_check(html[:x], [('data', html[:x])],
379 collector=collector())
380 # check a string with no charrefs
381 self._run_check('no charrefs here', [('data', 'no charrefs here')],
382 collector=collector())
383
Ezio Melotti73a43592014-08-02 14:10:30 +0300384 # the remaining tests were for the "tolerant" parser (which is now
385 # the default), and check various kind of broken markup
R. David Murrayb579dba2010-12-03 04:06:39 +0000386 def test_tolerant_parsing(self):
387 self._run_check('<html <html>te>>xt&a<<bc</a></html>\n'
388 '<img src="URL><//img></html</html>', [
Ezio Melottic2fe5772011-11-14 18:53:33 +0200389 ('starttag', 'html', [('<html', None)]),
390 ('data', 'te>>xt'),
391 ('entityref', 'a'),
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200392 ('data', '<'),
393 ('starttag', 'bc<', [('a', None)]),
Ezio Melottic2fe5772011-11-14 18:53:33 +0200394 ('endtag', 'html'),
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200395 ('data', '\n<img src="URL>'),
396 ('comment', '/img'),
397 ('endtag', 'html<')])
R. David Murrayb579dba2010-12-03 04:06:39 +0000398
Ezio Melotti86f67122012-02-13 14:11:27 +0200399 def test_starttag_junk_chars(self):
400 self._run_check("</>", [])
401 self._run_check("</$>", [('comment', '$')])
402 self._run_check("</", [('data', '</')])
403 self._run_check("</a", [('data', '</a')])
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200404 self._run_check("<a<a>", [('starttag', 'a<a', [])])
Ezio Melotti86f67122012-02-13 14:11:27 +0200405 self._run_check("</a<a>", [('endtag', 'a<a')])
406 self._run_check("<!", [('data', '<!')])
407 self._run_check("<a", [('data', '<a')])
408 self._run_check("<a foo='bar'", [('data', "<a foo='bar'")])
409 self._run_check("<a foo='bar", [('data', "<a foo='bar")])
410 self._run_check("<a foo='>'", [('data', "<a foo='>'")])
411 self._run_check("<a foo='>", [('data', "<a foo='>")])
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200412 self._run_check("<a$>", [('starttag', 'a$', [])])
413 self._run_check("<a$b>", [('starttag', 'a$b', [])])
414 self._run_check("<a$b/>", [('startendtag', 'a$b', [])])
415 self._run_check("<a$b >", [('starttag', 'a$b', [])])
416 self._run_check("<a$b />", [('startendtag', 'a$b', [])])
Ezio Melotti86f67122012-02-13 14:11:27 +0200417
Ezio Melotti29877e82012-02-21 09:25:00 +0200418 def test_slashes_in_starttag(self):
419 self._run_check('<a foo="var"/>', [('startendtag', 'a', [('foo', 'var')])])
420 html = ('<img width=902 height=250px '
421 'src="/sites/default/files/images/homepage/foo.jpg" '
422 '/*what am I doing here*/ />')
423 expected = [(
424 'startendtag', 'img',
425 [('width', '902'), ('height', '250px'),
426 ('src', '/sites/default/files/images/homepage/foo.jpg'),
427 ('*what', None), ('am', None), ('i', None),
428 ('doing', None), ('here*', None)]
429 )]
430 self._run_check(html, expected)
431 html = ('<a / /foo/ / /=/ / /bar/ / />'
432 '<a / /foo/ / /=/ / /bar/ / >')
433 expected = [
434 ('startendtag', 'a', [('foo', None), ('=', None), ('bar', None)]),
435 ('starttag', 'a', [('foo', None), ('=', None), ('bar', None)])
436 ]
437 self._run_check(html, expected)
Ezio Melotti0780b6b2012-04-18 19:18:22 -0600438 #see issue #14538
439 html = ('<meta><meta / ><meta // ><meta / / >'
440 '<meta/><meta /><meta //><meta//>')
441 expected = [
442 ('starttag', 'meta', []), ('starttag', 'meta', []),
443 ('starttag', 'meta', []), ('starttag', 'meta', []),
444 ('startendtag', 'meta', []), ('startendtag', 'meta', []),
445 ('startendtag', 'meta', []), ('startendtag', 'meta', []),
446 ]
447 self._run_check(html, expected)
Ezio Melotti29877e82012-02-21 09:25:00 +0200448
Ezio Melotti86f67122012-02-13 14:11:27 +0200449 def test_declaration_junk_chars(self):
Ezio Melottif4ab4912012-02-13 15:50:37 +0200450 self._run_check("<!DOCTYPE foo $ >", [('decl', 'DOCTYPE foo $ ')])
Ezio Melotti86f67122012-02-13 14:11:27 +0200451
452 def test_illegal_declarations(self):
Ezio Melotti86f67122012-02-13 14:11:27 +0200453 self._run_check('<!spacer type="block" height="25">',
454 [('comment', 'spacer type="block" height="25"')])
455
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200456 def test_with_unquoted_attributes(self):
Ezio Melottib9a48f72011-11-01 15:00:59 +0200457 # see #12008
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200458 html = ("<html><body bgcolor=d0ca90 text='181008'>"
459 "<table cellspacing=0 cellpadding=1 width=100% ><tr>"
460 "<td align=left><font size=-1>"
461 "- <a href=/rabota/><span class=en> software-and-i</span></a>"
462 "- <a href='/1/'><span class=en> library</span></a></table>")
463 expected = [
464 ('starttag', 'html', []),
465 ('starttag', 'body', [('bgcolor', 'd0ca90'), ('text', '181008')]),
466 ('starttag', 'table',
467 [('cellspacing', '0'), ('cellpadding', '1'), ('width', '100%')]),
468 ('starttag', 'tr', []),
469 ('starttag', 'td', [('align', 'left')]),
470 ('starttag', 'font', [('size', '-1')]),
471 ('data', '- '), ('starttag', 'a', [('href', '/rabota/')]),
472 ('starttag', 'span', [('class', 'en')]), ('data', ' software-and-i'),
473 ('endtag', 'span'), ('endtag', 'a'),
474 ('data', '- '), ('starttag', 'a', [('href', '/1/')]),
475 ('starttag', 'span', [('class', 'en')]), ('data', ' library'),
476 ('endtag', 'span'), ('endtag', 'a'), ('endtag', 'table')
477 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200478 self._run_check(html, expected)
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200479
R. David Murrayb579dba2010-12-03 04:06:39 +0000480 def test_comma_between_attributes(self):
481 self._run_check('<form action="/xxx.php?a=1&amp;b=2&amp", '
482 'method="post">', [
483 ('starttag', 'form',
Ezio Melotti46495182012-06-24 22:02:56 +0200484 [('action', '/xxx.php?a=1&b=2&'),
Ezio Melottic2fe5772011-11-14 18:53:33 +0200485 (',', None), ('method', 'post')])])
R. David Murrayb579dba2010-12-03 04:06:39 +0000486
487 def test_weird_chars_in_unquoted_attribute_values(self):
488 self._run_check('<form action=bogus|&#()value>', [
489 ('starttag', 'form',
Ezio Melottic1e73c32011-11-01 18:57:15 +0200490 [('action', 'bogus|&#()value')])])
R. David Murrayb579dba2010-12-03 04:06:39 +0000491
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200492 def test_invalid_end_tags(self):
493 # A collection of broken end tags. <br> is used as separator.
494 # see http://www.w3.org/TR/html5/tokenization.html#end-tag-open-state
495 # and #13993
496 html = ('<br></label</p><br></div end tmAd-leaderBoard><br></<h4><br>'
497 '</li class="unit"><br></li\r\n\t\t\t\t\t\t</ul><br></><br>')
498 expected = [('starttag', 'br', []),
499 # < is part of the name, / is discarded, p is an attribute
500 ('endtag', 'label<'),
501 ('starttag', 'br', []),
502 # text and attributes are discarded
503 ('endtag', 'div'),
504 ('starttag', 'br', []),
505 # comment because the first char after </ is not a-zA-Z
506 ('comment', '<h4'),
507 ('starttag', 'br', []),
508 # attributes are discarded
509 ('endtag', 'li'),
510 ('starttag', 'br', []),
511 # everything till ul (included) is discarded
512 ('endtag', 'li'),
513 ('starttag', 'br', []),
514 # </> is ignored
515 ('starttag', 'br', [])]
516 self._run_check(html, expected)
517
518 def test_broken_invalid_end_tag(self):
519 # This is technically wrong (the "> shouldn't be included in the 'data')
520 # but is probably not worth fixing it (in addition to all the cases of
521 # the previous test, it would require a full attribute parsing).
522 # see #13993
523 html = '<b>This</b attr=">"> confuses the parser'
524 expected = [('starttag', 'b', []),
525 ('data', 'This'),
526 ('endtag', 'b'),
527 ('data', '"> confuses the parser')]
528 self._run_check(html, expected)
529
Ezio Melottib9a48f72011-11-01 15:00:59 +0200530 def test_correct_detection_of_start_tags(self):
531 # see #13273
Ezio Melottif50ffa92011-10-28 13:21:09 +0300532 html = ('<div style="" ><b>The <a href="some_url">rain</a> '
533 '<br /> in <span>Spain</span></b></div>')
534 expected = [
535 ('starttag', 'div', [('style', '')]),
536 ('starttag', 'b', []),
537 ('data', 'The '),
538 ('starttag', 'a', [('href', 'some_url')]),
539 ('data', 'rain'),
540 ('endtag', 'a'),
541 ('data', ' '),
542 ('startendtag', 'br', []),
543 ('data', ' in '),
544 ('starttag', 'span', []),
545 ('data', 'Spain'),
546 ('endtag', 'span'),
547 ('endtag', 'b'),
548 ('endtag', 'div')
549 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200550 self._run_check(html, expected)
Ezio Melottif50ffa92011-10-28 13:21:09 +0300551
Ezio Melottif50ffa92011-10-28 13:21:09 +0300552 html = '<div style="", foo = "bar" ><b>The <a href="some_url">rain</a>'
553 expected = [
Ezio Melottic2fe5772011-11-14 18:53:33 +0200554 ('starttag', 'div', [('style', ''), (',', None), ('foo', 'bar')]),
Ezio Melottif50ffa92011-10-28 13:21:09 +0300555 ('starttag', 'b', []),
556 ('data', 'The '),
557 ('starttag', 'a', [('href', 'some_url')]),
558 ('data', 'rain'),
559 ('endtag', 'a'),
560 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200561 self._run_check(html, expected)
Ezio Melottif50ffa92011-10-28 13:21:09 +0300562
Ezio Melotti8e596a72013-05-01 16:18:25 +0300563 def test_EOF_in_charref(self):
564 # see #17802
565 # This test checks that the UnboundLocalError reported in the issue
566 # is not raised, however I'm not sure the returned values are correct.
567 # Maybe HTMLParser should use self.unescape for these
568 data = [
569 ('a&', [('data', 'a&')]),
570 ('a&b', [('data', 'ab')]),
571 ('a&b ', [('data', 'a'), ('entityref', 'b'), ('data', ' ')]),
572 ('a&b;', [('data', 'a'), ('entityref', 'b')]),
573 ]
574 for html, expected in data:
575 self._run_check(html, expected)
576
Ezio Melottif6de9eb2013-11-22 05:49:29 +0200577 def test_unescape_method(self):
578 from html import unescape
579 p = self.get_collector()
580 with self.assertWarns(DeprecationWarning):
581 s = '&quot;&#34;&#x22;&quot&#34&#x22&#bad;'
582 self.assertEqual(p.unescape(s), unescape(s))
583
Ezio Melottifa3702d2012-02-10 10:45:44 +0200584 def test_broken_comments(self):
585 html = ('<! not really a comment >'
586 '<! not a comment either -->'
587 '<! -- close enough -->'
Ezio Melottif4ab4912012-02-13 15:50:37 +0200588 '<!><!<-- this was an empty comment>'
Ezio Melottifa3702d2012-02-10 10:45:44 +0200589 '<!!! another bogus comment !!!>')
590 expected = [
591 ('comment', ' not really a comment '),
592 ('comment', ' not a comment either --'),
593 ('comment', ' -- close enough --'),
Ezio Melottif4ab4912012-02-13 15:50:37 +0200594 ('comment', ''),
595 ('comment', '<-- this was an empty comment'),
Ezio Melottifa3702d2012-02-10 10:45:44 +0200596 ('comment', '!! another bogus comment !!!'),
597 ]
598 self._run_check(html, expected)
599
Ezio Melotti62f3d032011-12-19 07:29:03 +0200600 def test_broken_condcoms(self):
601 # these condcoms are missing the '--' after '<!' and before the '>'
602 html = ('<![if !(IE)]>broken condcom<![endif]>'
603 '<![if ! IE]><link href="favicon.tiff"/><![endif]>'
604 '<![if !IE 6]><img src="firefox.png" /><![endif]>'
605 '<![if !ie 6]><b>foo</b><![endif]>'
606 '<![if (!IE)|(lt IE 9)]><img src="mammoth.bmp" /><![endif]>')
607 # According to the HTML5 specs sections "8.2.4.44 Bogus comment state"
608 # and "8.2.4.45 Markup declaration open state", comment tokens should
609 # be emitted instead of 'unknown decl', but calling unknown_decl
610 # provides more flexibility.
611 # See also Lib/_markupbase.py:parse_declaration
612 expected = [
613 ('unknown decl', 'if !(IE)'),
614 ('data', 'broken condcom'),
615 ('unknown decl', 'endif'),
616 ('unknown decl', 'if ! IE'),
617 ('startendtag', 'link', [('href', 'favicon.tiff')]),
618 ('unknown decl', 'endif'),
619 ('unknown decl', 'if !IE 6'),
620 ('startendtag', 'img', [('src', 'firefox.png')]),
621 ('unknown decl', 'endif'),
622 ('unknown decl', 'if !ie 6'),
623 ('starttag', 'b', []),
624 ('data', 'foo'),
625 ('endtag', 'b'),
626 ('unknown decl', 'endif'),
627 ('unknown decl', 'if (!IE)|(lt IE 9)'),
628 ('startendtag', 'img', [('src', 'mammoth.bmp')]),
629 ('unknown decl', 'endif')
630 ]
631 self._run_check(html, expected)
632
Ezio Melotti6f2bb982015-09-06 21:38:06 +0300633 def test_convert_charrefs_dropped_text(self):
634 # #23144: make sure that all the events are triggered when
635 # convert_charrefs is True, even if we don't call .close()
636 parser = EventCollector(convert_charrefs=True)
637 # before the fix, bar & baz was missing
638 parser.feed("foo <a>link</a> bar &amp; baz")
639 self.assertEqual(
640 parser.get_events(),
641 [('data', 'foo '), ('starttag', 'a', []), ('data', 'link'),
642 ('endtag', 'a'), ('data', ' bar & baz')]
643 )
644
Ezio Melottic1e73c32011-11-01 18:57:15 +0200645
Ezio Melotti73a43592014-08-02 14:10:30 +0300646class AttributesTestCase(TestCaseBase):
Ezio Melottib245ed12011-11-14 18:13:22 +0200647
648 def test_attr_syntax(self):
649 output = [
650 ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", None)])
651 ]
652 self._run_check("""<a b='v' c="v" d=v e>""", output)
653 self._run_check("""<a b = 'v' c = "v" d = v e>""", output)
654 self._run_check("""<a\nb\n=\n'v'\nc\n=\n"v"\nd\n=\nv\ne>""", output)
655 self._run_check("""<a\tb\t=\t'v'\tc\t=\t"v"\td\t=\tv\te>""", output)
656
657 def test_attr_values(self):
658 self._run_check("""<a b='xxx\n\txxx' c="yyy\t\nyyy" d='\txyz\n'>""",
659 [("starttag", "a", [("b", "xxx\n\txxx"),
660 ("c", "yyy\t\nyyy"),
661 ("d", "\txyz\n")])])
662 self._run_check("""<a b='' c="">""",
663 [("starttag", "a", [("b", ""), ("c", "")])])
664 # Regression test for SF patch #669683.
665 self._run_check("<e a=rgb(1,2,3)>",
666 [("starttag", "e", [("a", "rgb(1,2,3)")])])
667 # Regression test for SF bug #921657.
668 self._run_check(
669 "<a href=mailto:xyz@example.com>",
670 [("starttag", "a", [("href", "mailto:xyz@example.com")])])
671
672 def test_attr_nonascii(self):
673 # see issue 7311
674 self._run_check(
675 "<img src=/foo/bar.png alt=\u4e2d\u6587>",
676 [("starttag", "img", [("src", "/foo/bar.png"),
677 ("alt", "\u4e2d\u6587")])])
678 self._run_check(
679 "<a title='\u30c6\u30b9\u30c8' href='\u30c6\u30b9\u30c8.html'>",
680 [("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
681 ("href", "\u30c6\u30b9\u30c8.html")])])
682 self._run_check(
683 '<a title="\u30c6\u30b9\u30c8" href="\u30c6\u30b9\u30c8.html">',
684 [("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
685 ("href", "\u30c6\u30b9\u30c8.html")])])
686
687 def test_attr_entity_replacement(self):
688 self._run_check(
689 "<a b='&amp;&gt;&lt;&quot;&apos;'>",
690 [("starttag", "a", [("b", "&><\"'")])])
691
692 def test_attr_funky_names(self):
693 self._run_check(
694 "<a a.b='v' c:d=v e-f=v>",
695 [("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")])])
696
697 def test_entityrefs_in_attributes(self):
698 self._run_check(
699 "<html foo='&euro;&amp;&#97;&#x61;&unsupported;'>",
700 [("starttag", "html", [("foo", "\u20AC&aa&unsupported;")])])
701
702
Ezio Melottic2fe5772011-11-14 18:53:33 +0200703 def test_attr_funky_names2(self):
704 self._run_check(
705 "<a $><b $=%><c \=/>",
706 [("starttag", "a", [("$", None)]),
707 ("starttag", "b", [("$", "%")]),
708 ("starttag", "c", [("\\", "/")])])
709
710 def test_entities_in_attribute_value(self):
711 # see #1200313
712 for entity in ['&', '&amp;', '&#38;', '&#x26;']:
713 self._run_check('<a href="%s">' % entity,
714 [("starttag", "a", [("href", "&")])])
715 self._run_check("<a href='%s'>" % entity,
716 [("starttag", "a", [("href", "&")])])
717 self._run_check("<a href=%s>" % entity,
718 [("starttag", "a", [("href", "&")])])
719
720 def test_malformed_attributes(self):
721 # see #13357
722 html = (
723 "<a href=test'style='color:red;bad1'>test - bad1</a>"
724 "<a href=test'+style='color:red;ba2'>test - bad2</a>"
725 "<a href=test'&nbsp;style='color:red;bad3'>test - bad3</a>"
726 "<a href = test'&nbsp;style='color:red;bad4' >test - bad4</a>"
727 )
728 expected = [
729 ('starttag', 'a', [('href', "test'style='color:red;bad1'")]),
730 ('data', 'test - bad1'), ('endtag', 'a'),
731 ('starttag', 'a', [('href', "test'+style='color:red;ba2'")]),
732 ('data', 'test - bad2'), ('endtag', 'a'),
733 ('starttag', 'a', [('href', "test'\xa0style='color:red;bad3'")]),
734 ('data', 'test - bad3'), ('endtag', 'a'),
735 ('starttag', 'a', [('href', "test'\xa0style='color:red;bad4'")]),
736 ('data', 'test - bad4'), ('endtag', 'a')
737 ]
738 self._run_check(html, expected)
739
740 def test_malformed_adjacent_attributes(self):
741 # see #12629
742 self._run_check('<x><y z=""o"" /></x>',
743 [('starttag', 'x', []),
744 ('startendtag', 'y', [('z', ''), ('o""', None)]),
745 ('endtag', 'x')])
746 self._run_check('<x><y z="""" /></x>',
747 [('starttag', 'x', []),
748 ('startendtag', 'y', [('z', ''), ('""', None)]),
749 ('endtag', 'x')])
750
751 # see #755670 for the following 3 tests
752 def test_adjacent_attributes(self):
753 self._run_check('<a width="100%"cellspacing=0>',
754 [("starttag", "a",
755 [("width", "100%"), ("cellspacing","0")])])
756
757 self._run_check('<a id="foo"class="bar">',
758 [("starttag", "a",
759 [("id", "foo"), ("class","bar")])])
760
761 def test_missing_attribute_value(self):
762 self._run_check('<a v=>',
763 [("starttag", "a", [("v", "")])])
764
765 def test_javascript_attribute_value(self):
766 self._run_check("<a href=javascript:popup('/popup/help.html')>",
767 [("starttag", "a",
768 [("href", "javascript:popup('/popup/help.html')")])])
769
770 def test_end_tag_in_attribute_value(self):
771 # see #1745761
772 self._run_check("<a href='http://www.example.org/\">;'>spam</a>",
773 [("starttag", "a",
774 [("href", "http://www.example.org/\">;")]),
775 ("data", "spam"), ("endtag", "a")])
776
777
Fred Drakee8220492001-09-24 20:19:08 +0000778if __name__ == "__main__":
Ezio Melotti5028f4d2013-11-02 17:49:08 +0200779 unittest.main()