blob: 144f820af29c2262d1b883a25f9deec2a9b40615 [file] [log] [blame]
Fred Drakebd3090d2001-05-18 15:32:59 +00001"""Tests for HTMLParser.py."""
2
Mark Dickinsonf64dcf32008-05-21 13:51:18 +00003import html.parser
Fred Drake029acfb2001-08-20 21:24:19 +00004import pprint
Fred Drakebd3090d2001-05-18 15:32:59 +00005import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00006from test import support
Fred Drakebd3090d2001-05-18 15:32:59 +00007
8
Mark Dickinsonf64dcf32008-05-21 13:51:18 +00009class EventCollector(html.parser.HTMLParser):
Fred Drakebd3090d2001-05-18 15:32:59 +000010
R. David Murrayb579dba2010-12-03 04:06:39 +000011 def __init__(self, *args, **kw):
Fred Drakebd3090d2001-05-18 15:32:59 +000012 self.events = []
13 self.append = self.events.append
R. David Murrayb579dba2010-12-03 04:06:39 +000014 html.parser.HTMLParser.__init__(self, *args, **kw)
Fred Drakebd3090d2001-05-18 15:32:59 +000015
16 def get_events(self):
17 # Normalize the list of events so that buffer artefacts don't
18 # separate runs of contiguous characters.
19 L = []
20 prevtype = None
21 for event in self.events:
22 type = event[0]
23 if type == prevtype == "data":
24 L[-1] = ("data", L[-1][1] + event[1])
25 else:
26 L.append(event)
27 prevtype = type
28 self.events = L
29 return L
30
31 # structure markup
32
33 def handle_starttag(self, tag, attrs):
34 self.append(("starttag", tag, attrs))
35
36 def handle_startendtag(self, tag, attrs):
37 self.append(("startendtag", tag, attrs))
38
39 def handle_endtag(self, tag):
40 self.append(("endtag", tag))
41
42 # all other markup
43
44 def handle_comment(self, data):
45 self.append(("comment", data))
46
47 def handle_charref(self, data):
48 self.append(("charref", data))
49
50 def handle_data(self, data):
51 self.append(("data", data))
52
53 def handle_decl(self, data):
54 self.append(("decl", data))
55
56 def handle_entityref(self, data):
57 self.append(("entityref", data))
58
59 def handle_pi(self, data):
60 self.append(("pi", data))
61
Fred Drakec20a6982001-09-04 15:13:04 +000062 def unknown_decl(self, decl):
63 self.append(("unknown decl", decl))
64
Fred Drakebd3090d2001-05-18 15:32:59 +000065
66class EventCollectorExtra(EventCollector):
67
68 def handle_starttag(self, tag, attrs):
69 EventCollector.handle_starttag(self, tag, attrs)
70 self.append(("starttag_text", self.get_starttag_text()))
71
72
Ezio Melotti95401c52013-11-23 19:52:05 +020073class EventCollectorCharrefs(EventCollector):
74
Ezio Melotti95401c52013-11-23 19:52:05 +020075 def handle_charref(self, data):
76 self.fail('This should never be called with convert_charrefs=True')
77
78 def handle_entityref(self, data):
79 self.fail('This should never be called with convert_charrefs=True')
80
81
Fred Drakebd3090d2001-05-18 15:32:59 +000082class TestCaseBase(unittest.TestCase):
83
Ezio Melottic1e73c32011-11-01 18:57:15 +020084 def get_collector(self):
85 raise NotImplementedError
86
R. David Murrayb579dba2010-12-03 04:06:39 +000087 def _run_check(self, source, expected_events, collector=None):
88 if collector is None:
Ezio Melottic1e73c32011-11-01 18:57:15 +020089 collector = self.get_collector()
R. David Murrayb579dba2010-12-03 04:06:39 +000090 parser = collector
Fred Drakebd3090d2001-05-18 15:32:59 +000091 for s in source:
92 parser.feed(s)
Fred Drakebd3090d2001-05-18 15:32:59 +000093 parser.close()
Fred Drake029acfb2001-08-20 21:24:19 +000094 events = parser.get_events()
Fred Drakec20a6982001-09-04 15:13:04 +000095 if events != expected_events:
Ezio Melotti95401c52013-11-23 19:52:05 +020096 self.fail("received events did not match expected events" +
97 "\nSource:\n" + repr(source) +
98 "\nExpected:\n" + pprint.pformat(expected_events) +
Fred Drakec20a6982001-09-04 15:13:04 +000099 "\nReceived:\n" + pprint.pformat(events))
Fred Drakebd3090d2001-05-18 15:32:59 +0000100
101 def _run_check_extra(self, source, events):
Ezio Melotti95401c52013-11-23 19:52:05 +0200102 self._run_check(source, events,
103 EventCollectorExtra(convert_charrefs=False))
Fred Drakebd3090d2001-05-18 15:32:59 +0000104
105 def _parse_error(self, source):
106 def parse(source=source):
Ezio Melotti86f67122012-02-13 14:11:27 +0200107 parser = self.get_collector()
Fred Drakebd3090d2001-05-18 15:32:59 +0000108 parser.feed(source)
109 parser.close()
Ezio Melotti88ebfb12013-11-02 17:08:24 +0200110 with self.assertRaises(html.parser.HTMLParseError):
111 with self.assertWarns(DeprecationWarning):
112 parse()
Fred Drakebd3090d2001-05-18 15:32:59 +0000113
114
Ezio Melottic1e73c32011-11-01 18:57:15 +0200115class HTMLParserStrictTestCase(TestCaseBase):
116
117 def get_collector(self):
Ezio Melotti3861d8b2012-06-23 15:27:51 +0200118 with support.check_warnings(("", DeprecationWarning), quite=False):
Ezio Melotti95401c52013-11-23 19:52:05 +0200119 return EventCollector(strict=True, convert_charrefs=False)
Fred Drakebd3090d2001-05-18 15:32:59 +0000120
Fred Drake84bb9d82001-08-03 19:53:01 +0000121 def test_processing_instruction_only(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000122 self._run_check("<?processing instruction>", [
123 ("pi", "processing instruction"),
124 ])
Fred Drakefafd56f2003-04-17 22:19:26 +0000125 self._run_check("<?processing instruction ?>", [
126 ("pi", "processing instruction ?"),
127 ])
Fred Drakebd3090d2001-05-18 15:32:59 +0000128
Fred Drake84bb9d82001-08-03 19:53:01 +0000129 def test_simple_html(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000130 self._run_check("""
131<!DOCTYPE html PUBLIC 'foo'>
132<HTML>&entity;&#32;
133<!--comment1a
134-></foo><bar>&lt;<?pi?></foo<bar
135comment1b-->
136<Img sRc='Bar' isMAP>sample
137text
Fred Drake84bb9d82001-08-03 19:53:01 +0000138&#x201C;
Ezio Melottif4ab4912012-02-13 15:50:37 +0200139<!--comment2a-- --comment2b-->
Fred Drakebd3090d2001-05-18 15:32:59 +0000140</Html>
141""", [
142 ("data", "\n"),
143 ("decl", "DOCTYPE html PUBLIC 'foo'"),
144 ("data", "\n"),
145 ("starttag", "html", []),
146 ("entityref", "entity"),
147 ("charref", "32"),
148 ("data", "\n"),
149 ("comment", "comment1a\n-></foo><bar>&lt;<?pi?></foo<bar\ncomment1b"),
150 ("data", "\n"),
151 ("starttag", "img", [("src", "Bar"), ("ismap", None)]),
152 ("data", "sample\ntext\n"),
Fred Drake84bb9d82001-08-03 19:53:01 +0000153 ("charref", "x201C"),
154 ("data", "\n"),
Fred Drakebd3090d2001-05-18 15:32:59 +0000155 ("comment", "comment2a-- --comment2b"),
156 ("data", "\n"),
157 ("endtag", "html"),
158 ("data", "\n"),
159 ])
160
Victor Stinnere021f4b2010-05-24 21:46:25 +0000161 def test_malformatted_charref(self):
162 self._run_check("<p>&#bad;</p>", [
163 ("starttag", "p", []),
164 ("data", "&#bad;"),
165 ("endtag", "p"),
166 ])
Ezio Melottif27b9a72014-02-01 21:21:01 +0200167 # add the [] as a workaround to avoid buffering (see #20288)
168 self._run_check(["<div>&#bad;</div>"], [
169 ("starttag", "div", []),
170 ("data", "&#bad;"),
171 ("endtag", "div"),
172 ])
Victor Stinnere021f4b2010-05-24 21:46:25 +0000173
Fred Drake073148c2001-12-03 16:44:09 +0000174 def test_unclosed_entityref(self):
175 self._run_check("&entityref foo", [
176 ("entityref", "entityref"),
177 ("data", " foo"),
178 ])
179
Fred Drake84bb9d82001-08-03 19:53:01 +0000180 def test_bad_nesting(self):
181 # Strangely, this *is* supposed to test that overlapping
182 # elements are allowed. HTMLParser is more geared toward
183 # lexing the input that parsing the structure.
Fred Drakebd3090d2001-05-18 15:32:59 +0000184 self._run_check("<a><b></a></b>", [
185 ("starttag", "a", []),
186 ("starttag", "b", []),
187 ("endtag", "a"),
188 ("endtag", "b"),
189 ])
190
Fred Drake029acfb2001-08-20 21:24:19 +0000191 def test_bare_ampersands(self):
192 self._run_check("this text & contains & ampersands &", [
193 ("data", "this text & contains & ampersands &"),
194 ])
195
196 def test_bare_pointy_brackets(self):
197 self._run_check("this < text > contains < bare>pointy< brackets", [
198 ("data", "this < text > contains < bare>pointy< brackets"),
199 ])
200
Fred Drakec20a6982001-09-04 15:13:04 +0000201 def test_illegal_declarations(self):
Fred Drake7cf613d2001-09-04 16:26:03 +0000202 self._parse_error('<!spacer type="block" height="25">')
Fred Drakec20a6982001-09-04 15:13:04 +0000203
Fred Drake84bb9d82001-08-03 19:53:01 +0000204 def test_starttag_end_boundary(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000205 self._run_check("""<a b='<'>""", [("starttag", "a", [("b", "<")])])
206 self._run_check("""<a b='>'>""", [("starttag", "a", [("b", ">")])])
207
Fred Drake84bb9d82001-08-03 19:53:01 +0000208 def test_buffer_artefacts(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000209 output = [("starttag", "a", [("b", "<")])]
210 self._run_check(["<a b='<'>"], output)
211 self._run_check(["<a ", "b='<'>"], output)
212 self._run_check(["<a b", "='<'>"], output)
213 self._run_check(["<a b=", "'<'>"], output)
214 self._run_check(["<a b='<", "'>"], output)
215 self._run_check(["<a b='<'", ">"], output)
216
217 output = [("starttag", "a", [("b", ">")])]
218 self._run_check(["<a b='>'>"], output)
219 self._run_check(["<a ", "b='>'>"], output)
220 self._run_check(["<a b", "='>'>"], output)
221 self._run_check(["<a b=", "'>'>"], output)
222 self._run_check(["<a b='>", "'>"], output)
223 self._run_check(["<a b='>'", ">"], output)
224
Fred Drake75d9a622004-09-08 22:57:01 +0000225 output = [("comment", "abc")]
226 self._run_check(["", "<!--abc-->"], output)
227 self._run_check(["<", "!--abc-->"], output)
228 self._run_check(["<!", "--abc-->"], output)
229 self._run_check(["<!-", "-abc-->"], output)
230 self._run_check(["<!--", "abc-->"], output)
231 self._run_check(["<!--a", "bc-->"], output)
232 self._run_check(["<!--ab", "c-->"], output)
233 self._run_check(["<!--abc", "-->"], output)
234 self._run_check(["<!--abc-", "->"], output)
235 self._run_check(["<!--abc--", ">"], output)
236 self._run_check(["<!--abc-->", ""], output)
237
Fred Drake84bb9d82001-08-03 19:53:01 +0000238 def test_starttag_junk_chars(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000239 self._parse_error("</>")
240 self._parse_error("</$>")
241 self._parse_error("</")
242 self._parse_error("</a")
Fred Drakebd3090d2001-05-18 15:32:59 +0000243 self._parse_error("<a<a>")
244 self._parse_error("</a<a>")
Fred Drakebd3090d2001-05-18 15:32:59 +0000245 self._parse_error("<!")
Fred Drakebd3090d2001-05-18 15:32:59 +0000246 self._parse_error("<a")
247 self._parse_error("<a foo='bar'")
248 self._parse_error("<a foo='bar")
249 self._parse_error("<a foo='>'")
250 self._parse_error("<a foo='>")
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200251 self._parse_error("<a$>")
252 self._parse_error("<a$b>")
253 self._parse_error("<a$b/>")
254 self._parse_error("<a$b >")
255 self._parse_error("<a$b />")
Fred Drakebd3090d2001-05-18 15:32:59 +0000256
Ezio Melottif4ab4912012-02-13 15:50:37 +0200257 def test_valid_doctypes(self):
258 # from http://www.w3.org/QA/2002/04/valid-dtd-list.html
259 dtds = ['HTML', # HTML5 doctype
260 ('HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
261 '"http://www.w3.org/TR/html4/strict.dtd"'),
262 ('HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" '
263 '"http://www.w3.org/TR/html4/loose.dtd"'),
264 ('html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" '
265 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"'),
266 ('html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" '
267 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"'),
268 ('math PUBLIC "-//W3C//DTD MathML 2.0//EN" '
269 '"http://www.w3.org/Math/DTD/mathml2/mathml2.dtd"'),
270 ('html PUBLIC "-//W3C//DTD '
271 'XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" '
272 '"http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd"'),
273 ('svg PUBLIC "-//W3C//DTD SVG 1.1//EN" '
274 '"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"'),
275 'html PUBLIC "-//IETF//DTD HTML 2.0//EN"',
276 'html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"']
277 for dtd in dtds:
278 self._run_check("<!DOCTYPE %s>" % dtd,
279 [('decl', 'DOCTYPE ' + dtd)])
280
Fred Drake84bb9d82001-08-03 19:53:01 +0000281 def test_declaration_junk_chars(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000282 self._parse_error("<!DOCTYPE foo $ >")
283
Fred Drake84bb9d82001-08-03 19:53:01 +0000284 def test_startendtag(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000285 self._run_check("<p/>", [
286 ("startendtag", "p", []),
287 ])
288 self._run_check("<p></p>", [
289 ("starttag", "p", []),
290 ("endtag", "p"),
291 ])
292 self._run_check("<p><img src='foo' /></p>", [
293 ("starttag", "p", []),
294 ("startendtag", "img", [("src", "foo")]),
295 ("endtag", "p"),
296 ])
297
Fred Drake84bb9d82001-08-03 19:53:01 +0000298 def test_get_starttag_text(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000299 s = """<foo:bar \n one="1"\ttwo=2 >"""
300 self._run_check_extra(s, [
301 ("starttag", "foo:bar", [("one", "1"), ("two", "2")]),
302 ("starttag_text", s)])
303
Fred Drake84bb9d82001-08-03 19:53:01 +0000304 def test_cdata_content(self):
Ezio Melotti7de56f62011-11-01 14:12:22 +0200305 contents = [
306 '<!-- not a comment --> &not-an-entity-ref;',
307 "<not a='start tag'>",
308 '<a href="" /> <p> <span></span>',
309 'foo = "</scr" + "ipt>";',
310 'foo = "</SCRIPT" + ">";',
311 'foo = <\n/script> ',
312 '<!-- document.write("</scr" + "ipt>"); -->',
313 ('\n//<![CDATA[\n'
314 'document.write(\'<s\'+\'cript type="text/javascript" '
315 'src="http://www.example.org/r=\'+new '
316 'Date().getTime()+\'"><\\/s\'+\'cript>\');\n//]]>'),
317 '\n<!-- //\nvar foo = 3.14;\n// -->\n',
318 'foo = "</sty" + "le>";',
319 '<!-- \u2603 -->',
320 # these two should be invalid according to the HTML 5 spec,
321 # section 8.1.2.2
322 #'foo = </\nscript>',
323 #'foo = </ script>',
324 ]
325 elements = ['script', 'style', 'SCRIPT', 'STYLE', 'Script', 'Style']
326 for content in contents:
327 for element in elements:
328 element_lower = element.lower()
329 s = '<{element}>{content}</{element}>'.format(element=element,
330 content=content)
331 self._run_check(s, [("starttag", element_lower, []),
332 ("data", content),
333 ("endtag", element_lower)])
334
Ezio Melotti15cb4892011-11-18 18:01:49 +0200335 def test_cdata_with_closing_tags(self):
336 # see issue #13358
337 # make sure that HTMLParser calls handle_data only once for each CDATA.
338 # The normal event collector normalizes the events in get_events,
339 # so we override it to return the original list of events.
340 class Collector(EventCollector):
341 def get_events(self):
342 return self.events
Fred Drakebd3090d2001-05-18 15:32:59 +0000343
Ezio Melotti15cb4892011-11-18 18:01:49 +0200344 content = """<!-- not a comment --> &not-an-entity-ref;
345 <a href="" /> </p><p> <span></span></style>
346 '</script' + '>'"""
347 for element in [' script', 'script ', ' script ',
348 '\nscript', 'script\n', '\nscript\n']:
349 element_lower = element.lower().strip()
350 s = '<script>{content}</{element}>'.format(element=element,
351 content=content)
352 self._run_check(s, [("starttag", element_lower, []),
353 ("data", content),
354 ("endtag", element_lower)],
Ezio Melotti95401c52013-11-23 19:52:05 +0200355 collector=Collector(convert_charrefs=False))
Fred Drakebd3090d2001-05-18 15:32:59 +0000356
Ezio Melottifa3702d2012-02-10 10:45:44 +0200357 def test_comments(self):
358 html = ("<!-- I'm a valid comment -->"
359 '<!--me too!-->'
360 '<!------>'
361 '<!---->'
362 '<!----I have many hyphens---->'
363 '<!-- I have a > in the middle -->'
364 '<!-- and I have -- in the middle! -->')
365 expected = [('comment', " I'm a valid comment "),
366 ('comment', 'me too!'),
367 ('comment', '--'),
368 ('comment', ''),
369 ('comment', '--I have many hyphens--'),
370 ('comment', ' I have a > in the middle '),
371 ('comment', ' and I have -- in the middle! ')]
372 self._run_check(html, expected)
373
Ezio Melotti62f3d032011-12-19 07:29:03 +0200374 def test_condcoms(self):
375 html = ('<!--[if IE & !(lte IE 8)]>aren\'t<![endif]-->'
376 '<!--[if IE 8]>condcoms<![endif]-->'
377 '<!--[if lte IE 7]>pretty?<![endif]-->')
378 expected = [('comment', "[if IE & !(lte IE 8)]>aren't<![endif]"),
379 ('comment', '[if IE 8]>condcoms<![endif]'),
380 ('comment', '[if lte IE 7]>pretty?<![endif]')]
381 self._run_check(html, expected)
382
Ezio Melotti95401c52013-11-23 19:52:05 +0200383 def test_convert_charrefs(self):
384 collector = lambda: EventCollectorCharrefs(convert_charrefs=True)
385 self.assertTrue(collector().convert_charrefs)
386 charrefs = ['&quot;', '&#34;', '&#x22;', '&quot', '&#34', '&#x22']
387 # check charrefs in the middle of the text/attributes
388 expected = [('starttag', 'a', [('href', 'foo"zar')]),
389 ('data', 'a"z'), ('endtag', 'a')]
390 for charref in charrefs:
391 self._run_check('<a href="foo{0}zar">a{0}z</a>'.format(charref),
392 expected, collector=collector())
393 # check charrefs at the beginning/end of the text/attributes
394 expected = [('data', '"'),
395 ('starttag', 'a', [('x', '"'), ('y', '"X'), ('z', 'X"')]),
396 ('data', '"'), ('endtag', 'a'), ('data', '"')]
397 for charref in charrefs:
398 self._run_check('{0}<a x="{0}" y="{0}X" z="X{0}">'
399 '{0}</a>{0}'.format(charref),
400 expected, collector=collector())
401 # check charrefs in <script>/<style> elements
402 for charref in charrefs:
403 text = 'X'.join([charref]*3)
404 expected = [('data', '"'),
405 ('starttag', 'script', []), ('data', text),
406 ('endtag', 'script'), ('data', '"'),
407 ('starttag', 'style', []), ('data', text),
408 ('endtag', 'style'), ('data', '"')]
409 self._run_check('{1}<script>{0}</script>{1}'
410 '<style>{0}</style>{1}'.format(text, charref),
411 expected, collector=collector())
412 # check truncated charrefs at the end of the file
413 html = '&quo &# &#x'
414 for x in range(1, len(html)):
415 self._run_check(html[:x], [('data', html[:x])],
416 collector=collector())
417 # check a string with no charrefs
418 self._run_check('no charrefs here', [('data', 'no charrefs here')],
419 collector=collector())
420
Ezio Melotti62f3d032011-12-19 07:29:03 +0200421
Ezio Melottic1e73c32011-11-01 18:57:15 +0200422class HTMLParserTolerantTestCase(HTMLParserStrictTestCase):
R. David Murrayb579dba2010-12-03 04:06:39 +0000423
Ezio Melottib9a48f72011-11-01 15:00:59 +0200424 def get_collector(self):
Ezio Melotti95401c52013-11-23 19:52:05 +0200425 return EventCollector(convert_charrefs=False)
Ezio Melotti88ebfb12013-11-02 17:08:24 +0200426
427 def test_deprecation_warnings(self):
428 with self.assertWarns(DeprecationWarning):
Ezio Melotti95401c52013-11-23 19:52:05 +0200429 EventCollector() # convert_charrefs not passed explicitly
430 with self.assertWarns(DeprecationWarning):
Ezio Melotti88ebfb12013-11-02 17:08:24 +0200431 EventCollector(strict=True)
432 with self.assertWarns(DeprecationWarning):
433 EventCollector(strict=False)
434 with self.assertRaises(html.parser.HTMLParseError):
435 with self.assertWarns(DeprecationWarning):
436 EventCollector().error('test')
R. David Murrayb579dba2010-12-03 04:06:39 +0000437
438 def test_tolerant_parsing(self):
439 self._run_check('<html <html>te>>xt&a<<bc</a></html>\n'
440 '<img src="URL><//img></html</html>', [
Ezio Melottic2fe5772011-11-14 18:53:33 +0200441 ('starttag', 'html', [('<html', None)]),
442 ('data', 'te>>xt'),
443 ('entityref', 'a'),
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200444 ('data', '<'),
445 ('starttag', 'bc<', [('a', None)]),
Ezio Melottic2fe5772011-11-14 18:53:33 +0200446 ('endtag', 'html'),
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200447 ('data', '\n<img src="URL>'),
448 ('comment', '/img'),
449 ('endtag', 'html<')])
R. David Murrayb579dba2010-12-03 04:06:39 +0000450
Ezio Melotti86f67122012-02-13 14:11:27 +0200451 def test_starttag_junk_chars(self):
452 self._run_check("</>", [])
453 self._run_check("</$>", [('comment', '$')])
454 self._run_check("</", [('data', '</')])
455 self._run_check("</a", [('data', '</a')])
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200456 self._run_check("<a<a>", [('starttag', 'a<a', [])])
Ezio Melotti86f67122012-02-13 14:11:27 +0200457 self._run_check("</a<a>", [('endtag', 'a<a')])
458 self._run_check("<!", [('data', '<!')])
459 self._run_check("<a", [('data', '<a')])
460 self._run_check("<a foo='bar'", [('data', "<a foo='bar'")])
461 self._run_check("<a foo='bar", [('data', "<a foo='bar")])
462 self._run_check("<a foo='>'", [('data', "<a foo='>'")])
463 self._run_check("<a foo='>", [('data', "<a foo='>")])
Ezio Melotti7165d8b2013-11-07 18:33:24 +0200464 self._run_check("<a$>", [('starttag', 'a$', [])])
465 self._run_check("<a$b>", [('starttag', 'a$b', [])])
466 self._run_check("<a$b/>", [('startendtag', 'a$b', [])])
467 self._run_check("<a$b >", [('starttag', 'a$b', [])])
468 self._run_check("<a$b />", [('startendtag', 'a$b', [])])
Ezio Melotti86f67122012-02-13 14:11:27 +0200469
Ezio Melotti29877e82012-02-21 09:25:00 +0200470 def test_slashes_in_starttag(self):
471 self._run_check('<a foo="var"/>', [('startendtag', 'a', [('foo', 'var')])])
472 html = ('<img width=902 height=250px '
473 'src="/sites/default/files/images/homepage/foo.jpg" '
474 '/*what am I doing here*/ />')
475 expected = [(
476 'startendtag', 'img',
477 [('width', '902'), ('height', '250px'),
478 ('src', '/sites/default/files/images/homepage/foo.jpg'),
479 ('*what', None), ('am', None), ('i', None),
480 ('doing', None), ('here*', None)]
481 )]
482 self._run_check(html, expected)
483 html = ('<a / /foo/ / /=/ / /bar/ / />'
484 '<a / /foo/ / /=/ / /bar/ / >')
485 expected = [
486 ('startendtag', 'a', [('foo', None), ('=', None), ('bar', None)]),
487 ('starttag', 'a', [('foo', None), ('=', None), ('bar', None)])
488 ]
489 self._run_check(html, expected)
Ezio Melotti0780b6b2012-04-18 19:18:22 -0600490 #see issue #14538
491 html = ('<meta><meta / ><meta // ><meta / / >'
492 '<meta/><meta /><meta //><meta//>')
493 expected = [
494 ('starttag', 'meta', []), ('starttag', 'meta', []),
495 ('starttag', 'meta', []), ('starttag', 'meta', []),
496 ('startendtag', 'meta', []), ('startendtag', 'meta', []),
497 ('startendtag', 'meta', []), ('startendtag', 'meta', []),
498 ]
499 self._run_check(html, expected)
Ezio Melotti29877e82012-02-21 09:25:00 +0200500
Ezio Melotti86f67122012-02-13 14:11:27 +0200501 def test_declaration_junk_chars(self):
Ezio Melottif4ab4912012-02-13 15:50:37 +0200502 self._run_check("<!DOCTYPE foo $ >", [('decl', 'DOCTYPE foo $ ')])
Ezio Melotti86f67122012-02-13 14:11:27 +0200503
504 def test_illegal_declarations(self):
Ezio Melotti86f67122012-02-13 14:11:27 +0200505 self._run_check('<!spacer type="block" height="25">',
506 [('comment', 'spacer type="block" height="25"')])
507
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200508 def test_with_unquoted_attributes(self):
Ezio Melottib9a48f72011-11-01 15:00:59 +0200509 # see #12008
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200510 html = ("<html><body bgcolor=d0ca90 text='181008'>"
511 "<table cellspacing=0 cellpadding=1 width=100% ><tr>"
512 "<td align=left><font size=-1>"
513 "- <a href=/rabota/><span class=en> software-and-i</span></a>"
514 "- <a href='/1/'><span class=en> library</span></a></table>")
515 expected = [
516 ('starttag', 'html', []),
517 ('starttag', 'body', [('bgcolor', 'd0ca90'), ('text', '181008')]),
518 ('starttag', 'table',
519 [('cellspacing', '0'), ('cellpadding', '1'), ('width', '100%')]),
520 ('starttag', 'tr', []),
521 ('starttag', 'td', [('align', 'left')]),
522 ('starttag', 'font', [('size', '-1')]),
523 ('data', '- '), ('starttag', 'a', [('href', '/rabota/')]),
524 ('starttag', 'span', [('class', 'en')]), ('data', ' software-and-i'),
525 ('endtag', 'span'), ('endtag', 'a'),
526 ('data', '- '), ('starttag', 'a', [('href', '/1/')]),
527 ('starttag', 'span', [('class', 'en')]), ('data', ' library'),
528 ('endtag', 'span'), ('endtag', 'a'), ('endtag', 'table')
529 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200530 self._run_check(html, expected)
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200531
R. David Murrayb579dba2010-12-03 04:06:39 +0000532 def test_comma_between_attributes(self):
533 self._run_check('<form action="/xxx.php?a=1&amp;b=2&amp", '
534 'method="post">', [
535 ('starttag', 'form',
Ezio Melotti46495182012-06-24 22:02:56 +0200536 [('action', '/xxx.php?a=1&b=2&'),
Ezio Melottic2fe5772011-11-14 18:53:33 +0200537 (',', None), ('method', 'post')])])
R. David Murrayb579dba2010-12-03 04:06:39 +0000538
539 def test_weird_chars_in_unquoted_attribute_values(self):
540 self._run_check('<form action=bogus|&#()value>', [
541 ('starttag', 'form',
Ezio Melottic1e73c32011-11-01 18:57:15 +0200542 [('action', 'bogus|&#()value')])])
R. David Murrayb579dba2010-12-03 04:06:39 +0000543
Ezio Melotti5211ffe2012-02-13 11:24:50 +0200544 def test_invalid_end_tags(self):
545 # A collection of broken end tags. <br> is used as separator.
546 # see http://www.w3.org/TR/html5/tokenization.html#end-tag-open-state
547 # and #13993
548 html = ('<br></label</p><br></div end tmAd-leaderBoard><br></<h4><br>'
549 '</li class="unit"><br></li\r\n\t\t\t\t\t\t</ul><br></><br>')
550 expected = [('starttag', 'br', []),
551 # < is part of the name, / is discarded, p is an attribute
552 ('endtag', 'label<'),
553 ('starttag', 'br', []),
554 # text and attributes are discarded
555 ('endtag', 'div'),
556 ('starttag', 'br', []),
557 # comment because the first char after </ is not a-zA-Z
558 ('comment', '<h4'),
559 ('starttag', 'br', []),
560 # attributes are discarded
561 ('endtag', 'li'),
562 ('starttag', 'br', []),
563 # everything till ul (included) is discarded
564 ('endtag', 'li'),
565 ('starttag', 'br', []),
566 # </> is ignored
567 ('starttag', 'br', [])]
568 self._run_check(html, expected)
569
570 def test_broken_invalid_end_tag(self):
571 # This is technically wrong (the "> shouldn't be included in the 'data')
572 # but is probably not worth fixing it (in addition to all the cases of
573 # the previous test, it would require a full attribute parsing).
574 # see #13993
575 html = '<b>This</b attr=">"> confuses the parser'
576 expected = [('starttag', 'b', []),
577 ('data', 'This'),
578 ('endtag', 'b'),
579 ('data', '"> confuses the parser')]
580 self._run_check(html, expected)
581
Ezio Melottib9a48f72011-11-01 15:00:59 +0200582 def test_correct_detection_of_start_tags(self):
583 # see #13273
Ezio Melottif50ffa92011-10-28 13:21:09 +0300584 html = ('<div style="" ><b>The <a href="some_url">rain</a> '
585 '<br /> in <span>Spain</span></b></div>')
586 expected = [
587 ('starttag', 'div', [('style', '')]),
588 ('starttag', 'b', []),
589 ('data', 'The '),
590 ('starttag', 'a', [('href', 'some_url')]),
591 ('data', 'rain'),
592 ('endtag', 'a'),
593 ('data', ' '),
594 ('startendtag', 'br', []),
595 ('data', ' in '),
596 ('starttag', 'span', []),
597 ('data', 'Spain'),
598 ('endtag', 'span'),
599 ('endtag', 'b'),
600 ('endtag', 'div')
601 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200602 self._run_check(html, expected)
Ezio Melottif50ffa92011-10-28 13:21:09 +0300603
Ezio Melottif50ffa92011-10-28 13:21:09 +0300604 html = '<div style="", foo = "bar" ><b>The <a href="some_url">rain</a>'
605 expected = [
Ezio Melottic2fe5772011-11-14 18:53:33 +0200606 ('starttag', 'div', [('style', ''), (',', None), ('foo', 'bar')]),
Ezio Melottif50ffa92011-10-28 13:21:09 +0300607 ('starttag', 'b', []),
608 ('data', 'The '),
609 ('starttag', 'a', [('href', 'some_url')]),
610 ('data', 'rain'),
611 ('endtag', 'a'),
612 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200613 self._run_check(html, expected)
Ezio Melottif50ffa92011-10-28 13:21:09 +0300614
Ezio Melotti8e596a72013-05-01 16:18:25 +0300615 def test_EOF_in_charref(self):
616 # see #17802
617 # This test checks that the UnboundLocalError reported in the issue
618 # is not raised, however I'm not sure the returned values are correct.
619 # Maybe HTMLParser should use self.unescape for these
620 data = [
621 ('a&', [('data', 'a&')]),
622 ('a&b', [('data', 'ab')]),
623 ('a&b ', [('data', 'a'), ('entityref', 'b'), ('data', ' ')]),
624 ('a&b;', [('data', 'a'), ('entityref', 'b')]),
625 ]
626 for html, expected in data:
627 self._run_check(html, expected)
628
Ezio Melottif6de9eb2013-11-22 05:49:29 +0200629 def test_unescape_method(self):
630 from html import unescape
631 p = self.get_collector()
632 with self.assertWarns(DeprecationWarning):
633 s = '&quot;&#34;&#x22;&quot&#34&#x22&#bad;'
634 self.assertEqual(p.unescape(s), unescape(s))
635
Ezio Melottifa3702d2012-02-10 10:45:44 +0200636 def test_broken_comments(self):
637 html = ('<! not really a comment >'
638 '<! not a comment either -->'
639 '<! -- close enough -->'
Ezio Melottif4ab4912012-02-13 15:50:37 +0200640 '<!><!<-- this was an empty comment>'
Ezio Melottifa3702d2012-02-10 10:45:44 +0200641 '<!!! another bogus comment !!!>')
642 expected = [
643 ('comment', ' not really a comment '),
644 ('comment', ' not a comment either --'),
645 ('comment', ' -- close enough --'),
Ezio Melottif4ab4912012-02-13 15:50:37 +0200646 ('comment', ''),
647 ('comment', '<-- this was an empty comment'),
Ezio Melottifa3702d2012-02-10 10:45:44 +0200648 ('comment', '!! another bogus comment !!!'),
649 ]
650 self._run_check(html, expected)
651
Ezio Melotti62f3d032011-12-19 07:29:03 +0200652 def test_broken_condcoms(self):
653 # these condcoms are missing the '--' after '<!' and before the '>'
654 html = ('<![if !(IE)]>broken condcom<![endif]>'
655 '<![if ! IE]><link href="favicon.tiff"/><![endif]>'
656 '<![if !IE 6]><img src="firefox.png" /><![endif]>'
657 '<![if !ie 6]><b>foo</b><![endif]>'
658 '<![if (!IE)|(lt IE 9)]><img src="mammoth.bmp" /><![endif]>')
659 # According to the HTML5 specs sections "8.2.4.44 Bogus comment state"
660 # and "8.2.4.45 Markup declaration open state", comment tokens should
661 # be emitted instead of 'unknown decl', but calling unknown_decl
662 # provides more flexibility.
663 # See also Lib/_markupbase.py:parse_declaration
664 expected = [
665 ('unknown decl', 'if !(IE)'),
666 ('data', 'broken condcom'),
667 ('unknown decl', 'endif'),
668 ('unknown decl', 'if ! IE'),
669 ('startendtag', 'link', [('href', 'favicon.tiff')]),
670 ('unknown decl', 'endif'),
671 ('unknown decl', 'if !IE 6'),
672 ('startendtag', 'img', [('src', 'firefox.png')]),
673 ('unknown decl', 'endif'),
674 ('unknown decl', 'if !ie 6'),
675 ('starttag', 'b', []),
676 ('data', 'foo'),
677 ('endtag', 'b'),
678 ('unknown decl', 'endif'),
679 ('unknown decl', 'if (!IE)|(lt IE 9)'),
680 ('startendtag', 'img', [('src', 'mammoth.bmp')]),
681 ('unknown decl', 'endif')
682 ]
683 self._run_check(html, expected)
684
Ezio Melotti6f2bb982015-09-06 21:38:06 +0300685 def test_convert_charrefs_dropped_text(self):
686 # #23144: make sure that all the events are triggered when
687 # convert_charrefs is True, even if we don't call .close()
688 parser = EventCollector(convert_charrefs=True)
689 # before the fix, bar & baz was missing
690 parser.feed("foo <a>link</a> bar &amp; baz")
691 self.assertEqual(
692 parser.get_events(),
693 [('data', 'foo '), ('starttag', 'a', []), ('data', 'link'),
694 ('endtag', 'a'), ('data', ' bar & baz')]
695 )
696
Ezio Melottic1e73c32011-11-01 18:57:15 +0200697
Ezio Melottib245ed12011-11-14 18:13:22 +0200698class AttributesStrictTestCase(TestCaseBase):
699
700 def get_collector(self):
Ezio Melotti3861d8b2012-06-23 15:27:51 +0200701 with support.check_warnings(("", DeprecationWarning), quite=False):
Ezio Melotti95401c52013-11-23 19:52:05 +0200702 return EventCollector(strict=True, convert_charrefs=False)
Ezio Melottib245ed12011-11-14 18:13:22 +0200703
704 def test_attr_syntax(self):
705 output = [
706 ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", None)])
707 ]
708 self._run_check("""<a b='v' c="v" d=v e>""", output)
709 self._run_check("""<a b = 'v' c = "v" d = v e>""", output)
710 self._run_check("""<a\nb\n=\n'v'\nc\n=\n"v"\nd\n=\nv\ne>""", output)
711 self._run_check("""<a\tb\t=\t'v'\tc\t=\t"v"\td\t=\tv\te>""", output)
712
713 def test_attr_values(self):
714 self._run_check("""<a b='xxx\n\txxx' c="yyy\t\nyyy" d='\txyz\n'>""",
715 [("starttag", "a", [("b", "xxx\n\txxx"),
716 ("c", "yyy\t\nyyy"),
717 ("d", "\txyz\n")])])
718 self._run_check("""<a b='' c="">""",
719 [("starttag", "a", [("b", ""), ("c", "")])])
720 # Regression test for SF patch #669683.
721 self._run_check("<e a=rgb(1,2,3)>",
722 [("starttag", "e", [("a", "rgb(1,2,3)")])])
723 # Regression test for SF bug #921657.
724 self._run_check(
725 "<a href=mailto:xyz@example.com>",
726 [("starttag", "a", [("href", "mailto:xyz@example.com")])])
727
728 def test_attr_nonascii(self):
729 # see issue 7311
730 self._run_check(
731 "<img src=/foo/bar.png alt=\u4e2d\u6587>",
732 [("starttag", "img", [("src", "/foo/bar.png"),
733 ("alt", "\u4e2d\u6587")])])
734 self._run_check(
735 "<a title='\u30c6\u30b9\u30c8' href='\u30c6\u30b9\u30c8.html'>",
736 [("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
737 ("href", "\u30c6\u30b9\u30c8.html")])])
738 self._run_check(
739 '<a title="\u30c6\u30b9\u30c8" href="\u30c6\u30b9\u30c8.html">',
740 [("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
741 ("href", "\u30c6\u30b9\u30c8.html")])])
742
743 def test_attr_entity_replacement(self):
744 self._run_check(
745 "<a b='&amp;&gt;&lt;&quot;&apos;'>",
746 [("starttag", "a", [("b", "&><\"'")])])
747
748 def test_attr_funky_names(self):
749 self._run_check(
750 "<a a.b='v' c:d=v e-f=v>",
751 [("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")])])
752
753 def test_entityrefs_in_attributes(self):
754 self._run_check(
755 "<html foo='&euro;&amp;&#97;&#x61;&unsupported;'>",
756 [("starttag", "html", [("foo", "\u20AC&aa&unsupported;")])])
757
758
Ezio Melottic2fe5772011-11-14 18:53:33 +0200759
760class AttributesTolerantTestCase(AttributesStrictTestCase):
761
762 def get_collector(self):
Ezio Melotti95401c52013-11-23 19:52:05 +0200763 return EventCollector(convert_charrefs=False)
Ezio Melottic2fe5772011-11-14 18:53:33 +0200764
765 def test_attr_funky_names2(self):
766 self._run_check(
767 "<a $><b $=%><c \=/>",
768 [("starttag", "a", [("$", None)]),
769 ("starttag", "b", [("$", "%")]),
770 ("starttag", "c", [("\\", "/")])])
771
772 def test_entities_in_attribute_value(self):
773 # see #1200313
774 for entity in ['&', '&amp;', '&#38;', '&#x26;']:
775 self._run_check('<a href="%s">' % entity,
776 [("starttag", "a", [("href", "&")])])
777 self._run_check("<a href='%s'>" % entity,
778 [("starttag", "a", [("href", "&")])])
779 self._run_check("<a href=%s>" % entity,
780 [("starttag", "a", [("href", "&")])])
781
782 def test_malformed_attributes(self):
783 # see #13357
784 html = (
785 "<a href=test'style='color:red;bad1'>test - bad1</a>"
786 "<a href=test'+style='color:red;ba2'>test - bad2</a>"
787 "<a href=test'&nbsp;style='color:red;bad3'>test - bad3</a>"
788 "<a href = test'&nbsp;style='color:red;bad4' >test - bad4</a>"
789 )
790 expected = [
791 ('starttag', 'a', [('href', "test'style='color:red;bad1'")]),
792 ('data', 'test - bad1'), ('endtag', 'a'),
793 ('starttag', 'a', [('href', "test'+style='color:red;ba2'")]),
794 ('data', 'test - bad2'), ('endtag', 'a'),
795 ('starttag', 'a', [('href', "test'\xa0style='color:red;bad3'")]),
796 ('data', 'test - bad3'), ('endtag', 'a'),
797 ('starttag', 'a', [('href', "test'\xa0style='color:red;bad4'")]),
798 ('data', 'test - bad4'), ('endtag', 'a')
799 ]
800 self._run_check(html, expected)
801
802 def test_malformed_adjacent_attributes(self):
803 # see #12629
804 self._run_check('<x><y z=""o"" /></x>',
805 [('starttag', 'x', []),
806 ('startendtag', 'y', [('z', ''), ('o""', None)]),
807 ('endtag', 'x')])
808 self._run_check('<x><y z="""" /></x>',
809 [('starttag', 'x', []),
810 ('startendtag', 'y', [('z', ''), ('""', None)]),
811 ('endtag', 'x')])
812
813 # see #755670 for the following 3 tests
814 def test_adjacent_attributes(self):
815 self._run_check('<a width="100%"cellspacing=0>',
816 [("starttag", "a",
817 [("width", "100%"), ("cellspacing","0")])])
818
819 self._run_check('<a id="foo"class="bar">',
820 [("starttag", "a",
821 [("id", "foo"), ("class","bar")])])
822
823 def test_missing_attribute_value(self):
824 self._run_check('<a v=>',
825 [("starttag", "a", [("v", "")])])
826
827 def test_javascript_attribute_value(self):
828 self._run_check("<a href=javascript:popup('/popup/help.html')>",
829 [("starttag", "a",
830 [("href", "javascript:popup('/popup/help.html')")])])
831
832 def test_end_tag_in_attribute_value(self):
833 # see #1745761
834 self._run_check("<a href='http://www.example.org/\">;'>spam</a>",
835 [("starttag", "a",
836 [("href", "http://www.example.org/\">;")]),
837 ("data", "spam"), ("endtag", "a")])
838
839
Fred Drakee8220492001-09-24 20:19:08 +0000840if __name__ == "__main__":
Ezio Melotti5028f4d2013-11-02 17:49:08 +0200841 unittest.main()