blob: 31b54de384525f5f076f3632657b35cfbe9861f2 [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
Fred Drakefab461a2006-06-16 23:45:06 +000067class HTMLEntityCollector(EventCollector):
68 import re, htmlentitydefs
69 entity_or_charref = re.compile('(?:&([a-zA-Z][-.a-zA-Z0-9]*)'
70 '|&#(x[0-9a-zA-Z]+|[0-9]+))(;?)')
71
72 def convert_charref(self, name):
73 self.append(("charref", "convert", name))
74 if name.startswith('x'):
75 return unichr(int(name[1:],16))
76 else:
77 return unichr(int(name))
78
79 def convert_entityref(self, name):
80 self.append(("entityref", "convert", name))
81 return unichr(self.htmlentitydefs.name2codepoint[name])
82
83
Fred Drake19ff4ac2001-07-16 18:52:40 +000084class SGMLParserTestCase(unittest.TestCase):
85
86 collector = EventCollector
87
Fred Drake30c48492001-09-24 20:22:09 +000088 def get_events(self, source):
Fred Drake19ff4ac2001-07-16 18:52:40 +000089 parser = self.collector()
Fred Drake30c48492001-09-24 20:22:09 +000090 try:
91 for s in source:
92 parser.feed(s)
93 parser.close()
94 except:
95 #self.events = parser.events
96 raise
97 return parser.get_events()
98
99 def check_events(self, source, expected_events):
100 try:
101 events = self.get_events(source)
102 except:
103 import sys
104 #print >>sys.stderr, pprint.pformat(self.events)
105 raise
Fred Drake19ff4ac2001-07-16 18:52:40 +0000106 if events != expected_events:
107 self.fail("received events did not match expected events\n"
108 "Expected:\n" + pprint.pformat(expected_events) +
109 "\nReceived:\n" + pprint.pformat(events))
110
111 def check_parse_error(self, source):
112 parser = EventCollector()
113 try:
114 parser.feed(source)
115 parser.close()
116 except sgmllib.SGMLParseError:
117 pass
118 else:
119 self.fail("expected SGMLParseError for %r\nReceived:\n%s"
120 % (source, pprint.pformat(parser.get_events())))
121
Fred Drake30c48492001-09-24 20:22:09 +0000122 def test_doctype_decl_internal(self):
123 inside = """\
124DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01//EN'
125 SYSTEM 'http://www.w3.org/TR/html401/strict.dtd' [
126 <!ELEMENT html - O EMPTY>
127 <!ATTLIST html
128 version CDATA #IMPLIED
129 profile CDATA 'DublinCore'>
130 <!NOTATION datatype SYSTEM 'http://xml.python.org/notations/python-module'>
131 <!ENTITY myEntity 'internal parsed entity'>
132 <!ENTITY anEntity SYSTEM 'http://xml.python.org/entities/something.xml'>
133 <!ENTITY % paramEntity 'name|name|name'>
134 %paramEntity;
135 <!-- comment -->
136]"""
137 self.check_events(["<!%s>" % inside], [
138 ("decl", inside),
139 ])
140
141 def test_doctype_decl_external(self):
142 inside = "DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01//EN'"
143 self.check_events("<!%s>" % inside, [
144 ("decl", inside),
145 ])
146
Fred Drake19ff4ac2001-07-16 18:52:40 +0000147 def test_underscore_in_attrname(self):
148 # SF bug #436621
149 """Make sure attribute names with underscores are accepted"""
150 self.check_events("<a has_under _under>", [
151 ("starttag", "a", [("has_under", "has_under"),
152 ("_under", "_under")]),
153 ])
154
155 def test_underscore_in_tagname(self):
156 # SF bug #436621
157 """Make sure tag names with underscores are accepted"""
158 self.check_events("<has_under></has_under>", [
159 ("starttag", "has_under", []),
160 ("endtag", "has_under"),
161 ])
162
163 def test_quotes_in_unquoted_attrs(self):
164 # SF bug #436621
165 """Be sure quotes in unquoted attributes are made part of the value"""
166 self.check_events("<a href=foo'bar\"baz>", [
167 ("starttag", "a", [("href", "foo'bar\"baz")]),
168 ])
169
170 def test_xhtml_empty_tag(self):
171 """Handling of XHTML-style empty start tags"""
172 self.check_events("<br />text<i></i>", [
173 ("starttag", "br", []),
174 ("data", "text"),
175 ("starttag", "i", []),
176 ("endtag", "i"),
177 ])
178
179 def test_processing_instruction_only(self):
180 self.check_events("<?processing instruction>", [
181 ("pi", "processing instruction"),
182 ])
183
184 def test_bad_nesting(self):
185 self.check_events("<a><b></a></b>", [
186 ("starttag", "a", []),
187 ("starttag", "b", []),
188 ("endtag", "a"),
189 ("endtag", "b"),
190 ])
191
Fred Drake30c48492001-09-24 20:22:09 +0000192 def test_bare_ampersands(self):
193 self.check_events("this text & contains & ampersands &", [
194 ("data", "this text & contains & ampersands &"),
195 ])
196
197 def test_bare_pointy_brackets(self):
198 self.check_events("this < text > contains < bare>pointy< brackets", [
199 ("data", "this < text > contains < bare>pointy< brackets"),
200 ])
201
Fred Drake19ff4ac2001-07-16 18:52:40 +0000202 def test_attr_syntax(self):
203 output = [
204 ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", "e")])
205 ]
206 self.check_events("""<a b='v' c="v" d=v e>""", output)
207 self.check_events("""<a b = 'v' c = "v" d = v e>""", output)
208 self.check_events("""<a\nb\n=\n'v'\nc\n=\n"v"\nd\n=\nv\ne>""", output)
209 self.check_events("""<a\tb\t=\t'v'\tc\t=\t"v"\td\t=\tv\te>""", output)
210
211 def test_attr_values(self):
212 self.check_events("""<a b='xxx\n\txxx' c="yyy\t\nyyy" d='\txyz\n'>""",
213 [("starttag", "a", [("b", "xxx\n\txxx"),
214 ("c", "yyy\t\nyyy"),
215 ("d", "\txyz\n")])
216 ])
217 self.check_events("""<a b='' c="">""", [
218 ("starttag", "a", [("b", ""), ("c", "")]),
219 ])
Fred Drake75ab1462003-04-29 22:12:55 +0000220 # URL construction stuff from RFC 1808:
221 safe = "$-_.+"
222 extra = "!*'(),"
223 reserved = ";/?:@&="
224 url = "http://example.com:8080/path/to/file?%s%s%s" % (
225 safe, extra, reserved)
226 self.check_events("""<e a=%s>""" % url, [
227 ("starttag", "e", [("a", url)]),
228 ])
Fred Drake0834d772003-03-14 16:21:57 +0000229 # Regression test for SF patch #669683.
230 self.check_events("<e a=rgb(1,2,3)>", [
231 ("starttag", "e", [("a", "rgb(1,2,3)")]),
232 ])
Fred Drake19ff4ac2001-07-16 18:52:40 +0000233
Georg Brandl7f6b67c2006-04-01 08:35:18 +0000234 def test_attr_values_entities(self):
235 """Substitution of entities and charrefs in attribute values"""
236 # SF bug #1452246
237 self.check_events("""<a b=&lt; c=&lt;&gt; d=&lt-&gt; e='&lt; '
Fred Drakea16393e2006-06-14 05:04:47 +0000238 f="&xxx;" g='&#32;&#33;' h='&#500;'
239 i='x?a=b&c=d;'
240 j='&amp;#42;' k='&#38;#42;'>""",
Georg Brandl7f6b67c2006-04-01 08:35:18 +0000241 [("starttag", "a", [("b", "<"),
242 ("c", "<>"),
243 ("d", "&lt->"),
244 ("e", "< "),
245 ("f", "&xxx;"),
246 ("g", " !"),
247 ("h", "&#500;"),
Fred Drakea16393e2006-06-14 05:04:47 +0000248 ("i", "x?a=b&c=d;"),
249 ("j", "&#42;"),
250 ("k", "&#42;"),
251 ])])
Georg Brandl7f6b67c2006-04-01 08:35:18 +0000252
Fred Drakefab461a2006-06-16 23:45:06 +0000253 def test_convert_overrides(self):
254 self.collector = HTMLEntityCollector
255 self.check_events('<a title="&ldquo;test&#x201d;">foo</a>', [
256 ('entityref', 'convert', 'ldquo'),
257 ('charref', 'convert', 'x201d'),
258 ('starttag', 'a', [('title', u'\u201ctest\u201d')]),
259 ('data', 'foo'),
260 ('endtag', 'a'),
261 ])
262
Fred Drake19ff4ac2001-07-16 18:52:40 +0000263 def test_attr_funky_names(self):
264 self.check_events("""<a a.b='v' c:d=v e-f=v>""", [
265 ("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")]),
266 ])
267
Fred Drake30c48492001-09-24 20:22:09 +0000268 def test_illegal_declarations(self):
269 s = 'abc<!spacer type="block" height="25">def'
270 self.check_events(s, [
271 ("data", "abc"),
272 ("unknown decl", 'spacer type="block" height="25"'),
273 ("data", "def"),
274 ])
275
Fred Drake19ff4ac2001-07-16 18:52:40 +0000276 def test_weird_starttags(self):
277 self.check_events("<a<a>", [
278 ("starttag", "a", []),
279 ("starttag", "a", []),
280 ])
281 self.check_events("</a<a>", [
282 ("endtag", "a"),
283 ("starttag", "a", []),
284 ])
285
286 def test_declaration_junk_chars(self):
287 self.check_parse_error("<!DOCTYPE foo $ >")
288
289 def test_get_starttag_text(self):
290 s = """<foobar \n one="1"\ttwo=2 >"""
291 self.check_events(s, [
292 ("starttag", "foobar", [("one", "1"), ("two", "2")]),
293 ])
294
295 def test_cdata_content(self):
296 s = ("<cdata> <!-- not a comment --> &not-an-entity-ref; </cdata>"
297 "<notcdata> <!-- comment --> </notcdata>")
298 self.collector = CDATAEventCollector
299 self.check_events(s, [
300 ("starttag", "cdata", []),
301 ("data", " <!-- not a comment --> &not-an-entity-ref; "),
302 ("endtag", "cdata"),
303 ("starttag", "notcdata", []),
304 ("data", " "),
305 ("comment", " comment "),
306 ("data", " "),
307 ("endtag", "notcdata"),
308 ])
309 s = """<cdata> <not a='start tag'> </cdata>"""
310 self.check_events(s, [
311 ("starttag", "cdata", []),
312 ("data", " <not a='start tag'> "),
313 ("endtag", "cdata"),
314 ])
315
Fred Drake30c48492001-09-24 20:22:09 +0000316 def test_illegal_declarations(self):
317 s = 'abc<!spacer type="block" height="25">def'
318 self.check_events(s, [
319 ("data", "abc"),
320 ("unknown decl", 'spacer type="block" height="25"'),
321 ("data", "def"),
322 ])
323
Fred Drake04d9a802002-09-25 16:29:17 +0000324 def test_enumerated_attr_type(self):
325 s = "<!DOCTYPE doc [<!ATTLIST doc attr (a | b) >]>"
326 self.check_events(s, [
327 ('decl', 'DOCTYPE doc [<!ATTLIST doc attr (a | b) >]'),
328 ])
329
Fred Drake19ff4ac2001-07-16 18:52:40 +0000330 # XXX These tests have been disabled by prefixing their names with
331 # an underscore. The first two exercise outstanding bugs in the
332 # sgmllib module, and the third exhibits questionable behavior
333 # that needs to be carefully considered before changing it.
334
335 def _test_starttag_end_boundary(self):
Fred Drake72c9eff2006-06-14 04:25:02 +0000336 self.check_events("<a b='<'>", [("starttag", "a", [("b", "<")])])
337 self.check_events("<a b='>'>", [("starttag", "a", [("b", ">")])])
Fred Drake19ff4ac2001-07-16 18:52:40 +0000338
339 def _test_buffer_artefacts(self):
340 output = [("starttag", "a", [("b", "<")])]
341 self.check_events(["<a b='<'>"], output)
342 self.check_events(["<a ", "b='<'>"], output)
343 self.check_events(["<a b", "='<'>"], output)
344 self.check_events(["<a b=", "'<'>"], output)
345 self.check_events(["<a b='<", "'>"], output)
346 self.check_events(["<a b='<'", ">"], output)
347
348 output = [("starttag", "a", [("b", ">")])]
349 self.check_events(["<a b='>'>"], output)
350 self.check_events(["<a ", "b='>'>"], output)
351 self.check_events(["<a b", "='>'>"], output)
352 self.check_events(["<a b=", "'>'>"], output)
353 self.check_events(["<a b='>", "'>"], output)
354 self.check_events(["<a b='>'", ">"], output)
355
Fred Drake75d9a622004-09-08 22:57:01 +0000356 output = [("comment", "abc")]
Fred Drake72c9eff2006-06-14 04:25:02 +0000357 self.check_events(["", "<!--abc-->"], output)
358 self.check_events(["<", "!--abc-->"], output)
359 self.check_events(["<!", "--abc-->"], output)
360 self.check_events(["<!-", "-abc-->"], output)
361 self.check_events(["<!--", "abc-->"], output)
362 self.check_events(["<!--a", "bc-->"], output)
363 self.check_events(["<!--ab", "c-->"], output)
364 self.check_events(["<!--abc", "-->"], output)
365 self.check_events(["<!--abc-", "->"], output)
366 self.check_events(["<!--abc--", ">"], output)
367 self.check_events(["<!--abc-->", ""], output)
Fred Drake75d9a622004-09-08 22:57:01 +0000368
Fred Drake19ff4ac2001-07-16 18:52:40 +0000369 def _test_starttag_junk_chars(self):
370 self.check_parse_error("<")
371 self.check_parse_error("<>")
372 self.check_parse_error("</$>")
373 self.check_parse_error("</")
374 self.check_parse_error("</a")
375 self.check_parse_error("<$")
376 self.check_parse_error("<$>")
377 self.check_parse_error("<!")
378 self.check_parse_error("<a $>")
379 self.check_parse_error("<a")
380 self.check_parse_error("<a foo='bar'")
381 self.check_parse_error("<a foo='bar")
382 self.check_parse_error("<a foo='>'")
383 self.check_parse_error("<a foo='>")
384 self.check_parse_error("<a foo=>")
385
386
Fred Drake30c48492001-09-24 20:22:09 +0000387def test_main():
388 test_support.run_unittest(SGMLParserTestCase)
389
390
391if __name__ == "__main__":
392 test_main()