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

Python code coverage for Lib/test/test_sgmllib.py

#countcontent
11import pprint
21import re
31import unittest
41from test import test_support
51sgmllib = test_support.import_module('sgmllib', deprecated=True)
6n/a
7n/a
82class EventCollector(sgmllib.SGMLParser):
9n/a
101 def __init__(self):
1131 self.events = []
1231 self.append = self.events.append
1331 sgmllib.SGMLParser.__init__(self)
14n/a
151 def get_events(self):
16n/a # Normalize the list of events so that buffer artefacts don't
17n/a # separate runs of contiguous characters.
1830 L = []
1930 prevtype = None
20241 for event in self.events:
21211 type = event[0]
22211 if type == prevtype == "data":
23151 L[-1] = ("data", L[-1][1] + event[1])
24n/a else:
2560 L.append(event)
26211 prevtype = type
2730 self.events = L
2830 return L
29n/a
30n/a # structure markup
31n/a
321 def unknown_starttag(self, tag, attrs):
3326 self.append(("starttag", tag, attrs))
34n/a
351 def unknown_endtag(self, tag):
369 self.append(("endtag", tag))
37n/a
38n/a # all other markup
39n/a
401 def handle_comment(self, data):
411 self.append(("comment", data))
42n/a
431 def handle_charref(self, data):
440 self.append(("charref", data))
45n/a
461 def handle_data(self, data):
47161 self.append(("data", data))
48n/a
491 def handle_decl(self, decl):
503 self.append(("decl", decl))
51n/a
521 def handle_entityref(self, data):
530 self.append(("entityref", data))
54n/a
551 def handle_pi(self, data):
561 self.append(("pi", data))
57n/a
581 def unknown_decl(self, decl):
591 self.append(("unknown decl", decl))
60n/a
61n/a
622class CDATAEventCollector(EventCollector):
631 def start_cdata(self, attrs):
642 self.append(("starttag", "cdata", attrs))
652 self.setliteral()
66n/a
67n/a
682class HTMLEntityCollector(EventCollector):
69n/a
701 entity_or_charref = re.compile('(?:&([a-zA-Z][-.a-zA-Z0-9]*)'
71n/a '|&#(x[0-9a-zA-Z]+|[0-9]+))(;?)')
72n/a
731 def convert_charref(self, name):
742 self.append(("charref", "convert", name))
752 if name[0] != "x":
761 return EventCollector.convert_charref(self, name)
77n/a
781 def convert_codepoint(self, codepoint):
791 self.append(("codepoint", "convert", codepoint))
801 EventCollector.convert_codepoint(self, codepoint)
81n/a
821 def convert_entityref(self, name):
832 self.append(("entityref", "convert", name))
842 return EventCollector.convert_entityref(self, name)
85n/a
86n/a # These to record that they were called, then pass the call along
87n/a # to the default implementation so that it's actions can be
88n/a # recorded.
89n/a
901 def handle_charref(self, data):
911 self.append(("charref", data))
921 sgmllib.SGMLParser.handle_charref(self, data)
93n/a
941 def handle_entityref(self, data):
951 self.append(("entityref", data))
961 sgmllib.SGMLParser.handle_entityref(self, data)
97n/a
98n/a
992class SGMLParserTestCase(unittest.TestCase):
100n/a
1011 collector = EventCollector
102n/a
1031 def get_events(self, source):
10430 parser = self.collector()
10530 try:
1061211 for s in source:
1071181 parser.feed(s)
10830 parser.close()
1090 except:
110n/a #self.events = parser.events
1110 raise
11230 return parser.get_events()
113n/a
1141 def check_events(self, source, expected_events):
11530 try:
11630 events = self.get_events(source)
1170 except:
118n/a #import sys
119n/a #print >>sys.stderr, pprint.pformat(self.events)
1200 raise
12130 if events != expected_events:
1220 self.fail("received events did not match expected events\n"
123n/a "Expected:\n" + pprint.pformat(expected_events) +
1240 "\nReceived:\n" + pprint.pformat(events))
125n/a
1261 def check_parse_error(self, source):
1271 parser = EventCollector()
1281 try:
1291 parser.feed(source)
1300 parser.close()
1311 except sgmllib.SGMLParseError:
1321 pass
133n/a else:
1340 self.fail("expected SGMLParseError for %r\nReceived:\n%s"
1350 % (source, pprint.pformat(parser.get_events())))
136n/a
1371 def test_doctype_decl_internal(self):
138n/a inside = """\
139n/aDOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01//EN'
140n/a SYSTEM 'http://www.w3.org/TR/html401/strict.dtd' [
141n/a <!ELEMENT html - O EMPTY>
142n/a <!ATTLIST html
143n/a version CDATA #IMPLIED
144n/a profile CDATA 'DublinCore'>
145n/a <!NOTATION datatype SYSTEM 'http://xml.python.org/notations/python-module'>
146n/a <!ENTITY myEntity 'internal parsed entity'>
147n/a <!ENTITY anEntity SYSTEM 'http://xml.python.org/entities/something.xml'>
148n/a <!ENTITY % paramEntity 'name|name|name'>
149n/a %paramEntity;
150n/a <!-- comment -->
1511]"""
1521 self.check_events(["<!%s>" % inside], [
1531 ("decl", inside),
154n/a ])
155n/a
1561 def test_doctype_decl_external(self):
1571 inside = "DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01//EN'"
1581 self.check_events("<!%s>" % inside, [
1591 ("decl", inside),
160n/a ])
161n/a
1621 def test_underscore_in_attrname(self):
163n/a # SF bug #436621
164n/a """Make sure attribute names with underscores are accepted"""
1651 self.check_events("<a has_under _under>", [
1661 ("starttag", "a", [("has_under", "has_under"),
1671 ("_under", "_under")]),
168n/a ])
169n/a
1701 def test_underscore_in_tagname(self):
171n/a # SF bug #436621
172n/a """Make sure tag names with underscores are accepted"""
1731 self.check_events("<has_under></has_under>", [
1741 ("starttag", "has_under", []),
1751 ("endtag", "has_under"),
176n/a ])
177n/a
1781 def test_quotes_in_unquoted_attrs(self):
179n/a # SF bug #436621
180n/a """Be sure quotes in unquoted attributes are made part of the value"""
1811 self.check_events("<a href=foo'bar\"baz>", [
1821 ("starttag", "a", [("href", "foo'bar\"baz")]),
183n/a ])
184n/a
1851 def test_xhtml_empty_tag(self):
186n/a """Handling of XHTML-style empty start tags"""
1871 self.check_events("<br />text<i></i>", [
1881 ("starttag", "br", []),
1891 ("data", "text"),
1901 ("starttag", "i", []),
1911 ("endtag", "i"),
192n/a ])
193n/a
1941 def test_processing_instruction_only(self):
1951 self.check_events("<?processing instruction>", [
1961 ("pi", "processing instruction"),
197n/a ])
198n/a
1991 def test_bad_nesting(self):
2001 self.check_events("<a><b></a></b>", [
2011 ("starttag", "a", []),
2021 ("starttag", "b", []),
2031 ("endtag", "a"),
2041 ("endtag", "b"),
205n/a ])
206n/a
2071 def test_bare_ampersands(self):
2081 self.check_events("this text & contains & ampersands &", [
2091 ("data", "this text & contains & ampersands &"),
210n/a ])
211n/a
2121 def test_bare_pointy_brackets(self):
2131 self.check_events("this < text > contains < bare>pointy< brackets", [
2141 ("data", "this < text > contains < bare>pointy< brackets"),
215n/a ])
216n/a
2171 def test_attr_syntax(self):
218n/a output = [
2191 ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", "e")])
220n/a ]
2211 self.check_events("""<a b='v' c="v" d=v e>""", output)
2221 self.check_events("""<a b = 'v' c = "v" d = v e>""", output)
2231 self.check_events("""<a\nb\n=\n'v'\nc\n=\n"v"\nd\n=\nv\ne>""", output)
2241 self.check_events("""<a\tb\t=\t'v'\tc\t=\t"v"\td\t=\tv\te>""", output)
225n/a
2261 def test_attr_values(self):
2271 self.check_events("""<a b='xxx\n\txxx' c="yyy\t\nyyy" d='\txyz\n'>""",
2281 [("starttag", "a", [("b", "xxx\n\txxx"),
2291 ("c", "yyy\t\nyyy"),
2301 ("d", "\txyz\n")])
231n/a ])
2321 self.check_events("""<a b='' c="">""", [
2331 ("starttag", "a", [("b", ""), ("c", "")]),
234n/a ])
235n/a # URL construction stuff from RFC 1808:
2361 safe = "$-_.+"
2371 extra = "!*'(),"
2381 reserved = ";/?:@&="
2391 url = "http://example.com:8080/path/to/file?%s%s%s" % (
2401 safe, extra, reserved)
2411 self.check_events("""<e a=%s>""" % url, [
2421 ("starttag", "e", [("a", url)]),
243n/a ])
244n/a # Regression test for SF patch #669683.
2451 self.check_events("<e a=rgb(1,2,3)>", [
2461 ("starttag", "e", [("a", "rgb(1,2,3)")]),
247n/a ])
248n/a
2491 def test_attr_values_entities(self):
250n/a """Substitution of entities and charrefs in attribute values"""
251n/a # SF bug #1452246
2521 self.check_events("""<a b=&lt; c=&lt;&gt; d=&lt-&gt; e='&lt; '
253n/a f="&xxx;" g='&#32;&#33;' h='&#500;'
254n/a i='x?a=b&c=d;'
2551 j='&amp;#42;' k='&#38;#42;'>""",
2561 [("starttag", "a", [("b", "<"),
2571 ("c", "<>"),
2581 ("d", "&lt->"),
2591 ("e", "< "),
2601 ("f", "&xxx;"),
2611 ("g", " !"),
2621 ("h", "&#500;"),
2631 ("i", "x?a=b&c=d;"),
2641 ("j", "&#42;"),
2651 ("k", "&#42;"),
266n/a ])])
267n/a
2681 def test_convert_overrides(self):
269n/a # This checks that the character and entity reference
270n/a # conversion helpers are called at the documented times. No
271n/a # attempt is made to really change what the parser accepts.
272n/a #
2731 self.collector = HTMLEntityCollector
2741 self.check_events(('<a title="&ldquo;test&#x201d;">foo</a>'
275n/a '&foobar;&#42;'), [
2761 ('entityref', 'convert', 'ldquo'),
2771 ('charref', 'convert', 'x201d'),
2781 ('starttag', 'a', [('title', '&ldquo;test&#x201d;')]),
2791 ('data', 'foo'),
2801 ('endtag', 'a'),
2811 ('entityref', 'foobar'),
2821 ('entityref', 'convert', 'foobar'),
2831 ('charref', '42'),
2841 ('charref', 'convert', '42'),
2851 ('codepoint', 'convert', 42),
286n/a ])
287n/a
2881 def test_attr_funky_names(self):
2891 self.check_events("""<a a.b='v' c:d=v e-f=v>""", [
2901 ("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")]),
291n/a ])
292n/a
2931 def test_attr_value_ip6_url(self):
294n/a # http://www.python.org/sf/853506
2951 self.check_events(("<a href='http://[1080::8:800:200C:417A]/'>"
296n/a "<a href=http://[1080::8:800:200C:417A]/>"), [
2971 ("starttag", "a", [("href", "http://[1080::8:800:200C:417A]/")]),
2981 ("starttag", "a", [("href", "http://[1080::8:800:200C:417A]/")]),
299n/a ])
300n/a
3011 def test_weird_starttags(self):
3021 self.check_events("<a<a>", [
3031 ("starttag", "a", []),
3041 ("starttag", "a", []),
305n/a ])
3061 self.check_events("</a<a>", [
3071 ("endtag", "a"),
3081 ("starttag", "a", []),
309n/a ])
310n/a
3111 def test_declaration_junk_chars(self):
3121 self.check_parse_error("<!DOCTYPE foo $ >")
313n/a
3141 def test_get_starttag_text(self):
3151 s = """<foobar \n one="1"\ttwo=2 >"""
3161 self.check_events(s, [
3171 ("starttag", "foobar", [("one", "1"), ("two", "2")]),
318n/a ])
319n/a
3201 def test_cdata_content(self):
3211 s = ("<cdata> <!-- not a comment --> &not-an-entity-ref; </cdata>"
322n/a "<notcdata> <!-- comment --> </notcdata>")
3231 self.collector = CDATAEventCollector
3241 self.check_events(s, [
3251 ("starttag", "cdata", []),
3261 ("data", " <!-- not a comment --> &not-an-entity-ref; "),
3271 ("endtag", "cdata"),
3281 ("starttag", "notcdata", []),
3291 ("data", " "),
3301 ("comment", " comment "),
3311 ("data", " "),
3321 ("endtag", "notcdata"),
333n/a ])
3341 s = """<cdata> <not a='start tag'> </cdata>"""
3351 self.check_events(s, [
3361 ("starttag", "cdata", []),
3371 ("data", " <not a='start tag'> "),
3381 ("endtag", "cdata"),
339n/a ])
340n/a
3411 def test_illegal_declarations(self):
3421 s = 'abc<!spacer type="block" height="25">def'
3431 self.check_events(s, [
3441 ("data", "abc"),
3451 ("unknown decl", 'spacer type="block" height="25"'),
3461 ("data", "def"),
347n/a ])
348n/a
3491 def test_enumerated_attr_type(self):
3501 s = "<!DOCTYPE doc [<!ATTLIST doc attr (a | b) >]>"
3511 self.check_events(s, [
3521 ('decl', 'DOCTYPE doc [<!ATTLIST doc attr (a | b) >]'),
353n/a ])
354n/a
3551 def test_read_chunks(self):
356n/a # SF bug #1541697, this caused sgml parser to hang
357n/a # Just verify this code doesn't cause a hang.
3581 CHUNK = 1024 # increasing this to 8212 makes the problem go away
359n/a
3601 f = open(test_support.findfile('sgml_input.html'))
3611 fp = sgmllib.SGMLParser()
3621 while 1:
3639 data = f.read(CHUNK)
3649 fp.feed(data)
3659 if len(data) != CHUNK:
3661 break
367n/a
3681 def test_only_decode_ascii(self):
369n/a # SF bug #1651995, make sure non-ascii character references are not decoded
3701 s = '<signs exclamation="&#33" copyright="&#169" quoteleft="&#8216;">'
3711 self.check_events(s, [
3721 ('starttag', 'signs',
3731 [('exclamation', '!'), ('copyright', '&#169'),
3741 ('quoteleft', '&#8216;')]),
375n/a ])
376n/a
377n/a # XXX These tests have been disabled by prefixing their names with
378n/a # an underscore. The first two exercise outstanding bugs in the
379n/a # sgmllib module, and the third exhibits questionable behavior
380n/a # that needs to be carefully considered before changing it.
381n/a
3821 def _test_starttag_end_boundary(self):
3830 self.check_events("<a b='<'>", [("starttag", "a", [("b", "<")])])
3840 self.check_events("<a b='>'>", [("starttag", "a", [("b", ">")])])
385n/a
3861 def _test_buffer_artefacts(self):
3870 output = [("starttag", "a", [("b", "<")])]
3880 self.check_events(["<a b='<'>"], output)
3890 self.check_events(["<a ", "b='<'>"], output)
3900 self.check_events(["<a b", "='<'>"], output)
3910 self.check_events(["<a b=", "'<'>"], output)
3920 self.check_events(["<a b='<", "'>"], output)
3930 self.check_events(["<a b='<'", ">"], output)
394n/a
3950 output = [("starttag", "a", [("b", ">")])]
3960 self.check_events(["<a b='>'>"], output)
3970 self.check_events(["<a ", "b='>'>"], output)
3980 self.check_events(["<a b", "='>'>"], output)
3990 self.check_events(["<a b=", "'>'>"], output)
4000 self.check_events(["<a b='>", "'>"], output)
4010 self.check_events(["<a b='>'", ">"], output)
402n/a
4030 output = [("comment", "abc")]
4040 self.check_events(["", "<!--abc-->"], output)
4050 self.check_events(["<", "!--abc-->"], output)
4060 self.check_events(["<!", "--abc-->"], output)
4070 self.check_events(["<!-", "-abc-->"], output)
4080 self.check_events(["<!--", "abc-->"], output)
4090 self.check_events(["<!--a", "bc-->"], output)
4100 self.check_events(["<!--ab", "c-->"], output)
4110 self.check_events(["<!--abc", "-->"], output)
4120 self.check_events(["<!--abc-", "->"], output)
4130 self.check_events(["<!--abc--", ">"], output)
4140 self.check_events(["<!--abc-->", ""], output)
415n/a
4161 def _test_starttag_junk_chars(self):
4170 self.check_parse_error("<")
4180 self.check_parse_error("<>")
4190 self.check_parse_error("</$>")
4200 self.check_parse_error("</")
4210 self.check_parse_error("</a")
4220 self.check_parse_error("<$")
4230 self.check_parse_error("<$>")
4240 self.check_parse_error("<!")
4250 self.check_parse_error("<a $>")
4260 self.check_parse_error("<a")
4270 self.check_parse_error("<a foo='bar'")
4280 self.check_parse_error("<a foo='bar")
4290 self.check_parse_error("<a foo='>'")
4300 self.check_parse_error("<a foo='>")
4310 self.check_parse_error("<a foo=>")
432n/a
433n/a
4341def test_main():
4351 test_support.run_unittest(SGMLParserTestCase)
436n/a
437n/a
4381if __name__ == "__main__":
4390 test_main()