blob: 8863316a0f375d3d25720ebb5e519ae6b7c976ed [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='>")
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200234 self._parse_error("<a$>")
235 self._parse_error("<a$b>")
236 self._parse_error("<a$b/>")
237 self._parse_error("<a$b >")
238 self._parse_error("<a$b />")
Fred Drakebd3090d2001-05-18 15:32:59 +0000239
Ezio Melottif4ab4912012-02-13 15:50:37 +0200240 def test_valid_doctypes(self):
241 # from http://www.w3.org/QA/2002/04/valid-dtd-list.html
242 dtds = ['HTML', # HTML5 doctype
243 ('HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
244 '"http://www.w3.org/TR/html4/strict.dtd"'),
245 ('HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" '
246 '"http://www.w3.org/TR/html4/loose.dtd"'),
247 ('html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" '
248 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"'),
249 ('html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" '
250 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"'),
251 ('math PUBLIC "-//W3C//DTD MathML 2.0//EN" '
252 '"http://www.w3.org/Math/DTD/mathml2/mathml2.dtd"'),
253 ('html PUBLIC "-//W3C//DTD '
254 'XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" '
255 '"http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd"'),
256 ('svg PUBLIC "-//W3C//DTD SVG 1.1//EN" '
257 '"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"'),
258 'html PUBLIC "-//IETF//DTD HTML 2.0//EN"',
259 'html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"']
260 for dtd in dtds:
261 self._run_check("<!DOCTYPE %s>" % dtd,
262 [('decl', 'DOCTYPE ' + dtd)])
263
Fred Drake84bb9d82001-08-03 19:53:01 +0000264 def test_declaration_junk_chars(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000265 self._parse_error("<!DOCTYPE foo $ >")
266
Fred Drake84bb9d82001-08-03 19:53:01 +0000267 def test_startendtag(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000268 self._run_check("<p/>", [
269 ("startendtag", "p", []),
270 ])
271 self._run_check("<p></p>", [
272 ("starttag", "p", []),
273 ("endtag", "p"),
274 ])
275 self._run_check("<p><img src='foo' /></p>", [
276 ("starttag", "p", []),
277 ("startendtag", "img", [("src", "foo")]),
278 ("endtag", "p"),
279 ])
280
Fred Drake84bb9d82001-08-03 19:53:01 +0000281 def test_get_starttag_text(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000282 s = """<foo:bar \n one="1"\ttwo=2 >"""
283 self._run_check_extra(s, [
284 ("starttag", "foo:bar", [("one", "1"), ("two", "2")]),
285 ("starttag_text", s)])
286
Fred Drake84bb9d82001-08-03 19:53:01 +0000287 def test_cdata_content(self):
Ezio Melotti7de56f62011-11-01 14:12:22 +0200288 contents = [
289 '<!-- not a comment --> &not-an-entity-ref;',
290 "<not a='start tag'>",
291 '<a href="" /> <p> <span></span>',
292 'foo = "</scr" + "ipt>";',
293 'foo = "</SCRIPT" + ">";',
294 'foo = <\n/script> ',
295 '<!-- document.write("</scr" + "ipt>"); -->',
296 ('\n//<![CDATA[\n'
297 'document.write(\'<s\'+\'cript type="text/javascript" '
298 'src="http://www.example.org/r=\'+new '
299 'Date().getTime()+\'"><\\/s\'+\'cript>\');\n//]]>'),
300 '\n<!-- //\nvar foo = 3.14;\n// -->\n',
301 'foo = "</sty" + "le>";',
302 '<!-- \u2603 -->',
303 # these two should be invalid according to the HTML 5 spec,
304 # section 8.1.2.2
305 #'foo = </\nscript>',
306 #'foo = </ script>',
307 ]
308 elements = ['script', 'style', 'SCRIPT', 'STYLE', 'Script', 'Style']
309 for content in contents:
310 for element in elements:
311 element_lower = element.lower()
312 s = '<{element}>{content}</{element}>'.format(element=element,
313 content=content)
314 self._run_check(s, [("starttag", element_lower, []),
315 ("data", content),
316 ("endtag", element_lower)])
317
Ezio Melotti15cb4892011-11-18 18:01:49 +0200318 def test_cdata_with_closing_tags(self):
319 # see issue #13358
320 # make sure that HTMLParser calls handle_data only once for each CDATA.
321 # The normal event collector normalizes the events in get_events,
322 # so we override it to return the original list of events.
323 class Collector(EventCollector):
324 def get_events(self):
325 return self.events
Fred Drakebd3090d2001-05-18 15:32:59 +0000326
Ezio Melotti15cb4892011-11-18 18:01:49 +0200327 content = """<!-- not a comment --> &not-an-entity-ref;
328 <a href="" /> </p><p> <span></span></style>
329 '</script' + '>'"""
330 for element in [' script', 'script ', ' script ',
331 '\nscript', 'script\n', '\nscript\n']:
332 element_lower = element.lower().strip()
333 s = '<script>{content}</{element}>'.format(element=element,
334 content=content)
335 self._run_check(s, [("starttag", element_lower, []),
336 ("data", content),
337 ("endtag", element_lower)],
338 collector=Collector())
Fred Drakebd3090d2001-05-18 15:32:59 +0000339
Ezio Melottifa3702d2012-02-10 10:45:44 +0200340 def test_comments(self):
341 html = ("<!-- I'm a valid comment -->"
342 '<!--me too!-->'
343 '<!------>'
344 '<!---->'
345 '<!----I have many hyphens---->'
346 '<!-- I have a > in the middle -->'
347 '<!-- and I have -- in the middle! -->')
348 expected = [('comment', " I'm a valid comment "),
349 ('comment', 'me too!'),
350 ('comment', '--'),
351 ('comment', ''),
352 ('comment', '--I have many hyphens--'),
353 ('comment', ' I have a > in the middle '),
354 ('comment', ' and I have -- in the middle! ')]
355 self._run_check(html, expected)
356
Ezio Melotti62f3d032011-12-19 07:29:03 +0200357 def test_condcoms(self):
358 html = ('<!--[if IE & !(lte IE 8)]>aren\'t<![endif]-->'
359 '<!--[if IE 8]>condcoms<![endif]-->'
360 '<!--[if lte IE 7]>pretty?<![endif]-->')
361 expected = [('comment', "[if IE & !(lte IE 8)]>aren't<![endif]"),
362 ('comment', '[if IE 8]>condcoms<![endif]'),
363 ('comment', '[if lte IE 7]>pretty?<![endif]')]
364 self._run_check(html, expected)
365
366
Ezio Melottic1e73c32011-11-01 18:57:15 +0200367class HTMLParserTolerantTestCase(HTMLParserStrictTestCase):
R. David Murrayb579dba2010-12-03 04:06:39 +0000368
Ezio Melottib9a48f72011-11-01 15:00:59 +0200369 def get_collector(self):
Ezio Melotti88ebfb12013-11-02 17:08:24 +0200370 return EventCollector()
371
372 def test_deprecation_warnings(self):
373 with self.assertWarns(DeprecationWarning):
374 EventCollector(strict=True)
375 with self.assertWarns(DeprecationWarning):
376 EventCollector(strict=False)
377 with self.assertRaises(html.parser.HTMLParseError):
378 with self.assertWarns(DeprecationWarning):
379 EventCollector().error('test')
R. David Murrayb579dba2010-12-03 04:06:39 +0000380
381 def test_tolerant_parsing(self):
382 self._run_check('<html <html>te>>xt&a<<bc</a></html>\n'
383 '<img src="URL><//img></html</html>', [
Ezio Melottic2fe5772011-11-14 18:53:33 +0200384 ('starttag', 'html', [('<html', None)]),
385 ('data', 'te>>xt'),
386 ('entityref', 'a'),
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200387 ('data', '<'),
388 ('starttag', 'bc<', [('a', None)]),
Ezio Melottic2fe5772011-11-14 18:53:33 +0200389 ('endtag', 'html'),
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200390 ('data', '\n<img src="URL>'),
391 ('comment', '/img'),
392 ('endtag', 'html<')])
R. David Murrayb579dba2010-12-03 04:06:39 +0000393
Ezio Melotti86f67122012-02-13 14:11:27 +0200394 def test_starttag_junk_chars(self):
395 self._run_check("</>", [])
396 self._run_check("</$>", [('comment', '$')])
397 self._run_check("</", [('data', '</')])
398 self._run_check("</a", [('data', '</a')])
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200399 self._run_check("<a<a>", [('starttag', 'a<a', [])])
Ezio Melotti86f67122012-02-13 14:11:27 +0200400 self._run_check("</a<a>", [('endtag', 'a<a')])
401 self._run_check("<!", [('data', '<!')])
402 self._run_check("<a", [('data', '<a')])
403 self._run_check("<a foo='bar'", [('data', "<a foo='bar'")])
404 self._run_check("<a foo='bar", [('data', "<a foo='bar")])
405 self._run_check("<a foo='>'", [('data', "<a foo='>'")])
406 self._run_check("<a foo='>", [('data', "<a foo='>")])
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200407 self._run_check("<a$>", [('starttag', 'a$', [])])
408 self._run_check("<a$b>", [('starttag', 'a$b', [])])
409 self._run_check("<a$b/>", [('startendtag', 'a$b', [])])
410 self._run_check("<a$b >", [('starttag', 'a$b', [])])
411 self._run_check("<a$b />", [('startendtag', 'a$b', [])])
Ezio Melotti86f67122012-02-13 14:11:27 +0200412
Ezio Melotti29877e82012-02-21 09:25:00 +0200413 def test_slashes_in_starttag(self):
414 self._run_check('<a foo="var"/>', [('startendtag', 'a', [('foo', 'var')])])
415 html = ('<img width=902 height=250px '
416 'src="/sites/default/files/images/homepage/foo.jpg" '
417 '/*what am I doing here*/ />')
418 expected = [(
419 'startendtag', 'img',
420 [('width', '902'), ('height', '250px'),
421 ('src', '/sites/default/files/images/homepage/foo.jpg'),
422 ('*what', None), ('am', None), ('i', None),
423 ('doing', None), ('here*', None)]
424 )]
425 self._run_check(html, expected)
426 html = ('<a / /foo/ / /=/ / /bar/ / />'
427 '<a / /foo/ / /=/ / /bar/ / >')
428 expected = [
429 ('startendtag', 'a', [('foo', None), ('=', None), ('bar', None)]),
430 ('starttag', 'a', [('foo', None), ('=', None), ('bar', None)])
431 ]
432 self._run_check(html, expected)
Ezio Melotti0780b6b2012-04-18 19:18:22 -0600433 #see issue #14538
434 html = ('<meta><meta / ><meta // ><meta / / >'
435 '<meta/><meta /><meta //><meta//>')
436 expected = [
437 ('starttag', 'meta', []), ('starttag', 'meta', []),
438 ('starttag', 'meta', []), ('starttag', 'meta', []),
439 ('startendtag', 'meta', []), ('startendtag', 'meta', []),
440 ('startendtag', 'meta', []), ('startendtag', 'meta', []),
441 ]
442 self._run_check(html, expected)
Ezio Melotti29877e82012-02-21 09:25:00 +0200443
Ezio Melotti86f67122012-02-13 14:11:27 +0200444 def test_declaration_junk_chars(self):
Ezio Melottif4ab4912012-02-13 15:50:37 +0200445 self._run_check("<!DOCTYPE foo $ >", [('decl', 'DOCTYPE foo $ ')])
Ezio Melotti86f67122012-02-13 14:11:27 +0200446
447 def test_illegal_declarations(self):
Ezio Melotti86f67122012-02-13 14:11:27 +0200448 self._run_check('<!spacer type="block" height="25">',
449 [('comment', 'spacer type="block" height="25"')])
450
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200451 def test_with_unquoted_attributes(self):
Ezio Melottib9a48f72011-11-01 15:00:59 +0200452 # see #12008
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200453 html = ("<html><body bgcolor=d0ca90 text='181008'>"
454 "<table cellspacing=0 cellpadding=1 width=100% ><tr>"
455 "<td align=left><font size=-1>"
456 "- <a href=/rabota/><span class=en> software-and-i</span></a>"
457 "- <a href='/1/'><span class=en> library</span></a></table>")
458 expected = [
459 ('starttag', 'html', []),
460 ('starttag', 'body', [('bgcolor', 'd0ca90'), ('text', '181008')]),
461 ('starttag', 'table',
462 [('cellspacing', '0'), ('cellpadding', '1'), ('width', '100%')]),
463 ('starttag', 'tr', []),
464 ('starttag', 'td', [('align', 'left')]),
465 ('starttag', 'font', [('size', '-1')]),
466 ('data', '- '), ('starttag', 'a', [('href', '/rabota/')]),
467 ('starttag', 'span', [('class', 'en')]), ('data', ' software-and-i'),
468 ('endtag', 'span'), ('endtag', 'a'),
469 ('data', '- '), ('starttag', 'a', [('href', '/1/')]),
470 ('starttag', 'span', [('class', 'en')]), ('data', ' library'),
471 ('endtag', 'span'), ('endtag', 'a'), ('endtag', 'table')
472 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200473 self._run_check(html, expected)
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200474
R. David Murrayb579dba2010-12-03 04:06:39 +0000475 def test_comma_between_attributes(self):
476 self._run_check('<form action="/xxx.php?a=1&amp;b=2&amp", '
477 'method="post">', [
478 ('starttag', 'form',
Ezio Melotti46495182012-06-24 22:02:56 +0200479 [('action', '/xxx.php?a=1&b=2&'),
Ezio Melottic2fe5772011-11-14 18:53:33 +0200480 (',', None), ('method', 'post')])])
R. David Murrayb579dba2010-12-03 04:06:39 +0000481
482 def test_weird_chars_in_unquoted_attribute_values(self):
483 self._run_check('<form action=bogus|&#()value>', [
484 ('starttag', 'form',
Ezio Melottic1e73c32011-11-01 18:57:15 +0200485 [('action', 'bogus|&#()value')])])
R. David Murrayb579dba2010-12-03 04:06:39 +0000486
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200487 def test_invalid_end_tags(self):
488 # A collection of broken end tags. <br> is used as separator.
489 # see http://www.w3.org/TR/html5/tokenization.html#end-tag-open-state
490 # and #13993
491 html = ('<br></label</p><br></div end tmAd-leaderBoard><br></<h4><br>'
492 '</li class="unit"><br></li\r\n\t\t\t\t\t\t</ul><br></><br>')
493 expected = [('starttag', 'br', []),
494 # < is part of the name, / is discarded, p is an attribute
495 ('endtag', 'label<'),
496 ('starttag', 'br', []),
497 # text and attributes are discarded
498 ('endtag', 'div'),
499 ('starttag', 'br', []),
500 # comment because the first char after </ is not a-zA-Z
501 ('comment', '<h4'),
502 ('starttag', 'br', []),
503 # attributes are discarded
504 ('endtag', 'li'),
505 ('starttag', 'br', []),
506 # everything till ul (included) is discarded
507 ('endtag', 'li'),
508 ('starttag', 'br', []),
509 # </> is ignored
510 ('starttag', 'br', [])]
511 self._run_check(html, expected)
512
513 def test_broken_invalid_end_tag(self):
514 # This is technically wrong (the "> shouldn't be included in the 'data')
515 # but is probably not worth fixing it (in addition to all the cases of
516 # the previous test, it would require a full attribute parsing).
517 # see #13993
518 html = '<b>This</b attr=">"> confuses the parser'
519 expected = [('starttag', 'b', []),
520 ('data', 'This'),
521 ('endtag', 'b'),
522 ('data', '"> confuses the parser')]
523 self._run_check(html, expected)
524
Ezio Melottib9a48f72011-11-01 15:00:59 +0200525 def test_correct_detection_of_start_tags(self):
526 # see #13273
Ezio Melottif50ffa92011-10-28 13:21:09 +0300527 html = ('<div style="" ><b>The <a href="some_url">rain</a> '
528 '<br /> in <span>Spain</span></b></div>')
529 expected = [
530 ('starttag', 'div', [('style', '')]),
531 ('starttag', 'b', []),
532 ('data', 'The '),
533 ('starttag', 'a', [('href', 'some_url')]),
534 ('data', 'rain'),
535 ('endtag', 'a'),
536 ('data', ' '),
537 ('startendtag', 'br', []),
538 ('data', ' in '),
539 ('starttag', 'span', []),
540 ('data', 'Spain'),
541 ('endtag', 'span'),
542 ('endtag', 'b'),
543 ('endtag', 'div')
544 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200545 self._run_check(html, expected)
Ezio Melottif50ffa92011-10-28 13:21:09 +0300546
Ezio Melottif50ffa92011-10-28 13:21:09 +0300547 html = '<div style="", foo = "bar" ><b>The <a href="some_url">rain</a>'
548 expected = [
Ezio Melottic2fe5772011-11-14 18:53:33 +0200549 ('starttag', 'div', [('style', ''), (',', None), ('foo', 'bar')]),
Ezio Melottif50ffa92011-10-28 13:21:09 +0300550 ('starttag', 'b', []),
551 ('data', 'The '),
552 ('starttag', 'a', [('href', 'some_url')]),
553 ('data', 'rain'),
554 ('endtag', 'a'),
555 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200556 self._run_check(html, expected)
Ezio Melottif50ffa92011-10-28 13:21:09 +0300557
Ezio Melotti8e596a72013-05-01 16:18:25 +0300558 def test_EOF_in_charref(self):
559 # see #17802
560 # This test checks that the UnboundLocalError reported in the issue
561 # is not raised, however I'm not sure the returned values are correct.
562 # Maybe HTMLParser should use self.unescape for these
563 data = [
564 ('a&', [('data', 'a&')]),
565 ('a&b', [('data', 'ab')]),
566 ('a&b ', [('data', 'a'), ('entityref', 'b'), ('data', ' ')]),
567 ('a&b;', [('data', 'a'), ('entityref', 'b')]),
568 ]
569 for html, expected in data:
570 self._run_check(html, expected)
571
Senthil Kumaran164540f2010-12-28 15:55:16 +0000572 def test_unescape_function(self):
Ezio Melotti86f67122012-02-13 14:11:27 +0200573 p = self.get_collector()
Senthil Kumaran164540f2010-12-28 15:55:16 +0000574 self.assertEqual(p.unescape('&#bad;'),'&#bad;')
575 self.assertEqual(p.unescape('&#0038;'),'&')
Ezio Melottid9e0b062011-09-05 17:11:06 +0300576 # see #12888
577 self.assertEqual(p.unescape('&#123; ' * 1050), '{ ' * 1050)
Ezio Melotti46495182012-06-24 22:02:56 +0200578 # see #15156
579 self.assertEqual(p.unescape('&Eacuteric&Eacute;ric'
580 '&alphacentauri&alpha;centauri'),
581 'ÉricÉric&alphacentauriαcentauri')
582 self.assertEqual(p.unescape('&co;'), '&co;')
R. David Murrayb579dba2010-12-03 04:06:39 +0000583
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 Melottic1e73c32011-11-01 18:57:15 +0200633
Ezio Melottib245ed12011-11-14 18:13:22 +0200634class AttributesStrictTestCase(TestCaseBase):
635
636 def get_collector(self):
Ezio Melotti3861d8b2012-06-23 15:27:51 +0200637 with support.check_warnings(("", DeprecationWarning), quite=False):
638 return EventCollector(strict=True)
Ezio Melottib245ed12011-11-14 18:13:22 +0200639
640 def test_attr_syntax(self):
641 output = [
642 ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", None)])
643 ]
644 self._run_check("""<a b='v' c="v" d=v e>""", output)
645 self._run_check("""<a b = 'v' c = "v" d = v e>""", output)
646 self._run_check("""<a\nb\n=\n'v'\nc\n=\n"v"\nd\n=\nv\ne>""", output)
647 self._run_check("""<a\tb\t=\t'v'\tc\t=\t"v"\td\t=\tv\te>""", output)
648
649 def test_attr_values(self):
650 self._run_check("""<a b='xxx\n\txxx' c="yyy\t\nyyy" d='\txyz\n'>""",
651 [("starttag", "a", [("b", "xxx\n\txxx"),
652 ("c", "yyy\t\nyyy"),
653 ("d", "\txyz\n")])])
654 self._run_check("""<a b='' c="">""",
655 [("starttag", "a", [("b", ""), ("c", "")])])
656 # Regression test for SF patch #669683.
657 self._run_check("<e a=rgb(1,2,3)>",
658 [("starttag", "e", [("a", "rgb(1,2,3)")])])
659 # Regression test for SF bug #921657.
660 self._run_check(
661 "<a href=mailto:xyz@example.com>",
662 [("starttag", "a", [("href", "mailto:xyz@example.com")])])
663
664 def test_attr_nonascii(self):
665 # see issue 7311
666 self._run_check(
667 "<img src=/foo/bar.png alt=\u4e2d\u6587>",
668 [("starttag", "img", [("src", "/foo/bar.png"),
669 ("alt", "\u4e2d\u6587")])])
670 self._run_check(
671 "<a title='\u30c6\u30b9\u30c8' href='\u30c6\u30b9\u30c8.html'>",
672 [("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
673 ("href", "\u30c6\u30b9\u30c8.html")])])
674 self._run_check(
675 '<a title="\u30c6\u30b9\u30c8" href="\u30c6\u30b9\u30c8.html">',
676 [("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
677 ("href", "\u30c6\u30b9\u30c8.html")])])
678
679 def test_attr_entity_replacement(self):
680 self._run_check(
681 "<a b='&amp;&gt;&lt;&quot;&apos;'>",
682 [("starttag", "a", [("b", "&><\"'")])])
683
684 def test_attr_funky_names(self):
685 self._run_check(
686 "<a a.b='v' c:d=v e-f=v>",
687 [("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")])])
688
689 def test_entityrefs_in_attributes(self):
690 self._run_check(
691 "<html foo='&euro;&amp;&#97;&#x61;&unsupported;'>",
692 [("starttag", "html", [("foo", "\u20AC&aa&unsupported;")])])
693
694
Ezio Melottic2fe5772011-11-14 18:53:33 +0200695
696class AttributesTolerantTestCase(AttributesStrictTestCase):
697
698 def get_collector(self):
Ezio Melotti88ebfb12013-11-02 17:08:24 +0200699 return EventCollector()
Ezio Melottic2fe5772011-11-14 18:53:33 +0200700
701 def test_attr_funky_names2(self):
702 self._run_check(
703 "<a $><b $=%><c \=/>",
704 [("starttag", "a", [("$", None)]),
705 ("starttag", "b", [("$", "%")]),
706 ("starttag", "c", [("\\", "/")])])
707
708 def test_entities_in_attribute_value(self):
709 # see #1200313
710 for entity in ['&', '&amp;', '&#38;', '&#x26;']:
711 self._run_check('<a href="%s">' % entity,
712 [("starttag", "a", [("href", "&")])])
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
718 def test_malformed_attributes(self):
719 # see #13357
720 html = (
721 "<a href=test'style='color:red;bad1'>test - bad1</a>"
722 "<a href=test'+style='color:red;ba2'>test - bad2</a>"
723 "<a href=test'&nbsp;style='color:red;bad3'>test - bad3</a>"
724 "<a href = test'&nbsp;style='color:red;bad4' >test - bad4</a>"
725 )
726 expected = [
727 ('starttag', 'a', [('href', "test'style='color:red;bad1'")]),
728 ('data', 'test - bad1'), ('endtag', 'a'),
729 ('starttag', 'a', [('href', "test'+style='color:red;ba2'")]),
730 ('data', 'test - bad2'), ('endtag', 'a'),
731 ('starttag', 'a', [('href', "test'\xa0style='color:red;bad3'")]),
732 ('data', 'test - bad3'), ('endtag', 'a'),
733 ('starttag', 'a', [('href', "test'\xa0style='color:red;bad4'")]),
734 ('data', 'test - bad4'), ('endtag', 'a')
735 ]
736 self._run_check(html, expected)
737
738 def test_malformed_adjacent_attributes(self):
739 # see #12629
740 self._run_check('<x><y z=""o"" /></x>',
741 [('starttag', 'x', []),
742 ('startendtag', 'y', [('z', ''), ('o""', None)]),
743 ('endtag', 'x')])
744 self._run_check('<x><y z="""" /></x>',
745 [('starttag', 'x', []),
746 ('startendtag', 'y', [('z', ''), ('""', None)]),
747 ('endtag', 'x')])
748
749 # see #755670 for the following 3 tests
750 def test_adjacent_attributes(self):
751 self._run_check('<a width="100%"cellspacing=0>',
752 [("starttag", "a",
753 [("width", "100%"), ("cellspacing","0")])])
754
755 self._run_check('<a id="foo"class="bar">',
756 [("starttag", "a",
757 [("id", "foo"), ("class","bar")])])
758
759 def test_missing_attribute_value(self):
760 self._run_check('<a v=>',
761 [("starttag", "a", [("v", "")])])
762
763 def test_javascript_attribute_value(self):
764 self._run_check("<a href=javascript:popup('/popup/help.html')>",
765 [("starttag", "a",
766 [("href", "javascript:popup('/popup/help.html')")])])
767
768 def test_end_tag_in_attribute_value(self):
769 # see #1745761
770 self._run_check("<a href='http://www.example.org/\">;'>spam</a>",
771 [("starttag", "a",
772 [("href", "http://www.example.org/\">;")]),
773 ("data", "spam"), ("endtag", "a")])
774
775
Fred Drakee8220492001-09-24 20:19:08 +0000776if __name__ == "__main__":
Ezio Melotti5028f4d2013-11-02 17:49:08 +0200777 unittest.main()