blob: c977a9dd4d7111a3e1794bbadf007f5b73aeb390 [file] [log] [blame]
Fred Drakebd3090d2001-05-18 15:32:59 +00001"""Tests for HTMLParser.py."""
2
Mark Dickinsonf64dcf32008-05-21 13:51:18 +00003import html.parser
Fred Drake029acfb2001-08-20 21:24:19 +00004import pprint
Fred Drakebd3090d2001-05-18 15:32:59 +00005import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00006from test import support
Fred Drakebd3090d2001-05-18 15:32:59 +00007
8
Mark Dickinsonf64dcf32008-05-21 13:51:18 +00009class EventCollector(html.parser.HTMLParser):
Fred Drakebd3090d2001-05-18 15:32:59 +000010
R. David Murrayb579dba2010-12-03 04:06:39 +000011 def __init__(self, *args, **kw):
Fred Drakebd3090d2001-05-18 15:32:59 +000012 self.events = []
13 self.append = self.events.append
R. David Murrayb579dba2010-12-03 04:06:39 +000014 html.parser.HTMLParser.__init__(self, *args, **kw)
Fred Drakebd3090d2001-05-18 15:32:59 +000015
16 def get_events(self):
17 # Normalize the list of events so that buffer artefacts don't
18 # separate runs of contiguous characters.
19 L = []
20 prevtype = None
21 for event in self.events:
22 type = event[0]
23 if type == prevtype == "data":
24 L[-1] = ("data", L[-1][1] + event[1])
25 else:
26 L.append(event)
27 prevtype = type
28 self.events = L
29 return L
30
31 # structure markup
32
33 def handle_starttag(self, tag, attrs):
34 self.append(("starttag", tag, attrs))
35
36 def handle_startendtag(self, tag, attrs):
37 self.append(("startendtag", tag, attrs))
38
39 def handle_endtag(self, tag):
40 self.append(("endtag", tag))
41
42 # all other markup
43
44 def handle_comment(self, data):
45 self.append(("comment", data))
46
47 def handle_charref(self, data):
48 self.append(("charref", data))
49
50 def handle_data(self, data):
51 self.append(("data", data))
52
53 def handle_decl(self, data):
54 self.append(("decl", data))
55
56 def handle_entityref(self, data):
57 self.append(("entityref", data))
58
59 def handle_pi(self, data):
60 self.append(("pi", data))
61
Fred Drakec20a6982001-09-04 15:13:04 +000062 def unknown_decl(self, decl):
63 self.append(("unknown decl", decl))
64
Fred Drakebd3090d2001-05-18 15:32:59 +000065
66class EventCollectorExtra(EventCollector):
67
68 def handle_starttag(self, tag, attrs):
69 EventCollector.handle_starttag(self, tag, attrs)
70 self.append(("starttag_text", self.get_starttag_text()))
71
72
73class TestCaseBase(unittest.TestCase):
74
Ezio Melottic1e73c32011-11-01 18:57:15 +020075 def get_collector(self):
76 raise NotImplementedError
77
R. David Murrayb579dba2010-12-03 04:06:39 +000078 def _run_check(self, source, expected_events, collector=None):
79 if collector is None:
Ezio Melottic1e73c32011-11-01 18:57:15 +020080 collector = self.get_collector()
R. David Murrayb579dba2010-12-03 04:06:39 +000081 parser = collector
Fred Drakebd3090d2001-05-18 15:32:59 +000082 for s in source:
83 parser.feed(s)
Fred Drakebd3090d2001-05-18 15:32:59 +000084 parser.close()
Fred Drake029acfb2001-08-20 21:24:19 +000085 events = parser.get_events()
Fred Drakec20a6982001-09-04 15:13:04 +000086 if events != expected_events:
87 self.fail("received events did not match expected events\n"
88 "Expected:\n" + pprint.pformat(expected_events) +
89 "\nReceived:\n" + pprint.pformat(events))
Fred Drakebd3090d2001-05-18 15:32:59 +000090
91 def _run_check_extra(self, source, events):
R. David Murrayb579dba2010-12-03 04:06:39 +000092 self._run_check(source, events, EventCollectorExtra())
Fred Drakebd3090d2001-05-18 15:32:59 +000093
94 def _parse_error(self, source):
95 def parse(source=source):
Ezio Melotti86f67122012-02-13 14:11:27 +020096 parser = self.get_collector()
Fred Drakebd3090d2001-05-18 15:32:59 +000097 parser.feed(source)
98 parser.close()
Mark Dickinsonf64dcf32008-05-21 13:51:18 +000099 self.assertRaises(html.parser.HTMLParseError, parse)
Fred Drakebd3090d2001-05-18 15:32:59 +0000100
101
Ezio Melottic1e73c32011-11-01 18:57:15 +0200102class HTMLParserStrictTestCase(TestCaseBase):
103
104 def get_collector(self):
Ezio Melotti3861d8b2012-06-23 15:27:51 +0200105 with support.check_warnings(("", DeprecationWarning), quite=False):
106 return EventCollector(strict=True)
Fred Drakebd3090d2001-05-18 15:32:59 +0000107
Fred Drake84bb9d82001-08-03 19:53:01 +0000108 def test_processing_instruction_only(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000109 self._run_check("<?processing instruction>", [
110 ("pi", "processing instruction"),
111 ])
Fred Drakefafd56f2003-04-17 22:19:26 +0000112 self._run_check("<?processing instruction ?>", [
113 ("pi", "processing instruction ?"),
114 ])
Fred Drakebd3090d2001-05-18 15:32:59 +0000115
Fred Drake84bb9d82001-08-03 19:53:01 +0000116 def test_simple_html(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000117 self._run_check("""
118<!DOCTYPE html PUBLIC 'foo'>
119<HTML>&entity;&#32;
120<!--comment1a
121-></foo><bar>&lt;<?pi?></foo<bar
122comment1b-->
123<Img sRc='Bar' isMAP>sample
124text
Fred Drake84bb9d82001-08-03 19:53:01 +0000125&#x201C;
Ezio Melottif4ab4912012-02-13 15:50:37 +0200126<!--comment2a-- --comment2b-->
Fred Drakebd3090d2001-05-18 15:32:59 +0000127</Html>
128""", [
129 ("data", "\n"),
130 ("decl", "DOCTYPE html PUBLIC 'foo'"),
131 ("data", "\n"),
132 ("starttag", "html", []),
133 ("entityref", "entity"),
134 ("charref", "32"),
135 ("data", "\n"),
136 ("comment", "comment1a\n-></foo><bar>&lt;<?pi?></foo<bar\ncomment1b"),
137 ("data", "\n"),
138 ("starttag", "img", [("src", "Bar"), ("ismap", None)]),
139 ("data", "sample\ntext\n"),
Fred Drake84bb9d82001-08-03 19:53:01 +0000140 ("charref", "x201C"),
141 ("data", "\n"),
Fred Drakebd3090d2001-05-18 15:32:59 +0000142 ("comment", "comment2a-- --comment2b"),
143 ("data", "\n"),
144 ("endtag", "html"),
145 ("data", "\n"),
146 ])
147
Victor Stinnere021f4b2010-05-24 21:46:25 +0000148 def test_malformatted_charref(self):
149 self._run_check("<p>&#bad;</p>", [
150 ("starttag", "p", []),
151 ("data", "&#bad;"),
152 ("endtag", "p"),
153 ])
154
Fred Drake073148c2001-12-03 16:44:09 +0000155 def test_unclosed_entityref(self):
156 self._run_check("&entityref foo", [
157 ("entityref", "entityref"),
158 ("data", " foo"),
159 ])
160
Fred Drake84bb9d82001-08-03 19:53:01 +0000161 def test_bad_nesting(self):
162 # Strangely, this *is* supposed to test that overlapping
163 # elements are allowed. HTMLParser is more geared toward
164 # lexing the input that parsing the structure.
Fred Drakebd3090d2001-05-18 15:32:59 +0000165 self._run_check("<a><b></a></b>", [
166 ("starttag", "a", []),
167 ("starttag", "b", []),
168 ("endtag", "a"),
169 ("endtag", "b"),
170 ])
171
Fred Drake029acfb2001-08-20 21:24:19 +0000172 def test_bare_ampersands(self):
173 self._run_check("this text & contains & ampersands &", [
174 ("data", "this text & contains & ampersands &"),
175 ])
176
177 def test_bare_pointy_brackets(self):
178 self._run_check("this < text > contains < bare>pointy< brackets", [
179 ("data", "this < text > contains < bare>pointy< brackets"),
180 ])
181
Fred Drakec20a6982001-09-04 15:13:04 +0000182 def test_illegal_declarations(self):
Fred Drake7cf613d2001-09-04 16:26:03 +0000183 self._parse_error('<!spacer type="block" height="25">')
Fred Drakec20a6982001-09-04 15:13:04 +0000184
Fred Drake84bb9d82001-08-03 19:53:01 +0000185 def test_starttag_end_boundary(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000186 self._run_check("""<a b='<'>""", [("starttag", "a", [("b", "<")])])
187 self._run_check("""<a b='>'>""", [("starttag", "a", [("b", ">")])])
188
Fred Drake84bb9d82001-08-03 19:53:01 +0000189 def test_buffer_artefacts(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000190 output = [("starttag", "a", [("b", "<")])]
191 self._run_check(["<a b='<'>"], output)
192 self._run_check(["<a ", "b='<'>"], output)
193 self._run_check(["<a b", "='<'>"], output)
194 self._run_check(["<a b=", "'<'>"], output)
195 self._run_check(["<a b='<", "'>"], output)
196 self._run_check(["<a b='<'", ">"], output)
197
198 output = [("starttag", "a", [("b", ">")])]
199 self._run_check(["<a b='>'>"], output)
200 self._run_check(["<a ", "b='>'>"], output)
201 self._run_check(["<a b", "='>'>"], output)
202 self._run_check(["<a b=", "'>'>"], output)
203 self._run_check(["<a b='>", "'>"], output)
204 self._run_check(["<a b='>'", ">"], output)
205
Fred Drake75d9a622004-09-08 22:57:01 +0000206 output = [("comment", "abc")]
207 self._run_check(["", "<!--abc-->"], output)
208 self._run_check(["<", "!--abc-->"], output)
209 self._run_check(["<!", "--abc-->"], output)
210 self._run_check(["<!-", "-abc-->"], output)
211 self._run_check(["<!--", "abc-->"], output)
212 self._run_check(["<!--a", "bc-->"], output)
213 self._run_check(["<!--ab", "c-->"], output)
214 self._run_check(["<!--abc", "-->"], output)
215 self._run_check(["<!--abc-", "->"], output)
216 self._run_check(["<!--abc--", ">"], output)
217 self._run_check(["<!--abc-->", ""], output)
218
Fred Drake84bb9d82001-08-03 19:53:01 +0000219 def test_starttag_junk_chars(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000220 self._parse_error("</>")
221 self._parse_error("</$>")
222 self._parse_error("</")
223 self._parse_error("</a")
Fred Drakebd3090d2001-05-18 15:32:59 +0000224 self._parse_error("<a<a>")
225 self._parse_error("</a<a>")
Fred Drakebd3090d2001-05-18 15:32:59 +0000226 self._parse_error("<!")
Fred Drakebd3090d2001-05-18 15:32:59 +0000227 self._parse_error("<a")
228 self._parse_error("<a foo='bar'")
229 self._parse_error("<a foo='bar")
230 self._parse_error("<a foo='>'")
231 self._parse_error("<a foo='>")
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200232 self._parse_error("<a$>")
233 self._parse_error("<a$b>")
234 self._parse_error("<a$b/>")
235 self._parse_error("<a$b >")
236 self._parse_error("<a$b />")
Fred Drakebd3090d2001-05-18 15:32:59 +0000237
Ezio Melottif4ab4912012-02-13 15:50:37 +0200238 def test_valid_doctypes(self):
239 # from http://www.w3.org/QA/2002/04/valid-dtd-list.html
240 dtds = ['HTML', # HTML5 doctype
241 ('HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
242 '"http://www.w3.org/TR/html4/strict.dtd"'),
243 ('HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" '
244 '"http://www.w3.org/TR/html4/loose.dtd"'),
245 ('html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" '
246 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"'),
247 ('html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" '
248 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"'),
249 ('math PUBLIC "-//W3C//DTD MathML 2.0//EN" '
250 '"http://www.w3.org/Math/DTD/mathml2/mathml2.dtd"'),
251 ('html PUBLIC "-//W3C//DTD '
252 'XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" '
253 '"http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd"'),
254 ('svg PUBLIC "-//W3C//DTD SVG 1.1//EN" '
255 '"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"'),
256 'html PUBLIC "-//IETF//DTD HTML 2.0//EN"',
257 'html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"']
258 for dtd in dtds:
259 self._run_check("<!DOCTYPE %s>" % dtd,
260 [('decl', 'DOCTYPE ' + dtd)])
261
Fred Drake84bb9d82001-08-03 19:53:01 +0000262 def test_declaration_junk_chars(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000263 self._parse_error("<!DOCTYPE foo $ >")
264
Fred Drake84bb9d82001-08-03 19:53:01 +0000265 def test_startendtag(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000266 self._run_check("<p/>", [
267 ("startendtag", "p", []),
268 ])
269 self._run_check("<p></p>", [
270 ("starttag", "p", []),
271 ("endtag", "p"),
272 ])
273 self._run_check("<p><img src='foo' /></p>", [
274 ("starttag", "p", []),
275 ("startendtag", "img", [("src", "foo")]),
276 ("endtag", "p"),
277 ])
278
Fred Drake84bb9d82001-08-03 19:53:01 +0000279 def test_get_starttag_text(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000280 s = """<foo:bar \n one="1"\ttwo=2 >"""
281 self._run_check_extra(s, [
282 ("starttag", "foo:bar", [("one", "1"), ("two", "2")]),
283 ("starttag_text", s)])
284
Fred Drake84bb9d82001-08-03 19:53:01 +0000285 def test_cdata_content(self):
Ezio Melotti7de56f62011-11-01 14:12:22 +0200286 contents = [
287 '<!-- not a comment --> &not-an-entity-ref;',
288 "<not a='start tag'>",
289 '<a href="" /> <p> <span></span>',
290 'foo = "</scr" + "ipt>";',
291 'foo = "</SCRIPT" + ">";',
292 'foo = <\n/script> ',
293 '<!-- document.write("</scr" + "ipt>"); -->',
294 ('\n//<![CDATA[\n'
295 'document.write(\'<s\'+\'cript type="text/javascript" '
296 'src="http://www.example.org/r=\'+new '
297 'Date().getTime()+\'"><\\/s\'+\'cript>\');\n//]]>'),
298 '\n<!-- //\nvar foo = 3.14;\n// -->\n',
299 'foo = "</sty" + "le>";',
300 '<!-- \u2603 -->',
301 # these two should be invalid according to the HTML 5 spec,
302 # section 8.1.2.2
303 #'foo = </\nscript>',
304 #'foo = </ script>',
305 ]
306 elements = ['script', 'style', 'SCRIPT', 'STYLE', 'Script', 'Style']
307 for content in contents:
308 for element in elements:
309 element_lower = element.lower()
310 s = '<{element}>{content}</{element}>'.format(element=element,
311 content=content)
312 self._run_check(s, [("starttag", element_lower, []),
313 ("data", content),
314 ("endtag", element_lower)])
315
Ezio Melotti15cb4892011-11-18 18:01:49 +0200316 def test_cdata_with_closing_tags(self):
317 # see issue #13358
318 # make sure that HTMLParser calls handle_data only once for each CDATA.
319 # The normal event collector normalizes the events in get_events,
320 # so we override it to return the original list of events.
321 class Collector(EventCollector):
322 def get_events(self):
323 return self.events
Fred Drakebd3090d2001-05-18 15:32:59 +0000324
Ezio Melotti15cb4892011-11-18 18:01:49 +0200325 content = """<!-- not a comment --> &not-an-entity-ref;
326 <a href="" /> </p><p> <span></span></style>
327 '</script' + '>'"""
328 for element in [' script', 'script ', ' script ',
329 '\nscript', 'script\n', '\nscript\n']:
330 element_lower = element.lower().strip()
331 s = '<script>{content}</{element}>'.format(element=element,
332 content=content)
333 self._run_check(s, [("starttag", element_lower, []),
334 ("data", content),
335 ("endtag", element_lower)],
336 collector=Collector())
Fred Drakebd3090d2001-05-18 15:32:59 +0000337
Ezio Melottifa3702d2012-02-10 10:45:44 +0200338 def test_comments(self):
339 html = ("<!-- I'm a valid comment -->"
340 '<!--me too!-->'
341 '<!------>'
342 '<!---->'
343 '<!----I have many hyphens---->'
344 '<!-- I have a > in the middle -->'
345 '<!-- and I have -- in the middle! -->')
346 expected = [('comment', " I'm a valid comment "),
347 ('comment', 'me too!'),
348 ('comment', '--'),
349 ('comment', ''),
350 ('comment', '--I have many hyphens--'),
351 ('comment', ' I have a > in the middle '),
352 ('comment', ' and I have -- in the middle! ')]
353 self._run_check(html, expected)
354
Ezio Melotti62f3d032011-12-19 07:29:03 +0200355 def test_condcoms(self):
356 html = ('<!--[if IE & !(lte IE 8)]>aren\'t<![endif]-->'
357 '<!--[if IE 8]>condcoms<![endif]-->'
358 '<!--[if lte IE 7]>pretty?<![endif]-->')
359 expected = [('comment', "[if IE & !(lte IE 8)]>aren't<![endif]"),
360 ('comment', '[if IE 8]>condcoms<![endif]'),
361 ('comment', '[if lte IE 7]>pretty?<![endif]')]
362 self._run_check(html, expected)
363
364
Ezio Melottic1e73c32011-11-01 18:57:15 +0200365class HTMLParserTolerantTestCase(HTMLParserStrictTestCase):
R. David Murrayb579dba2010-12-03 04:06:39 +0000366
Ezio Melottib9a48f72011-11-01 15:00:59 +0200367 def get_collector(self):
368 return EventCollector(strict=False)
R. David Murrayb579dba2010-12-03 04:06:39 +0000369
370 def test_tolerant_parsing(self):
371 self._run_check('<html <html>te>>xt&a<<bc</a></html>\n'
372 '<img src="URL><//img></html</html>', [
Ezio Melottic2fe5772011-11-14 18:53:33 +0200373 ('starttag', 'html', [('<html', None)]),
374 ('data', 'te>>xt'),
375 ('entityref', 'a'),
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200376 ('data', '<'),
377 ('starttag', 'bc<', [('a', None)]),
Ezio Melottic2fe5772011-11-14 18:53:33 +0200378 ('endtag', 'html'),
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200379 ('data', '\n<img src="URL>'),
380 ('comment', '/img'),
381 ('endtag', 'html<')])
R. David Murrayb579dba2010-12-03 04:06:39 +0000382
Ezio Melotti86f67122012-02-13 14:11:27 +0200383 def test_starttag_junk_chars(self):
384 self._run_check("</>", [])
385 self._run_check("</$>", [('comment', '$')])
386 self._run_check("</", [('data', '</')])
387 self._run_check("</a", [('data', '</a')])
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200388 self._run_check("<a<a>", [('starttag', 'a<a', [])])
Ezio Melotti86f67122012-02-13 14:11:27 +0200389 self._run_check("</a<a>", [('endtag', 'a<a')])
390 self._run_check("<!", [('data', '<!')])
391 self._run_check("<a", [('data', '<a')])
392 self._run_check("<a foo='bar'", [('data', "<a foo='bar'")])
393 self._run_check("<a foo='bar", [('data', "<a foo='bar")])
394 self._run_check("<a foo='>'", [('data', "<a foo='>'")])
395 self._run_check("<a foo='>", [('data', "<a foo='>")])
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200396 self._run_check("<a$>", [('starttag', 'a$', [])])
397 self._run_check("<a$b>", [('starttag', 'a$b', [])])
398 self._run_check("<a$b/>", [('startendtag', 'a$b', [])])
399 self._run_check("<a$b >", [('starttag', 'a$b', [])])
400 self._run_check("<a$b />", [('startendtag', 'a$b', [])])
Ezio Melotti86f67122012-02-13 14:11:27 +0200401
Ezio Melotti29877e82012-02-21 09:25:00 +0200402 def test_slashes_in_starttag(self):
403 self._run_check('<a foo="var"/>', [('startendtag', 'a', [('foo', 'var')])])
404 html = ('<img width=902 height=250px '
405 'src="/sites/default/files/images/homepage/foo.jpg" '
406 '/*what am I doing here*/ />')
407 expected = [(
408 'startendtag', 'img',
409 [('width', '902'), ('height', '250px'),
410 ('src', '/sites/default/files/images/homepage/foo.jpg'),
411 ('*what', None), ('am', None), ('i', None),
412 ('doing', None), ('here*', None)]
413 )]
414 self._run_check(html, expected)
415 html = ('<a / /foo/ / /=/ / /bar/ / />'
416 '<a / /foo/ / /=/ / /bar/ / >')
417 expected = [
418 ('startendtag', 'a', [('foo', None), ('=', None), ('bar', None)]),
419 ('starttag', 'a', [('foo', None), ('=', None), ('bar', None)])
420 ]
421 self._run_check(html, expected)
Ezio Melotti0780b6b2012-04-18 19:18:22 -0600422 #see issue #14538
423 html = ('<meta><meta / ><meta // ><meta / / >'
424 '<meta/><meta /><meta //><meta//>')
425 expected = [
426 ('starttag', 'meta', []), ('starttag', 'meta', []),
427 ('starttag', 'meta', []), ('starttag', 'meta', []),
428 ('startendtag', 'meta', []), ('startendtag', 'meta', []),
429 ('startendtag', 'meta', []), ('startendtag', 'meta', []),
430 ]
431 self._run_check(html, expected)
Ezio Melotti29877e82012-02-21 09:25:00 +0200432
Ezio Melotti86f67122012-02-13 14:11:27 +0200433 def test_declaration_junk_chars(self):
Ezio Melottif4ab4912012-02-13 15:50:37 +0200434 self._run_check("<!DOCTYPE foo $ >", [('decl', 'DOCTYPE foo $ ')])
Ezio Melotti86f67122012-02-13 14:11:27 +0200435
436 def test_illegal_declarations(self):
Ezio Melotti86f67122012-02-13 14:11:27 +0200437 self._run_check('<!spacer type="block" height="25">',
438 [('comment', 'spacer type="block" height="25"')])
439
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200440 def test_with_unquoted_attributes(self):
Ezio Melottib9a48f72011-11-01 15:00:59 +0200441 # see #12008
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200442 html = ("<html><body bgcolor=d0ca90 text='181008'>"
443 "<table cellspacing=0 cellpadding=1 width=100% ><tr>"
444 "<td align=left><font size=-1>"
445 "- <a href=/rabota/><span class=en> software-and-i</span></a>"
446 "- <a href='/1/'><span class=en> library</span></a></table>")
447 expected = [
448 ('starttag', 'html', []),
449 ('starttag', 'body', [('bgcolor', 'd0ca90'), ('text', '181008')]),
450 ('starttag', 'table',
451 [('cellspacing', '0'), ('cellpadding', '1'), ('width', '100%')]),
452 ('starttag', 'tr', []),
453 ('starttag', 'td', [('align', 'left')]),
454 ('starttag', 'font', [('size', '-1')]),
455 ('data', '- '), ('starttag', 'a', [('href', '/rabota/')]),
456 ('starttag', 'span', [('class', 'en')]), ('data', ' software-and-i'),
457 ('endtag', 'span'), ('endtag', 'a'),
458 ('data', '- '), ('starttag', 'a', [('href', '/1/')]),
459 ('starttag', 'span', [('class', 'en')]), ('data', ' library'),
460 ('endtag', 'span'), ('endtag', 'a'), ('endtag', 'table')
461 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200462 self._run_check(html, expected)
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200463
R. David Murrayb579dba2010-12-03 04:06:39 +0000464 def test_comma_between_attributes(self):
465 self._run_check('<form action="/xxx.php?a=1&amp;b=2&amp", '
466 'method="post">', [
467 ('starttag', 'form',
Ezio Melotti46495182012-06-24 22:02:56 +0200468 [('action', '/xxx.php?a=1&b=2&'),
Ezio Melottic2fe5772011-11-14 18:53:33 +0200469 (',', None), ('method', 'post')])])
R. David Murrayb579dba2010-12-03 04:06:39 +0000470
471 def test_weird_chars_in_unquoted_attribute_values(self):
472 self._run_check('<form action=bogus|&#()value>', [
473 ('starttag', 'form',
Ezio Melottic1e73c32011-11-01 18:57:15 +0200474 [('action', 'bogus|&#()value')])])
R. David Murrayb579dba2010-12-03 04:06:39 +0000475
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200476 def test_invalid_end_tags(self):
477 # A collection of broken end tags. <br> is used as separator.
478 # see http://www.w3.org/TR/html5/tokenization.html#end-tag-open-state
479 # and #13993
480 html = ('<br></label</p><br></div end tmAd-leaderBoard><br></<h4><br>'
481 '</li class="unit"><br></li\r\n\t\t\t\t\t\t</ul><br></><br>')
482 expected = [('starttag', 'br', []),
483 # < is part of the name, / is discarded, p is an attribute
484 ('endtag', 'label<'),
485 ('starttag', 'br', []),
486 # text and attributes are discarded
487 ('endtag', 'div'),
488 ('starttag', 'br', []),
489 # comment because the first char after </ is not a-zA-Z
490 ('comment', '<h4'),
491 ('starttag', 'br', []),
492 # attributes are discarded
493 ('endtag', 'li'),
494 ('starttag', 'br', []),
495 # everything till ul (included) is discarded
496 ('endtag', 'li'),
497 ('starttag', 'br', []),
498 # </> is ignored
499 ('starttag', 'br', [])]
500 self._run_check(html, expected)
501
502 def test_broken_invalid_end_tag(self):
503 # This is technically wrong (the "> shouldn't be included in the 'data')
504 # but is probably not worth fixing it (in addition to all the cases of
505 # the previous test, it would require a full attribute parsing).
506 # see #13993
507 html = '<b>This</b attr=">"> confuses the parser'
508 expected = [('starttag', 'b', []),
509 ('data', 'This'),
510 ('endtag', 'b'),
511 ('data', '"> confuses the parser')]
512 self._run_check(html, expected)
513
Ezio Melottib9a48f72011-11-01 15:00:59 +0200514 def test_correct_detection_of_start_tags(self):
515 # see #13273
Ezio Melottif50ffa92011-10-28 13:21:09 +0300516 html = ('<div style="" ><b>The <a href="some_url">rain</a> '
517 '<br /> in <span>Spain</span></b></div>')
518 expected = [
519 ('starttag', 'div', [('style', '')]),
520 ('starttag', 'b', []),
521 ('data', 'The '),
522 ('starttag', 'a', [('href', 'some_url')]),
523 ('data', 'rain'),
524 ('endtag', 'a'),
525 ('data', ' '),
526 ('startendtag', 'br', []),
527 ('data', ' in '),
528 ('starttag', 'span', []),
529 ('data', 'Spain'),
530 ('endtag', 'span'),
531 ('endtag', 'b'),
532 ('endtag', 'div')
533 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200534 self._run_check(html, expected)
Ezio Melottif50ffa92011-10-28 13:21:09 +0300535
Ezio Melottif50ffa92011-10-28 13:21:09 +0300536 html = '<div style="", foo = "bar" ><b>The <a href="some_url">rain</a>'
537 expected = [
Ezio Melottic2fe5772011-11-14 18:53:33 +0200538 ('starttag', 'div', [('style', ''), (',', None), ('foo', 'bar')]),
Ezio Melottif50ffa92011-10-28 13:21:09 +0300539 ('starttag', 'b', []),
540 ('data', 'The '),
541 ('starttag', 'a', [('href', 'some_url')]),
542 ('data', 'rain'),
543 ('endtag', 'a'),
544 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200545 self._run_check(html, expected)
Ezio Melottif50ffa92011-10-28 13:21:09 +0300546
Ezio Melotti8e596a72013-05-01 16:18:25 +0300547 def test_EOF_in_charref(self):
548 # see #17802
549 # This test checks that the UnboundLocalError reported in the issue
550 # is not raised, however I'm not sure the returned values are correct.
551 # Maybe HTMLParser should use self.unescape for these
552 data = [
553 ('a&', [('data', 'a&')]),
554 ('a&b', [('data', 'ab')]),
555 ('a&b ', [('data', 'a'), ('entityref', 'b'), ('data', ' ')]),
556 ('a&b;', [('data', 'a'), ('entityref', 'b')]),
557 ]
558 for html, expected in data:
559 self._run_check(html, expected)
560
Senthil Kumaran164540f2010-12-28 15:55:16 +0000561 def test_unescape_function(self):
Ezio Melotti86f67122012-02-13 14:11:27 +0200562 p = self.get_collector()
Senthil Kumaran164540f2010-12-28 15:55:16 +0000563 self.assertEqual(p.unescape('&#bad;'),'&#bad;')
564 self.assertEqual(p.unescape('&#0038;'),'&')
Ezio Melottid9e0b062011-09-05 17:11:06 +0300565 # see #12888
566 self.assertEqual(p.unescape('&#123; ' * 1050), '{ ' * 1050)
Ezio Melotti46495182012-06-24 22:02:56 +0200567 # see #15156
568 self.assertEqual(p.unescape('&Eacuteric&Eacute;ric'
569 '&alphacentauri&alpha;centauri'),
570 'ÉricÉric&alphacentauriαcentauri')
571 self.assertEqual(p.unescape('&co;'), '&co;')
R. David Murrayb579dba2010-12-03 04:06:39 +0000572
Ezio Melottifa3702d2012-02-10 10:45:44 +0200573 def test_broken_comments(self):
574 html = ('<! not really a comment >'
575 '<! not a comment either -->'
576 '<! -- close enough -->'
Ezio Melottif4ab4912012-02-13 15:50:37 +0200577 '<!><!<-- this was an empty comment>'
Ezio Melottifa3702d2012-02-10 10:45:44 +0200578 '<!!! another bogus comment !!!>')
579 expected = [
580 ('comment', ' not really a comment '),
581 ('comment', ' not a comment either --'),
582 ('comment', ' -- close enough --'),
Ezio Melottif4ab4912012-02-13 15:50:37 +0200583 ('comment', ''),
584 ('comment', '<-- this was an empty comment'),
Ezio Melottifa3702d2012-02-10 10:45:44 +0200585 ('comment', '!! another bogus comment !!!'),
586 ]
587 self._run_check(html, expected)
588
Ezio Melotti62f3d032011-12-19 07:29:03 +0200589 def test_broken_condcoms(self):
590 # these condcoms are missing the '--' after '<!' and before the '>'
591 html = ('<![if !(IE)]>broken condcom<![endif]>'
592 '<![if ! IE]><link href="favicon.tiff"/><![endif]>'
593 '<![if !IE 6]><img src="firefox.png" /><![endif]>'
594 '<![if !ie 6]><b>foo</b><![endif]>'
595 '<![if (!IE)|(lt IE 9)]><img src="mammoth.bmp" /><![endif]>')
596 # According to the HTML5 specs sections "8.2.4.44 Bogus comment state"
597 # and "8.2.4.45 Markup declaration open state", comment tokens should
598 # be emitted instead of 'unknown decl', but calling unknown_decl
599 # provides more flexibility.
600 # See also Lib/_markupbase.py:parse_declaration
601 expected = [
602 ('unknown decl', 'if !(IE)'),
603 ('data', 'broken condcom'),
604 ('unknown decl', 'endif'),
605 ('unknown decl', 'if ! IE'),
606 ('startendtag', 'link', [('href', 'favicon.tiff')]),
607 ('unknown decl', 'endif'),
608 ('unknown decl', 'if !IE 6'),
609 ('startendtag', 'img', [('src', 'firefox.png')]),
610 ('unknown decl', 'endif'),
611 ('unknown decl', 'if !ie 6'),
612 ('starttag', 'b', []),
613 ('data', 'foo'),
614 ('endtag', 'b'),
615 ('unknown decl', 'endif'),
616 ('unknown decl', 'if (!IE)|(lt IE 9)'),
617 ('startendtag', 'img', [('src', 'mammoth.bmp')]),
618 ('unknown decl', 'endif')
619 ]
620 self._run_check(html, expected)
621
Ezio Melottic1e73c32011-11-01 18:57:15 +0200622
Ezio Melottib245ed12011-11-14 18:13:22 +0200623class AttributesStrictTestCase(TestCaseBase):
624
625 def get_collector(self):
Ezio Melotti3861d8b2012-06-23 15:27:51 +0200626 with support.check_warnings(("", DeprecationWarning), quite=False):
627 return EventCollector(strict=True)
Ezio Melottib245ed12011-11-14 18:13:22 +0200628
629 def test_attr_syntax(self):
630 output = [
631 ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", None)])
632 ]
633 self._run_check("""<a b='v' c="v" d=v e>""", output)
634 self._run_check("""<a b = 'v' c = "v" d = v e>""", output)
635 self._run_check("""<a\nb\n=\n'v'\nc\n=\n"v"\nd\n=\nv\ne>""", output)
636 self._run_check("""<a\tb\t=\t'v'\tc\t=\t"v"\td\t=\tv\te>""", output)
637
638 def test_attr_values(self):
639 self._run_check("""<a b='xxx\n\txxx' c="yyy\t\nyyy" d='\txyz\n'>""",
640 [("starttag", "a", [("b", "xxx\n\txxx"),
641 ("c", "yyy\t\nyyy"),
642 ("d", "\txyz\n")])])
643 self._run_check("""<a b='' c="">""",
644 [("starttag", "a", [("b", ""), ("c", "")])])
645 # Regression test for SF patch #669683.
646 self._run_check("<e a=rgb(1,2,3)>",
647 [("starttag", "e", [("a", "rgb(1,2,3)")])])
648 # Regression test for SF bug #921657.
649 self._run_check(
650 "<a href=mailto:xyz@example.com>",
651 [("starttag", "a", [("href", "mailto:xyz@example.com")])])
652
653 def test_attr_nonascii(self):
654 # see issue 7311
655 self._run_check(
656 "<img src=/foo/bar.png alt=\u4e2d\u6587>",
657 [("starttag", "img", [("src", "/foo/bar.png"),
658 ("alt", "\u4e2d\u6587")])])
659 self._run_check(
660 "<a title='\u30c6\u30b9\u30c8' href='\u30c6\u30b9\u30c8.html'>",
661 [("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
662 ("href", "\u30c6\u30b9\u30c8.html")])])
663 self._run_check(
664 '<a title="\u30c6\u30b9\u30c8" href="\u30c6\u30b9\u30c8.html">',
665 [("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
666 ("href", "\u30c6\u30b9\u30c8.html")])])
667
668 def test_attr_entity_replacement(self):
669 self._run_check(
670 "<a b='&amp;&gt;&lt;&quot;&apos;'>",
671 [("starttag", "a", [("b", "&><\"'")])])
672
673 def test_attr_funky_names(self):
674 self._run_check(
675 "<a a.b='v' c:d=v e-f=v>",
676 [("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")])])
677
678 def test_entityrefs_in_attributes(self):
679 self._run_check(
680 "<html foo='&euro;&amp;&#97;&#x61;&unsupported;'>",
681 [("starttag", "html", [("foo", "\u20AC&aa&unsupported;")])])
682
683
Ezio Melottic2fe5772011-11-14 18:53:33 +0200684
685class AttributesTolerantTestCase(AttributesStrictTestCase):
686
687 def get_collector(self):
688 return EventCollector(strict=False)
689
690 def test_attr_funky_names2(self):
691 self._run_check(
692 "<a $><b $=%><c \=/>",
693 [("starttag", "a", [("$", None)]),
694 ("starttag", "b", [("$", "%")]),
695 ("starttag", "c", [("\\", "/")])])
696
697 def test_entities_in_attribute_value(self):
698 # see #1200313
699 for entity in ['&', '&amp;', '&#38;', '&#x26;']:
700 self._run_check('<a href="%s">' % entity,
701 [("starttag", "a", [("href", "&")])])
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
707 def test_malformed_attributes(self):
708 # see #13357
709 html = (
710 "<a href=test'style='color:red;bad1'>test - bad1</a>"
711 "<a href=test'+style='color:red;ba2'>test - bad2</a>"
712 "<a href=test'&nbsp;style='color:red;bad3'>test - bad3</a>"
713 "<a href = test'&nbsp;style='color:red;bad4' >test - bad4</a>"
714 )
715 expected = [
716 ('starttag', 'a', [('href', "test'style='color:red;bad1'")]),
717 ('data', 'test - bad1'), ('endtag', 'a'),
718 ('starttag', 'a', [('href', "test'+style='color:red;ba2'")]),
719 ('data', 'test - bad2'), ('endtag', 'a'),
720 ('starttag', 'a', [('href', "test'\xa0style='color:red;bad3'")]),
721 ('data', 'test - bad3'), ('endtag', 'a'),
722 ('starttag', 'a', [('href', "test'\xa0style='color:red;bad4'")]),
723 ('data', 'test - bad4'), ('endtag', 'a')
724 ]
725 self._run_check(html, expected)
726
727 def test_malformed_adjacent_attributes(self):
728 # see #12629
729 self._run_check('<x><y z=""o"" /></x>',
730 [('starttag', 'x', []),
731 ('startendtag', 'y', [('z', ''), ('o""', None)]),
732 ('endtag', 'x')])
733 self._run_check('<x><y z="""" /></x>',
734 [('starttag', 'x', []),
735 ('startendtag', 'y', [('z', ''), ('""', None)]),
736 ('endtag', 'x')])
737
738 # see #755670 for the following 3 tests
739 def test_adjacent_attributes(self):
740 self._run_check('<a width="100%"cellspacing=0>',
741 [("starttag", "a",
742 [("width", "100%"), ("cellspacing","0")])])
743
744 self._run_check('<a id="foo"class="bar">',
745 [("starttag", "a",
746 [("id", "foo"), ("class","bar")])])
747
748 def test_missing_attribute_value(self):
749 self._run_check('<a v=>',
750 [("starttag", "a", [("v", "")])])
751
752 def test_javascript_attribute_value(self):
753 self._run_check("<a href=javascript:popup('/popup/help.html')>",
754 [("starttag", "a",
755 [("href", "javascript:popup('/popup/help.html')")])])
756
757 def test_end_tag_in_attribute_value(self):
758 # see #1745761
759 self._run_check("<a href='http://www.example.org/\">;'>spam</a>",
760 [("starttag", "a",
761 [("href", "http://www.example.org/\">;")]),
762 ("data", "spam"), ("endtag", "a")])
763
764
Fred Drakee8220492001-09-24 20:19:08 +0000765if __name__ == "__main__":
Ezio Melotti5028f4d2013-11-02 17:49:08 +0200766 unittest.main()