4 from test
import test_support
5 sgmllib
= test_support
.import_module('sgmllib', deprecated
=True)
8 class EventCollector(sgmllib
.SGMLParser
):
12 self
.append
= self
.events
.append
13 sgmllib
.SGMLParser
.__init
__(self
)
16 # Normalize the list of events so that buffer artefacts don't
17 # separate runs of contiguous characters.
20 for event
in self
.events
:
22 if type == prevtype
== "data":
23 L
[-1] = ("data", L
[-1][1] + event
[1])
32 def unknown_starttag(self
, tag
, attrs
):
33 self
.append(("starttag", tag
, attrs
))
35 def unknown_endtag(self
, tag
):
36 self
.append(("endtag", tag
))
40 def handle_comment(self
, data
):
41 self
.append(("comment", data
))
43 def handle_charref(self
, data
):
44 self
.append(("charref", data
))
46 def handle_data(self
, data
):
47 self
.append(("data", data
))
49 def handle_decl(self
, decl
):
50 self
.append(("decl", decl
))
52 def handle_entityref(self
, data
):
53 self
.append(("entityref", data
))
55 def handle_pi(self
, data
):
56 self
.append(("pi", data
))
58 def unknown_decl(self
, decl
):
59 self
.append(("unknown decl", decl
))
62 class CDATAEventCollector(EventCollector
):
63 def start_cdata(self
, attrs
):
64 self
.append(("starttag", "cdata", attrs
))
68 class HTMLEntityCollector(EventCollector
):
70 entity_or_charref
= re
.compile('(?:&([a-zA-Z][-.a-zA-Z0-9]*)'
71 '|&#(x[0-9a-zA-Z]+|[0-9]+))(;?)')
73 def convert_charref(self
, name
):
74 self
.append(("charref", "convert", name
))
76 return EventCollector
.convert_charref(self
, name
)
78 def convert_codepoint(self
, codepoint
):
79 self
.append(("codepoint", "convert", codepoint
))
80 EventCollector
.convert_codepoint(self
, codepoint
)
82 def convert_entityref(self
, name
):
83 self
.append(("entityref", "convert", name
))
84 return EventCollector
.convert_entityref(self
, name
)
86 # These to record that they were called, then pass the call along
87 # to the default implementation so that it's actions can be
90 def handle_charref(self
, data
):
91 self
.append(("charref", data
))
92 sgmllib
.SGMLParser
.handle_charref(self
, data
)
94 def handle_entityref(self
, data
):
95 self
.append(("entityref", data
))
96 sgmllib
.SGMLParser
.handle_entityref(self
, data
)
99 class SGMLParserTestCase(unittest
.TestCase
):
101 collector
= EventCollector
103 def get_events(self
, source
):
104 parser
= self
.collector()
110 #self.events = parser.events
112 return parser
.get_events()
114 def check_events(self
, source
, expected_events
):
116 events
= self
.get_events(source
)
119 #print >>sys.stderr, pprint.pformat(self.events)
121 if events
!= expected_events
:
122 self
.fail("received events did not match expected events\n"
123 "Expected:\n" + pprint
.pformat(expected_events
) +
124 "\nReceived:\n" + pprint
.pformat(events
))
126 def check_parse_error(self
, source
):
127 parser
= EventCollector()
131 except sgmllib
.SGMLParseError
:
134 self
.fail("expected SGMLParseError for %r\nReceived:\n%s"
135 % (source
, pprint
.pformat(parser
.get_events())))
137 def test_doctype_decl_internal(self
):
139 DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01//EN'
140 SYSTEM 'http://www.w3.org/TR/html401/strict.dtd' [
141 <!ELEMENT html - O EMPTY>
143 version CDATA #IMPLIED
144 profile CDATA 'DublinCore'>
145 <!NOTATION datatype SYSTEM 'http://xml.python.org/notations/python-module'>
146 <!ENTITY myEntity 'internal parsed entity'>
147 <!ENTITY anEntity SYSTEM 'http://xml.python.org/entities/something.xml'>
148 <!ENTITY % paramEntity 'name|name|name'>
152 self
.check_events(["<!%s>" % inside
], [
156 def test_doctype_decl_external(self
):
157 inside
= "DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01//EN'"
158 self
.check_events("<!%s>" % inside
, [
162 def test_underscore_in_attrname(self
):
164 """Make sure attribute names with underscores are accepted"""
165 self
.check_events("<a has_under _under>", [
166 ("starttag", "a", [("has_under", "has_under"),
167 ("_under", "_under")]),
170 def test_underscore_in_tagname(self
):
172 """Make sure tag names with underscores are accepted"""
173 self
.check_events("<has_under></has_under>", [
174 ("starttag", "has_under", []),
175 ("endtag", "has_under"),
178 def test_quotes_in_unquoted_attrs(self
):
180 """Be sure quotes in unquoted attributes are made part of the value"""
181 self
.check_events("<a href=foo'bar\"baz>", [
182 ("starttag", "a", [("href", "foo'bar\"baz")]),
185 def test_xhtml_empty_tag(self
):
186 """Handling of XHTML-style empty start tags"""
187 self
.check_events("<br />text<i></i>", [
188 ("starttag", "br", []),
190 ("starttag", "i", []),
194 def test_processing_instruction_only(self
):
195 self
.check_events("<?processing instruction>", [
196 ("pi", "processing instruction"),
199 def test_bad_nesting(self
):
200 self
.check_events("<a><b></a></b>", [
201 ("starttag", "a", []),
202 ("starttag", "b", []),
207 def test_bare_ampersands(self
):
208 self
.check_events("this text & contains & ampersands &", [
209 ("data", "this text & contains & ampersands &"),
212 def test_bare_pointy_brackets(self
):
213 self
.check_events("this < text > contains < bare>pointy< brackets", [
214 ("data", "this < text > contains < bare>pointy< brackets"),
217 def test_attr_syntax(self
):
219 ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", "e")])
221 self
.check_events("""<a b='v' c="v" d=v e>""", output
)
222 self
.check_events("""<a b = 'v' c = "v" d = v e>""", output
)
223 self
.check_events("""<a\nb\n=\n'v'\nc\n=\n"v"\nd\n=\nv\ne>""", output
)
224 self
.check_events("""<a\tb\t=\t'v'\tc\t=\t"v"\td\t=\tv\te>""", output
)
226 def test_attr_values(self
):
227 self
.check_events("""<a b='xxx\n\txxx' c="yyy\t\nyyy" d='\txyz\n'>""",
228 [("starttag", "a", [("b", "xxx\n\txxx"),
232 self
.check_events("""<a b='' c="">""", [
233 ("starttag", "a", [("b", ""), ("c", "")]),
235 # URL construction stuff from RFC 1808:
239 url
= "http://example.com:8080/path/to/file?%s%s%s" % (
240 safe
, extra
, reserved
)
241 self
.check_events("""<e a=%s>""" % url
, [
242 ("starttag", "e", [("a", url
)]),
244 # Regression test for SF patch #669683.
245 self
.check_events("<e a=rgb(1,2,3)>", [
246 ("starttag", "e", [("a", "rgb(1,2,3)")]),
249 def test_attr_values_entities(self
):
250 """Substitution of entities and charrefs in attribute values"""
252 self
.check_events("""<a b=< c=<> d=<-> e='< '
253 f="&xxx;" g=' !' h='Ǵ'
255 j='&#42;' k='&#42;'>""",
256 [("starttag", "a", [("b", "<"),
268 def test_convert_overrides(self
):
269 # This checks that the character and entity reference
270 # conversion helpers are called at the documented times. No
271 # attempt is made to really change what the parser accepts.
273 self
.collector
= HTMLEntityCollector
274 self
.check_events(('<a title="“test”">foo</a>'
276 ('entityref', 'convert', 'ldquo'),
277 ('charref', 'convert', 'x201d'),
278 ('starttag', 'a', [('title', '“test”')]),
281 ('entityref', 'foobar'),
282 ('entityref', 'convert', 'foobar'),
284 ('charref', 'convert', '42'),
285 ('codepoint', 'convert', 42),
288 def test_attr_funky_names(self
):
289 self
.check_events("""<a a.b='v' c:d=v e-f=v>""", [
290 ("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")]),
293 def test_attr_value_ip6_url(self
):
294 # http://www.python.org/sf/853506
295 self
.check_events(("<a href='http://[1080::8:800:200C:417A]/'>"
296 "<a href=http://[1080::8:800:200C:417A]/>"), [
297 ("starttag", "a", [("href", "http://[1080::8:800:200C:417A]/")]),
298 ("starttag", "a", [("href", "http://[1080::8:800:200C:417A]/")]),
301 def test_weird_starttags(self
):
302 self
.check_events("<a<a>", [
303 ("starttag", "a", []),
304 ("starttag", "a", []),
306 self
.check_events("</a<a>", [
308 ("starttag", "a", []),
311 def test_declaration_junk_chars(self
):
312 self
.check_parse_error("<!DOCTYPE foo $ >")
314 def test_get_starttag_text(self
):
315 s
= """<foobar \n one="1"\ttwo=2 >"""
316 self
.check_events(s
, [
317 ("starttag", "foobar", [("one", "1"), ("two", "2")]),
320 def test_cdata_content(self
):
321 s
= ("<cdata> <!-- not a comment --> ¬-an-entity-ref; </cdata>"
322 "<notcdata> <!-- comment --> </notcdata>")
323 self
.collector
= CDATAEventCollector
324 self
.check_events(s
, [
325 ("starttag", "cdata", []),
326 ("data", " <!-- not a comment --> ¬-an-entity-ref; "),
328 ("starttag", "notcdata", []),
330 ("comment", " comment "),
332 ("endtag", "notcdata"),
334 s
= """<cdata> <not a='start tag'> </cdata>"""
335 self
.check_events(s
, [
336 ("starttag", "cdata", []),
337 ("data", " <not a='start tag'> "),
341 def test_illegal_declarations(self
):
342 s
= 'abc<!spacer type="block" height="25">def'
343 self
.check_events(s
, [
345 ("unknown decl", 'spacer type="block" height="25"'),
349 def test_enumerated_attr_type(self
):
350 s
= "<!DOCTYPE doc [<!ATTLIST doc attr (a | b) >]>"
351 self
.check_events(s
, [
352 ('decl', 'DOCTYPE doc [<!ATTLIST doc attr (a | b) >]'),
355 def test_read_chunks(self
):
356 # SF bug #1541697, this caused sgml parser to hang
357 # Just verify this code doesn't cause a hang.
358 CHUNK
= 1024 # increasing this to 8212 makes the problem go away
360 f
= open(test_support
.findfile('sgml_input.html'))
361 fp
= sgmllib
.SGMLParser()
365 if len(data
) != CHUNK
:
368 def test_only_decode_ascii(self
):
369 # SF bug #1651995, make sure non-ascii character references are not decoded
370 s
= '<signs exclamation="!" copyright="©" quoteleft="‘">'
371 self
.check_events(s
, [
372 ('starttag', 'signs',
373 [('exclamation', '!'), ('copyright', '©'),
374 ('quoteleft', '‘')]),
377 # XXX These tests have been disabled by prefixing their names with
378 # an underscore. The first two exercise outstanding bugs in the
379 # sgmllib module, and the third exhibits questionable behavior
380 # that needs to be carefully considered before changing it.
382 def _test_starttag_end_boundary(self
):
383 self
.check_events("<a b='<'>", [("starttag", "a", [("b", "<")])])
384 self
.check_events("<a b='>'>", [("starttag", "a", [("b", ">")])])
386 def _test_buffer_artefacts(self
):
387 output
= [("starttag", "a", [("b", "<")])]
388 self
.check_events(["<a b='<'>"], output
)
389 self
.check_events(["<a ", "b='<'>"], output
)
390 self
.check_events(["<a b", "='<'>"], output
)
391 self
.check_events(["<a b=", "'<'>"], output
)
392 self
.check_events(["<a b='<", "'>"], output
)
393 self
.check_events(["<a b='<'", ">"], output
)
395 output
= [("starttag", "a", [("b", ">")])]
396 self
.check_events(["<a b='>'>"], output
)
397 self
.check_events(["<a ", "b='>'>"], output
)
398 self
.check_events(["<a b", "='>'>"], output
)
399 self
.check_events(["<a b=", "'>'>"], output
)
400 self
.check_events(["<a b='>", "'>"], output
)
401 self
.check_events(["<a b='>'", ">"], output
)
403 output
= [("comment", "abc")]
404 self
.check_events(["", "<!--abc-->"], output
)
405 self
.check_events(["<", "!--abc-->"], output
)
406 self
.check_events(["<!", "--abc-->"], output
)
407 self
.check_events(["<!-", "-abc-->"], output
)
408 self
.check_events(["<!--", "abc-->"], output
)
409 self
.check_events(["<!--a", "bc-->"], output
)
410 self
.check_events(["<!--ab", "c-->"], output
)
411 self
.check_events(["<!--abc", "-->"], output
)
412 self
.check_events(["<!--abc-", "->"], output
)
413 self
.check_events(["<!--abc--", ">"], output
)
414 self
.check_events(["<!--abc-->", ""], output
)
416 def _test_starttag_junk_chars(self
):
417 self
.check_parse_error("<")
418 self
.check_parse_error("<>")
419 self
.check_parse_error("</$>")
420 self
.check_parse_error("</")
421 self
.check_parse_error("</a")
422 self
.check_parse_error("<$")
423 self
.check_parse_error("<$>")
424 self
.check_parse_error("<!")
425 self
.check_parse_error("<a $>")
426 self
.check_parse_error("<a")
427 self
.check_parse_error("<a foo='bar'")
428 self
.check_parse_error("<a foo='bar")
429 self
.check_parse_error("<a foo='>'")
430 self
.check_parse_error("<a foo='>")
431 self
.check_parse_error("<a foo=>")
435 test_support
.run_unittest(SGMLParserTestCase
)
438 if __name__
== "__main__":