blob: 6ebf5b8e240d16ea03c6b0fc7e52f1eca53e6838 [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()
Ezio Melotti88ebfb12013-11-02 17:08:24 +020099 with self.assertRaises(html.parser.HTMLParseError):
100 with self.assertWarns(DeprecationWarning):
101 parse()
Fred Drakebd3090d2001-05-18 15:32:59 +0000102
103
Ezio Melottic1e73c32011-11-01 18:57:15 +0200104class HTMLParserStrictTestCase(TestCaseBase):
105
106 def get_collector(self):
Ezio Melotti3861d8b2012-06-23 15:27:51 +0200107 with support.check_warnings(("", DeprecationWarning), quite=False):
108 return EventCollector(strict=True)
Fred Drakebd3090d2001-05-18 15:32:59 +0000109
Fred Drake84bb9d82001-08-03 19:53:01 +0000110 def test_processing_instruction_only(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000111 self._run_check("<?processing instruction>", [
112 ("pi", "processing instruction"),
113 ])
Fred Drakefafd56f2003-04-17 22:19:26 +0000114 self._run_check("<?processing instruction ?>", [
115 ("pi", "processing instruction ?"),
116 ])
Fred Drakebd3090d2001-05-18 15:32:59 +0000117
Fred Drake84bb9d82001-08-03 19:53:01 +0000118 def test_simple_html(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000119 self._run_check("""
120<!DOCTYPE html PUBLIC 'foo'>
121<HTML>&entity;&#32;
122<!--comment1a
123-></foo><bar>&lt;<?pi?></foo<bar
124comment1b-->
125<Img sRc='Bar' isMAP>sample
126text
Fred Drake84bb9d82001-08-03 19:53:01 +0000127&#x201C;
Ezio Melottif4ab4912012-02-13 15:50:37 +0200128<!--comment2a-- --comment2b-->
Fred Drakebd3090d2001-05-18 15:32:59 +0000129</Html>
130""", [
131 ("data", "\n"),
132 ("decl", "DOCTYPE html PUBLIC 'foo'"),
133 ("data", "\n"),
134 ("starttag", "html", []),
135 ("entityref", "entity"),
136 ("charref", "32"),
137 ("data", "\n"),
138 ("comment", "comment1a\n-></foo><bar>&lt;<?pi?></foo<bar\ncomment1b"),
139 ("data", "\n"),
140 ("starttag", "img", [("src", "Bar"), ("ismap", None)]),
141 ("data", "sample\ntext\n"),
Fred Drake84bb9d82001-08-03 19:53:01 +0000142 ("charref", "x201C"),
143 ("data", "\n"),
Fred Drakebd3090d2001-05-18 15:32:59 +0000144 ("comment", "comment2a-- --comment2b"),
145 ("data", "\n"),
146 ("endtag", "html"),
147 ("data", "\n"),
148 ])
149
Victor Stinnere021f4b2010-05-24 21:46:25 +0000150 def test_malformatted_charref(self):
151 self._run_check("<p>&#bad;</p>", [
152 ("starttag", "p", []),
153 ("data", "&#bad;"),
154 ("endtag", "p"),
155 ])
156
Fred Drake073148c2001-12-03 16:44:09 +0000157 def test_unclosed_entityref(self):
158 self._run_check("&entityref foo", [
159 ("entityref", "entityref"),
160 ("data", " foo"),
161 ])
162
Fred Drake84bb9d82001-08-03 19:53:01 +0000163 def test_bad_nesting(self):
164 # Strangely, this *is* supposed to test that overlapping
165 # elements are allowed. HTMLParser is more geared toward
166 # lexing the input that parsing the structure.
Fred Drakebd3090d2001-05-18 15:32:59 +0000167 self._run_check("<a><b></a></b>", [
168 ("starttag", "a", []),
169 ("starttag", "b", []),
170 ("endtag", "a"),
171 ("endtag", "b"),
172 ])
173
Fred Drake029acfb2001-08-20 21:24:19 +0000174 def test_bare_ampersands(self):
175 self._run_check("this text & contains & ampersands &", [
176 ("data", "this text & contains & ampersands &"),
177 ])
178
179 def test_bare_pointy_brackets(self):
180 self._run_check("this < text > contains < bare>pointy< brackets", [
181 ("data", "this < text > contains < bare>pointy< brackets"),
182 ])
183
Fred Drakec20a6982001-09-04 15:13:04 +0000184 def test_illegal_declarations(self):
Fred Drake7cf613d2001-09-04 16:26:03 +0000185 self._parse_error('<!spacer type="block" height="25">')
Fred Drakec20a6982001-09-04 15:13:04 +0000186
Fred Drake84bb9d82001-08-03 19:53:01 +0000187 def test_starttag_end_boundary(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000188 self._run_check("""<a b='<'>""", [("starttag", "a", [("b", "<")])])
189 self._run_check("""<a b='>'>""", [("starttag", "a", [("b", ">")])])
190
Fred Drake84bb9d82001-08-03 19:53:01 +0000191 def test_buffer_artefacts(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000192 output = [("starttag", "a", [("b", "<")])]
193 self._run_check(["<a b='<'>"], output)
194 self._run_check(["<a ", "b='<'>"], output)
195 self._run_check(["<a b", "='<'>"], output)
196 self._run_check(["<a b=", "'<'>"], output)
197 self._run_check(["<a b='<", "'>"], output)
198 self._run_check(["<a b='<'", ">"], output)
199
200 output = [("starttag", "a", [("b", ">")])]
201 self._run_check(["<a b='>'>"], output)
202 self._run_check(["<a ", "b='>'>"], output)
203 self._run_check(["<a b", "='>'>"], output)
204 self._run_check(["<a b=", "'>'>"], output)
205 self._run_check(["<a b='>", "'>"], output)
206 self._run_check(["<a b='>'", ">"], output)
207
Fred Drake75d9a622004-09-08 22:57:01 +0000208 output = [("comment", "abc")]
209 self._run_check(["", "<!--abc-->"], output)
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(["<!--a", "bc-->"], output)
215 self._run_check(["<!--ab", "c-->"], output)
216 self._run_check(["<!--abc", "-->"], output)
217 self._run_check(["<!--abc-", "->"], output)
218 self._run_check(["<!--abc--", ">"], output)
219 self._run_check(["<!--abc-->", ""], output)
220
Fred Drake84bb9d82001-08-03 19:53:01 +0000221 def test_starttag_junk_chars(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000222 self._parse_error("</>")
223 self._parse_error("</$>")
224 self._parse_error("</")
225 self._parse_error("</a")
Fred Drakebd3090d2001-05-18 15:32:59 +0000226 self._parse_error("<a<a>")
227 self._parse_error("</a<a>")
Fred Drakebd3090d2001-05-18 15:32:59 +0000228 self._parse_error("<!")
Fred Drakebd3090d2001-05-18 15:32:59 +0000229 self._parse_error("<a")
230 self._parse_error("<a foo='bar'")
231 self._parse_error("<a foo='bar")
232 self._parse_error("<a foo='>'")
233 self._parse_error("<a foo='>")
Fred Drakebd3090d2001-05-18 15:32:59 +0000234
Ezio Melottif4ab4912012-02-13 15:50:37 +0200235 def test_valid_doctypes(self):
236 # from http://www.w3.org/QA/2002/04/valid-dtd-list.html
237 dtds = ['HTML', # HTML5 doctype
238 ('HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
239 '"http://www.w3.org/TR/html4/strict.dtd"'),
240 ('HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" '
241 '"http://www.w3.org/TR/html4/loose.dtd"'),
242 ('html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" '
243 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"'),
244 ('html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" '
245 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"'),
246 ('math PUBLIC "-//W3C//DTD MathML 2.0//EN" '
247 '"http://www.w3.org/Math/DTD/mathml2/mathml2.dtd"'),
248 ('html PUBLIC "-//W3C//DTD '
249 'XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" '
250 '"http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd"'),
251 ('svg PUBLIC "-//W3C//DTD SVG 1.1//EN" '
252 '"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"'),
253 'html PUBLIC "-//IETF//DTD HTML 2.0//EN"',
254 'html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"']
255 for dtd in dtds:
256 self._run_check("<!DOCTYPE %s>" % dtd,
257 [('decl', 'DOCTYPE ' + dtd)])
258
Fred Drake84bb9d82001-08-03 19:53:01 +0000259 def test_declaration_junk_chars(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000260 self._parse_error("<!DOCTYPE foo $ >")
261
Fred Drake84bb9d82001-08-03 19:53:01 +0000262 def test_startendtag(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000263 self._run_check("<p/>", [
264 ("startendtag", "p", []),
265 ])
266 self._run_check("<p></p>", [
267 ("starttag", "p", []),
268 ("endtag", "p"),
269 ])
270 self._run_check("<p><img src='foo' /></p>", [
271 ("starttag", "p", []),
272 ("startendtag", "img", [("src", "foo")]),
273 ("endtag", "p"),
274 ])
275
Fred Drake84bb9d82001-08-03 19:53:01 +0000276 def test_get_starttag_text(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000277 s = """<foo:bar \n one="1"\ttwo=2 >"""
278 self._run_check_extra(s, [
279 ("starttag", "foo:bar", [("one", "1"), ("two", "2")]),
280 ("starttag_text", s)])
281
Fred Drake84bb9d82001-08-03 19:53:01 +0000282 def test_cdata_content(self):
Ezio Melotti7de56f62011-11-01 14:12:22 +0200283 contents = [
284 '<!-- not a comment --> &not-an-entity-ref;',
285 "<not a='start tag'>",
286 '<a href="" /> <p> <span></span>',
287 'foo = "</scr" + "ipt>";',
288 'foo = "</SCRIPT" + ">";',
289 'foo = <\n/script> ',
290 '<!-- document.write("</scr" + "ipt>"); -->',
291 ('\n//<![CDATA[\n'
292 'document.write(\'<s\'+\'cript type="text/javascript" '
293 'src="http://www.example.org/r=\'+new '
294 'Date().getTime()+\'"><\\/s\'+\'cript>\');\n//]]>'),
295 '\n<!-- //\nvar foo = 3.14;\n// -->\n',
296 'foo = "</sty" + "le>";',
297 '<!-- \u2603 -->',
298 # these two should be invalid according to the HTML 5 spec,
299 # section 8.1.2.2
300 #'foo = </\nscript>',
301 #'foo = </ script>',
302 ]
303 elements = ['script', 'style', 'SCRIPT', 'STYLE', 'Script', 'Style']
304 for content in contents:
305 for element in elements:
306 element_lower = element.lower()
307 s = '<{element}>{content}</{element}>'.format(element=element,
308 content=content)
309 self._run_check(s, [("starttag", element_lower, []),
310 ("data", content),
311 ("endtag", element_lower)])
312
Ezio Melotti15cb4892011-11-18 18:01:49 +0200313 def test_cdata_with_closing_tags(self):
314 # see issue #13358
315 # make sure that HTMLParser calls handle_data only once for each CDATA.
316 # The normal event collector normalizes the events in get_events,
317 # so we override it to return the original list of events.
318 class Collector(EventCollector):
319 def get_events(self):
320 return self.events
Fred Drakebd3090d2001-05-18 15:32:59 +0000321
Ezio Melotti15cb4892011-11-18 18:01:49 +0200322 content = """<!-- not a comment --> &not-an-entity-ref;
323 <a href="" /> </p><p> <span></span></style>
324 '</script' + '>'"""
325 for element in [' script', 'script ', ' script ',
326 '\nscript', 'script\n', '\nscript\n']:
327 element_lower = element.lower().strip()
328 s = '<script>{content}</{element}>'.format(element=element,
329 content=content)
330 self._run_check(s, [("starttag", element_lower, []),
331 ("data", content),
332 ("endtag", element_lower)],
333 collector=Collector())
Fred Drakebd3090d2001-05-18 15:32:59 +0000334
Ezio Melottifa3702d2012-02-10 10:45:44 +0200335 def test_comments(self):
336 html = ("<!-- I'm a valid comment -->"
337 '<!--me too!-->'
338 '<!------>'
339 '<!---->'
340 '<!----I have many hyphens---->'
341 '<!-- I have a > in the middle -->'
342 '<!-- and I have -- in the middle! -->')
343 expected = [('comment', " I'm a valid comment "),
344 ('comment', 'me too!'),
345 ('comment', '--'),
346 ('comment', ''),
347 ('comment', '--I have many hyphens--'),
348 ('comment', ' I have a > in the middle '),
349 ('comment', ' and I have -- in the middle! ')]
350 self._run_check(html, expected)
351
Ezio Melotti62f3d032011-12-19 07:29:03 +0200352 def test_condcoms(self):
353 html = ('<!--[if IE & !(lte IE 8)]>aren\'t<![endif]-->'
354 '<!--[if IE 8]>condcoms<![endif]-->'
355 '<!--[if lte IE 7]>pretty?<![endif]-->')
356 expected = [('comment', "[if IE & !(lte IE 8)]>aren't<![endif]"),
357 ('comment', '[if IE 8]>condcoms<![endif]'),
358 ('comment', '[if lte IE 7]>pretty?<![endif]')]
359 self._run_check(html, expected)
360
361
Ezio Melottic1e73c32011-11-01 18:57:15 +0200362class HTMLParserTolerantTestCase(HTMLParserStrictTestCase):
R. David Murrayb579dba2010-12-03 04:06:39 +0000363
Ezio Melottib9a48f72011-11-01 15:00:59 +0200364 def get_collector(self):
Ezio Melotti88ebfb12013-11-02 17:08:24 +0200365 return EventCollector()
366
367 def test_deprecation_warnings(self):
368 with self.assertWarns(DeprecationWarning):
369 EventCollector(strict=True)
370 with self.assertWarns(DeprecationWarning):
371 EventCollector(strict=False)
372 with self.assertRaises(html.parser.HTMLParseError):
373 with self.assertWarns(DeprecationWarning):
374 EventCollector().error('test')
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'),
382 ('data', '<<bc'),
383 ('endtag', 'a'),
384 ('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')])
394 # XXX this might be wrong
395 self._run_check("<a<a>", [('data', '<a'), ('starttag', 'a', [])])
396 self._run_check("</a<a>", [('endtag', 'a<a')])
397 self._run_check("<!", [('data', '<!')])
398 self._run_check("<a", [('data', '<a')])
399 self._run_check("<a foo='bar'", [('data', "<a foo='bar'")])
400 self._run_check("<a foo='bar", [('data', "<a foo='bar")])
401 self._run_check("<a foo='>'", [('data', "<a foo='>'")])
402 self._run_check("<a foo='>", [('data', "<a foo='>")])
403
Ezio Melotti29877e82012-02-21 09:25:00 +0200404 def test_slashes_in_starttag(self):
405 self._run_check('<a foo="var"/>', [('startendtag', 'a', [('foo', 'var')])])
406 html = ('<img width=902 height=250px '
407 'src="/sites/default/files/images/homepage/foo.jpg" '
408 '/*what am I doing here*/ />')
409 expected = [(
410 'startendtag', 'img',
411 [('width', '902'), ('height', '250px'),
412 ('src', '/sites/default/files/images/homepage/foo.jpg'),
413 ('*what', None), ('am', None), ('i', None),
414 ('doing', None), ('here*', None)]
415 )]
416 self._run_check(html, expected)
417 html = ('<a / /foo/ / /=/ / /bar/ / />'
418 '<a / /foo/ / /=/ / /bar/ / >')
419 expected = [
420 ('startendtag', 'a', [('foo', None), ('=', None), ('bar', None)]),
421 ('starttag', 'a', [('foo', None), ('=', None), ('bar', None)])
422 ]
423 self._run_check(html, expected)
Ezio Melotti0780b6b2012-04-18 19:18:22 -0600424 #see issue #14538
425 html = ('<meta><meta / ><meta // ><meta / / >'
426 '<meta/><meta /><meta //><meta//>')
427 expected = [
428 ('starttag', 'meta', []), ('starttag', 'meta', []),
429 ('starttag', 'meta', []), ('starttag', 'meta', []),
430 ('startendtag', 'meta', []), ('startendtag', 'meta', []),
431 ('startendtag', 'meta', []), ('startendtag', 'meta', []),
432 ]
433 self._run_check(html, expected)
Ezio Melotti29877e82012-02-21 09:25:00 +0200434
Ezio Melotti86f67122012-02-13 14:11:27 +0200435 def test_declaration_junk_chars(self):
Ezio Melottif4ab4912012-02-13 15:50:37 +0200436 self._run_check("<!DOCTYPE foo $ >", [('decl', 'DOCTYPE foo $ ')])
Ezio Melotti86f67122012-02-13 14:11:27 +0200437
438 def test_illegal_declarations(self):
Ezio Melotti86f67122012-02-13 14:11:27 +0200439 self._run_check('<!spacer type="block" height="25">',
440 [('comment', 'spacer type="block" height="25"')])
441
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200442 def test_with_unquoted_attributes(self):
Ezio Melottib9a48f72011-11-01 15:00:59 +0200443 # see #12008
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200444 html = ("<html><body bgcolor=d0ca90 text='181008'>"
445 "<table cellspacing=0 cellpadding=1 width=100% ><tr>"
446 "<td align=left><font size=-1>"
447 "- <a href=/rabota/><span class=en> software-and-i</span></a>"
448 "- <a href='/1/'><span class=en> library</span></a></table>")
449 expected = [
450 ('starttag', 'html', []),
451 ('starttag', 'body', [('bgcolor', 'd0ca90'), ('text', '181008')]),
452 ('starttag', 'table',
453 [('cellspacing', '0'), ('cellpadding', '1'), ('width', '100%')]),
454 ('starttag', 'tr', []),
455 ('starttag', 'td', [('align', 'left')]),
456 ('starttag', 'font', [('size', '-1')]),
457 ('data', '- '), ('starttag', 'a', [('href', '/rabota/')]),
458 ('starttag', 'span', [('class', 'en')]), ('data', ' software-and-i'),
459 ('endtag', 'span'), ('endtag', 'a'),
460 ('data', '- '), ('starttag', 'a', [('href', '/1/')]),
461 ('starttag', 'span', [('class', 'en')]), ('data', ' library'),
462 ('endtag', 'span'), ('endtag', 'a'), ('endtag', 'table')
463 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200464 self._run_check(html, expected)
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200465
R. David Murrayb579dba2010-12-03 04:06:39 +0000466 def test_comma_between_attributes(self):
467 self._run_check('<form action="/xxx.php?a=1&amp;b=2&amp", '
468 'method="post">', [
469 ('starttag', 'form',
Ezio Melotti46495182012-06-24 22:02:56 +0200470 [('action', '/xxx.php?a=1&b=2&'),
Ezio Melottic2fe5772011-11-14 18:53:33 +0200471 (',', None), ('method', 'post')])])
R. David Murrayb579dba2010-12-03 04:06:39 +0000472
473 def test_weird_chars_in_unquoted_attribute_values(self):
474 self._run_check('<form action=bogus|&#()value>', [
475 ('starttag', 'form',
Ezio Melottic1e73c32011-11-01 18:57:15 +0200476 [('action', 'bogus|&#()value')])])
R. David Murrayb579dba2010-12-03 04:06:39 +0000477
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200478 def test_invalid_end_tags(self):
479 # A collection of broken end tags. <br> is used as separator.
480 # see http://www.w3.org/TR/html5/tokenization.html#end-tag-open-state
481 # and #13993
482 html = ('<br></label</p><br></div end tmAd-leaderBoard><br></<h4><br>'
483 '</li class="unit"><br></li\r\n\t\t\t\t\t\t</ul><br></><br>')
484 expected = [('starttag', 'br', []),
485 # < is part of the name, / is discarded, p is an attribute
486 ('endtag', 'label<'),
487 ('starttag', 'br', []),
488 # text and attributes are discarded
489 ('endtag', 'div'),
490 ('starttag', 'br', []),
491 # comment because the first char after </ is not a-zA-Z
492 ('comment', '<h4'),
493 ('starttag', 'br', []),
494 # attributes are discarded
495 ('endtag', 'li'),
496 ('starttag', 'br', []),
497 # everything till ul (included) is discarded
498 ('endtag', 'li'),
499 ('starttag', 'br', []),
500 # </> is ignored
501 ('starttag', 'br', [])]
502 self._run_check(html, expected)
503
504 def test_broken_invalid_end_tag(self):
505 # This is technically wrong (the "> shouldn't be included in the 'data')
506 # but is probably not worth fixing it (in addition to all the cases of
507 # the previous test, it would require a full attribute parsing).
508 # see #13993
509 html = '<b>This</b attr=">"> confuses the parser'
510 expected = [('starttag', 'b', []),
511 ('data', 'This'),
512 ('endtag', 'b'),
513 ('data', '"> confuses the parser')]
514 self._run_check(html, expected)
515
Ezio Melottib9a48f72011-11-01 15:00:59 +0200516 def test_correct_detection_of_start_tags(self):
517 # see #13273
Ezio Melottif50ffa92011-10-28 13:21:09 +0300518 html = ('<div style="" ><b>The <a href="some_url">rain</a> '
519 '<br /> in <span>Spain</span></b></div>')
520 expected = [
521 ('starttag', 'div', [('style', '')]),
522 ('starttag', 'b', []),
523 ('data', 'The '),
524 ('starttag', 'a', [('href', 'some_url')]),
525 ('data', 'rain'),
526 ('endtag', 'a'),
527 ('data', ' '),
528 ('startendtag', 'br', []),
529 ('data', ' in '),
530 ('starttag', 'span', []),
531 ('data', 'Spain'),
532 ('endtag', 'span'),
533 ('endtag', 'b'),
534 ('endtag', 'div')
535 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200536 self._run_check(html, expected)
Ezio Melottif50ffa92011-10-28 13:21:09 +0300537
Ezio Melottif50ffa92011-10-28 13:21:09 +0300538 html = '<div style="", foo = "bar" ><b>The <a href="some_url">rain</a>'
539 expected = [
Ezio Melottic2fe5772011-11-14 18:53:33 +0200540 ('starttag', 'div', [('style', ''), (',', None), ('foo', 'bar')]),
Ezio Melottif50ffa92011-10-28 13:21:09 +0300541 ('starttag', 'b', []),
542 ('data', 'The '),
543 ('starttag', 'a', [('href', 'some_url')]),
544 ('data', 'rain'),
545 ('endtag', 'a'),
546 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200547 self._run_check(html, expected)
Ezio Melottif50ffa92011-10-28 13:21:09 +0300548
Ezio Melotti8e596a72013-05-01 16:18:25 +0300549 def test_EOF_in_charref(self):
550 # see #17802
551 # This test checks that the UnboundLocalError reported in the issue
552 # is not raised, however I'm not sure the returned values are correct.
553 # Maybe HTMLParser should use self.unescape for these
554 data = [
555 ('a&', [('data', 'a&')]),
556 ('a&b', [('data', 'ab')]),
557 ('a&b ', [('data', 'a'), ('entityref', 'b'), ('data', ' ')]),
558 ('a&b;', [('data', 'a'), ('entityref', 'b')]),
559 ]
560 for html, expected in data:
561 self._run_check(html, expected)
562
Senthil Kumaran164540f2010-12-28 15:55:16 +0000563 def test_unescape_function(self):
Ezio Melotti86f67122012-02-13 14:11:27 +0200564 p = self.get_collector()
Senthil Kumaran164540f2010-12-28 15:55:16 +0000565 self.assertEqual(p.unescape('&#bad;'),'&#bad;')
566 self.assertEqual(p.unescape('&#0038;'),'&')
Ezio Melottid9e0b062011-09-05 17:11:06 +0300567 # see #12888
568 self.assertEqual(p.unescape('&#123; ' * 1050), '{ ' * 1050)
Ezio Melotti46495182012-06-24 22:02:56 +0200569 # see #15156
570 self.assertEqual(p.unescape('&Eacuteric&Eacute;ric'
571 '&alphacentauri&alpha;centauri'),
572 'ÉricÉric&alphacentauriαcentauri')
573 self.assertEqual(p.unescape('&co;'), '&co;')
R. David Murrayb579dba2010-12-03 04:06:39 +0000574
Ezio Melottifa3702d2012-02-10 10:45:44 +0200575 def test_broken_comments(self):
576 html = ('<! not really a comment >'
577 '<! not a comment either -->'
578 '<! -- close enough -->'
Ezio Melottif4ab4912012-02-13 15:50:37 +0200579 '<!><!<-- this was an empty comment>'
Ezio Melottifa3702d2012-02-10 10:45:44 +0200580 '<!!! another bogus comment !!!>')
581 expected = [
582 ('comment', ' not really a comment '),
583 ('comment', ' not a comment either --'),
584 ('comment', ' -- close enough --'),
Ezio Melottif4ab4912012-02-13 15:50:37 +0200585 ('comment', ''),
586 ('comment', '<-- this was an empty comment'),
Ezio Melottifa3702d2012-02-10 10:45:44 +0200587 ('comment', '!! another bogus comment !!!'),
588 ]
589 self._run_check(html, expected)
590
Ezio Melotti62f3d032011-12-19 07:29:03 +0200591 def test_broken_condcoms(self):
592 # these condcoms are missing the '--' after '<!' and before the '>'
593 html = ('<![if !(IE)]>broken condcom<![endif]>'
594 '<![if ! IE]><link href="favicon.tiff"/><![endif]>'
595 '<![if !IE 6]><img src="firefox.png" /><![endif]>'
596 '<![if !ie 6]><b>foo</b><![endif]>'
597 '<![if (!IE)|(lt IE 9)]><img src="mammoth.bmp" /><![endif]>')
598 # According to the HTML5 specs sections "8.2.4.44 Bogus comment state"
599 # and "8.2.4.45 Markup declaration open state", comment tokens should
600 # be emitted instead of 'unknown decl', but calling unknown_decl
601 # provides more flexibility.
602 # See also Lib/_markupbase.py:parse_declaration
603 expected = [
604 ('unknown decl', 'if !(IE)'),
605 ('data', 'broken condcom'),
606 ('unknown decl', 'endif'),
607 ('unknown decl', 'if ! IE'),
608 ('startendtag', 'link', [('href', 'favicon.tiff')]),
609 ('unknown decl', 'endif'),
610 ('unknown decl', 'if !IE 6'),
611 ('startendtag', 'img', [('src', 'firefox.png')]),
612 ('unknown decl', 'endif'),
613 ('unknown decl', 'if !ie 6'),
614 ('starttag', 'b', []),
615 ('data', 'foo'),
616 ('endtag', 'b'),
617 ('unknown decl', 'endif'),
618 ('unknown decl', 'if (!IE)|(lt IE 9)'),
619 ('startendtag', 'img', [('src', 'mammoth.bmp')]),
620 ('unknown decl', 'endif')
621 ]
622 self._run_check(html, expected)
623
Ezio Melottic1e73c32011-11-01 18:57:15 +0200624
Ezio Melottib245ed12011-11-14 18:13:22 +0200625class AttributesStrictTestCase(TestCaseBase):
626
627 def get_collector(self):
Ezio Melotti3861d8b2012-06-23 15:27:51 +0200628 with support.check_warnings(("", DeprecationWarning), quite=False):
629 return EventCollector(strict=True)
Ezio Melottib245ed12011-11-14 18:13:22 +0200630
631 def test_attr_syntax(self):
632 output = [
633 ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", None)])
634 ]
635 self._run_check("""<a b='v' c="v" d=v e>""", output)
636 self._run_check("""<a b = 'v' c = "v" d = v e>""", output)
637 self._run_check("""<a\nb\n=\n'v'\nc\n=\n"v"\nd\n=\nv\ne>""", output)
638 self._run_check("""<a\tb\t=\t'v'\tc\t=\t"v"\td\t=\tv\te>""", output)
639
640 def test_attr_values(self):
641 self._run_check("""<a b='xxx\n\txxx' c="yyy\t\nyyy" d='\txyz\n'>""",
642 [("starttag", "a", [("b", "xxx\n\txxx"),
643 ("c", "yyy\t\nyyy"),
644 ("d", "\txyz\n")])])
645 self._run_check("""<a b='' c="">""",
646 [("starttag", "a", [("b", ""), ("c", "")])])
647 # Regression test for SF patch #669683.
648 self._run_check("<e a=rgb(1,2,3)>",
649 [("starttag", "e", [("a", "rgb(1,2,3)")])])
650 # Regression test for SF bug #921657.
651 self._run_check(
652 "<a href=mailto:xyz@example.com>",
653 [("starttag", "a", [("href", "mailto:xyz@example.com")])])
654
655 def test_attr_nonascii(self):
656 # see issue 7311
657 self._run_check(
658 "<img src=/foo/bar.png alt=\u4e2d\u6587>",
659 [("starttag", "img", [("src", "/foo/bar.png"),
660 ("alt", "\u4e2d\u6587")])])
661 self._run_check(
662 "<a title='\u30c6\u30b9\u30c8' href='\u30c6\u30b9\u30c8.html'>",
663 [("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
664 ("href", "\u30c6\u30b9\u30c8.html")])])
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
670 def test_attr_entity_replacement(self):
671 self._run_check(
672 "<a b='&amp;&gt;&lt;&quot;&apos;'>",
673 [("starttag", "a", [("b", "&><\"'")])])
674
675 def test_attr_funky_names(self):
676 self._run_check(
677 "<a a.b='v' c:d=v e-f=v>",
678 [("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")])])
679
680 def test_entityrefs_in_attributes(self):
681 self._run_check(
682 "<html foo='&euro;&amp;&#97;&#x61;&unsupported;'>",
683 [("starttag", "html", [("foo", "\u20AC&aa&unsupported;")])])
684
685
Ezio Melottic2fe5772011-11-14 18:53:33 +0200686
687class AttributesTolerantTestCase(AttributesStrictTestCase):
688
689 def get_collector(self):
Ezio Melotti88ebfb12013-11-02 17:08:24 +0200690 return EventCollector()
Ezio Melottic2fe5772011-11-14 18:53:33 +0200691
692 def test_attr_funky_names2(self):
693 self._run_check(
694 "<a $><b $=%><c \=/>",
695 [("starttag", "a", [("$", None)]),
696 ("starttag", "b", [("$", "%")]),
697 ("starttag", "c", [("\\", "/")])])
698
699 def test_entities_in_attribute_value(self):
700 # see #1200313
701 for entity in ['&', '&amp;', '&#38;', '&#x26;']:
702 self._run_check('<a href="%s">' % entity,
703 [("starttag", "a", [("href", "&")])])
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
709 def test_malformed_attributes(self):
710 # see #13357
711 html = (
712 "<a href=test'style='color:red;bad1'>test - bad1</a>"
713 "<a href=test'+style='color:red;ba2'>test - bad2</a>"
714 "<a href=test'&nbsp;style='color:red;bad3'>test - bad3</a>"
715 "<a href = test'&nbsp;style='color:red;bad4' >test - bad4</a>"
716 )
717 expected = [
718 ('starttag', 'a', [('href', "test'style='color:red;bad1'")]),
719 ('data', 'test - bad1'), ('endtag', 'a'),
720 ('starttag', 'a', [('href', "test'+style='color:red;ba2'")]),
721 ('data', 'test - bad2'), ('endtag', 'a'),
722 ('starttag', 'a', [('href', "test'\xa0style='color:red;bad3'")]),
723 ('data', 'test - bad3'), ('endtag', 'a'),
724 ('starttag', 'a', [('href', "test'\xa0style='color:red;bad4'")]),
725 ('data', 'test - bad4'), ('endtag', 'a')
726 ]
727 self._run_check(html, expected)
728
729 def test_malformed_adjacent_attributes(self):
730 # see #12629
731 self._run_check('<x><y z=""o"" /></x>',
732 [('starttag', 'x', []),
733 ('startendtag', 'y', [('z', ''), ('o""', None)]),
734 ('endtag', 'x')])
735 self._run_check('<x><y z="""" /></x>',
736 [('starttag', 'x', []),
737 ('startendtag', 'y', [('z', ''), ('""', None)]),
738 ('endtag', 'x')])
739
740 # see #755670 for the following 3 tests
741 def test_adjacent_attributes(self):
742 self._run_check('<a width="100%"cellspacing=0>',
743 [("starttag", "a",
744 [("width", "100%"), ("cellspacing","0")])])
745
746 self._run_check('<a id="foo"class="bar">',
747 [("starttag", "a",
748 [("id", "foo"), ("class","bar")])])
749
750 def test_missing_attribute_value(self):
751 self._run_check('<a v=>',
752 [("starttag", "a", [("v", "")])])
753
754 def test_javascript_attribute_value(self):
755 self._run_check("<a href=javascript:popup('/popup/help.html')>",
756 [("starttag", "a",
757 [("href", "javascript:popup('/popup/help.html')")])])
758
759 def test_end_tag_in_attribute_value(self):
760 # see #1745761
761 self._run_check("<a href='http://www.example.org/\">;'>spam</a>",
762 [("starttag", "a",
763 [("href", "http://www.example.org/\">;")]),
764 ("data", "spam"), ("endtag", "a")])
765
766
767
Fred Drakee8220492001-09-24 20:19:08 +0000768def test_main():
Ezio Melottib245ed12011-11-14 18:13:22 +0200769 support.run_unittest(HTMLParserStrictTestCase, HTMLParserTolerantTestCase,
Ezio Melottic2fe5772011-11-14 18:53:33 +0200770 AttributesStrictTestCase, AttributesTolerantTestCase)
Fred Drakee8220492001-09-24 20:19:08 +0000771
772
773if __name__ == "__main__":
774 test_main()