blob: 2d771a2a974c572cf05c1dbeeb42c9ec68c54a18 [file] [log] [blame]
Fred Drakebd3090d2001-05-18 15:32:59 +00001"""Tests for HTMLParser.py."""
2
Mark Dickinsonf64dcf32008-05-21 13:51:18 +00003import html.parser
Fred Drake029acfb2001-08-20 21:24:19 +00004import pprint
Fred Drakebd3090d2001-05-18 15:32:59 +00005import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00006from test import support
Fred Drakebd3090d2001-05-18 15:32:59 +00007
8
Mark Dickinsonf64dcf32008-05-21 13:51:18 +00009class EventCollector(html.parser.HTMLParser):
Fred Drakebd3090d2001-05-18 15:32:59 +000010
R. David Murrayb579dba2010-12-03 04:06:39 +000011 def __init__(self, *args, **kw):
Fred Drakebd3090d2001-05-18 15:32:59 +000012 self.events = []
13 self.append = self.events.append
R. David Murrayb579dba2010-12-03 04:06:39 +000014 html.parser.HTMLParser.__init__(self, *args, **kw)
Fred Drakebd3090d2001-05-18 15:32:59 +000015
16 def get_events(self):
17 # Normalize the list of events so that buffer artefacts don't
18 # separate runs of contiguous characters.
19 L = []
20 prevtype = None
21 for event in self.events:
22 type = event[0]
23 if type == prevtype == "data":
24 L[-1] = ("data", L[-1][1] + event[1])
25 else:
26 L.append(event)
27 prevtype = type
28 self.events = L
29 return L
30
31 # structure markup
32
33 def handle_starttag(self, tag, attrs):
34 self.append(("starttag", tag, attrs))
35
36 def handle_startendtag(self, tag, attrs):
37 self.append(("startendtag", tag, attrs))
38
39 def handle_endtag(self, tag):
40 self.append(("endtag", tag))
41
42 # all other markup
43
44 def handle_comment(self, data):
45 self.append(("comment", data))
46
47 def handle_charref(self, data):
48 self.append(("charref", data))
49
50 def handle_data(self, data):
51 self.append(("data", data))
52
53 def handle_decl(self, data):
54 self.append(("decl", data))
55
56 def handle_entityref(self, data):
57 self.append(("entityref", data))
58
59 def handle_pi(self, data):
60 self.append(("pi", data))
61
Fred Drakec20a6982001-09-04 15:13:04 +000062 def unknown_decl(self, decl):
63 self.append(("unknown decl", decl))
64
Fred Drakebd3090d2001-05-18 15:32:59 +000065
66class EventCollectorExtra(EventCollector):
67
68 def handle_starttag(self, tag, attrs):
69 EventCollector.handle_starttag(self, tag, attrs)
70 self.append(("starttag_text", self.get_starttag_text()))
71
72
Ezio Melotti95401c52013-11-23 19:52:05 +020073class EventCollectorCharrefs(EventCollector):
74
75 def get_events(self):
76 return self.events
77
78 def handle_charref(self, data):
79 self.fail('This should never be called with convert_charrefs=True')
80
81 def handle_entityref(self, data):
82 self.fail('This should never be called with convert_charrefs=True')
83
84
Fred Drakebd3090d2001-05-18 15:32:59 +000085class TestCaseBase(unittest.TestCase):
86
Ezio Melottic1e73c32011-11-01 18:57:15 +020087 def get_collector(self):
88 raise NotImplementedError
89
R. David Murrayb579dba2010-12-03 04:06:39 +000090 def _run_check(self, source, expected_events, collector=None):
91 if collector is None:
Ezio Melottic1e73c32011-11-01 18:57:15 +020092 collector = self.get_collector()
R. David Murrayb579dba2010-12-03 04:06:39 +000093 parser = collector
Fred Drakebd3090d2001-05-18 15:32:59 +000094 for s in source:
95 parser.feed(s)
Fred Drakebd3090d2001-05-18 15:32:59 +000096 parser.close()
Fred Drake029acfb2001-08-20 21:24:19 +000097 events = parser.get_events()
Fred Drakec20a6982001-09-04 15:13:04 +000098 if events != expected_events:
Ezio Melotti95401c52013-11-23 19:52:05 +020099 self.fail("received events did not match expected events" +
100 "\nSource:\n" + repr(source) +
101 "\nExpected:\n" + pprint.pformat(expected_events) +
Fred Drakec20a6982001-09-04 15:13:04 +0000102 "\nReceived:\n" + pprint.pformat(events))
Fred Drakebd3090d2001-05-18 15:32:59 +0000103
104 def _run_check_extra(self, source, events):
Ezio Melotti95401c52013-11-23 19:52:05 +0200105 self._run_check(source, events,
106 EventCollectorExtra(convert_charrefs=False))
Fred Drakebd3090d2001-05-18 15:32:59 +0000107
108 def _parse_error(self, source):
109 def parse(source=source):
Ezio Melotti86f67122012-02-13 14:11:27 +0200110 parser = self.get_collector()
Fred Drakebd3090d2001-05-18 15:32:59 +0000111 parser.feed(source)
112 parser.close()
Ezio Melotti88ebfb12013-11-02 17:08:24 +0200113 with self.assertRaises(html.parser.HTMLParseError):
114 with self.assertWarns(DeprecationWarning):
115 parse()
Fred Drakebd3090d2001-05-18 15:32:59 +0000116
117
Ezio Melottic1e73c32011-11-01 18:57:15 +0200118class HTMLParserStrictTestCase(TestCaseBase):
119
120 def get_collector(self):
Ezio Melotti3861d8b2012-06-23 15:27:51 +0200121 with support.check_warnings(("", DeprecationWarning), quite=False):
Ezio Melotti95401c52013-11-23 19:52:05 +0200122 return EventCollector(strict=True, convert_charrefs=False)
Fred Drakebd3090d2001-05-18 15:32:59 +0000123
Fred Drake84bb9d82001-08-03 19:53:01 +0000124 def test_processing_instruction_only(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000125 self._run_check("<?processing instruction>", [
126 ("pi", "processing instruction"),
127 ])
Fred Drakefafd56f2003-04-17 22:19:26 +0000128 self._run_check("<?processing instruction ?>", [
129 ("pi", "processing instruction ?"),
130 ])
Fred Drakebd3090d2001-05-18 15:32:59 +0000131
Fred Drake84bb9d82001-08-03 19:53:01 +0000132 def test_simple_html(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000133 self._run_check("""
134<!DOCTYPE html PUBLIC 'foo'>
135<HTML>&entity;&#32;
136<!--comment1a
137-></foo><bar>&lt;<?pi?></foo<bar
138comment1b-->
139<Img sRc='Bar' isMAP>sample
140text
Fred Drake84bb9d82001-08-03 19:53:01 +0000141&#x201C;
Ezio Melottif4ab4912012-02-13 15:50:37 +0200142<!--comment2a-- --comment2b-->
Fred Drakebd3090d2001-05-18 15:32:59 +0000143</Html>
144""", [
145 ("data", "\n"),
146 ("decl", "DOCTYPE html PUBLIC 'foo'"),
147 ("data", "\n"),
148 ("starttag", "html", []),
149 ("entityref", "entity"),
150 ("charref", "32"),
151 ("data", "\n"),
152 ("comment", "comment1a\n-></foo><bar>&lt;<?pi?></foo<bar\ncomment1b"),
153 ("data", "\n"),
154 ("starttag", "img", [("src", "Bar"), ("ismap", None)]),
155 ("data", "sample\ntext\n"),
Fred Drake84bb9d82001-08-03 19:53:01 +0000156 ("charref", "x201C"),
157 ("data", "\n"),
Fred Drakebd3090d2001-05-18 15:32:59 +0000158 ("comment", "comment2a-- --comment2b"),
159 ("data", "\n"),
160 ("endtag", "html"),
161 ("data", "\n"),
162 ])
163
Victor Stinnere021f4b2010-05-24 21:46:25 +0000164 def test_malformatted_charref(self):
165 self._run_check("<p>&#bad;</p>", [
166 ("starttag", "p", []),
167 ("data", "&#bad;"),
168 ("endtag", "p"),
169 ])
Ezio Melottif27b9a72014-02-01 21:21:01 +0200170 # add the [] as a workaround to avoid buffering (see #20288)
171 self._run_check(["<div>&#bad;</div>"], [
172 ("starttag", "div", []),
173 ("data", "&#bad;"),
174 ("endtag", "div"),
175 ])
Victor Stinnere021f4b2010-05-24 21:46:25 +0000176
Fred Drake073148c2001-12-03 16:44:09 +0000177 def test_unclosed_entityref(self):
178 self._run_check("&entityref foo", [
179 ("entityref", "entityref"),
180 ("data", " foo"),
181 ])
182
Fred Drake84bb9d82001-08-03 19:53:01 +0000183 def test_bad_nesting(self):
184 # Strangely, this *is* supposed to test that overlapping
185 # elements are allowed. HTMLParser is more geared toward
186 # lexing the input that parsing the structure.
Fred Drakebd3090d2001-05-18 15:32:59 +0000187 self._run_check("<a><b></a></b>", [
188 ("starttag", "a", []),
189 ("starttag", "b", []),
190 ("endtag", "a"),
191 ("endtag", "b"),
192 ])
193
Fred Drake029acfb2001-08-20 21:24:19 +0000194 def test_bare_ampersands(self):
195 self._run_check("this text & contains & ampersands &", [
196 ("data", "this text & contains & ampersands &"),
197 ])
198
199 def test_bare_pointy_brackets(self):
200 self._run_check("this < text > contains < bare>pointy< brackets", [
201 ("data", "this < text > contains < bare>pointy< brackets"),
202 ])
203
Fred Drakec20a6982001-09-04 15:13:04 +0000204 def test_illegal_declarations(self):
Fred Drake7cf613d2001-09-04 16:26:03 +0000205 self._parse_error('<!spacer type="block" height="25">')
Fred Drakec20a6982001-09-04 15:13:04 +0000206
Fred Drake84bb9d82001-08-03 19:53:01 +0000207 def test_starttag_end_boundary(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000208 self._run_check("""<a b='<'>""", [("starttag", "a", [("b", "<")])])
209 self._run_check("""<a b='>'>""", [("starttag", "a", [("b", ">")])])
210
Fred Drake84bb9d82001-08-03 19:53:01 +0000211 def test_buffer_artefacts(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000212 output = [("starttag", "a", [("b", "<")])]
213 self._run_check(["<a b='<'>"], output)
214 self._run_check(["<a ", "b='<'>"], output)
215 self._run_check(["<a b", "='<'>"], output)
216 self._run_check(["<a b=", "'<'>"], output)
217 self._run_check(["<a b='<", "'>"], output)
218 self._run_check(["<a b='<'", ">"], output)
219
220 output = [("starttag", "a", [("b", ">")])]
221 self._run_check(["<a b='>'>"], output)
222 self._run_check(["<a ", "b='>'>"], output)
223 self._run_check(["<a b", "='>'>"], output)
224 self._run_check(["<a b=", "'>'>"], output)
225 self._run_check(["<a b='>", "'>"], output)
226 self._run_check(["<a b='>'", ">"], output)
227
Fred Drake75d9a622004-09-08 22:57:01 +0000228 output = [("comment", "abc")]
229 self._run_check(["", "<!--abc-->"], output)
230 self._run_check(["<", "!--abc-->"], output)
231 self._run_check(["<!", "--abc-->"], output)
232 self._run_check(["<!-", "-abc-->"], output)
233 self._run_check(["<!--", "abc-->"], output)
234 self._run_check(["<!--a", "bc-->"], output)
235 self._run_check(["<!--ab", "c-->"], output)
236 self._run_check(["<!--abc", "-->"], output)
237 self._run_check(["<!--abc-", "->"], output)
238 self._run_check(["<!--abc--", ">"], output)
239 self._run_check(["<!--abc-->", ""], output)
240
Fred Drake84bb9d82001-08-03 19:53:01 +0000241 def test_starttag_junk_chars(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000242 self._parse_error("</>")
243 self._parse_error("</$>")
244 self._parse_error("</")
245 self._parse_error("</a")
Fred Drakebd3090d2001-05-18 15:32:59 +0000246 self._parse_error("<a<a>")
247 self._parse_error("</a<a>")
Fred Drakebd3090d2001-05-18 15:32:59 +0000248 self._parse_error("<!")
Fred Drakebd3090d2001-05-18 15:32:59 +0000249 self._parse_error("<a")
250 self._parse_error("<a foo='bar'")
251 self._parse_error("<a foo='bar")
252 self._parse_error("<a foo='>'")
253 self._parse_error("<a foo='>")
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200254 self._parse_error("<a$>")
255 self._parse_error("<a$b>")
256 self._parse_error("<a$b/>")
257 self._parse_error("<a$b >")
258 self._parse_error("<a$b />")
Fred Drakebd3090d2001-05-18 15:32:59 +0000259
Ezio Melottif4ab4912012-02-13 15:50:37 +0200260 def test_valid_doctypes(self):
261 # from http://www.w3.org/QA/2002/04/valid-dtd-list.html
262 dtds = ['HTML', # HTML5 doctype
263 ('HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
264 '"http://www.w3.org/TR/html4/strict.dtd"'),
265 ('HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" '
266 '"http://www.w3.org/TR/html4/loose.dtd"'),
267 ('html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" '
268 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"'),
269 ('html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" '
270 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"'),
271 ('math PUBLIC "-//W3C//DTD MathML 2.0//EN" '
272 '"http://www.w3.org/Math/DTD/mathml2/mathml2.dtd"'),
273 ('html PUBLIC "-//W3C//DTD '
274 'XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" '
275 '"http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd"'),
276 ('svg PUBLIC "-//W3C//DTD SVG 1.1//EN" '
277 '"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"'),
278 'html PUBLIC "-//IETF//DTD HTML 2.0//EN"',
279 'html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"']
280 for dtd in dtds:
281 self._run_check("<!DOCTYPE %s>" % dtd,
282 [('decl', 'DOCTYPE ' + dtd)])
283
Fred Drake84bb9d82001-08-03 19:53:01 +0000284 def test_declaration_junk_chars(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000285 self._parse_error("<!DOCTYPE foo $ >")
286
Fred Drake84bb9d82001-08-03 19:53:01 +0000287 def test_startendtag(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000288 self._run_check("<p/>", [
289 ("startendtag", "p", []),
290 ])
291 self._run_check("<p></p>", [
292 ("starttag", "p", []),
293 ("endtag", "p"),
294 ])
295 self._run_check("<p><img src='foo' /></p>", [
296 ("starttag", "p", []),
297 ("startendtag", "img", [("src", "foo")]),
298 ("endtag", "p"),
299 ])
300
Fred Drake84bb9d82001-08-03 19:53:01 +0000301 def test_get_starttag_text(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000302 s = """<foo:bar \n one="1"\ttwo=2 >"""
303 self._run_check_extra(s, [
304 ("starttag", "foo:bar", [("one", "1"), ("two", "2")]),
305 ("starttag_text", s)])
306
Fred Drake84bb9d82001-08-03 19:53:01 +0000307 def test_cdata_content(self):
Ezio Melotti7de56f62011-11-01 14:12:22 +0200308 contents = [
309 '<!-- not a comment --> &not-an-entity-ref;',
310 "<not a='start tag'>",
311 '<a href="" /> <p> <span></span>',
312 'foo = "</scr" + "ipt>";',
313 'foo = "</SCRIPT" + ">";',
314 'foo = <\n/script> ',
315 '<!-- document.write("</scr" + "ipt>"); -->',
316 ('\n//<![CDATA[\n'
317 'document.write(\'<s\'+\'cript type="text/javascript" '
318 'src="http://www.example.org/r=\'+new '
319 'Date().getTime()+\'"><\\/s\'+\'cript>\');\n//]]>'),
320 '\n<!-- //\nvar foo = 3.14;\n// -->\n',
321 'foo = "</sty" + "le>";',
322 '<!-- \u2603 -->',
323 # these two should be invalid according to the HTML 5 spec,
324 # section 8.1.2.2
325 #'foo = </\nscript>',
326 #'foo = </ script>',
327 ]
328 elements = ['script', 'style', 'SCRIPT', 'STYLE', 'Script', 'Style']
329 for content in contents:
330 for element in elements:
331 element_lower = element.lower()
332 s = '<{element}>{content}</{element}>'.format(element=element,
333 content=content)
334 self._run_check(s, [("starttag", element_lower, []),
335 ("data", content),
336 ("endtag", element_lower)])
337
Ezio Melotti15cb4892011-11-18 18:01:49 +0200338 def test_cdata_with_closing_tags(self):
339 # see issue #13358
340 # make sure that HTMLParser calls handle_data only once for each CDATA.
341 # The normal event collector normalizes the events in get_events,
342 # so we override it to return the original list of events.
343 class Collector(EventCollector):
344 def get_events(self):
345 return self.events
Fred Drakebd3090d2001-05-18 15:32:59 +0000346
Ezio Melotti15cb4892011-11-18 18:01:49 +0200347 content = """<!-- not a comment --> &not-an-entity-ref;
348 <a href="" /> </p><p> <span></span></style>
349 '</script' + '>'"""
350 for element in [' script', 'script ', ' script ',
351 '\nscript', 'script\n', '\nscript\n']:
352 element_lower = element.lower().strip()
353 s = '<script>{content}</{element}>'.format(element=element,
354 content=content)
355 self._run_check(s, [("starttag", element_lower, []),
356 ("data", content),
357 ("endtag", element_lower)],
Ezio Melotti95401c52013-11-23 19:52:05 +0200358 collector=Collector(convert_charrefs=False))
Fred Drakebd3090d2001-05-18 15:32:59 +0000359
Ezio Melottifa3702d2012-02-10 10:45:44 +0200360 def test_comments(self):
361 html = ("<!-- I'm a valid comment -->"
362 '<!--me too!-->'
363 '<!------>'
364 '<!---->'
365 '<!----I have many hyphens---->'
366 '<!-- I have a > in the middle -->'
367 '<!-- and I have -- in the middle! -->')
368 expected = [('comment', " I'm a valid comment "),
369 ('comment', 'me too!'),
370 ('comment', '--'),
371 ('comment', ''),
372 ('comment', '--I have many hyphens--'),
373 ('comment', ' I have a > in the middle '),
374 ('comment', ' and I have -- in the middle! ')]
375 self._run_check(html, expected)
376
Ezio Melotti62f3d032011-12-19 07:29:03 +0200377 def test_condcoms(self):
378 html = ('<!--[if IE & !(lte IE 8)]>aren\'t<![endif]-->'
379 '<!--[if IE 8]>condcoms<![endif]-->'
380 '<!--[if lte IE 7]>pretty?<![endif]-->')
381 expected = [('comment', "[if IE & !(lte IE 8)]>aren't<![endif]"),
382 ('comment', '[if IE 8]>condcoms<![endif]'),
383 ('comment', '[if lte IE 7]>pretty?<![endif]')]
384 self._run_check(html, expected)
385
Ezio Melotti95401c52013-11-23 19:52:05 +0200386 def test_convert_charrefs(self):
387 collector = lambda: EventCollectorCharrefs(convert_charrefs=True)
388 self.assertTrue(collector().convert_charrefs)
389 charrefs = ['&quot;', '&#34;', '&#x22;', '&quot', '&#34', '&#x22']
390 # check charrefs in the middle of the text/attributes
391 expected = [('starttag', 'a', [('href', 'foo"zar')]),
392 ('data', 'a"z'), ('endtag', 'a')]
393 for charref in charrefs:
394 self._run_check('<a href="foo{0}zar">a{0}z</a>'.format(charref),
395 expected, collector=collector())
396 # check charrefs at the beginning/end of the text/attributes
397 expected = [('data', '"'),
398 ('starttag', 'a', [('x', '"'), ('y', '"X'), ('z', 'X"')]),
399 ('data', '"'), ('endtag', 'a'), ('data', '"')]
400 for charref in charrefs:
401 self._run_check('{0}<a x="{0}" y="{0}X" z="X{0}">'
402 '{0}</a>{0}'.format(charref),
403 expected, collector=collector())
404 # check charrefs in <script>/<style> elements
405 for charref in charrefs:
406 text = 'X'.join([charref]*3)
407 expected = [('data', '"'),
408 ('starttag', 'script', []), ('data', text),
409 ('endtag', 'script'), ('data', '"'),
410 ('starttag', 'style', []), ('data', text),
411 ('endtag', 'style'), ('data', '"')]
412 self._run_check('{1}<script>{0}</script>{1}'
413 '<style>{0}</style>{1}'.format(text, charref),
414 expected, collector=collector())
415 # check truncated charrefs at the end of the file
416 html = '&quo &# &#x'
417 for x in range(1, len(html)):
418 self._run_check(html[:x], [('data', html[:x])],
419 collector=collector())
420 # check a string with no charrefs
421 self._run_check('no charrefs here', [('data', 'no charrefs here')],
422 collector=collector())
423
Ezio Melotti62f3d032011-12-19 07:29:03 +0200424
Ezio Melottic1e73c32011-11-01 18:57:15 +0200425class HTMLParserTolerantTestCase(HTMLParserStrictTestCase):
R. David Murrayb579dba2010-12-03 04:06:39 +0000426
Ezio Melottib9a48f72011-11-01 15:00:59 +0200427 def get_collector(self):
Ezio Melotti95401c52013-11-23 19:52:05 +0200428 return EventCollector(convert_charrefs=False)
Ezio Melotti88ebfb12013-11-02 17:08:24 +0200429
430 def test_deprecation_warnings(self):
431 with self.assertWarns(DeprecationWarning):
Ezio Melotti95401c52013-11-23 19:52:05 +0200432 EventCollector() # convert_charrefs not passed explicitly
433 with self.assertWarns(DeprecationWarning):
Ezio Melotti88ebfb12013-11-02 17:08:24 +0200434 EventCollector(strict=True)
435 with self.assertWarns(DeprecationWarning):
436 EventCollector(strict=False)
437 with self.assertRaises(html.parser.HTMLParseError):
438 with self.assertWarns(DeprecationWarning):
439 EventCollector().error('test')
R. David Murrayb579dba2010-12-03 04:06:39 +0000440
441 def test_tolerant_parsing(self):
442 self._run_check('<html <html>te>>xt&a<<bc</a></html>\n'
443 '<img src="URL><//img></html</html>', [
Ezio Melottic2fe5772011-11-14 18:53:33 +0200444 ('starttag', 'html', [('<html', None)]),
445 ('data', 'te>>xt'),
446 ('entityref', 'a'),
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200447 ('data', '<'),
448 ('starttag', 'bc<', [('a', None)]),
Ezio Melottic2fe5772011-11-14 18:53:33 +0200449 ('endtag', 'html'),
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200450 ('data', '\n<img src="URL>'),
451 ('comment', '/img'),
452 ('endtag', 'html<')])
R. David Murrayb579dba2010-12-03 04:06:39 +0000453
Ezio Melotti86f67122012-02-13 14:11:27 +0200454 def test_starttag_junk_chars(self):
455 self._run_check("</>", [])
456 self._run_check("</$>", [('comment', '$')])
457 self._run_check("</", [('data', '</')])
458 self._run_check("</a", [('data', '</a')])
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200459 self._run_check("<a<a>", [('starttag', 'a<a', [])])
Ezio Melotti86f67122012-02-13 14:11:27 +0200460 self._run_check("</a<a>", [('endtag', 'a<a')])
461 self._run_check("<!", [('data', '<!')])
462 self._run_check("<a", [('data', '<a')])
463 self._run_check("<a foo='bar'", [('data', "<a foo='bar'")])
464 self._run_check("<a foo='bar", [('data', "<a foo='bar")])
465 self._run_check("<a foo='>'", [('data', "<a foo='>'")])
466 self._run_check("<a foo='>", [('data', "<a foo='>")])
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200467 self._run_check("<a$>", [('starttag', 'a$', [])])
468 self._run_check("<a$b>", [('starttag', 'a$b', [])])
469 self._run_check("<a$b/>", [('startendtag', 'a$b', [])])
470 self._run_check("<a$b >", [('starttag', 'a$b', [])])
471 self._run_check("<a$b />", [('startendtag', 'a$b', [])])
Ezio Melotti86f67122012-02-13 14:11:27 +0200472
Ezio Melotti29877e82012-02-21 09:25:00 +0200473 def test_slashes_in_starttag(self):
474 self._run_check('<a foo="var"/>', [('startendtag', 'a', [('foo', 'var')])])
475 html = ('<img width=902 height=250px '
476 'src="/sites/default/files/images/homepage/foo.jpg" '
477 '/*what am I doing here*/ />')
478 expected = [(
479 'startendtag', 'img',
480 [('width', '902'), ('height', '250px'),
481 ('src', '/sites/default/files/images/homepage/foo.jpg'),
482 ('*what', None), ('am', None), ('i', None),
483 ('doing', None), ('here*', None)]
484 )]
485 self._run_check(html, expected)
486 html = ('<a / /foo/ / /=/ / /bar/ / />'
487 '<a / /foo/ / /=/ / /bar/ / >')
488 expected = [
489 ('startendtag', 'a', [('foo', None), ('=', None), ('bar', None)]),
490 ('starttag', 'a', [('foo', None), ('=', None), ('bar', None)])
491 ]
492 self._run_check(html, expected)
Ezio Melotti0780b6b2012-04-18 19:18:22 -0600493 #see issue #14538
494 html = ('<meta><meta / ><meta // ><meta / / >'
495 '<meta/><meta /><meta //><meta//>')
496 expected = [
497 ('starttag', 'meta', []), ('starttag', 'meta', []),
498 ('starttag', 'meta', []), ('starttag', 'meta', []),
499 ('startendtag', 'meta', []), ('startendtag', 'meta', []),
500 ('startendtag', 'meta', []), ('startendtag', 'meta', []),
501 ]
502 self._run_check(html, expected)
Ezio Melotti29877e82012-02-21 09:25:00 +0200503
Ezio Melotti86f67122012-02-13 14:11:27 +0200504 def test_declaration_junk_chars(self):
Ezio Melottif4ab4912012-02-13 15:50:37 +0200505 self._run_check("<!DOCTYPE foo $ >", [('decl', 'DOCTYPE foo $ ')])
Ezio Melotti86f67122012-02-13 14:11:27 +0200506
507 def test_illegal_declarations(self):
Ezio Melotti86f67122012-02-13 14:11:27 +0200508 self._run_check('<!spacer type="block" height="25">',
509 [('comment', 'spacer type="block" height="25"')])
510
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200511 def test_with_unquoted_attributes(self):
Ezio Melottib9a48f72011-11-01 15:00:59 +0200512 # see #12008
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200513 html = ("<html><body bgcolor=d0ca90 text='181008'>"
514 "<table cellspacing=0 cellpadding=1 width=100% ><tr>"
515 "<td align=left><font size=-1>"
516 "- <a href=/rabota/><span class=en> software-and-i</span></a>"
517 "- <a href='/1/'><span class=en> library</span></a></table>")
518 expected = [
519 ('starttag', 'html', []),
520 ('starttag', 'body', [('bgcolor', 'd0ca90'), ('text', '181008')]),
521 ('starttag', 'table',
522 [('cellspacing', '0'), ('cellpadding', '1'), ('width', '100%')]),
523 ('starttag', 'tr', []),
524 ('starttag', 'td', [('align', 'left')]),
525 ('starttag', 'font', [('size', '-1')]),
526 ('data', '- '), ('starttag', 'a', [('href', '/rabota/')]),
527 ('starttag', 'span', [('class', 'en')]), ('data', ' software-and-i'),
528 ('endtag', 'span'), ('endtag', 'a'),
529 ('data', '- '), ('starttag', 'a', [('href', '/1/')]),
530 ('starttag', 'span', [('class', 'en')]), ('data', ' library'),
531 ('endtag', 'span'), ('endtag', 'a'), ('endtag', 'table')
532 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200533 self._run_check(html, expected)
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200534
R. David Murrayb579dba2010-12-03 04:06:39 +0000535 def test_comma_between_attributes(self):
536 self._run_check('<form action="/xxx.php?a=1&amp;b=2&amp", '
537 'method="post">', [
538 ('starttag', 'form',
Ezio Melotti46495182012-06-24 22:02:56 +0200539 [('action', '/xxx.php?a=1&b=2&'),
Ezio Melottic2fe5772011-11-14 18:53:33 +0200540 (',', None), ('method', 'post')])])
R. David Murrayb579dba2010-12-03 04:06:39 +0000541
542 def test_weird_chars_in_unquoted_attribute_values(self):
543 self._run_check('<form action=bogus|&#()value>', [
544 ('starttag', 'form',
Ezio Melottic1e73c32011-11-01 18:57:15 +0200545 [('action', 'bogus|&#()value')])])
R. David Murrayb579dba2010-12-03 04:06:39 +0000546
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200547 def test_invalid_end_tags(self):
548 # A collection of broken end tags. <br> is used as separator.
549 # see http://www.w3.org/TR/html5/tokenization.html#end-tag-open-state
550 # and #13993
551 html = ('<br></label</p><br></div end tmAd-leaderBoard><br></<h4><br>'
552 '</li class="unit"><br></li\r\n\t\t\t\t\t\t</ul><br></><br>')
553 expected = [('starttag', 'br', []),
554 # < is part of the name, / is discarded, p is an attribute
555 ('endtag', 'label<'),
556 ('starttag', 'br', []),
557 # text and attributes are discarded
558 ('endtag', 'div'),
559 ('starttag', 'br', []),
560 # comment because the first char after </ is not a-zA-Z
561 ('comment', '<h4'),
562 ('starttag', 'br', []),
563 # attributes are discarded
564 ('endtag', 'li'),
565 ('starttag', 'br', []),
566 # everything till ul (included) is discarded
567 ('endtag', 'li'),
568 ('starttag', 'br', []),
569 # </> is ignored
570 ('starttag', 'br', [])]
571 self._run_check(html, expected)
572
573 def test_broken_invalid_end_tag(self):
574 # This is technically wrong (the "> shouldn't be included in the 'data')
575 # but is probably not worth fixing it (in addition to all the cases of
576 # the previous test, it would require a full attribute parsing).
577 # see #13993
578 html = '<b>This</b attr=">"> confuses the parser'
579 expected = [('starttag', 'b', []),
580 ('data', 'This'),
581 ('endtag', 'b'),
582 ('data', '"> confuses the parser')]
583 self._run_check(html, expected)
584
Ezio Melottib9a48f72011-11-01 15:00:59 +0200585 def test_correct_detection_of_start_tags(self):
586 # see #13273
Ezio Melottif50ffa92011-10-28 13:21:09 +0300587 html = ('<div style="" ><b>The <a href="some_url">rain</a> '
588 '<br /> in <span>Spain</span></b></div>')
589 expected = [
590 ('starttag', 'div', [('style', '')]),
591 ('starttag', 'b', []),
592 ('data', 'The '),
593 ('starttag', 'a', [('href', 'some_url')]),
594 ('data', 'rain'),
595 ('endtag', 'a'),
596 ('data', ' '),
597 ('startendtag', 'br', []),
598 ('data', ' in '),
599 ('starttag', 'span', []),
600 ('data', 'Spain'),
601 ('endtag', 'span'),
602 ('endtag', 'b'),
603 ('endtag', 'div')
604 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200605 self._run_check(html, expected)
Ezio Melottif50ffa92011-10-28 13:21:09 +0300606
Ezio Melottif50ffa92011-10-28 13:21:09 +0300607 html = '<div style="", foo = "bar" ><b>The <a href="some_url">rain</a>'
608 expected = [
Ezio Melottic2fe5772011-11-14 18:53:33 +0200609 ('starttag', 'div', [('style', ''), (',', None), ('foo', 'bar')]),
Ezio Melottif50ffa92011-10-28 13:21:09 +0300610 ('starttag', 'b', []),
611 ('data', 'The '),
612 ('starttag', 'a', [('href', 'some_url')]),
613 ('data', 'rain'),
614 ('endtag', 'a'),
615 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200616 self._run_check(html, expected)
Ezio Melottif50ffa92011-10-28 13:21:09 +0300617
Ezio Melotti8e596a72013-05-01 16:18:25 +0300618 def test_EOF_in_charref(self):
619 # see #17802
620 # This test checks that the UnboundLocalError reported in the issue
621 # is not raised, however I'm not sure the returned values are correct.
622 # Maybe HTMLParser should use self.unescape for these
623 data = [
624 ('a&', [('data', 'a&')]),
625 ('a&b', [('data', 'ab')]),
626 ('a&b ', [('data', 'a'), ('entityref', 'b'), ('data', ' ')]),
627 ('a&b;', [('data', 'a'), ('entityref', 'b')]),
628 ]
629 for html, expected in data:
630 self._run_check(html, expected)
631
Ezio Melottif6de9eb2013-11-22 05:49:29 +0200632 def test_unescape_method(self):
633 from html import unescape
634 p = self.get_collector()
635 with self.assertWarns(DeprecationWarning):
636 s = '&quot;&#34;&#x22;&quot&#34&#x22&#bad;'
637 self.assertEqual(p.unescape(s), unescape(s))
638
Ezio Melottifa3702d2012-02-10 10:45:44 +0200639 def test_broken_comments(self):
640 html = ('<! not really a comment >'
641 '<! not a comment either -->'
642 '<! -- close enough -->'
Ezio Melottif4ab4912012-02-13 15:50:37 +0200643 '<!><!<-- this was an empty comment>'
Ezio Melottifa3702d2012-02-10 10:45:44 +0200644 '<!!! another bogus comment !!!>')
645 expected = [
646 ('comment', ' not really a comment '),
647 ('comment', ' not a comment either --'),
648 ('comment', ' -- close enough --'),
Ezio Melottif4ab4912012-02-13 15:50:37 +0200649 ('comment', ''),
650 ('comment', '<-- this was an empty comment'),
Ezio Melottifa3702d2012-02-10 10:45:44 +0200651 ('comment', '!! another bogus comment !!!'),
652 ]
653 self._run_check(html, expected)
654
Ezio Melotti62f3d032011-12-19 07:29:03 +0200655 def test_broken_condcoms(self):
656 # these condcoms are missing the '--' after '<!' and before the '>'
657 html = ('<![if !(IE)]>broken condcom<![endif]>'
658 '<![if ! IE]><link href="favicon.tiff"/><![endif]>'
659 '<![if !IE 6]><img src="firefox.png" /><![endif]>'
660 '<![if !ie 6]><b>foo</b><![endif]>'
661 '<![if (!IE)|(lt IE 9)]><img src="mammoth.bmp" /><![endif]>')
662 # According to the HTML5 specs sections "8.2.4.44 Bogus comment state"
663 # and "8.2.4.45 Markup declaration open state", comment tokens should
664 # be emitted instead of 'unknown decl', but calling unknown_decl
665 # provides more flexibility.
666 # See also Lib/_markupbase.py:parse_declaration
667 expected = [
668 ('unknown decl', 'if !(IE)'),
669 ('data', 'broken condcom'),
670 ('unknown decl', 'endif'),
671 ('unknown decl', 'if ! IE'),
672 ('startendtag', 'link', [('href', 'favicon.tiff')]),
673 ('unknown decl', 'endif'),
674 ('unknown decl', 'if !IE 6'),
675 ('startendtag', 'img', [('src', 'firefox.png')]),
676 ('unknown decl', 'endif'),
677 ('unknown decl', 'if !ie 6'),
678 ('starttag', 'b', []),
679 ('data', 'foo'),
680 ('endtag', 'b'),
681 ('unknown decl', 'endif'),
682 ('unknown decl', 'if (!IE)|(lt IE 9)'),
683 ('startendtag', 'img', [('src', 'mammoth.bmp')]),
684 ('unknown decl', 'endif')
685 ]
686 self._run_check(html, expected)
687
Ezio Melottic1e73c32011-11-01 18:57:15 +0200688
Ezio Melottib245ed12011-11-14 18:13:22 +0200689class AttributesStrictTestCase(TestCaseBase):
690
691 def get_collector(self):
Ezio Melotti3861d8b2012-06-23 15:27:51 +0200692 with support.check_warnings(("", DeprecationWarning), quite=False):
Ezio Melotti95401c52013-11-23 19:52:05 +0200693 return EventCollector(strict=True, convert_charrefs=False)
Ezio Melottib245ed12011-11-14 18:13:22 +0200694
695 def test_attr_syntax(self):
696 output = [
697 ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", None)])
698 ]
699 self._run_check("""<a b='v' c="v" d=v e>""", output)
700 self._run_check("""<a b = 'v' c = "v" d = v e>""", output)
701 self._run_check("""<a\nb\n=\n'v'\nc\n=\n"v"\nd\n=\nv\ne>""", output)
702 self._run_check("""<a\tb\t=\t'v'\tc\t=\t"v"\td\t=\tv\te>""", output)
703
704 def test_attr_values(self):
705 self._run_check("""<a b='xxx\n\txxx' c="yyy\t\nyyy" d='\txyz\n'>""",
706 [("starttag", "a", [("b", "xxx\n\txxx"),
707 ("c", "yyy\t\nyyy"),
708 ("d", "\txyz\n")])])
709 self._run_check("""<a b='' c="">""",
710 [("starttag", "a", [("b", ""), ("c", "")])])
711 # Regression test for SF patch #669683.
712 self._run_check("<e a=rgb(1,2,3)>",
713 [("starttag", "e", [("a", "rgb(1,2,3)")])])
714 # Regression test for SF bug #921657.
715 self._run_check(
716 "<a href=mailto:xyz@example.com>",
717 [("starttag", "a", [("href", "mailto:xyz@example.com")])])
718
719 def test_attr_nonascii(self):
720 # see issue 7311
721 self._run_check(
722 "<img src=/foo/bar.png alt=\u4e2d\u6587>",
723 [("starttag", "img", [("src", "/foo/bar.png"),
724 ("alt", "\u4e2d\u6587")])])
725 self._run_check(
726 "<a title='\u30c6\u30b9\u30c8' href='\u30c6\u30b9\u30c8.html'>",
727 [("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
728 ("href", "\u30c6\u30b9\u30c8.html")])])
729 self._run_check(
730 '<a title="\u30c6\u30b9\u30c8" href="\u30c6\u30b9\u30c8.html">',
731 [("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
732 ("href", "\u30c6\u30b9\u30c8.html")])])
733
734 def test_attr_entity_replacement(self):
735 self._run_check(
736 "<a b='&amp;&gt;&lt;&quot;&apos;'>",
737 [("starttag", "a", [("b", "&><\"'")])])
738
739 def test_attr_funky_names(self):
740 self._run_check(
741 "<a a.b='v' c:d=v e-f=v>",
742 [("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")])])
743
744 def test_entityrefs_in_attributes(self):
745 self._run_check(
746 "<html foo='&euro;&amp;&#97;&#x61;&unsupported;'>",
747 [("starttag", "html", [("foo", "\u20AC&aa&unsupported;")])])
748
749
Ezio Melottic2fe5772011-11-14 18:53:33 +0200750
751class AttributesTolerantTestCase(AttributesStrictTestCase):
752
753 def get_collector(self):
Ezio Melotti95401c52013-11-23 19:52:05 +0200754 return EventCollector(convert_charrefs=False)
Ezio Melottic2fe5772011-11-14 18:53:33 +0200755
756 def test_attr_funky_names2(self):
757 self._run_check(
758 "<a $><b $=%><c \=/>",
759 [("starttag", "a", [("$", None)]),
760 ("starttag", "b", [("$", "%")]),
761 ("starttag", "c", [("\\", "/")])])
762
763 def test_entities_in_attribute_value(self):
764 # see #1200313
765 for entity in ['&', '&amp;', '&#38;', '&#x26;']:
766 self._run_check('<a href="%s">' % entity,
767 [("starttag", "a", [("href", "&")])])
768 self._run_check("<a href='%s'>" % entity,
769 [("starttag", "a", [("href", "&")])])
770 self._run_check("<a href=%s>" % entity,
771 [("starttag", "a", [("href", "&")])])
772
773 def test_malformed_attributes(self):
774 # see #13357
775 html = (
776 "<a href=test'style='color:red;bad1'>test - bad1</a>"
777 "<a href=test'+style='color:red;ba2'>test - bad2</a>"
778 "<a href=test'&nbsp;style='color:red;bad3'>test - bad3</a>"
779 "<a href = test'&nbsp;style='color:red;bad4' >test - bad4</a>"
780 )
781 expected = [
782 ('starttag', 'a', [('href', "test'style='color:red;bad1'")]),
783 ('data', 'test - bad1'), ('endtag', 'a'),
784 ('starttag', 'a', [('href', "test'+style='color:red;ba2'")]),
785 ('data', 'test - bad2'), ('endtag', 'a'),
786 ('starttag', 'a', [('href', "test'\xa0style='color:red;bad3'")]),
787 ('data', 'test - bad3'), ('endtag', 'a'),
788 ('starttag', 'a', [('href', "test'\xa0style='color:red;bad4'")]),
789 ('data', 'test - bad4'), ('endtag', 'a')
790 ]
791 self._run_check(html, expected)
792
793 def test_malformed_adjacent_attributes(self):
794 # see #12629
795 self._run_check('<x><y z=""o"" /></x>',
796 [('starttag', 'x', []),
797 ('startendtag', 'y', [('z', ''), ('o""', None)]),
798 ('endtag', 'x')])
799 self._run_check('<x><y z="""" /></x>',
800 [('starttag', 'x', []),
801 ('startendtag', 'y', [('z', ''), ('""', None)]),
802 ('endtag', 'x')])
803
804 # see #755670 for the following 3 tests
805 def test_adjacent_attributes(self):
806 self._run_check('<a width="100%"cellspacing=0>',
807 [("starttag", "a",
808 [("width", "100%"), ("cellspacing","0")])])
809
810 self._run_check('<a id="foo"class="bar">',
811 [("starttag", "a",
812 [("id", "foo"), ("class","bar")])])
813
814 def test_missing_attribute_value(self):
815 self._run_check('<a v=>',
816 [("starttag", "a", [("v", "")])])
817
818 def test_javascript_attribute_value(self):
819 self._run_check("<a href=javascript:popup('/popup/help.html')>",
820 [("starttag", "a",
821 [("href", "javascript:popup('/popup/help.html')")])])
822
823 def test_end_tag_in_attribute_value(self):
824 # see #1745761
825 self._run_check("<a href='http://www.example.org/\">;'>spam</a>",
826 [("starttag", "a",
827 [("href", "http://www.example.org/\">;")]),
828 ("data", "spam"), ("endtag", "a")])
829
830
Fred Drakee8220492001-09-24 20:19:08 +0000831if __name__ == "__main__":
Ezio Melotti5028f4d2013-11-02 17:49:08 +0200832 unittest.main()