Debian Codegraph @

lib-python/3/test/test_htmlparser.py

raw symbols SCIP
1 """Tests for HTMLParser.py."""
2
3 import html.parser
4 import pprint
5 import unittest
6
7 from test import support
8
9
10 SAMPLE_RCDATA = (
11 '<!-- not a comment -->'
12 "<not a='start tag'>"
13 '<![CDATA[not a cdata]]>'
14 '<!not a bogus comment>'
15 '</not a bogus comment>'
16 '\u2603'
17 )
18
19 SAMPLE_RAWTEXT = SAMPLE_RCDATA + '&amp;&#9786;'
20
21
22 class EventCollector(html.parser.HTMLParser):
23
24 def __init__(self, *args, autocdata=False, **kw):
25 self.autocdata = autocdata
26 self.events = []
27 self.append = self.events.append
28 html.parser.HTMLParser.__init__(self, *args, **kw)
29 if autocdata:
30 self._set_support_cdata(False)
31
32 def get_events(self):
33 # Normalize the list of events so that buffer artefacts don't
34 # separate runs of contiguous characters.
35 L = []
36 prevtype = None
37 for event in self.events:
38 type = event[0]
39 if type == prevtype == "data":
40 L[-1] = ("data", L[-1][1] + event[1])
41 else:
42 L.append(event)
43 prevtype = type
44 self.events = L
45 return L
46
47 # structure markup
48
49 def handle_starttag(self, tag, attrs):
50 self.append(("starttag", tag, attrs))
51 if self.autocdata and tag == 'svg':
52 self._set_support_cdata(True)
53
54 def handle_startendtag(self, tag, attrs):
55 self.append(("startendtag", tag, attrs))
56
57 def handle_endtag(self, tag):
58 self.append(("endtag", tag))
59 if self.autocdata and tag == 'svg':
60 self._set_support_cdata(False)
61
62 # all other markup
63
64 def handle_comment(self, data):
65 self.append(("comment", data))
66
67 def handle_charref(self, data):
68 self.append(("charref", data))
69
70 def handle_data(self, data):
71 self.append(("data", data))
72
73 def handle_decl(self, data):
74 self.append(("decl", data))
75
76 def handle_entityref(self, data):
77 self.append(("entityref", data))
78
79 def handle_pi(self, data):
80 self.append(("pi", data))
81
82 def unknown_decl(self, decl):
83 self.append(("unknown decl", decl))
84
85
86 class EventCollectorExtra(EventCollector):
87
88 def handle_starttag(self, tag, attrs):
89 EventCollector.handle_starttag(self, tag, attrs)
90 self.append(("starttag_text", self.get_starttag_text()))
91
92
93 class EventCollectorCharrefs(EventCollector):
94
95 def handle_charref(self, data):
96 self.fail('This should never be called with convert_charrefs=True')
97
98 def handle_entityref(self, data):
99 self.fail('This should never be called with convert_charrefs=True')
100
101
102 # The normal event collector normalizes the events in get_events,
103 # so we override it to return the original list of events.
104 class EventCollectorNoNormalize(EventCollector):
105 def get_events(self):
106 return self.events
107
108
109 class TestCaseBase(unittest.TestCase):
110
111 def get_collector(self):
112 return EventCollector(convert_charrefs=False)
113
114 def _run_check(self, source, expected_events, collector=None):
115 if collector is None:
116 collector = self.get_collector()
117 parser = collector
118 for s in source:
119 parser.feed(s)
120 parser.close()
121 events = parser.get_events()
122 if events != expected_events:
123 self.fail("received events did not match expected events" +
124 "\nSource:\n" + repr(source) +
125 "\nExpected:\n" + pprint.pformat(expected_events) +
126 "\nReceived:\n" + pprint.pformat(events))
127
128 def _run_check_extra(self, source, events):
129 self._run_check(source, events,
130 EventCollectorExtra(convert_charrefs=False))
131
132
133 class HTMLParserTestCase(TestCaseBase):
134
135 def test_processing_instruction_only(self):
136 self._run_check("<?processing instruction>", [
137 ("pi", "processing instruction"),
138 ])
139 self._run_check("<?processing instruction ?>", [
140 ("pi", "processing instruction ?"),
141 ])
142
143 def test_simple_html(self):
144 self._run_check("""
145 <!DOCTYPE html PUBLIC 'foo'>
146 <HTML>&entity;&#32;
147 <!--comment1a
148 -></foo><bar>&lt;<?pi?></foo<bar
149 comment1b-->
150 <Img sRc='Bar' isMAP>sample
151 text
152 &#x201C;
153 <!--comment2a-- --comment2b-->
154 </Html>
155 """, [
156 ("data", "\n"),
157 ("decl", "DOCTYPE html PUBLIC 'foo'"),
158 ("data", "\n"),
159 ("starttag", "html", []),
160 ("entityref", "entity"),
161 ("charref", "32"),
162 ("data", "\n"),
163 ("comment", "comment1a\n-></foo><bar>&lt;<?pi?></foo<bar\ncomment1b"),
164 ("data", "\n"),
165 ("starttag", "img", [("src", "Bar"), ("ismap", None)]),
166 ("data", "sample\ntext\n"),
167 ("charref", "x201C"),
168 ("data", "\n"),
169 ("comment", "comment2a-- --comment2b"),
170 ("data", "\n"),
171 ("endtag", "html"),
172 ("data", "\n"),
173 ])
174
175 def test_malformatted_charref(self):
176 self._run_check("<p>&#bad;</p>", [
177 ("starttag", "p", []),
178 ("data", "&#bad;"),
179 ("endtag", "p"),
180 ])
181 # add the [] as a workaround to avoid buffering (see #20288)
182 self._run_check(["<div>&#bad;</div>"], [
183 ("starttag", "div", []),
184 ("data", "&#bad;"),
185 ("endtag", "div"),
186 ])
187
188 def test_unclosed_entityref(self):
189 self._run_check("&entityref foo", [
190 ("entityref", "entityref"),
191 ("data", " foo"),
192 ])
193
194 def test_bad_nesting(self):
195 # Strangely, this *is* supposed to test that overlapping
196 # elements are allowed. HTMLParser is more geared toward
197 # lexing the input that parsing the structure.
198 self._run_check("<a><b></a></b>", [
199 ("starttag", "a", []),
200 ("starttag", "b", []),
201 ("endtag", "a"),
202 ("endtag", "b"),
203 ])
204
205 def test_bare_ampersands(self):
206 self._run_check("this text & contains & ampersands &", [
207 ("data", "this text & contains & ampersands &"),
208 ])
209
210 def test_bare_pointy_brackets(self):
211 self._run_check("this < text > contains < bare>pointy< brackets", [
212 ("data", "this < text > contains < bare>pointy< brackets"),
213 ])
214
215 def test_starttag_end_boundary(self):
216 self._run_check("""<a b='<'>""", [("starttag", "a", [("b", "<")])])
217 self._run_check("""<a b='>'>""", [("starttag", "a", [("b", ">")])])
218
219 def test_buffer_artefacts(self):
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
228 output = [("starttag", "a", [("b", ">")])]
229 self._run_check(["<a b='>'>"], output)
230 self._run_check(["<a ", "b='>'>"], output)
231 self._run_check(["<a b", "='>'>"], output)
232 self._run_check(["<a b=", "'>'>"], output)
233 self._run_check(["<a b='>", "'>"], output)
234 self._run_check(["<a b='>'", ">"], output)
235
236 output = [("comment", "abc")]
237 self._run_check(["", "<!--abc-->"], output)
238 self._run_check(["<", "!--abc-->"], output)
239 self._run_check(["<!", "--abc-->"], output)
240 self._run_check(["<!-", "-abc-->"], output)
241 self._run_check(["<!--", "abc-->"], output)
242 self._run_check(["<!--a", "bc-->"], output)
243 self._run_check(["<!--ab", "c-->"], output)
244 self._run_check(["<!--abc", "-->"], output)
245 self._run_check(["<!--abc-", "->"], output)
246 self._run_check(["<!--abc--", ">"], output)
247 self._run_check(["<!--abc-->", ""], output)
248
249 def test_valid_doctypes(self):
250 # from http://www.w3.org/QA/2002/04/valid-dtd-list.html
251 dtds = ['HTML', # HTML5 doctype
252 ('HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
253 '"http://www.w3.org/TR/html4/strict.dtd"'),
254 ('HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" '
255 '"http://www.w3.org/TR/html4/loose.dtd"'),
256 ('html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" '
257 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"'),
258 ('html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" '
259 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"'),
260 ('math PUBLIC "-//W3C//DTD MathML 2.0//EN" '
261 '"http://www.w3.org/Math/DTD/mathml2/mathml2.dtd"'),
262 ('html PUBLIC "-//W3C//DTD '
263 'XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" '
264 '"http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd"'),
265 ('svg PUBLIC "-//W3C//DTD SVG 1.1//EN" '
266 '"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"'),
267 'html PUBLIC "-//IETF//DTD HTML 2.0//EN"',
268 'html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"']
269 for dtd in dtds:
270 self._run_check("<!DOCTYPE %s>" % dtd,
271 [('decl', 'DOCTYPE ' + dtd)])
272
273 def test_startendtag(self):
274 self._run_check("<p/>", [
275 ("startendtag", "p", []),
276 ])
277 self._run_check("<p></p>", [
278 ("starttag", "p", []),
279 ("endtag", "p"),
280 ])
281 self._run_check("<p><img src='foo' /></p>", [
282 ("starttag", "p", []),
283 ("startendtag", "img", [("src", "foo")]),
284 ("endtag", "p"),
285 ])
286
287 def test_get_starttag_text(self):
288 s = """<foo:bar \n one="1"\ttwo=2 >"""
289 self._run_check_extra(s, [
290 ("starttag", "foo:bar", [("one", "1"), ("two", "2")]),
291 ("starttag_text", s)])
292
293 @support.subTests('content', [
294 '<!-- not a comment --> &not-an-entity-ref;',
295 "<not a='start tag'>",
296 '<a href="" /> <p> <span></span>',
297 'foo = "</scr" + "ipt>";',
298 'foo = "</SCRIPT" + ">";',
299 'foo = <\n/script> ',
300 '<!-- document.write("</scr" + "ipt>"); -->',
301 ('\n//<![CDATA[\n'
302 'document.write(\'<s\'+\'cript type="text/javascript" '
303 'src="http://www.example.org/r=\'+new '
304 'Date().getTime()+\'"><\\/s\'+\'cript>\');\n//]]>'),
305 '\n<!-- //\nvar foo = 3.14;\n// -->\n',
306 '<!-- \u2603 -->',
307 ])
308 def test_script_content(self, content):
309 s = f'<script>{content}</script>'
310 self._run_check(s, [
311 ("starttag", "script", []),
312 ("data", content),
313 ("endtag", "script"),
314 ])
315
316 @support.subTests('content', [
317 'a::before { content: "<!-- not a comment -->"; }',
318 'a::before { content: "&not-an-entity-ref;"; }',
319 'a::before { content: "<not a=\'start tag\'>"; }',
320 'a::before { content: "\u2603"; }',
321 ])
322 def test_style_content(self, content):
323 s = f'<style>{content}</style>'
324 self._run_check(s, [("starttag", "style", []),
325 ("data", content),
326 ("endtag", "style")])
327
328 @support.subTests('tag', ['title', 'textarea'])
329 def test_rcdata_content(self, tag):
330 source = f"<{tag}>{SAMPLE_RCDATA}</{tag}>"
331 self._run_check(source, [
332 ("starttag", tag, []),
333 ("data", SAMPLE_RCDATA),
334 ("endtag", tag),
335 ])
336 source = f"<{tag}>&amp;</{tag}>"
337 self._run_check(source, [
338 ("starttag", tag, []),
339 ('entityref', 'amp'),
340 ("endtag", tag),
341 ])
342
343 @support.subTests('tag',
344 ['style', 'xmp', 'iframe', 'noembed', 'noframes', 'script'])
345 def test_rawtext_content(self, tag):
346 source = f"<{tag}>{SAMPLE_RAWTEXT}</{tag}>"
347 self._run_check(source, [
348 ("starttag", tag, []),
349 ("data", SAMPLE_RAWTEXT),
350 ("endtag", tag),
351 ])
352
353 def test_noscript_content(self):
354 source = f"<noscript>{SAMPLE_RAWTEXT}</noscript>"
355 # scripting=False -- normal mode
356 self._run_check(source, [
357 ('starttag', 'noscript', []),
358 ('comment', ' not a comment '),
359 ('starttag', 'not', [('a', 'start tag')]),
360 ('unknown decl', 'CDATA[not a cdata'),
361 ('comment', 'not a bogus comment'),
362 ('endtag', 'not'),
363 ('data', '☃'),
364 ('entityref', 'amp'),
365 ('charref', '9786'),
366 ('endtag', 'noscript'),
367 ])
368 # scripting=True -- RAWTEXT mode
369 self._run_check(source, [
370 ("starttag", "noscript", []),
371 ("data", SAMPLE_RAWTEXT),
372 ("endtag", "noscript"),
373 ], collector=EventCollector(scripting=True))
374
375 def test_plaintext_content(self):
376 content = SAMPLE_RAWTEXT + '</plaintext>' # not closing
377 source = f"<plaintext>{content}"
378 self._run_check(source, [
379 ("starttag", "plaintext", []),
380 ("data", content),
381 ])
382
383 @support.subTests('endtag', ['script', 'SCRIPT', 'script ', 'script\n',
384 'script/', 'script foo=bar', 'script foo=">"'])
385 def test_script_closing_tag(self, endtag):
386 # see issue #13358
387 # make sure that HTMLParser calls handle_data only once for each CDATA.
388 content = """<!-- not a comment --> &not-an-entity-ref;
389 <a href="" /> </p><p> <span></span></style>
390 '</script' + '>'"""
391 s = f'<ScrIPt>{content}</{endtag}>'
392 self._run_check(s, [("starttag", "script", []),
393 ("data", content),
394 ("endtag", "script")],
395 collector=EventCollectorNoNormalize(convert_charrefs=False))
396
397 @support.subTests('tag', [
398 'script', 'style', 'xmp', 'iframe', 'noembed', 'noframes',
399 'textarea', 'title', 'noscript',
400 ])
401 def test_closing_tag(self, tag):
402 for endtag in [tag, tag.upper(), f'{tag} ', f'{tag}\n',
403 f'{tag}/', f'{tag} foo=bar', f'{tag} foo=">"']:
404 content = "<!-- not a comment --><i>Spam</i>"
405 s = f'<{tag.upper()}>{content}</{endtag}>'
406 self._run_check(s, [
407 ("starttag", tag, []),
408 ('data', content),
409 ("endtag", tag),
410 ], collector=EventCollectorNoNormalize(convert_charrefs=False, scripting=True))
411
412 @support.subTests('tag', [
413 'script', 'style', 'xmp', 'iframe', 'noembed', 'noframes',
414 'textarea', 'title', 'noscript',
415 ])
416 def test_invalid_closing_tag(self, tag):
417 content = (
418 f'< /{tag}>'
419 f'</ {tag}>'
420 f'</{tag}x>'
421 f'</{tag}\v>'
422 f'</{tag}\xa0>'
423 )
424 source = f"<{tag}>{content}</{tag}>"
425 self._run_check(source, [
426 ("starttag", tag, []),
427 ("data", content),
428 ("endtag", tag),
429 ], collector=EventCollector(convert_charrefs=False, scripting=True))
430
431 @support.subTests('tag,endtag', [
432 ('title', 'tıtle'),
433 ('style', 'ſtyle'),
434 ('style', 'ſtyle'),
435 ('style', 'style'),
436 ('iframe', 'ıframe'),
437 ('noframes', 'noframeſ'),
438 ('noscript', 'noſcript'),
439 ('noscript', 'noscrıpt'),
440 ('script', 'ſcript'),
441 ('script', 'scrıpt'),
442 ])
443 def test_invalid_nonascii_closing_tag(self, tag, endtag):
444 content = f"<br></{endtag}>"
445 source = f"<{tag}>{content}"
446 self._run_check(source, [
447 ("starttag", tag, []),
448 ("data", content),
449 ], collector=EventCollector(convert_charrefs=False, scripting=True))
450 source = f"<{tag}>{content}</{tag}>"
451 self._run_check(source, [
452 ("starttag", tag, []),
453 ("data", content),
454 ("endtag", tag),
455 ], collector=EventCollector(convert_charrefs=False, scripting=True))
456
457 @support.subTests('tail,end', [
458 ('', False),
459 ('<', False),
460 ('</', False),
461 ('</s', False),
462 ('</script', False),
463 ('</script ', True),
464 ('</script foo=bar', True),
465 ('</script foo=">', True),
466 ])
467 def test_eof_in_script(self, tail, end):
468 content = "a = 123"
469 s = f'<ScrIPt>{content}{tail}'
470 self._run_check(s, [("starttag", "script", []),
471 ("data", content if end else content + tail)],
472 collector=EventCollectorNoNormalize(convert_charrefs=False))
473
474 @support.subTests('tail,end', [
475 ('', False),
476 ('<', False),
477 ('</', False),
478 ('</t', False),
479 ('</title', False),
480 ('</title ', True),
481 ('</title foo=bar', True),
482 ('</title foo=">', True),
483 ])
484 def test_eof_in_title(self, tail, end):
485 s = f'<TitLe>Egg &amp; Spam{tail}'
486 self._run_check(s, [("starttag", "title", []),
487 ("data", "Egg & Spam" + ('' if end else tail))],
488 collector=EventCollectorNoNormalize(convert_charrefs=True))
489 self._run_check(s, [("starttag", "title", []),
490 ('data', 'Egg '),
491 ('entityref', 'amp'),
492 ('data', ' Spam' + ('' if end else tail))],
493 collector=EventCollectorNoNormalize(convert_charrefs=False))
494
495 def test_comments(self):
496 html = ("<!-- I'm a valid comment -->"
497 '<!--me too!-->'
498 '<!------>'
499 '<!----->'
500 '<!---->'
501 # abrupt-closing-of-empty-comment
502 '<!--->'
503 '<!-->'
504 '<!----I have many hyphens---->'
505 '<!-- I have a > in the middle -->'
506 '<!-- and I have -- in the middle! -->'
507 '<!--incorrectly-closed-comment--!>'
508 '<!----!>'
509 '<!----!-->'
510 '<!---- >-->'
511 '<!---!>-->'
512 '<!--!>-->'
513 # nested-comment
514 '<!-- <!-- nested --> -->'
515 '<!--<!-->'
516 '<!--<!--!>'
517 )
518 expected = [('comment', " I'm a valid comment "),
519 ('comment', 'me too!'),
520 ('comment', '--'),
521 ('comment', '-'),
522 ('comment', ''),
523 ('comment', ''),
524 ('comment', ''),
525 ('comment', '--I have many hyphens--'),
526 ('comment', ' I have a > in the middle '),
527 ('comment', ' and I have -- in the middle! '),
528 ('comment', 'incorrectly-closed-comment'),
529 ('comment', ''),
530 ('comment', '--!'),
531 ('comment', '-- >'),
532 ('comment', '-!>'),
533 ('comment', '!>'),
534 ('comment', ' <!-- nested '), ('data', ' -->'),
535 ('comment', '<!'),
536 ('comment', '<!'),
537 ]
538 self._run_check(html, expected)
539
540 def test_condcoms(self):
541 html = ('<!--[if IE & !(lte IE 8)]>aren\'t<![endif]-->'
542 '<!--[if IE 8]>condcoms<![endif]-->'
543 '<!--[if lte IE 7]>pretty?<![endif]-->')
544 expected = [('comment', "[if IE & !(lte IE 8)]>aren't<![endif]"),
545 ('comment', '[if IE 8]>condcoms<![endif]'),
546 ('comment', '[if lte IE 7]>pretty?<![endif]')]
547 self._run_check(html, expected)
548
549 def test_convert_charrefs(self):
550 # default value for convert_charrefs is now True
551 collector = lambda: EventCollectorCharrefs()
552 self.assertTrue(collector().convert_charrefs)
553 charrefs = ['&quot;', '&#34;', '&#x22;', '&quot', '&#34', '&#x22']
554 # check charrefs in the middle of the text/attributes
555 expected = [('starttag', 'a', [('href', 'foo"zar')]),
556 ('data', 'a"z'), ('endtag', 'a')]
557 for charref in charrefs:
558 self._run_check('<a href="foo{0}zar">a{0}z</a>'.format(charref),
559 expected, collector=collector())
560 # check charrefs at the beginning/end of the text/attributes
561 expected = [('data', '"'),
562 ('starttag', 'a', [('x', '"'), ('y', '"X'), ('z', 'X"')]),
563 ('data', '"'), ('endtag', 'a'), ('data', '"')]
564 for charref in charrefs:
565 self._run_check('{0}<a x="{0}" y="{0}X" z="X{0}">'
566 '{0}</a>{0}'.format(charref),
567 expected, collector=collector())
568 # check charrefs in <script>/<style> elements
569 for charref in charrefs:
570 text = 'X'.join([charref]*3)
571 expected = [('data', '"'),
572 ('starttag', 'script', []), ('data', text),
573 ('endtag', 'script'), ('data', '"'),
574 ('starttag', 'style', []), ('data', text),
575 ('endtag', 'style'), ('data', '"')]
576 self._run_check('{1}<script>{0}</script>{1}'
577 '<style>{0}</style>{1}'.format(text, charref),
578 expected, collector=collector())
579 # check truncated charrefs at the end of the file
580 html = '&quo &# &#x'
581 for x in range(1, len(html)):
582 self._run_check(html[:x], [('data', html[:x])],
583 collector=collector())
584 # check a string with no charrefs
585 self._run_check('no charrefs here', [('data', 'no charrefs here')],
586 collector=collector())
587
588 # the remaining tests were for the "tolerant" parser (which is now
589 # the default), and check various kind of broken markup
590 def test_tolerant_parsing(self):
591 self._run_check('<html <html>te>>xt&a<<bc</a></html>\n'
592 '<img src="URL><//img></html</html>', [
593 ('starttag', 'html', [('<html', None)]),
594 ('data', 'te>>xt'),
595 ('entityref', 'a'),
596 ('data', '<'),
597 ('starttag', 'bc<', [('a', None)]),
598 ('endtag', 'html'),
599 ('data', '\n')])
600
601 def test_starttag_junk_chars(self):
602 self._run_check("<", [('data', '<')])
603 self._run_check("<>", [('data', '<>')])
604 self._run_check("< >", [('data', '< >')])
605 self._run_check("< ", [('data', '< ')])
606 self._run_check("</>", [])
607 self._run_check("<$>", [('data', '<$>')])
608 self._run_check("</$>", [('comment', '$')])
609 self._run_check("</", [('data', '</')])
610 self._run_check("</a", [])
611 self._run_check("</ a>", [('comment', ' a')])
612 self._run_check("</ a", [('comment', ' a')])
613 self._run_check("<a<a>", [('starttag', 'a<a', [])])
614 self._run_check("</a<a>", [('endtag', 'a<a')])
615 self._run_check("<!", [('comment', '')])
616 self._run_check("<a", [])
617 self._run_check("<a foo='bar'", [])
618 self._run_check("<a foo='bar", [])
619 self._run_check("<a foo='>'", [])
620 self._run_check("<a foo='>", [])
621 self._run_check("<a$>", [('starttag', 'a$', [])])
622 self._run_check("<a$b>", [('starttag', 'a$b', [])])
623 self._run_check("<a$b/>", [('startendtag', 'a$b', [])])
624 self._run_check("<a$b >", [('starttag', 'a$b', [])])
625 self._run_check("<a$b />", [('startendtag', 'a$b', [])])
626 self._run_check("</a$b>", [('endtag', 'a$b')])
627
628 def test_slashes_in_starttag(self):
629 self._run_check('<a foo="var"/>', [('startendtag', 'a', [('foo', 'var')])])
630 html = ('<img width=902 height=250px '
631 'src="/sites/default/files/images/homepage/foo.jpg" '
632 '/*what am I doing here*/ />')
633 expected = [(
634 'startendtag', 'img',
635 [('width', '902'), ('height', '250px'),
636 ('src', '/sites/default/files/images/homepage/foo.jpg'),
637 ('*what', None), ('am', None), ('i', None),
638 ('doing', None), ('here*', None)]
639 )]
640 self._run_check(html, expected)
641 html = ('<a / /foo/ / /=/ / /bar/ / />'
642 '<a / /foo/ / /=/ / /bar/ / >')
643 expected = [
644 ('startendtag', 'a', [('foo', None), ('=', None), ('bar', None)]),
645 ('starttag', 'a', [('foo', None), ('=', None), ('bar', None)])
646 ]
647 self._run_check(html, expected)
648 #see issue #14538
649 html = ('<meta><meta / ><meta // ><meta / / >'
650 '<meta/><meta /><meta //><meta//>')
651 expected = [
652 ('starttag', 'meta', []), ('starttag', 'meta', []),
653 ('starttag', 'meta', []), ('starttag', 'meta', []),
654 ('startendtag', 'meta', []), ('startendtag', 'meta', []),
655 ('startendtag', 'meta', []), ('startendtag', 'meta', []),
656 ]
657 self._run_check(html, expected)
658
659 def test_slashes_in_endtag(self):
660 self._run_check('</a/>', [('endtag', 'a')])
661 self._run_check('</a foo="var"/>', [('endtag', 'a')])
662
663 def test_declaration_junk_chars(self):
664 self._run_check("<!DOCTYPE foo $ >", [('decl', 'DOCTYPE foo $ ')])
665
666 def test_illegal_declarations(self):
667 self._run_check('<!spacer type="block" height="25">',
668 [('comment', 'spacer type="block" height="25"')])
669
670 def test_invalid_end_tags(self):
671 # A collection of broken end tags. <br> is used as separator.
672 # see http://www.w3.org/TR/html5/tokenization.html#end-tag-open-state
673 # and #13993
674 html = ('<br></label</p><br></div end tmAd-leaderBoard><br></<h4><br>'
675 '</li class="unit"><br></li\r\n\t\t\t\t\t\t</ul><br></><br>')
676 expected = [('starttag', 'br', []),
677 # < is part of the name, / is discarded, p is an attribute
678 ('endtag', 'label<'),
679 ('starttag', 'br', []),
680 # text and attributes are discarded
681 ('endtag', 'div'),
682 ('starttag', 'br', []),
683 # comment because the first char after </ is not a-zA-Z
684 ('comment', '<h4'),
685 ('starttag', 'br', []),
686 # attributes are discarded
687 ('endtag', 'li'),
688 ('starttag', 'br', []),
689 # everything till ul (included) is discarded
690 ('endtag', 'li'),
691 ('starttag', 'br', []),
692 # </> is ignored
693 ('starttag', 'br', [])]
694 self._run_check(html, expected)
695
696 def test_broken_invalid_end_tag(self):
697 html = '<b>This</b attr=">"> confuses the parser'
698 expected = [('starttag', 'b', []),
699 ('data', 'This'),
700 ('endtag', 'b'),
701 ('data', ' confuses the parser')]
702 self._run_check(html, expected)
703
704 def test_correct_detection_of_start_tags(self):
705 # see #13273
706 html = ('<div style="" ><b>The <a href="some_url">rain</a> '
707 '<br /> in <span>Spain</span></b></div>')
708 expected = [
709 ('starttag', 'div', [('style', '')]),
710 ('starttag', 'b', []),
711 ('data', 'The '),
712 ('starttag', 'a', [('href', 'some_url')]),
713 ('data', 'rain'),
714 ('endtag', 'a'),
715 ('data', ' '),
716 ('startendtag', 'br', []),
717 ('data', ' in '),
718 ('starttag', 'span', []),
719 ('data', 'Spain'),
720 ('endtag', 'span'),
721 ('endtag', 'b'),
722 ('endtag', 'div')
723 ]
724 self._run_check(html, expected)
725
726 html = '<div style="", foo = "bar" ><b>The <a href="some_url">rain</a>'
727 expected = [
728 ('starttag', 'div', [('style', ''), (',', None), ('foo', 'bar')]),
729 ('starttag', 'b', []),
730 ('data', 'The '),
731 ('starttag', 'a', [('href', 'some_url')]),
732 ('data', 'rain'),
733 ('endtag', 'a'),
734 ]
735 self._run_check(html, expected)
736
737 def test_EOF_in_charref(self):
738 # see #17802
739 # This test checks that the UnboundLocalError reported in the issue
740 # is not raised, however I'm not sure the returned values are correct.
741 # Maybe HTMLParser should use self.unescape for these
742 data = [
743 ('a&', [('data', 'a&')]),
744 ('a&b', [('data', 'ab')]),
745 ('a&b ', [('data', 'a'), ('entityref', 'b'), ('data', ' ')]),
746 ('a&b;', [('data', 'a'), ('entityref', 'b')]),
747 ]
748 for html, expected in data:
749 self._run_check(html, expected)
750
751 def test_eof_in_comments(self):
752 data = [
753 ('<!--', [('comment', '')]),
754 ('<!---', [('comment', '')]),
755 ('<!----', [('comment', '')]),
756 ('<!-----', [('comment', '-')]),
757 ('<!------', [('comment', '--')]),
758 ('<!----!', [('comment', '')]),
759 ('<!---!', [('comment', '-!')]),
760 ('<!---!>', [('comment', '-!>')]),
761 ('<!--foo', [('comment', 'foo')]),
762 ('<!--foo-', [('comment', 'foo')]),
763 ('<!--foo--', [('comment', 'foo')]),
764 ('<!--foo--!', [('comment', 'foo')]),
765 ('<!--<!--', [('comment', '<!')]),
766 ('<!--<!--!', [('comment', '<!')]),
767 ]
768 for html, expected in data:
769 self._run_check(html, expected)
770
771 def test_eof_in_declarations(self):
772 data = [
773 ('<!', [('comment', '')]),
774 ('<!-', [('comment', '-')]),
775 ('<![', [('comment', '[')]),
776 ('<!DOCTYPE', [('decl', 'DOCTYPE')]),
777 ('<!DOCTYPE ', [('decl', 'DOCTYPE ')]),
778 ('<!DOCTYPE html', [('decl', 'DOCTYPE html')]),
779 ('<!DOCTYPE html ', [('decl', 'DOCTYPE html ')]),
780 ('<!DOCTYPE html PUBLIC', [('decl', 'DOCTYPE html PUBLIC')]),
781 ('<!DOCTYPE html PUBLIC "foo', [('decl', 'DOCTYPE html PUBLIC "foo')]),
782 ('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "foo',
783 [('decl', 'DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "foo')]),
784 ]
785 for html, expected in data:
786 self._run_check(html, expected)
787
788 @support.subTests('content', ['', 'x', 'x]', 'x]]'])
789 def test_eof_in_cdata(self, content):
790 self._run_check('<![CDATA[' + content,
791 [('unknown decl', 'CDATA[' + content)])
792 self._run_check('<![CDATA[' + content,
793 [('comment', '[CDATA[' + content)],
794 collector=EventCollector(autocdata=True))
795 self._run_check('<svg><text y="100"><![CDATA[' + content,
796 [('starttag', 'svg', []),
797 ('starttag', 'text', [('y', '100')]),
798 ('unknown decl', 'CDATA[' + content)])
799
800 def test_bogus_comments(self):
801 html = ('<!ELEMENT br EMPTY>'
802 '<! not really a comment >'
803 '<! not a comment either -->'
804 '<! -- close enough -->'
805 '<!><!<-- this was an empty comment>'
806 '<!!! another bogus comment !!!>')
807 expected = [
808 ('comment', 'ELEMENT br EMPTY'),
809 ('comment', ' not really a comment '),
810 ('comment', ' not a comment either --'),
811 ('comment', ' -- close enough --'),
812 ('comment', ''),
813 ('comment', '<-- this was an empty comment'),
814 ('comment', '!! another bogus comment !!!'),
815 ]
816 self._run_check(html, expected)
817
818 def test_broken_condcoms(self):
819 # these condcoms are missing the '--' after '<!' and before the '>'
820 html = ('<![if !(IE)]>broken condcom<![endif]>'
821 '<![if ! IE]><link href="favicon.tiff"/><![endif]>'
822 '<![if !IE 6]><img src="firefox.png" /><![endif]>'
823 '<![if !ie 6]><b>foo</b><![endif]>'
824 '<![if (!IE)|(lt IE 9)]><img src="mammoth.bmp" /><![endif]>')
825 # According to the HTML5 specs sections "8.2.4.44 Bogus comment state"
826 # and "8.2.4.45 Markup declaration open state", comment tokens should
827 # be emitted instead of 'unknown decl', but calling unknown_decl
828 # provides more flexibility.
829 # See also Lib/_markupbase.py:parse_declaration
830 expected = [
831 ('unknown decl', 'if !(IE)'),
832 ('data', 'broken condcom'),
833 ('unknown decl', 'endif'),
834 ('unknown decl', 'if ! IE'),
835 ('startendtag', 'link', [('href', 'favicon.tiff')]),
836 ('unknown decl', 'endif'),
837 ('unknown decl', 'if !IE 6'),
838 ('startendtag', 'img', [('src', 'firefox.png')]),
839 ('unknown decl', 'endif'),
840 ('unknown decl', 'if !ie 6'),
841 ('starttag', 'b', []),
842 ('data', 'foo'),
843 ('endtag', 'b'),
844 ('unknown decl', 'endif'),
845 ('unknown decl', 'if (!IE)|(lt IE 9)'),
846 ('startendtag', 'img', [('src', 'mammoth.bmp')]),
847 ('unknown decl', 'endif')
848 ]
849
850 self._run_check(html, expected)
851
852 @support.subTests('content', [
853 'just some plain text',
854 '<!-- not a comment -->',
855 '&not-an-entity-ref;',
856 "<not a='start tag'>",
857 '',
858 '[[I have many brackets]]',
859 'I have a > in the middle',
860 'I have a ]] in the middle',
861 '] ]>',
862 ']] >',
863 ('\n'
864 ' if (a < b && a > b) {\n'
865 ' printf("[<marquee>How?</marquee>]");\n'
866 ' }\n'),
867 ])
868 def test_cdata_section_content(self, content):
869 # See "13.2.5.42 Markup declaration open state",
870 # "13.2.5.69 CDATA section state", and issue bpo-32876.
871 html = f'<svg><text y="100"><![CDATA[{content}]]></text></svg>'
872 expected = [
873 ('starttag', 'svg', []),
874 ('starttag', 'text', [('y', '100')]),
875 ('unknown decl', 'CDATA[' + content),
876 ('endtag', 'text'),
877 ('endtag', 'svg'),
878 ]
879 self._run_check(html, expected)
880 self._run_check(html, expected, collector=EventCollector(autocdata=True))
881
882 def test_cdata_section(self):
883 # See "13.2.5.42 Markup declaration open state".
884 html = ('<![CDATA[foo<br>bar]]>'
885 '<svg><text y="100"><![CDATA[foo<br>bar]]></text></svg>'
886 '<![CDATA[foo<br>bar]]>')
887 expected = [
888 ('comment', '[CDATA[foo<br'),
889 ('data', 'bar]]>'),
890 ('starttag', 'svg', []),
891 ('starttag', 'text', [('y', '100')]),
892 ('unknown decl', 'CDATA[foo<br>bar'),
893 ('endtag', 'text'),
894 ('endtag', 'svg'),
895 ('comment', '[CDATA[foo<br'),
896 ('data', 'bar]]>'),
897 ]
898 self._run_check(html, expected, collector=EventCollector(autocdata=True))
899
900 def test_convert_charrefs_dropped_text(self):
901 # #23144: make sure that all the events are triggered when
902 # convert_charrefs is True, even if we don't call .close()
903 parser = EventCollector(convert_charrefs=True)
904 # before the fix, bar & baz was missing
905 parser.feed("foo <a>link</a> bar &amp; baz")
906 self.assertEqual(
907 parser.get_events(),
908 [('data', 'foo '), ('starttag', 'a', []), ('data', 'link'),
909 ('endtag', 'a'), ('data', ' bar & baz')]
910 )
911
912 @support.requires_resource('cpu')
913 def test_eof_no_quadratic_complexity(self):
914 # Each of these examples used to take about an hour.
915 # Now they take a fraction of a second.
916 def check(source):
917 parser = html.parser.HTMLParser()
918 parser.feed(source)
919 parser.close()
920 n = 120_000
921 check("<a " * n)
922 check("<a a=" * n)
923 check("</a " * 14 * n)
924 check("</a a=" * 11 * n)
925 check("<!--" * 4 * n)
926 check("<!" * 60 * n)
927 check("<?" * 19 * n)
928 check("</$" * 15 * n)
929 check("<![CDATA[" * 9 * n)
930 check("<!doctype" * 35 * n)
931
932
933 class AttributesTestCase(TestCaseBase):
934
935 def test_attr_syntax(self):
936 output = [
937 ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", None)])
938 ]
939 self._run_check("""<a b='v' c="v" d=v e>""", output)
940 self._run_check("<a foo==bar>", [('starttag', 'a', [('foo', '=bar')])])
941 self._run_check("<a foo =bar>", [('starttag', 'a', [('foo', 'bar')])])
942 self._run_check("<a foo\t=bar>", [('starttag', 'a', [('foo', 'bar')])])
943 self._run_check("<a foo\v=bar>", [('starttag', 'a', [('foo\v', 'bar')])])
944 self._run_check("<a foo\xa0=bar>", [('starttag', 'a', [('foo\xa0', 'bar')])])
945 self._run_check("<a foo= bar>", [('starttag', 'a', [('foo', 'bar')])])
946 self._run_check("<a foo=\tbar>", [('starttag', 'a', [('foo', 'bar')])])
947 self._run_check("<a foo=\vbar>", [('starttag', 'a', [('foo', '\vbar')])])
948 self._run_check("<a foo=\xa0bar>", [('starttag', 'a', [('foo', '\xa0bar')])])
949
950 def test_attr_values(self):
951 self._run_check("""<a b='xxx\n\txxx' c="yyy\t\nyyy" d='\txyz\n'>""",
952 [("starttag", "a", [("b", "xxx\n\txxx"),
953 ("c", "yyy\t\nyyy"),
954 ("d", "\txyz\n")])])
955 self._run_check("""<a b='' c="">""",
956 [("starttag", "a", [("b", ""), ("c", "")])])
957 self._run_check("<a b=\tx c=\ny>",
958 [('starttag', 'a', [('b', 'x'), ('c', 'y')])])
959 self._run_check("<a b=\v c=\xa0>",
960 [("starttag", "a", [("b", "\v"), ("c", "\xa0")])])
961 # Regression test for SF patch #669683.
962 self._run_check("<e a=rgb(1,2,3)>",
963 [("starttag", "e", [("a", "rgb(1,2,3)")])])
964 # Regression test for SF bug #921657.
965 self._run_check(
966 "<a href=mailto:[email protected]>",
967 [("starttag", "a", [("href", "mailto:[email protected]")])])
968
969 def test_attr_nonascii(self):
970 # see issue 7311
971 self._run_check(
972 "<img src=/foo/bar.png alt=\u4e2d\u6587>",
973 [("starttag", "img", [("src", "/foo/bar.png"),
974 ("alt", "\u4e2d\u6587")])])
975 self._run_check(
976 "<a title='\u30c6\u30b9\u30c8' href='\u30c6\u30b9\u30c8.html'>",
977 [("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
978 ("href", "\u30c6\u30b9\u30c8.html")])])
979 self._run_check(
980 '<a title="\u30c6\u30b9\u30c8" href="\u30c6\u30b9\u30c8.html">',
981 [("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
982 ("href", "\u30c6\u30b9\u30c8.html")])])
983
984 def test_attr_entity_replacement(self):
985 self._run_check(
986 "<a b='&amp;&gt;&lt;&quot;&apos;'>",
987 [("starttag", "a", [("b", "&><\"'")])])
988
989 def test_attr_funky_names(self):
990 self._run_check(
991 "<a a.b='v' c:d=v e-f=v>",
992 [("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")])])
993
994 def test_entityrefs_in_attributes(self):
995 self._run_check(
996 "<html foo='&euro;&amp;&#97;&#x61;&unsupported;'>",
997 [("starttag", "html", [("foo", "\u20AC&aa&unsupported;")])])
998
999
1000 def test_attr_funky_names2(self):
1001 self._run_check(
1002 r"<a $><b $=%><c \=/>",
1003 [("starttag", "a", [("$", None)]),
1004 ("starttag", "b", [("$", "%")]),
1005 ("starttag", "c", [("\\", "/")])])
1006
1007 def test_entities_in_attribute_value(self):
1008 # see #1200313
1009 for entity in ['&', '&amp;', '&#38;', '&#x26;']:
1010 self._run_check('<a href="%s">' % entity,
1011 [("starttag", "a", [("href", "&")])])
1012 self._run_check("<a href='%s'>" % entity,
1013 [("starttag", "a", [("href", "&")])])
1014 self._run_check("<a href=%s>" % entity,
1015 [("starttag", "a", [("href", "&")])])
1016
1017 def test_malformed_attributes(self):
1018 # see #13357
1019 html = (
1020 "<a href=test'style='color:red;bad1'>test - bad1</a>"
1021 "<a href=test'+style='color:red;ba2'>test - bad2</a>"
1022 "<a href=test'&nbsp;style='color:red;bad3'>test - bad3</a>"
1023 "<a href = test'&nbsp;style='color:red;bad4' >test - bad4</a>"
1024 )
1025 expected = [
1026 ('starttag', 'a', [('href', "test'style='color:red;bad1'")]),
1027 ('data', 'test - bad1'),
1028 ('endtag', 'a'),
1029 ('starttag', 'a', [('href', "test'+style='color:red;ba2'")]),
1030 ('data', 'test - bad2'),
1031 ('endtag', 'a'),
1032 ('starttag', 'a', [('href', "test'\xa0style='color:red;bad3'")]),
1033 ('data', 'test - bad3'),
1034 ('endtag', 'a'),
1035 ('starttag', 'a', [('href', "test'\xa0style='color:red;bad4'")]),
1036 ('data', 'test - bad4'),
1037 ('endtag', 'a'),
1038 ]
1039 self._run_check(html, expected)
1040
1041 def test_malformed_adjacent_attributes(self):
1042 # see #12629
1043 self._run_check('<x><y z=""o"" /></x>',
1044 [('starttag', 'x', []),
1045 ('startendtag', 'y', [('z', ''), ('o""', None)]),
1046 ('endtag', 'x')])
1047 self._run_check('<x><y z="""" /></x>',
1048 [('starttag', 'x', []),
1049 ('startendtag', 'y', [('z', ''), ('""', None)]),
1050 ('endtag', 'x')])
1051
1052 # see #755670 for the following 3 tests
1053 def test_adjacent_attributes(self):
1054 self._run_check('<a width="100%"cellspacing=0>',
1055 [("starttag", "a",
1056 [("width", "100%"), ("cellspacing","0")])])
1057
1058 self._run_check('<a id="foo"class="bar">',
1059 [("starttag", "a",
1060 [("id", "foo"), ("class","bar")])])
1061
1062 def test_missing_attribute_value(self):
1063 self._run_check('<a v=>',
1064 [("starttag", "a", [("v", "")])])
1065
1066 def test_javascript_attribute_value(self):
1067 self._run_check("<a href=javascript:popup('/popup/help.html')>",
1068 [("starttag", "a",
1069 [("href", "javascript:popup('/popup/help.html')")])])
1070
1071 def test_end_tag_in_attribute_value(self):
1072 # see #1745761
1073 self._run_check("<a href='http://www.example.org/\">;'>spam</a>",
1074 [("starttag", "a",
1075 [("href", "http://www.example.org/\">;")]),
1076 ("data", "spam"), ("endtag", "a")])
1077
1078 def test_with_unquoted_attributes(self):
1079 # see #12008
1080 html = ("<html><body bgcolor=d0ca90 text='181008'>"
1081 "<table cellspacing=0 cellpadding=1 width=100% ><tr>"
1082 "<td align=left><font size=-1>"
1083 "- <a href=/rabota/><span class=en> software-and-i</span></a>"
1084 "- <a href='/1/'><span class=en> library</span></a></table>")
1085 expected = [
1086 ('starttag', 'html', []),
1087 ('starttag', 'body', [('bgcolor', 'd0ca90'), ('text', '181008')]),
1088 ('starttag', 'table',
1089 [('cellspacing', '0'), ('cellpadding', '1'), ('width', '100%')]),
1090 ('starttag', 'tr', []),
1091 ('starttag', 'td', [('align', 'left')]),
1092 ('starttag', 'font', [('size', '-1')]),
1093 ('data', '- '), ('starttag', 'a', [('href', '/rabota/')]),
1094 ('starttag', 'span', [('class', 'en')]), ('data', ' software-and-i'),
1095 ('endtag', 'span'), ('endtag', 'a'),
1096 ('data', '- '), ('starttag', 'a', [('href', '/1/')]),
1097 ('starttag', 'span', [('class', 'en')]), ('data', ' library'),
1098 ('endtag', 'span'), ('endtag', 'a'), ('endtag', 'table')
1099 ]
1100 self._run_check(html, expected)
1101
1102 def test_comma_between_attributes(self):
1103 # see bpo 41478
1104 # HTMLParser preserves duplicate attributes, leaving the task of
1105 # removing duplicate attributes to a conformant html tree builder
1106 html = ('<div class=bar,baz=asd>' # between attrs (unquoted)
1107 '<div class="bar",baz="asd">' # between attrs (quoted)
1108 '<div class=bar, baz=asd,>' # after values (unquoted)
1109 '<div class="bar", baz="asd",>' # after values (quoted)
1110 '<div class="bar",>' # one comma values (quoted)
1111 '<div class=,bar baz=,asd>' # before values (unquoted)
1112 '<div class=,"bar" baz=,"asd">' # before values (quoted)
1113 '<div ,class=bar ,baz=asd>' # before names
1114 '<div class,="bar" baz,="asd">' # after names
1115 )
1116 expected = [
1117 ('starttag', 'div', [('class', 'bar,baz=asd'),]),
1118 ('starttag', 'div', [('class', 'bar'), (',baz', 'asd')]),
1119 ('starttag', 'div', [('class', 'bar,'), ('baz', 'asd,')]),
1120 ('starttag', 'div', [('class', 'bar'), (',', None),
1121 ('baz', 'asd'), (',', None)]),
1122 ('starttag', 'div', [('class', 'bar'), (',', None)]),
1123 ('starttag', 'div', [('class', ',bar'), ('baz', ',asd')]),
1124 ('starttag', 'div', [('class', ',"bar"'), ('baz', ',"asd"')]),
1125 ('starttag', 'div', [(',class', 'bar'), (',baz', 'asd')]),
1126 ('starttag', 'div', [('class,', 'bar'), ('baz,', 'asd')]),
1127 ]
1128 self._run_check(html, expected)
1129
1130 def test_weird_chars_in_unquoted_attribute_values(self):
1131 self._run_check('<form action=bogus|&#()value>', [
1132 ('starttag', 'form',
1133 [('action', 'bogus|&#()value')])])
1134
1135 if __name__ == "__main__":
1136 unittest.main()