blob: 8c2e25e61a69429a0fac2e1d87c07a15225d907e [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):
Mark Dickinsonf64dcf32008-05-21 13:51:18 +000096 parser = html.parser.HTMLParser()
Fred Drakebd3090d2001-05-18 15:32:59 +000097 parser.feed(source)
98 parser.close()
Mark Dickinsonf64dcf32008-05-21 13:51:18 +000099 self.assertRaises(html.parser.HTMLParseError, parse)
Fred Drakebd3090d2001-05-18 15:32:59 +0000100
101
Ezio Melottic1e73c32011-11-01 18:57:15 +0200102class HTMLParserStrictTestCase(TestCaseBase):
103
104 def get_collector(self):
105 return EventCollector(strict=True)
Fred Drakebd3090d2001-05-18 15:32:59 +0000106
Fred Drake84bb9d82001-08-03 19:53:01 +0000107 def test_processing_instruction_only(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000108 self._run_check("<?processing instruction>", [
109 ("pi", "processing instruction"),
110 ])
Fred Drakefafd56f2003-04-17 22:19:26 +0000111 self._run_check("<?processing instruction ?>", [
112 ("pi", "processing instruction ?"),
113 ])
Fred Drakebd3090d2001-05-18 15:32:59 +0000114
Fred Drake84bb9d82001-08-03 19:53:01 +0000115 def test_simple_html(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000116 self._run_check("""
117<!DOCTYPE html PUBLIC 'foo'>
118<HTML>&entity;&#32;
119<!--comment1a
120-></foo><bar>&lt;<?pi?></foo<bar
121comment1b-->
122<Img sRc='Bar' isMAP>sample
123text
Fred Drake84bb9d82001-08-03 19:53:01 +0000124&#x201C;
Georg Brandld09def32006-03-09 13:27:14 +0000125<!--comment2a-- --comment2b--><!>
Fred Drakebd3090d2001-05-18 15:32:59 +0000126</Html>
127""", [
128 ("data", "\n"),
129 ("decl", "DOCTYPE html PUBLIC 'foo'"),
130 ("data", "\n"),
131 ("starttag", "html", []),
132 ("entityref", "entity"),
133 ("charref", "32"),
134 ("data", "\n"),
135 ("comment", "comment1a\n-></foo><bar>&lt;<?pi?></foo<bar\ncomment1b"),
136 ("data", "\n"),
137 ("starttag", "img", [("src", "Bar"), ("ismap", None)]),
138 ("data", "sample\ntext\n"),
Fred Drake84bb9d82001-08-03 19:53:01 +0000139 ("charref", "x201C"),
140 ("data", "\n"),
Fred Drakebd3090d2001-05-18 15:32:59 +0000141 ("comment", "comment2a-- --comment2b"),
142 ("data", "\n"),
143 ("endtag", "html"),
144 ("data", "\n"),
145 ])
146
Victor Stinnere021f4b2010-05-24 21:46:25 +0000147 def test_malformatted_charref(self):
148 self._run_check("<p>&#bad;</p>", [
149 ("starttag", "p", []),
150 ("data", "&#bad;"),
151 ("endtag", "p"),
152 ])
153
Fred Drake073148c2001-12-03 16:44:09 +0000154 def test_unclosed_entityref(self):
155 self._run_check("&entityref foo", [
156 ("entityref", "entityref"),
157 ("data", " foo"),
158 ])
159
Fred Drake029acfb2001-08-20 21:24:19 +0000160 def test_doctype_decl(self):
161 inside = """\
162DOCTYPE html [
163 <!ELEMENT html - O EMPTY>
164 <!ATTLIST html
Fred Drakec20a6982001-09-04 15:13:04 +0000165 version CDATA #IMPLIED
166 profile CDATA 'DublinCore'>
167 <!NOTATION datatype SYSTEM 'http://xml.python.org/notations/python-module'>
168 <!ENTITY myEntity 'internal parsed entity'>
169 <!ENTITY anEntity SYSTEM 'http://xml.python.org/entities/something.xml'>
170 <!ENTITY % paramEntity 'name|name|name'>
171 %paramEntity;
Fred Drake029acfb2001-08-20 21:24:19 +0000172 <!-- comment -->
173]"""
174 self._run_check("<!%s>" % inside, [
175 ("decl", inside),
176 ])
177
Fred Drake84bb9d82001-08-03 19:53:01 +0000178 def test_bad_nesting(self):
179 # Strangely, this *is* supposed to test that overlapping
180 # elements are allowed. HTMLParser is more geared toward
181 # lexing the input that parsing the structure.
Fred Drakebd3090d2001-05-18 15:32:59 +0000182 self._run_check("<a><b></a></b>", [
183 ("starttag", "a", []),
184 ("starttag", "b", []),
185 ("endtag", "a"),
186 ("endtag", "b"),
187 ])
188
Fred Drake029acfb2001-08-20 21:24:19 +0000189 def test_bare_ampersands(self):
190 self._run_check("this text & contains & ampersands &", [
191 ("data", "this text & contains & ampersands &"),
192 ])
193
194 def test_bare_pointy_brackets(self):
195 self._run_check("this < text > contains < bare>pointy< brackets", [
196 ("data", "this < text > contains < bare>pointy< brackets"),
197 ])
198
Fred Drakec20a6982001-09-04 15:13:04 +0000199 def test_illegal_declarations(self):
Fred Drake7cf613d2001-09-04 16:26:03 +0000200 self._parse_error('<!spacer type="block" height="25">')
Fred Drakec20a6982001-09-04 15:13:04 +0000201
Fred Drake84bb9d82001-08-03 19:53:01 +0000202 def test_starttag_end_boundary(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000203 self._run_check("""<a b='<'>""", [("starttag", "a", [("b", "<")])])
204 self._run_check("""<a b='>'>""", [("starttag", "a", [("b", ">")])])
205
Fred Drake84bb9d82001-08-03 19:53:01 +0000206 def test_buffer_artefacts(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000207 output = [("starttag", "a", [("b", "<")])]
208 self._run_check(["<a b='<'>"], output)
209 self._run_check(["<a ", "b='<'>"], output)
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
215 output = [("starttag", "a", [("b", ">")])]
216 self._run_check(["<a b='>'>"], output)
217 self._run_check(["<a ", "b='>'>"], output)
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
Fred Drake75d9a622004-09-08 22:57:01 +0000223 output = [("comment", "abc")]
224 self._run_check(["", "<!--abc-->"], output)
225 self._run_check(["<", "!--abc-->"], output)
226 self._run_check(["<!", "--abc-->"], output)
227 self._run_check(["<!-", "-abc-->"], output)
228 self._run_check(["<!--", "abc-->"], output)
229 self._run_check(["<!--a", "bc-->"], output)
230 self._run_check(["<!--ab", "c-->"], output)
231 self._run_check(["<!--abc", "-->"], output)
232 self._run_check(["<!--abc-", "->"], output)
233 self._run_check(["<!--abc--", ">"], output)
234 self._run_check(["<!--abc-->", ""], output)
235
Fred Drake84bb9d82001-08-03 19:53:01 +0000236 def test_starttag_junk_chars(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000237 self._parse_error("</>")
238 self._parse_error("</$>")
239 self._parse_error("</")
240 self._parse_error("</a")
Fred Drakebd3090d2001-05-18 15:32:59 +0000241 self._parse_error("<a<a>")
242 self._parse_error("</a<a>")
Fred Drakebd3090d2001-05-18 15:32:59 +0000243 self._parse_error("<!")
Fred Drakebd3090d2001-05-18 15:32:59 +0000244 self._parse_error("<a")
245 self._parse_error("<a foo='bar'")
246 self._parse_error("<a foo='bar")
247 self._parse_error("<a foo='>'")
248 self._parse_error("<a foo='>")
Fred Drakebd3090d2001-05-18 15:32:59 +0000249
Fred Drake84bb9d82001-08-03 19:53:01 +0000250 def test_declaration_junk_chars(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000251 self._parse_error("<!DOCTYPE foo $ >")
252
Fred Drake84bb9d82001-08-03 19:53:01 +0000253 def test_startendtag(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000254 self._run_check("<p/>", [
255 ("startendtag", "p", []),
256 ])
257 self._run_check("<p></p>", [
258 ("starttag", "p", []),
259 ("endtag", "p"),
260 ])
261 self._run_check("<p><img src='foo' /></p>", [
262 ("starttag", "p", []),
263 ("startendtag", "img", [("src", "foo")]),
264 ("endtag", "p"),
265 ])
266
Fred Drake84bb9d82001-08-03 19:53:01 +0000267 def test_get_starttag_text(self):
Fred Drakebd3090d2001-05-18 15:32:59 +0000268 s = """<foo:bar \n one="1"\ttwo=2 >"""
269 self._run_check_extra(s, [
270 ("starttag", "foo:bar", [("one", "1"), ("two", "2")]),
271 ("starttag_text", s)])
272
Fred Drake84bb9d82001-08-03 19:53:01 +0000273 def test_cdata_content(self):
Ezio Melotti7de56f62011-11-01 14:12:22 +0200274 contents = [
275 '<!-- not a comment --> &not-an-entity-ref;',
276 "<not a='start tag'>",
277 '<a href="" /> <p> <span></span>',
278 'foo = "</scr" + "ipt>";',
279 'foo = "</SCRIPT" + ">";',
280 'foo = <\n/script> ',
281 '<!-- document.write("</scr" + "ipt>"); -->',
282 ('\n//<![CDATA[\n'
283 'document.write(\'<s\'+\'cript type="text/javascript" '
284 'src="http://www.example.org/r=\'+new '
285 'Date().getTime()+\'"><\\/s\'+\'cript>\');\n//]]>'),
286 '\n<!-- //\nvar foo = 3.14;\n// -->\n',
287 'foo = "</sty" + "le>";',
288 '<!-- \u2603 -->',
289 # these two should be invalid according to the HTML 5 spec,
290 # section 8.1.2.2
291 #'foo = </\nscript>',
292 #'foo = </ script>',
293 ]
294 elements = ['script', 'style', 'SCRIPT', 'STYLE', 'Script', 'Style']
295 for content in contents:
296 for element in elements:
297 element_lower = element.lower()
298 s = '<{element}>{content}</{element}>'.format(element=element,
299 content=content)
300 self._run_check(s, [("starttag", element_lower, []),
301 ("data", content),
302 ("endtag", element_lower)])
303
Ezio Melotti15cb4892011-11-18 18:01:49 +0200304 def test_cdata_with_closing_tags(self):
305 # see issue #13358
306 # make sure that HTMLParser calls handle_data only once for each CDATA.
307 # The normal event collector normalizes the events in get_events,
308 # so we override it to return the original list of events.
309 class Collector(EventCollector):
310 def get_events(self):
311 return self.events
Fred Drakebd3090d2001-05-18 15:32:59 +0000312
Ezio Melotti15cb4892011-11-18 18:01:49 +0200313 content = """<!-- not a comment --> &not-an-entity-ref;
314 <a href="" /> </p><p> <span></span></style>
315 '</script' + '>'"""
316 for element in [' script', 'script ', ' script ',
317 '\nscript', 'script\n', '\nscript\n']:
318 element_lower = element.lower().strip()
319 s = '<script>{content}</{element}>'.format(element=element,
320 content=content)
321 self._run_check(s, [("starttag", element_lower, []),
322 ("data", content),
323 ("endtag", element_lower)],
324 collector=Collector())
Fred Drakebd3090d2001-05-18 15:32:59 +0000325
Ezio Melotti62f3d032011-12-19 07:29:03 +0200326 def test_condcoms(self):
327 html = ('<!--[if IE & !(lte IE 8)]>aren\'t<![endif]-->'
328 '<!--[if IE 8]>condcoms<![endif]-->'
329 '<!--[if lte IE 7]>pretty?<![endif]-->')
330 expected = [('comment', "[if IE & !(lte IE 8)]>aren't<![endif]"),
331 ('comment', '[if IE 8]>condcoms<![endif]'),
332 ('comment', '[if lte IE 7]>pretty?<![endif]')]
333 self._run_check(html, expected)
334
335
Ezio Melottic1e73c32011-11-01 18:57:15 +0200336class HTMLParserTolerantTestCase(HTMLParserStrictTestCase):
R. David Murrayb579dba2010-12-03 04:06:39 +0000337
Ezio Melottib9a48f72011-11-01 15:00:59 +0200338 def get_collector(self):
339 return EventCollector(strict=False)
R. David Murrayb579dba2010-12-03 04:06:39 +0000340
341 def test_tolerant_parsing(self):
342 self._run_check('<html <html>te>>xt&a<<bc</a></html>\n'
343 '<img src="URL><//img></html</html>', [
Ezio Melottic2fe5772011-11-14 18:53:33 +0200344 ('starttag', 'html', [('<html', None)]),
345 ('data', 'te>>xt'),
346 ('entityref', 'a'),
347 ('data', '<<bc'),
348 ('endtag', 'a'),
349 ('endtag', 'html'),
350 ('data', '\n<img src="URL><//img></html'),
351 ('endtag', 'html')])
R. David Murrayb579dba2010-12-03 04:06:39 +0000352
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200353 def test_with_unquoted_attributes(self):
Ezio Melottib9a48f72011-11-01 15:00:59 +0200354 # see #12008
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200355 html = ("<html><body bgcolor=d0ca90 text='181008'>"
356 "<table cellspacing=0 cellpadding=1 width=100% ><tr>"
357 "<td align=left><font size=-1>"
358 "- <a href=/rabota/><span class=en> software-and-i</span></a>"
359 "- <a href='/1/'><span class=en> library</span></a></table>")
360 expected = [
361 ('starttag', 'html', []),
362 ('starttag', 'body', [('bgcolor', 'd0ca90'), ('text', '181008')]),
363 ('starttag', 'table',
364 [('cellspacing', '0'), ('cellpadding', '1'), ('width', '100%')]),
365 ('starttag', 'tr', []),
366 ('starttag', 'td', [('align', 'left')]),
367 ('starttag', 'font', [('size', '-1')]),
368 ('data', '- '), ('starttag', 'a', [('href', '/rabota/')]),
369 ('starttag', 'span', [('class', 'en')]), ('data', ' software-and-i'),
370 ('endtag', 'span'), ('endtag', 'a'),
371 ('data', '- '), ('starttag', 'a', [('href', '/1/')]),
372 ('starttag', 'span', [('class', 'en')]), ('data', ' library'),
373 ('endtag', 'span'), ('endtag', 'a'), ('endtag', 'table')
374 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200375 self._run_check(html, expected)
Ezio Melotti18b0e5b2011-11-01 14:42:54 +0200376
R. David Murrayb579dba2010-12-03 04:06:39 +0000377 def test_comma_between_attributes(self):
378 self._run_check('<form action="/xxx.php?a=1&amp;b=2&amp", '
379 'method="post">', [
380 ('starttag', 'form',
381 [('action', '/xxx.php?a=1&b=2&amp'),
Ezio Melottic2fe5772011-11-14 18:53:33 +0200382 (',', None), ('method', 'post')])])
R. David Murrayb579dba2010-12-03 04:06:39 +0000383
384 def test_weird_chars_in_unquoted_attribute_values(self):
385 self._run_check('<form action=bogus|&#()value>', [
386 ('starttag', 'form',
Ezio Melottic1e73c32011-11-01 18:57:15 +0200387 [('action', 'bogus|&#()value')])])
R. David Murrayb579dba2010-12-03 04:06:39 +0000388
Ezio Melottib9a48f72011-11-01 15:00:59 +0200389 def test_correct_detection_of_start_tags(self):
390 # see #13273
Ezio Melottif50ffa92011-10-28 13:21:09 +0300391 html = ('<div style="" ><b>The <a href="some_url">rain</a> '
392 '<br /> in <span>Spain</span></b></div>')
393 expected = [
394 ('starttag', 'div', [('style', '')]),
395 ('starttag', 'b', []),
396 ('data', 'The '),
397 ('starttag', 'a', [('href', 'some_url')]),
398 ('data', 'rain'),
399 ('endtag', 'a'),
400 ('data', ' '),
401 ('startendtag', 'br', []),
402 ('data', ' in '),
403 ('starttag', 'span', []),
404 ('data', 'Spain'),
405 ('endtag', 'span'),
406 ('endtag', 'b'),
407 ('endtag', 'div')
408 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200409 self._run_check(html, expected)
Ezio Melottif50ffa92011-10-28 13:21:09 +0300410
Ezio Melottif50ffa92011-10-28 13:21:09 +0300411 html = '<div style="", foo = "bar" ><b>The <a href="some_url">rain</a>'
412 expected = [
Ezio Melottic2fe5772011-11-14 18:53:33 +0200413 ('starttag', 'div', [('style', ''), (',', None), ('foo', 'bar')]),
Ezio Melottif50ffa92011-10-28 13:21:09 +0300414 ('starttag', 'b', []),
415 ('data', 'The '),
416 ('starttag', 'a', [('href', 'some_url')]),
417 ('data', 'rain'),
418 ('endtag', 'a'),
419 ]
Ezio Melottic1e73c32011-11-01 18:57:15 +0200420 self._run_check(html, expected)
Ezio Melottif50ffa92011-10-28 13:21:09 +0300421
Senthil Kumaran164540f2010-12-28 15:55:16 +0000422 def test_unescape_function(self):
423 p = html.parser.HTMLParser()
424 self.assertEqual(p.unescape('&#bad;'),'&#bad;')
425 self.assertEqual(p.unescape('&#0038;'),'&')
Ezio Melottid9e0b062011-09-05 17:11:06 +0300426 # see #12888
427 self.assertEqual(p.unescape('&#123; ' * 1050), '{ ' * 1050)
R. David Murrayb579dba2010-12-03 04:06:39 +0000428
Ezio Melotti62f3d032011-12-19 07:29:03 +0200429 def test_broken_condcoms(self):
430 # these condcoms are missing the '--' after '<!' and before the '>'
431 html = ('<![if !(IE)]>broken condcom<![endif]>'
432 '<![if ! IE]><link href="favicon.tiff"/><![endif]>'
433 '<![if !IE 6]><img src="firefox.png" /><![endif]>'
434 '<![if !ie 6]><b>foo</b><![endif]>'
435 '<![if (!IE)|(lt IE 9)]><img src="mammoth.bmp" /><![endif]>')
436 # According to the HTML5 specs sections "8.2.4.44 Bogus comment state"
437 # and "8.2.4.45 Markup declaration open state", comment tokens should
438 # be emitted instead of 'unknown decl', but calling unknown_decl
439 # provides more flexibility.
440 # See also Lib/_markupbase.py:parse_declaration
441 expected = [
442 ('unknown decl', 'if !(IE)'),
443 ('data', 'broken condcom'),
444 ('unknown decl', 'endif'),
445 ('unknown decl', 'if ! IE'),
446 ('startendtag', 'link', [('href', 'favicon.tiff')]),
447 ('unknown decl', 'endif'),
448 ('unknown decl', 'if !IE 6'),
449 ('startendtag', 'img', [('src', 'firefox.png')]),
450 ('unknown decl', 'endif'),
451 ('unknown decl', 'if !ie 6'),
452 ('starttag', 'b', []),
453 ('data', 'foo'),
454 ('endtag', 'b'),
455 ('unknown decl', 'endif'),
456 ('unknown decl', 'if (!IE)|(lt IE 9)'),
457 ('startendtag', 'img', [('src', 'mammoth.bmp')]),
458 ('unknown decl', 'endif')
459 ]
460 self._run_check(html, expected)
461
Ezio Melottic1e73c32011-11-01 18:57:15 +0200462
Ezio Melottib245ed12011-11-14 18:13:22 +0200463class AttributesStrictTestCase(TestCaseBase):
464
465 def get_collector(self):
466 return EventCollector(strict=True)
467
468 def test_attr_syntax(self):
469 output = [
470 ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", None)])
471 ]
472 self._run_check("""<a b='v' c="v" d=v e>""", output)
473 self._run_check("""<a b = 'v' c = "v" d = v e>""", output)
474 self._run_check("""<a\nb\n=\n'v'\nc\n=\n"v"\nd\n=\nv\ne>""", output)
475 self._run_check("""<a\tb\t=\t'v'\tc\t=\t"v"\td\t=\tv\te>""", output)
476
477 def test_attr_values(self):
478 self._run_check("""<a b='xxx\n\txxx' c="yyy\t\nyyy" d='\txyz\n'>""",
479 [("starttag", "a", [("b", "xxx\n\txxx"),
480 ("c", "yyy\t\nyyy"),
481 ("d", "\txyz\n")])])
482 self._run_check("""<a b='' c="">""",
483 [("starttag", "a", [("b", ""), ("c", "")])])
484 # Regression test for SF patch #669683.
485 self._run_check("<e a=rgb(1,2,3)>",
486 [("starttag", "e", [("a", "rgb(1,2,3)")])])
487 # Regression test for SF bug #921657.
488 self._run_check(
489 "<a href=mailto:xyz@example.com>",
490 [("starttag", "a", [("href", "mailto:xyz@example.com")])])
491
492 def test_attr_nonascii(self):
493 # see issue 7311
494 self._run_check(
495 "<img src=/foo/bar.png alt=\u4e2d\u6587>",
496 [("starttag", "img", [("src", "/foo/bar.png"),
497 ("alt", "\u4e2d\u6587")])])
498 self._run_check(
499 "<a title='\u30c6\u30b9\u30c8' href='\u30c6\u30b9\u30c8.html'>",
500 [("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
501 ("href", "\u30c6\u30b9\u30c8.html")])])
502 self._run_check(
503 '<a title="\u30c6\u30b9\u30c8" href="\u30c6\u30b9\u30c8.html">',
504 [("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
505 ("href", "\u30c6\u30b9\u30c8.html")])])
506
507 def test_attr_entity_replacement(self):
508 self._run_check(
509 "<a b='&amp;&gt;&lt;&quot;&apos;'>",
510 [("starttag", "a", [("b", "&><\"'")])])
511
512 def test_attr_funky_names(self):
513 self._run_check(
514 "<a a.b='v' c:d=v e-f=v>",
515 [("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")])])
516
517 def test_entityrefs_in_attributes(self):
518 self._run_check(
519 "<html foo='&euro;&amp;&#97;&#x61;&unsupported;'>",
520 [("starttag", "html", [("foo", "\u20AC&aa&unsupported;")])])
521
522
Ezio Melottic2fe5772011-11-14 18:53:33 +0200523
524class AttributesTolerantTestCase(AttributesStrictTestCase):
525
526 def get_collector(self):
527 return EventCollector(strict=False)
528
529 def test_attr_funky_names2(self):
530 self._run_check(
531 "<a $><b $=%><c \=/>",
532 [("starttag", "a", [("$", None)]),
533 ("starttag", "b", [("$", "%")]),
534 ("starttag", "c", [("\\", "/")])])
535
536 def test_entities_in_attribute_value(self):
537 # see #1200313
538 for entity in ['&', '&amp;', '&#38;', '&#x26;']:
539 self._run_check('<a href="%s">' % entity,
540 [("starttag", "a", [("href", "&")])])
541 self._run_check("<a href='%s'>" % entity,
542 [("starttag", "a", [("href", "&")])])
543 self._run_check("<a href=%s>" % entity,
544 [("starttag", "a", [("href", "&")])])
545
546 def test_malformed_attributes(self):
547 # see #13357
548 html = (
549 "<a href=test'style='color:red;bad1'>test - bad1</a>"
550 "<a href=test'+style='color:red;ba2'>test - bad2</a>"
551 "<a href=test'&nbsp;style='color:red;bad3'>test - bad3</a>"
552 "<a href = test'&nbsp;style='color:red;bad4' >test - bad4</a>"
553 )
554 expected = [
555 ('starttag', 'a', [('href', "test'style='color:red;bad1'")]),
556 ('data', 'test - bad1'), ('endtag', 'a'),
557 ('starttag', 'a', [('href', "test'+style='color:red;ba2'")]),
558 ('data', 'test - bad2'), ('endtag', 'a'),
559 ('starttag', 'a', [('href', "test'\xa0style='color:red;bad3'")]),
560 ('data', 'test - bad3'), ('endtag', 'a'),
561 ('starttag', 'a', [('href', "test'\xa0style='color:red;bad4'")]),
562 ('data', 'test - bad4'), ('endtag', 'a')
563 ]
564 self._run_check(html, expected)
565
566 def test_malformed_adjacent_attributes(self):
567 # see #12629
568 self._run_check('<x><y z=""o"" /></x>',
569 [('starttag', 'x', []),
570 ('startendtag', 'y', [('z', ''), ('o""', None)]),
571 ('endtag', 'x')])
572 self._run_check('<x><y z="""" /></x>',
573 [('starttag', 'x', []),
574 ('startendtag', 'y', [('z', ''), ('""', None)]),
575 ('endtag', 'x')])
576
577 # see #755670 for the following 3 tests
578 def test_adjacent_attributes(self):
579 self._run_check('<a width="100%"cellspacing=0>',
580 [("starttag", "a",
581 [("width", "100%"), ("cellspacing","0")])])
582
583 self._run_check('<a id="foo"class="bar">',
584 [("starttag", "a",
585 [("id", "foo"), ("class","bar")])])
586
587 def test_missing_attribute_value(self):
588 self._run_check('<a v=>',
589 [("starttag", "a", [("v", "")])])
590
591 def test_javascript_attribute_value(self):
592 self._run_check("<a href=javascript:popup('/popup/help.html')>",
593 [("starttag", "a",
594 [("href", "javascript:popup('/popup/help.html')")])])
595
596 def test_end_tag_in_attribute_value(self):
597 # see #1745761
598 self._run_check("<a href='http://www.example.org/\">;'>spam</a>",
599 [("starttag", "a",
600 [("href", "http://www.example.org/\">;")]),
601 ("data", "spam"), ("endtag", "a")])
602
603
604
Fred Drakee8220492001-09-24 20:19:08 +0000605def test_main():
Ezio Melottib245ed12011-11-14 18:13:22 +0200606 support.run_unittest(HTMLParserStrictTestCase, HTMLParserTolerantTestCase,
Ezio Melottic2fe5772011-11-14 18:53:33 +0200607 AttributesStrictTestCase, AttributesTolerantTestCase)
Fred Drakee8220492001-09-24 20:19:08 +0000608
609
610if __name__ == "__main__":
611 test_main()