ยปCore Development>Code coverage>Lib/test/test_htmlparser.py

Python code coverage for Lib/test/test_htmlparser.py

#countcontent
1n/a"""Tests for HTMLParser.py."""
2n/a
3n/aimport html.parser
4n/aimport pprint
5n/aimport unittest
6n/a
7n/a
8n/aclass EventCollector(html.parser.HTMLParser):
9n/a
10n/a def __init__(self, *args, **kw):
11n/a self.events = []
12n/a self.append = self.events.append
13n/a html.parser.HTMLParser.__init__(self, *args, **kw)
14n/a
15n/a def get_events(self):
16n/a # Normalize the list of events so that buffer artefacts don't
17n/a # separate runs of contiguous characters.
18n/a L = []
19n/a prevtype = None
20n/a for event in self.events:
21n/a type = event[0]
22n/a if type == prevtype == "data":
23n/a L[-1] = ("data", L[-1][1] + event[1])
24n/a else:
25n/a L.append(event)
26n/a prevtype = type
27n/a self.events = L
28n/a return L
29n/a
30n/a # structure markup
31n/a
32n/a def handle_starttag(self, tag, attrs):
33n/a self.append(("starttag", tag, attrs))
34n/a
35n/a def handle_startendtag(self, tag, attrs):
36n/a self.append(("startendtag", tag, attrs))
37n/a
38n/a def handle_endtag(self, tag):
39n/a self.append(("endtag", tag))
40n/a
41n/a # all other markup
42n/a
43n/a def handle_comment(self, data):
44n/a self.append(("comment", data))
45n/a
46n/a def handle_charref(self, data):
47n/a self.append(("charref", data))
48n/a
49n/a def handle_data(self, data):
50n/a self.append(("data", data))
51n/a
52n/a def handle_decl(self, data):
53n/a self.append(("decl", data))
54n/a
55n/a def handle_entityref(self, data):
56n/a self.append(("entityref", data))
57n/a
58n/a def handle_pi(self, data):
59n/a self.append(("pi", data))
60n/a
61n/a def unknown_decl(self, decl):
62n/a self.append(("unknown decl", decl))
63n/a
64n/a
65n/aclass EventCollectorExtra(EventCollector):
66n/a
67n/a def handle_starttag(self, tag, attrs):
68n/a EventCollector.handle_starttag(self, tag, attrs)
69n/a self.append(("starttag_text", self.get_starttag_text()))
70n/a
71n/a
72n/aclass EventCollectorCharrefs(EventCollector):
73n/a
74n/a def handle_charref(self, data):
75n/a self.fail('This should never be called with convert_charrefs=True')
76n/a
77n/a def handle_entityref(self, data):
78n/a self.fail('This should never be called with convert_charrefs=True')
79n/a
80n/a
81n/aclass TestCaseBase(unittest.TestCase):
82n/a
83n/a def get_collector(self):
84n/a return EventCollector(convert_charrefs=False)
85n/a
86n/a def _run_check(self, source, expected_events, collector=None):
87n/a if collector is None:
88n/a collector = self.get_collector()
89n/a parser = collector
90n/a for s in source:
91n/a parser.feed(s)
92n/a parser.close()
93n/a events = parser.get_events()
94n/a if events != expected_events:
95n/a self.fail("received events did not match expected events" +
96n/a "\nSource:\n" + repr(source) +
97n/a "\nExpected:\n" + pprint.pformat(expected_events) +
98n/a "\nReceived:\n" + pprint.pformat(events))
99n/a
100n/a def _run_check_extra(self, source, events):
101n/a self._run_check(source, events,
102n/a EventCollectorExtra(convert_charrefs=False))
103n/a
104n/a
105n/aclass HTMLParserTestCase(TestCaseBase):
106n/a
107n/a def test_processing_instruction_only(self):
108n/a self._run_check("<?processing instruction>", [
109n/a ("pi", "processing instruction"),
110n/a ])
111n/a self._run_check("<?processing instruction ?>", [
112n/a ("pi", "processing instruction ?"),
113n/a ])
114n/a
115n/a def test_simple_html(self):
116n/a self._run_check("""
117n/a<!DOCTYPE html PUBLIC 'foo'>
118n/a<HTML>&entity;&#32;
119n/a<!--comment1a
120n/a-></foo><bar>&lt;<?pi?></foo<bar
121n/acomment1b-->
122n/a<Img sRc='Bar' isMAP>sample
123n/atext
124n/a&#x201C;
125n/a<!--comment2a-- --comment2b-->
126n/a</Html>
127n/a""", [
128n/a ("data", "\n"),
129n/a ("decl", "DOCTYPE html PUBLIC 'foo'"),
130n/a ("data", "\n"),
131n/a ("starttag", "html", []),
132n/a ("entityref", "entity"),
133n/a ("charref", "32"),
134n/a ("data", "\n"),
135n/a ("comment", "comment1a\n-></foo><bar>&lt;<?pi?></foo<bar\ncomment1b"),
136n/a ("data", "\n"),
137n/a ("starttag", "img", [("src", "Bar"), ("ismap", None)]),
138n/a ("data", "sample\ntext\n"),
139n/a ("charref", "x201C"),
140n/a ("data", "\n"),
141n/a ("comment", "comment2a-- --comment2b"),
142n/a ("data", "\n"),
143n/a ("endtag", "html"),
144n/a ("data", "\n"),
145n/a ])
146n/a
147n/a def test_malformatted_charref(self):
148n/a self._run_check("<p>&#bad;</p>", [
149n/a ("starttag", "p", []),
150n/a ("data", "&#bad;"),
151n/a ("endtag", "p"),
152n/a ])
153n/a # add the [] as a workaround to avoid buffering (see #20288)
154n/a self._run_check(["<div>&#bad;</div>"], [
155n/a ("starttag", "div", []),
156n/a ("data", "&#bad;"),
157n/a ("endtag", "div"),
158n/a ])
159n/a
160n/a def test_unclosed_entityref(self):
161n/a self._run_check("&entityref foo", [
162n/a ("entityref", "entityref"),
163n/a ("data", " foo"),
164n/a ])
165n/a
166n/a def test_bad_nesting(self):
167n/a # Strangely, this *is* supposed to test that overlapping
168n/a # elements are allowed. HTMLParser is more geared toward
169n/a # lexing the input that parsing the structure.
170n/a self._run_check("<a><b></a></b>", [
171n/a ("starttag", "a", []),
172n/a ("starttag", "b", []),
173n/a ("endtag", "a"),
174n/a ("endtag", "b"),
175n/a ])
176n/a
177n/a def test_bare_ampersands(self):
178n/a self._run_check("this text & contains & ampersands &", [
179n/a ("data", "this text & contains & ampersands &"),
180n/a ])
181n/a
182n/a def test_bare_pointy_brackets(self):
183n/a self._run_check("this < text > contains < bare>pointy< brackets", [
184n/a ("data", "this < text > contains < bare>pointy< brackets"),
185n/a ])
186n/a
187n/a def test_starttag_end_boundary(self):
188n/a self._run_check("""<a b='<'>""", [("starttag", "a", [("b", "<")])])
189n/a self._run_check("""<a b='>'>""", [("starttag", "a", [("b", ">")])])
190n/a
191n/a def test_buffer_artefacts(self):
192n/a output = [("starttag", "a", [("b", "<")])]
193n/a self._run_check(["<a b='<'>"], output)
194n/a self._run_check(["<a ", "b='<'>"], output)
195n/a self._run_check(["<a b", "='<'>"], output)
196n/a self._run_check(["<a b=", "'<'>"], output)
197n/a self._run_check(["<a b='<", "'>"], output)
198n/a self._run_check(["<a b='<'", ">"], output)
199n/a
200n/a output = [("starttag", "a", [("b", ">")])]
201n/a self._run_check(["<a b='>'>"], output)
202n/a self._run_check(["<a ", "b='>'>"], output)
203n/a self._run_check(["<a b", "='>'>"], output)
204n/a self._run_check(["<a b=", "'>'>"], output)
205n/a self._run_check(["<a b='>", "'>"], output)
206n/a self._run_check(["<a b='>'", ">"], output)
207n/a
208n/a output = [("comment", "abc")]
209n/a self._run_check(["", "<!--abc-->"], output)
210n/a self._run_check(["<", "!--abc-->"], output)
211n/a self._run_check(["<!", "--abc-->"], output)
212n/a self._run_check(["<!-", "-abc-->"], output)
213n/a self._run_check(["<!--", "abc-->"], output)
214n/a self._run_check(["<!--a", "bc-->"], output)
215n/a self._run_check(["<!--ab", "c-->"], output)
216n/a self._run_check(["<!--abc", "-->"], output)
217n/a self._run_check(["<!--abc-", "->"], output)
218n/a self._run_check(["<!--abc--", ">"], output)
219n/a self._run_check(["<!--abc-->", ""], output)
220n/a
221n/a def test_valid_doctypes(self):
222n/a # from http://www.w3.org/QA/2002/04/valid-dtd-list.html
223n/a dtds = ['HTML', # HTML5 doctype
224n/a ('HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
225n/a '"http://www.w3.org/TR/html4/strict.dtd"'),
226n/a ('HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" '
227n/a '"http://www.w3.org/TR/html4/loose.dtd"'),
228n/a ('html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" '
229n/a '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"'),
230n/a ('html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" '
231n/a '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"'),
232n/a ('math PUBLIC "-//W3C//DTD MathML 2.0//EN" '
233n/a '"http://www.w3.org/Math/DTD/mathml2/mathml2.dtd"'),
234n/a ('html PUBLIC "-//W3C//DTD '
235n/a 'XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" '
236n/a '"http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd"'),
237n/a ('svg PUBLIC "-//W3C//DTD SVG 1.1//EN" '
238n/a '"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"'),
239n/a 'html PUBLIC "-//IETF//DTD HTML 2.0//EN"',
240n/a 'html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"']
241n/a for dtd in dtds:
242n/a self._run_check("<!DOCTYPE %s>" % dtd,
243n/a [('decl', 'DOCTYPE ' + dtd)])
244n/a
245n/a def test_startendtag(self):
246n/a self._run_check("<p/>", [
247n/a ("startendtag", "p", []),
248n/a ])
249n/a self._run_check("<p></p>", [
250n/a ("starttag", "p", []),
251n/a ("endtag", "p"),
252n/a ])
253n/a self._run_check("<p><img src='foo' /></p>", [
254n/a ("starttag", "p", []),
255n/a ("startendtag", "img", [("src", "foo")]),
256n/a ("endtag", "p"),
257n/a ])
258n/a
259n/a def test_get_starttag_text(self):
260n/a s = """<foo:bar \n one="1"\ttwo=2 >"""
261n/a self._run_check_extra(s, [
262n/a ("starttag", "foo:bar", [("one", "1"), ("two", "2")]),
263n/a ("starttag_text", s)])
264n/a
265n/a def test_cdata_content(self):
266n/a contents = [
267n/a '<!-- not a comment --> &not-an-entity-ref;',
268n/a "<not a='start tag'>",
269n/a '<a href="" /> <p> <span></span>',
270n/a 'foo = "</scr" + "ipt>";',
271n/a 'foo = "</SCRIPT" + ">";',
272n/a 'foo = <\n/script> ',
273n/a '<!-- document.write("</scr" + "ipt>"); -->',
274n/a ('\n//<![CDATA[\n'
275n/a 'document.write(\'<s\'+\'cript type="text/javascript" '
276n/a 'src="http://www.example.org/r=\'+new '
277n/a 'Date().getTime()+\'"><\\/s\'+\'cript>\');\n//]]>'),
278n/a '\n<!-- //\nvar foo = 3.14;\n// -->\n',
279n/a 'foo = "</sty" + "le>";',
280n/a '<!-- \u2603 -->',
281n/a # these two should be invalid according to the HTML 5 spec,
282n/a # section 8.1.2.2
283n/a #'foo = </\nscript>',
284n/a #'foo = </ script>',
285n/a ]
286n/a elements = ['script', 'style', 'SCRIPT', 'STYLE', 'Script', 'Style']
287n/a for content in contents:
288n/a for element in elements:
289n/a element_lower = element.lower()
290n/a s = '<{element}>{content}</{element}>'.format(element=element,
291n/a content=content)
292n/a self._run_check(s, [("starttag", element_lower, []),
293n/a ("data", content),
294n/a ("endtag", element_lower)])
295n/a
296n/a def test_cdata_with_closing_tags(self):
297n/a # see issue #13358
298n/a # make sure that HTMLParser calls handle_data only once for each CDATA.
299n/a # The normal event collector normalizes the events in get_events,
300n/a # so we override it to return the original list of events.
301n/a class Collector(EventCollector):
302n/a def get_events(self):
303n/a return self.events
304n/a
305n/a content = """<!-- not a comment --> &not-an-entity-ref;
306n/a <a href="" /> </p><p> <span></span></style>
307n/a '</script' + '>'"""
308n/a for element in [' script', 'script ', ' script ',
309n/a '\nscript', 'script\n', '\nscript\n']:
310n/a element_lower = element.lower().strip()
311n/a s = '<script>{content}</{element}>'.format(element=element,
312n/a content=content)
313n/a self._run_check(s, [("starttag", element_lower, []),
314n/a ("data", content),
315n/a ("endtag", element_lower)],
316n/a collector=Collector(convert_charrefs=False))
317n/a
318n/a def test_comments(self):
319n/a html = ("<!-- I'm a valid comment -->"
320n/a '<!--me too!-->'
321n/a '<!------>'
322n/a '<!---->'
323n/a '<!----I have many hyphens---->'
324n/a '<!-- I have a > in the middle -->'
325n/a '<!-- and I have -- in the middle! -->')
326n/a expected = [('comment', " I'm a valid comment "),
327n/a ('comment', 'me too!'),
328n/a ('comment', '--'),
329n/a ('comment', ''),
330n/a ('comment', '--I have many hyphens--'),
331n/a ('comment', ' I have a > in the middle '),
332n/a ('comment', ' and I have -- in the middle! ')]
333n/a self._run_check(html, expected)
334n/a
335n/a def test_condcoms(self):
336n/a html = ('<!--[if IE & !(lte IE 8)]>aren\'t<![endif]-->'
337n/a '<!--[if IE 8]>condcoms<![endif]-->'
338n/a '<!--[if lte IE 7]>pretty?<![endif]-->')
339n/a expected = [('comment', "[if IE & !(lte IE 8)]>aren't<![endif]"),
340n/a ('comment', '[if IE 8]>condcoms<![endif]'),
341n/a ('comment', '[if lte IE 7]>pretty?<![endif]')]
342n/a self._run_check(html, expected)
343n/a
344n/a def test_convert_charrefs(self):
345n/a # default value for convert_charrefs is now True
346n/a collector = lambda: EventCollectorCharrefs()
347n/a self.assertTrue(collector().convert_charrefs)
348n/a charrefs = ['&quot;', '&#34;', '&#x22;', '&quot', '&#34', '&#x22']
349n/a # check charrefs in the middle of the text/attributes
350n/a expected = [('starttag', 'a', [('href', 'foo"zar')]),
351n/a ('data', 'a"z'), ('endtag', 'a')]
352n/a for charref in charrefs:
353n/a self._run_check('<a href="foo{0}zar">a{0}z</a>'.format(charref),
354n/a expected, collector=collector())
355n/a # check charrefs at the beginning/end of the text/attributes
356n/a expected = [('data', '"'),
357n/a ('starttag', 'a', [('x', '"'), ('y', '"X'), ('z', 'X"')]),
358n/a ('data', '"'), ('endtag', 'a'), ('data', '"')]
359n/a for charref in charrefs:
360n/a self._run_check('{0}<a x="{0}" y="{0}X" z="X{0}">'
361n/a '{0}</a>{0}'.format(charref),
362n/a expected, collector=collector())
363n/a # check charrefs in <script>/<style> elements
364n/a for charref in charrefs:
365n/a text = 'X'.join([charref]*3)
366n/a expected = [('data', '"'),
367n/a ('starttag', 'script', []), ('data', text),
368n/a ('endtag', 'script'), ('data', '"'),
369n/a ('starttag', 'style', []), ('data', text),
370n/a ('endtag', 'style'), ('data', '"')]
371n/a self._run_check('{1}<script>{0}</script>{1}'
372n/a '<style>{0}</style>{1}'.format(text, charref),
373n/a expected, collector=collector())
374n/a # check truncated charrefs at the end of the file
375n/a html = '&quo &# &#x'
376n/a for x in range(1, len(html)):
377n/a self._run_check(html[:x], [('data', html[:x])],
378n/a collector=collector())
379n/a # check a string with no charrefs
380n/a self._run_check('no charrefs here', [('data', 'no charrefs here')],
381n/a collector=collector())
382n/a
383n/a # the remaining tests were for the "tolerant" parser (which is now
384n/a # the default), and check various kind of broken markup
385n/a def test_tolerant_parsing(self):
386n/a self._run_check('<html <html>te>>xt&a<<bc</a></html>\n'
387n/a '<img src="URL><//img></html</html>', [
388n/a ('starttag', 'html', [('<html', None)]),
389n/a ('data', 'te>>xt'),
390n/a ('entityref', 'a'),
391n/a ('data', '<'),
392n/a ('starttag', 'bc<', [('a', None)]),
393n/a ('endtag', 'html'),
394n/a ('data', '\n<img src="URL>'),
395n/a ('comment', '/img'),
396n/a ('endtag', 'html<')])
397n/a
398n/a def test_starttag_junk_chars(self):
399n/a self._run_check("</>", [])
400n/a self._run_check("</$>", [('comment', '$')])
401n/a self._run_check("</", [('data', '</')])
402n/a self._run_check("</a", [('data', '</a')])
403n/a self._run_check("<a<a>", [('starttag', 'a<a', [])])
404n/a self._run_check("</a<a>", [('endtag', 'a<a')])
405n/a self._run_check("<!", [('data', '<!')])
406n/a self._run_check("<a", [('data', '<a')])
407n/a self._run_check("<a foo='bar'", [('data', "<a foo='bar'")])
408n/a self._run_check("<a foo='bar", [('data', "<a foo='bar")])
409n/a self._run_check("<a foo='>'", [('data', "<a foo='>'")])
410n/a self._run_check("<a foo='>", [('data', "<a foo='>")])
411n/a self._run_check("<a$>", [('starttag', 'a$', [])])
412n/a self._run_check("<a$b>", [('starttag', 'a$b', [])])
413n/a self._run_check("<a$b/>", [('startendtag', 'a$b', [])])
414n/a self._run_check("<a$b >", [('starttag', 'a$b', [])])
415n/a self._run_check("<a$b />", [('startendtag', 'a$b', [])])
416n/a
417n/a def test_slashes_in_starttag(self):
418n/a self._run_check('<a foo="var"/>', [('startendtag', 'a', [('foo', 'var')])])
419n/a html = ('<img width=902 height=250px '
420n/a 'src="/sites/default/files/images/homepage/foo.jpg" '
421n/a '/*what am I doing here*/ />')
422n/a expected = [(
423n/a 'startendtag', 'img',
424n/a [('width', '902'), ('height', '250px'),
425n/a ('src', '/sites/default/files/images/homepage/foo.jpg'),
426n/a ('*what', None), ('am', None), ('i', None),
427n/a ('doing', None), ('here*', None)]
428n/a )]
429n/a self._run_check(html, expected)
430n/a html = ('<a / /foo/ / /=/ / /bar/ / />'
431n/a '<a / /foo/ / /=/ / /bar/ / >')
432n/a expected = [
433n/a ('startendtag', 'a', [('foo', None), ('=', None), ('bar', None)]),
434n/a ('starttag', 'a', [('foo', None), ('=', None), ('bar', None)])
435n/a ]
436n/a self._run_check(html, expected)
437n/a #see issue #14538
438n/a html = ('<meta><meta / ><meta // ><meta / / >'
439n/a '<meta/><meta /><meta //><meta//>')
440n/a expected = [
441n/a ('starttag', 'meta', []), ('starttag', 'meta', []),
442n/a ('starttag', 'meta', []), ('starttag', 'meta', []),
443n/a ('startendtag', 'meta', []), ('startendtag', 'meta', []),
444n/a ('startendtag', 'meta', []), ('startendtag', 'meta', []),
445n/a ]
446n/a self._run_check(html, expected)
447n/a
448n/a def test_declaration_junk_chars(self):
449n/a self._run_check("<!DOCTYPE foo $ >", [('decl', 'DOCTYPE foo $ ')])
450n/a
451n/a def test_illegal_declarations(self):
452n/a self._run_check('<!spacer type="block" height="25">',
453n/a [('comment', 'spacer type="block" height="25"')])
454n/a
455n/a def test_with_unquoted_attributes(self):
456n/a # see #12008
457n/a html = ("<html><body bgcolor=d0ca90 text='181008'>"
458n/a "<table cellspacing=0 cellpadding=1 width=100% ><tr>"
459n/a "<td align=left><font size=-1>"
460n/a "- <a href=/rabota/><span class=en> software-and-i</span></a>"
461n/a "- <a href='/1/'><span class=en> library</span></a></table>")
462n/a expected = [
463n/a ('starttag', 'html', []),
464n/a ('starttag', 'body', [('bgcolor', 'd0ca90'), ('text', '181008')]),
465n/a ('starttag', 'table',
466n/a [('cellspacing', '0'), ('cellpadding', '1'), ('width', '100%')]),
467n/a ('starttag', 'tr', []),
468n/a ('starttag', 'td', [('align', 'left')]),
469n/a ('starttag', 'font', [('size', '-1')]),
470n/a ('data', '- '), ('starttag', 'a', [('href', '/rabota/')]),
471n/a ('starttag', 'span', [('class', 'en')]), ('data', ' software-and-i'),
472n/a ('endtag', 'span'), ('endtag', 'a'),
473n/a ('data', '- '), ('starttag', 'a', [('href', '/1/')]),
474n/a ('starttag', 'span', [('class', 'en')]), ('data', ' library'),
475n/a ('endtag', 'span'), ('endtag', 'a'), ('endtag', 'table')
476n/a ]
477n/a self._run_check(html, expected)
478n/a
479n/a def test_comma_between_attributes(self):
480n/a self._run_check('<form action="/xxx.php?a=1&amp;b=2&amp", '
481n/a 'method="post">', [
482n/a ('starttag', 'form',
483n/a [('action', '/xxx.php?a=1&b=2&'),
484n/a (',', None), ('method', 'post')])])
485n/a
486n/a def test_weird_chars_in_unquoted_attribute_values(self):
487n/a self._run_check('<form action=bogus|&#()value>', [
488n/a ('starttag', 'form',
489n/a [('action', 'bogus|&#()value')])])
490n/a
491n/a def test_invalid_end_tags(self):
492n/a # A collection of broken end tags. <br> is used as separator.
493n/a # see http://www.w3.org/TR/html5/tokenization.html#end-tag-open-state
494n/a # and #13993
495n/a html = ('<br></label</p><br></div end tmAd-leaderBoard><br></<h4><br>'
496n/a '</li class="unit"><br></li\r\n\t\t\t\t\t\t</ul><br></><br>')
497n/a expected = [('starttag', 'br', []),
498n/a # < is part of the name, / is discarded, p is an attribute
499n/a ('endtag', 'label<'),
500n/a ('starttag', 'br', []),
501n/a # text and attributes are discarded
502n/a ('endtag', 'div'),
503n/a ('starttag', 'br', []),
504n/a # comment because the first char after </ is not a-zA-Z
505n/a ('comment', '<h4'),
506n/a ('starttag', 'br', []),
507n/a # attributes are discarded
508n/a ('endtag', 'li'),
509n/a ('starttag', 'br', []),
510n/a # everything till ul (included) is discarded
511n/a ('endtag', 'li'),
512n/a ('starttag', 'br', []),
513n/a # </> is ignored
514n/a ('starttag', 'br', [])]
515n/a self._run_check(html, expected)
516n/a
517n/a def test_broken_invalid_end_tag(self):
518n/a # This is technically wrong (the "> shouldn't be included in the 'data')
519n/a # but is probably not worth fixing it (in addition to all the cases of
520n/a # the previous test, it would require a full attribute parsing).
521n/a # see #13993
522n/a html = '<b>This</b attr=">"> confuses the parser'
523n/a expected = [('starttag', 'b', []),
524n/a ('data', 'This'),
525n/a ('endtag', 'b'),
526n/a ('data', '"> confuses the parser')]
527n/a self._run_check(html, expected)
528n/a
529n/a def test_correct_detection_of_start_tags(self):
530n/a # see #13273
531n/a html = ('<div style="" ><b>The <a href="some_url">rain</a> '
532n/a '<br /> in <span>Spain</span></b></div>')
533n/a expected = [
534n/a ('starttag', 'div', [('style', '')]),
535n/a ('starttag', 'b', []),
536n/a ('data', 'The '),
537n/a ('starttag', 'a', [('href', 'some_url')]),
538n/a ('data', 'rain'),
539n/a ('endtag', 'a'),
540n/a ('data', ' '),
541n/a ('startendtag', 'br', []),
542n/a ('data', ' in '),
543n/a ('starttag', 'span', []),
544n/a ('data', 'Spain'),
545n/a ('endtag', 'span'),
546n/a ('endtag', 'b'),
547n/a ('endtag', 'div')
548n/a ]
549n/a self._run_check(html, expected)
550n/a
551n/a html = '<div style="", foo = "bar" ><b>The <a href="some_url">rain</a>'
552n/a expected = [
553n/a ('starttag', 'div', [('style', ''), (',', None), ('foo', 'bar')]),
554n/a ('starttag', 'b', []),
555n/a ('data', 'The '),
556n/a ('starttag', 'a', [('href', 'some_url')]),
557n/a ('data', 'rain'),
558n/a ('endtag', 'a'),
559n/a ]
560n/a self._run_check(html, expected)
561n/a
562n/a def test_EOF_in_charref(self):
563n/a # see #17802
564n/a # This test checks that the UnboundLocalError reported in the issue
565n/a # is not raised, however I'm not sure the returned values are correct.
566n/a # Maybe HTMLParser should use self.unescape for these
567n/a data = [
568n/a ('a&', [('data', 'a&')]),
569n/a ('a&b', [('data', 'ab')]),
570n/a ('a&b ', [('data', 'a'), ('entityref', 'b'), ('data', ' ')]),
571n/a ('a&b;', [('data', 'a'), ('entityref', 'b')]),
572n/a ]
573n/a for html, expected in data:
574n/a self._run_check(html, expected)
575n/a
576n/a def test_unescape_method(self):
577n/a from html import unescape
578n/a p = self.get_collector()
579n/a with self.assertWarns(DeprecationWarning):
580n/a s = '&quot;&#34;&#x22;&quot&#34&#x22&#bad;'
581n/a self.assertEqual(p.unescape(s), unescape(s))
582n/a
583n/a def test_broken_comments(self):
584n/a html = ('<! not really a comment >'
585n/a '<! not a comment either -->'
586n/a '<! -- close enough -->'
587n/a '<!><!<-- this was an empty comment>'
588n/a '<!!! another bogus comment !!!>')
589n/a expected = [
590n/a ('comment', ' not really a comment '),
591n/a ('comment', ' not a comment either --'),
592n/a ('comment', ' -- close enough --'),
593n/a ('comment', ''),
594n/a ('comment', '<-- this was an empty comment'),
595n/a ('comment', '!! another bogus comment !!!'),
596n/a ]
597n/a self._run_check(html, expected)
598n/a
599n/a def test_broken_condcoms(self):
600n/a # these condcoms are missing the '--' after '<!' and before the '>'
601n/a html = ('<![if !(IE)]>broken condcom<![endif]>'
602n/a '<![if ! IE]><link href="favicon.tiff"/><![endif]>'
603n/a '<![if !IE 6]><img src="firefox.png" /><![endif]>'
604n/a '<![if !ie 6]><b>foo</b><![endif]>'
605n/a '<![if (!IE)|(lt IE 9)]><img src="mammoth.bmp" /><![endif]>')
606n/a # According to the HTML5 specs sections "8.2.4.44 Bogus comment state"
607n/a # and "8.2.4.45 Markup declaration open state", comment tokens should
608n/a # be emitted instead of 'unknown decl', but calling unknown_decl
609n/a # provides more flexibility.
610n/a # See also Lib/_markupbase.py:parse_declaration
611n/a expected = [
612n/a ('unknown decl', 'if !(IE)'),
613n/a ('data', 'broken condcom'),
614n/a ('unknown decl', 'endif'),
615n/a ('unknown decl', 'if ! IE'),
616n/a ('startendtag', 'link', [('href', 'favicon.tiff')]),
617n/a ('unknown decl', 'endif'),
618n/a ('unknown decl', 'if !IE 6'),
619n/a ('startendtag', 'img', [('src', 'firefox.png')]),
620n/a ('unknown decl', 'endif'),
621n/a ('unknown decl', 'if !ie 6'),
622n/a ('starttag', 'b', []),
623n/a ('data', 'foo'),
624n/a ('endtag', 'b'),
625n/a ('unknown decl', 'endif'),
626n/a ('unknown decl', 'if (!IE)|(lt IE 9)'),
627n/a ('startendtag', 'img', [('src', 'mammoth.bmp')]),
628n/a ('unknown decl', 'endif')
629n/a ]
630n/a self._run_check(html, expected)
631n/a
632n/a def test_convert_charrefs_dropped_text(self):
633n/a # #23144: make sure that all the events are triggered when
634n/a # convert_charrefs is True, even if we don't call .close()
635n/a parser = EventCollector(convert_charrefs=True)
636n/a # before the fix, bar & baz was missing
637n/a parser.feed("foo <a>link</a> bar &amp; baz")
638n/a self.assertEqual(
639n/a parser.get_events(),
640n/a [('data', 'foo '), ('starttag', 'a', []), ('data', 'link'),
641n/a ('endtag', 'a'), ('data', ' bar & baz')]
642n/a )
643n/a
644n/a
645n/aclass AttributesTestCase(TestCaseBase):
646n/a
647n/a def test_attr_syntax(self):
648n/a output = [
649n/a ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", None)])
650n/a ]
651n/a self._run_check("""<a b='v' c="v" d=v e>""", output)
652n/a self._run_check("""<a b = 'v' c = "v" d = v e>""", output)
653n/a self._run_check("""<a\nb\n=\n'v'\nc\n=\n"v"\nd\n=\nv\ne>""", output)
654n/a self._run_check("""<a\tb\t=\t'v'\tc\t=\t"v"\td\t=\tv\te>""", output)
655n/a
656n/a def test_attr_values(self):
657n/a self._run_check("""<a b='xxx\n\txxx' c="yyy\t\nyyy" d='\txyz\n'>""",
658n/a [("starttag", "a", [("b", "xxx\n\txxx"),
659n/a ("c", "yyy\t\nyyy"),
660n/a ("d", "\txyz\n")])])
661n/a self._run_check("""<a b='' c="">""",
662n/a [("starttag", "a", [("b", ""), ("c", "")])])
663n/a # Regression test for SF patch #669683.
664n/a self._run_check("<e a=rgb(1,2,3)>",
665n/a [("starttag", "e", [("a", "rgb(1,2,3)")])])
666n/a # Regression test for SF bug #921657.
667n/a self._run_check(
668n/a "<a href=mailto:xyz@example.com>",
669n/a [("starttag", "a", [("href", "mailto:xyz@example.com")])])
670n/a
671n/a def test_attr_nonascii(self):
672n/a # see issue 7311
673n/a self._run_check(
674n/a "<img src=/foo/bar.png alt=\u4e2d\u6587>",
675n/a [("starttag", "img", [("src", "/foo/bar.png"),
676n/a ("alt", "\u4e2d\u6587")])])
677n/a self._run_check(
678n/a "<a title='\u30c6\u30b9\u30c8' href='\u30c6\u30b9\u30c8.html'>",
679n/a [("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
680n/a ("href", "\u30c6\u30b9\u30c8.html")])])
681n/a self._run_check(
682n/a '<a title="\u30c6\u30b9\u30c8" href="\u30c6\u30b9\u30c8.html">',
683n/a [("starttag", "a", [("title", "\u30c6\u30b9\u30c8"),
684n/a ("href", "\u30c6\u30b9\u30c8.html")])])
685n/a
686n/a def test_attr_entity_replacement(self):
687n/a self._run_check(
688n/a "<a b='&amp;&gt;&lt;&quot;&apos;'>",
689n/a [("starttag", "a", [("b", "&><\"'")])])
690n/a
691n/a def test_attr_funky_names(self):
692n/a self._run_check(
693n/a "<a a.b='v' c:d=v e-f=v>",
694n/a [("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")])])
695n/a
696n/a def test_entityrefs_in_attributes(self):
697n/a self._run_check(
698n/a "<html foo='&euro;&amp;&#97;&#x61;&unsupported;'>",
699n/a [("starttag", "html", [("foo", "\u20AC&aa&unsupported;")])])
700n/a
701n/a
702n/a def test_attr_funky_names2(self):
703n/a self._run_check(
704n/a r"<a $><b $=%><c \=/>",
705n/a [("starttag", "a", [("$", None)]),
706n/a ("starttag", "b", [("$", "%")]),
707n/a ("starttag", "c", [("\\", "/")])])
708n/a
709n/a def test_entities_in_attribute_value(self):
710n/a # see #1200313
711n/a for entity in ['&', '&amp;', '&#38;', '&#x26;']:
712n/a self._run_check('<a href="%s">' % entity,
713n/a [("starttag", "a", [("href", "&")])])
714n/a self._run_check("<a href='%s'>" % entity,
715n/a [("starttag", "a", [("href", "&")])])
716n/a self._run_check("<a href=%s>" % entity,
717n/a [("starttag", "a", [("href", "&")])])
718n/a
719n/a def test_malformed_attributes(self):
720n/a # see #13357
721n/a html = (
722n/a "<a href=test'style='color:red;bad1'>test - bad1</a>"
723n/a "<a href=test'+style='color:red;ba2'>test - bad2</a>"
724n/a "<a href=test'&nbsp;style='color:red;bad3'>test - bad3</a>"
725n/a "<a href = test'&nbsp;style='color:red;bad4' >test - bad4</a>"
726n/a )
727n/a expected = [
728n/a ('starttag', 'a', [('href', "test'style='color:red;bad1'")]),
729n/a ('data', 'test - bad1'), ('endtag', 'a'),
730n/a ('starttag', 'a', [('href', "test'+style='color:red;ba2'")]),
731n/a ('data', 'test - bad2'), ('endtag', 'a'),
732n/a ('starttag', 'a', [('href', "test'\xa0style='color:red;bad3'")]),
733n/a ('data', 'test - bad3'), ('endtag', 'a'),
734n/a ('starttag', 'a', [('href', "test'\xa0style='color:red;bad4'")]),
735n/a ('data', 'test - bad4'), ('endtag', 'a')
736n/a ]
737n/a self._run_check(html, expected)
738n/a
739n/a def test_malformed_adjacent_attributes(self):
740n/a # see #12629
741n/a self._run_check('<x><y z=""o"" /></x>',
742n/a [('starttag', 'x', []),
743n/a ('startendtag', 'y', [('z', ''), ('o""', None)]),
744n/a ('endtag', 'x')])
745n/a self._run_check('<x><y z="""" /></x>',
746n/a [('starttag', 'x', []),
747n/a ('startendtag', 'y', [('z', ''), ('""', None)]),
748n/a ('endtag', 'x')])
749n/a
750n/a # see #755670 for the following 3 tests
751n/a def test_adjacent_attributes(self):
752n/a self._run_check('<a width="100%"cellspacing=0>',
753n/a [("starttag", "a",
754n/a [("width", "100%"), ("cellspacing","0")])])
755n/a
756n/a self._run_check('<a id="foo"class="bar">',
757n/a [("starttag", "a",
758n/a [("id", "foo"), ("class","bar")])])
759n/a
760n/a def test_missing_attribute_value(self):
761n/a self._run_check('<a v=>',
762n/a [("starttag", "a", [("v", "")])])
763n/a
764n/a def test_javascript_attribute_value(self):
765n/a self._run_check("<a href=javascript:popup('/popup/help.html')>",
766n/a [("starttag", "a",
767n/a [("href", "javascript:popup('/popup/help.html')")])])
768n/a
769n/a def test_end_tag_in_attribute_value(self):
770n/a # see #1745761
771n/a self._run_check("<a href='http://www.example.org/\">;'>spam</a>",
772n/a [("starttag", "a",
773n/a [("href", "http://www.example.org/\">;")]),
774n/a ("data", "spam"), ("endtag", "a")])
775n/a
776n/a
777n/aif __name__ == "__main__":
778n/a unittest.main()