blob: ec417d032adc6d75f150229b6f82ea2247d24dc8 [file] [log] [blame]
Fred Drake19ff4ac2001-07-16 18:52:40 +00001import pprint
2import sgmllib
Fred Drake19ff4ac2001-07-16 18:52:40 +00003import unittest
Barry Warsaw04f357c2002-07-23 19:04:11 +00004from test import test_support
Fred Drake19ff4ac2001-07-16 18:52:40 +00005
6
7class EventCollector(sgmllib.SGMLParser):
8
9 def __init__(self):
10 self.events = []
11 self.append = self.events.append
12 sgmllib.SGMLParser.__init__(self)
13
14 def get_events(self):
15 # Normalize the list of events so that buffer artefacts don't
16 # separate runs of contiguous characters.
17 L = []
18 prevtype = None
19 for event in self.events:
20 type = event[0]
21 if type == prevtype == "data":
22 L[-1] = ("data", L[-1][1] + event[1])
23 else:
24 L.append(event)
25 prevtype = type
26 self.events = L
27 return L
28
29 # structure markup
30
31 def unknown_starttag(self, tag, attrs):
32 self.append(("starttag", tag, attrs))
33
34 def unknown_endtag(self, tag):
35 self.append(("endtag", tag))
36
37 # all other markup
38
39 def handle_comment(self, data):
40 self.append(("comment", data))
41
42 def handle_charref(self, data):
43 self.append(("charref", data))
44
45 def handle_data(self, data):
46 self.append(("data", data))
47
48 def handle_decl(self, decl):
49 self.append(("decl", decl))
50
51 def handle_entityref(self, data):
52 self.append(("entityref", data))
53
54 def handle_pi(self, data):
55 self.append(("pi", data))
56
Fred Drake30c48492001-09-24 20:22:09 +000057 def unknown_decl(self, decl):
58 self.append(("unknown decl", decl))
59
Fred Drake19ff4ac2001-07-16 18:52:40 +000060
61class CDATAEventCollector(EventCollector):
62 def start_cdata(self, attrs):
63 self.append(("starttag", "cdata", attrs))
64 self.setliteral()
65
66
67class SGMLParserTestCase(unittest.TestCase):
68
69 collector = EventCollector
70
Fred Drake30c48492001-09-24 20:22:09 +000071 def get_events(self, source):
Fred Drake19ff4ac2001-07-16 18:52:40 +000072 parser = self.collector()
Fred Drake30c48492001-09-24 20:22:09 +000073 try:
74 for s in source:
75 parser.feed(s)
76 parser.close()
77 except:
78 #self.events = parser.events
79 raise
80 return parser.get_events()
81
82 def check_events(self, source, expected_events):
83 try:
84 events = self.get_events(source)
85 except:
86 import sys
87 #print >>sys.stderr, pprint.pformat(self.events)
88 raise
Fred Drake19ff4ac2001-07-16 18:52:40 +000089 if events != expected_events:
90 self.fail("received events did not match expected events\n"
91 "Expected:\n" + pprint.pformat(expected_events) +
92 "\nReceived:\n" + pprint.pformat(events))
93
94 def check_parse_error(self, source):
95 parser = EventCollector()
96 try:
97 parser.feed(source)
98 parser.close()
99 except sgmllib.SGMLParseError:
100 pass
101 else:
102 self.fail("expected SGMLParseError for %r\nReceived:\n%s"
103 % (source, pprint.pformat(parser.get_events())))
104
Fred Drake30c48492001-09-24 20:22:09 +0000105 def test_doctype_decl_internal(self):
106 inside = """\
107DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01//EN'
108 SYSTEM 'http://www.w3.org/TR/html401/strict.dtd' [
109 <!ELEMENT html - O EMPTY>
110 <!ATTLIST html
111 version CDATA #IMPLIED
112 profile CDATA 'DublinCore'>
113 <!NOTATION datatype SYSTEM 'http://xml.python.org/notations/python-module'>
114 <!ENTITY myEntity 'internal parsed entity'>
115 <!ENTITY anEntity SYSTEM 'http://xml.python.org/entities/something.xml'>
116 <!ENTITY % paramEntity 'name|name|name'>
117 %paramEntity;
118 <!-- comment -->
119]"""
120 self.check_events(["<!%s>" % inside], [
121 ("decl", inside),
122 ])
123
124 def test_doctype_decl_external(self):
125 inside = "DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01//EN'"
126 self.check_events("<!%s>" % inside, [
127 ("decl", inside),
128 ])
129
Fred Drake19ff4ac2001-07-16 18:52:40 +0000130 def test_underscore_in_attrname(self):
131 # SF bug #436621
132 """Make sure attribute names with underscores are accepted"""
133 self.check_events("<a has_under _under>", [
134 ("starttag", "a", [("has_under", "has_under"),
135 ("_under", "_under")]),
136 ])
137
138 def test_underscore_in_tagname(self):
139 # SF bug #436621
140 """Make sure tag names with underscores are accepted"""
141 self.check_events("<has_under></has_under>", [
142 ("starttag", "has_under", []),
143 ("endtag", "has_under"),
144 ])
145
146 def test_quotes_in_unquoted_attrs(self):
147 # SF bug #436621
148 """Be sure quotes in unquoted attributes are made part of the value"""
149 self.check_events("<a href=foo'bar\"baz>", [
150 ("starttag", "a", [("href", "foo'bar\"baz")]),
151 ])
152
153 def test_xhtml_empty_tag(self):
154 """Handling of XHTML-style empty start tags"""
155 self.check_events("<br />text<i></i>", [
156 ("starttag", "br", []),
157 ("data", "text"),
158 ("starttag", "i", []),
159 ("endtag", "i"),
160 ])
161
162 def test_processing_instruction_only(self):
163 self.check_events("<?processing instruction>", [
164 ("pi", "processing instruction"),
165 ])
166
167 def test_bad_nesting(self):
168 self.check_events("<a><b></a></b>", [
169 ("starttag", "a", []),
170 ("starttag", "b", []),
171 ("endtag", "a"),
172 ("endtag", "b"),
173 ])
174
Fred Drake30c48492001-09-24 20:22:09 +0000175 def test_bare_ampersands(self):
176 self.check_events("this text & contains & ampersands &", [
177 ("data", "this text & contains & ampersands &"),
178 ])
179
180 def test_bare_pointy_brackets(self):
181 self.check_events("this < text > contains < bare>pointy< brackets", [
182 ("data", "this < text > contains < bare>pointy< brackets"),
183 ])
184
Fred Drake19ff4ac2001-07-16 18:52:40 +0000185 def test_attr_syntax(self):
186 output = [
187 ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", "e")])
188 ]
189 self.check_events("""<a b='v' c="v" d=v e>""", output)
190 self.check_events("""<a b = 'v' c = "v" d = v e>""", output)
191 self.check_events("""<a\nb\n=\n'v'\nc\n=\n"v"\nd\n=\nv\ne>""", output)
192 self.check_events("""<a\tb\t=\t'v'\tc\t=\t"v"\td\t=\tv\te>""", output)
193
194 def test_attr_values(self):
195 self.check_events("""<a b='xxx\n\txxx' c="yyy\t\nyyy" d='\txyz\n'>""",
196 [("starttag", "a", [("b", "xxx\n\txxx"),
197 ("c", "yyy\t\nyyy"),
198 ("d", "\txyz\n")])
199 ])
200 self.check_events("""<a b='' c="">""", [
201 ("starttag", "a", [("b", ""), ("c", "")]),
202 ])
Fred Drake75ab1462003-04-29 22:12:55 +0000203 # URL construction stuff from RFC 1808:
204 safe = "$-_.+"
205 extra = "!*'(),"
206 reserved = ";/?:@&="
207 url = "http://example.com:8080/path/to/file?%s%s%s" % (
208 safe, extra, reserved)
209 self.check_events("""<e a=%s>""" % url, [
210 ("starttag", "e", [("a", url)]),
211 ])
Fred Drake0834d772003-03-14 16:21:57 +0000212 # Regression test for SF patch #669683.
213 self.check_events("<e a=rgb(1,2,3)>", [
214 ("starttag", "e", [("a", "rgb(1,2,3)")]),
215 ])
Fred Drake19ff4ac2001-07-16 18:52:40 +0000216
Georg Brandl7f6b67c2006-04-01 08:35:18 +0000217 def test_attr_values_entities(self):
218 """Substitution of entities and charrefs in attribute values"""
219 # SF bug #1452246
220 self.check_events("""<a b=&lt; c=&lt;&gt; d=&lt-&gt; e='&lt; '
Fred Drakea16393e2006-06-14 05:04:47 +0000221 f="&xxx;" g='&#32;&#33;' h='&#500;'
222 i='x?a=b&c=d;'
223 j='&amp;#42;' k='&#38;#42;'>""",
Georg Brandl7f6b67c2006-04-01 08:35:18 +0000224 [("starttag", "a", [("b", "<"),
225 ("c", "<>"),
226 ("d", "&lt->"),
227 ("e", "< "),
228 ("f", "&xxx;"),
229 ("g", " !"),
230 ("h", "&#500;"),
Fred Drakea16393e2006-06-14 05:04:47 +0000231 ("i", "x?a=b&c=d;"),
232 ("j", "&#42;"),
233 ("k", "&#42;"),
234 ])])
Georg Brandl7f6b67c2006-04-01 08:35:18 +0000235
Fred Drake19ff4ac2001-07-16 18:52:40 +0000236 def test_attr_funky_names(self):
237 self.check_events("""<a a.b='v' c:d=v e-f=v>""", [
238 ("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")]),
239 ])
240
Fred Drake30c48492001-09-24 20:22:09 +0000241 def test_illegal_declarations(self):
242 s = 'abc<!spacer type="block" height="25">def'
243 self.check_events(s, [
244 ("data", "abc"),
245 ("unknown decl", 'spacer type="block" height="25"'),
246 ("data", "def"),
247 ])
248
Fred Drake19ff4ac2001-07-16 18:52:40 +0000249 def test_weird_starttags(self):
250 self.check_events("<a<a>", [
251 ("starttag", "a", []),
252 ("starttag", "a", []),
253 ])
254 self.check_events("</a<a>", [
255 ("endtag", "a"),
256 ("starttag", "a", []),
257 ])
258
259 def test_declaration_junk_chars(self):
260 self.check_parse_error("<!DOCTYPE foo $ >")
261
262 def test_get_starttag_text(self):
263 s = """<foobar \n one="1"\ttwo=2 >"""
264 self.check_events(s, [
265 ("starttag", "foobar", [("one", "1"), ("two", "2")]),
266 ])
267
268 def test_cdata_content(self):
269 s = ("<cdata> <!-- not a comment --> &not-an-entity-ref; </cdata>"
270 "<notcdata> <!-- comment --> </notcdata>")
271 self.collector = CDATAEventCollector
272 self.check_events(s, [
273 ("starttag", "cdata", []),
274 ("data", " <!-- not a comment --> &not-an-entity-ref; "),
275 ("endtag", "cdata"),
276 ("starttag", "notcdata", []),
277 ("data", " "),
278 ("comment", " comment "),
279 ("data", " "),
280 ("endtag", "notcdata"),
281 ])
282 s = """<cdata> <not a='start tag'> </cdata>"""
283 self.check_events(s, [
284 ("starttag", "cdata", []),
285 ("data", " <not a='start tag'> "),
286 ("endtag", "cdata"),
287 ])
288
Fred Drake30c48492001-09-24 20:22:09 +0000289 def test_illegal_declarations(self):
290 s = 'abc<!spacer type="block" height="25">def'
291 self.check_events(s, [
292 ("data", "abc"),
293 ("unknown decl", 'spacer type="block" height="25"'),
294 ("data", "def"),
295 ])
296
Fred Drake04d9a802002-09-25 16:29:17 +0000297 def test_enumerated_attr_type(self):
298 s = "<!DOCTYPE doc [<!ATTLIST doc attr (a | b) >]>"
299 self.check_events(s, [
300 ('decl', 'DOCTYPE doc [<!ATTLIST doc attr (a | b) >]'),
301 ])
302
Fred Drake19ff4ac2001-07-16 18:52:40 +0000303 # XXX These tests have been disabled by prefixing their names with
304 # an underscore. The first two exercise outstanding bugs in the
305 # sgmllib module, and the third exhibits questionable behavior
306 # that needs to be carefully considered before changing it.
307
308 def _test_starttag_end_boundary(self):
Fred Drake72c9eff2006-06-14 04:25:02 +0000309 self.check_events("<a b='<'>", [("starttag", "a", [("b", "<")])])
310 self.check_events("<a b='>'>", [("starttag", "a", [("b", ">")])])
Fred Drake19ff4ac2001-07-16 18:52:40 +0000311
312 def _test_buffer_artefacts(self):
313 output = [("starttag", "a", [("b", "<")])]
314 self.check_events(["<a b='<'>"], output)
315 self.check_events(["<a ", "b='<'>"], output)
316 self.check_events(["<a b", "='<'>"], output)
317 self.check_events(["<a b=", "'<'>"], output)
318 self.check_events(["<a b='<", "'>"], output)
319 self.check_events(["<a b='<'", ">"], output)
320
321 output = [("starttag", "a", [("b", ">")])]
322 self.check_events(["<a b='>'>"], output)
323 self.check_events(["<a ", "b='>'>"], output)
324 self.check_events(["<a b", "='>'>"], output)
325 self.check_events(["<a b=", "'>'>"], output)
326 self.check_events(["<a b='>", "'>"], output)
327 self.check_events(["<a b='>'", ">"], output)
328
Fred Drake75d9a622004-09-08 22:57:01 +0000329 output = [("comment", "abc")]
Fred Drake72c9eff2006-06-14 04:25:02 +0000330 self.check_events(["", "<!--abc-->"], output)
331 self.check_events(["<", "!--abc-->"], output)
332 self.check_events(["<!", "--abc-->"], output)
333 self.check_events(["<!-", "-abc-->"], output)
334 self.check_events(["<!--", "abc-->"], output)
335 self.check_events(["<!--a", "bc-->"], output)
336 self.check_events(["<!--ab", "c-->"], output)
337 self.check_events(["<!--abc", "-->"], output)
338 self.check_events(["<!--abc-", "->"], output)
339 self.check_events(["<!--abc--", ">"], output)
340 self.check_events(["<!--abc-->", ""], output)
Fred Drake75d9a622004-09-08 22:57:01 +0000341
Fred Drake19ff4ac2001-07-16 18:52:40 +0000342 def _test_starttag_junk_chars(self):
343 self.check_parse_error("<")
344 self.check_parse_error("<>")
345 self.check_parse_error("</$>")
346 self.check_parse_error("</")
347 self.check_parse_error("</a")
348 self.check_parse_error("<$")
349 self.check_parse_error("<$>")
350 self.check_parse_error("<!")
351 self.check_parse_error("<a $>")
352 self.check_parse_error("<a")
353 self.check_parse_error("<a foo='bar'")
354 self.check_parse_error("<a foo='bar")
355 self.check_parse_error("<a foo='>'")
356 self.check_parse_error("<a foo='>")
357 self.check_parse_error("<a foo=>")
358
359
Fred Drake30c48492001-09-24 20:22:09 +0000360def test_main():
361 test_support.run_unittest(SGMLParserTestCase)
362
363
364if __name__ == "__main__":
365 test_main()