1 | #!/usr/bin/env python2
|
2 | from __future__ import print_function
|
3 |
|
4 | import unittest
|
5 |
|
6 | from lazylex import html # module under test log = html.log
|
7 |
|
8 | log = html.log
|
9 |
|
10 | with open('lazylex/testdata.html') as f:
|
11 | TEST_HTML = f.read()
|
12 |
|
13 |
|
14 | class RegexTest(unittest.TestCase):
|
15 |
|
16 | def testDotAll(self):
|
17 | import re
|
18 |
|
19 | # Note that $ matches end of line, not end of string
|
20 | p1 = re.compile(r'.')
|
21 | print(p1.match('\n'))
|
22 |
|
23 | p2 = re.compile(r'.', re.DOTALL)
|
24 | print(p2.match('\n'))
|
25 |
|
26 | #p3 = re.compile(r'[.\n]', re.VERBOSE)
|
27 | p3 = re.compile(r'[.\n]')
|
28 | print(p3.match('\n'))
|
29 |
|
30 | print('Negation')
|
31 |
|
32 | p4 = re.compile(r'[^>]')
|
33 | print(p4.match('\n'))
|
34 |
|
35 | def testAttrRe(self):
|
36 | _ATTR_RE = html._ATTR_RE
|
37 | m = _ATTR_RE.match(' empty= val')
|
38 | print(m.groups())
|
39 |
|
40 |
|
41 | class FunctionsTest(unittest.TestCase):
|
42 |
|
43 | def testFindLineNum(self):
|
44 | s = 'foo\n' * 3
|
45 | for pos in [1, 5, 10, 50]: # out of bounds
|
46 | line_num = html.FindLineNum(s, pos)
|
47 | print(line_num)
|
48 |
|
49 | def testToText(self):
|
50 | t = html.ToText('<b name="&"> three < four && five </b>')
|
51 | self.assertEqual(' three < four && five ', t)
|
52 |
|
53 |
|
54 | def _MakeTagLexer(s):
|
55 | lex = html.TagLexer(s)
|
56 | lex.Reset(0, len(s))
|
57 | return lex
|
58 |
|
59 |
|
60 | def _PrintTokens(lex):
|
61 | log('')
|
62 | log('tag = %r', lex.TagName())
|
63 | for tok, start, end in lex.Tokens():
|
64 | log('%s %r', tok, lex.s[start:end])
|
65 |
|
66 |
|
67 | class TagLexerTest(unittest.TestCase):
|
68 |
|
69 | def testTagLexer(self):
|
70 | # Invalid!
|
71 | #lex = _MakeTagLexer('< >')
|
72 | #print(lex.Tag())
|
73 |
|
74 | lex = _MakeTagLexer('<a>')
|
75 | _PrintTokens(lex)
|
76 |
|
77 | lex = _MakeTagLexer('<a novalue>')
|
78 | _PrintTokens(lex)
|
79 |
|
80 | # Note: we could have a different HasAttr() method
|
81 | # <a novalue> means lex.Get('novalue') == ''
|
82 | # https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttribute
|
83 | self.assertEqual('', lex.GetAttrRaw('novalue'))
|
84 |
|
85 | lex = _MakeTagLexer('<a href="double quoted">')
|
86 | _PrintTokens(lex)
|
87 |
|
88 | self.assertEqual('double quoted', lex.GetAttrRaw('href'))
|
89 | self.assertEqual(None, lex.GetAttrRaw('oops'))
|
90 |
|
91 | lex = _MakeTagLexer('<a href=foo class="bar">')
|
92 | _PrintTokens(lex)
|
93 |
|
94 | lex = _MakeTagLexer('<a href=foo class="bar" />')
|
95 | _PrintTokens(lex)
|
96 |
|
97 | lex = _MakeTagLexer('<a href="?foo=1&bar=2" />')
|
98 | self.assertEqual('?foo=1&bar=2', lex.GetAttrRaw('href'))
|
99 |
|
100 | def testTagName(self):
|
101 | lex = _MakeTagLexer('<a href=foo class="bar" />')
|
102 | self.assertEqual('a', lex.TagName())
|
103 |
|
104 | def testAllAttrs(self):
|
105 | """
|
106 | [('key', 'value')] for all
|
107 | """
|
108 | # closed
|
109 | lex = _MakeTagLexer('<a href=foo class="bar" />')
|
110 | self.assertEqual([('href', 'foo'), ('class', 'bar')],
|
111 | lex.AllAttrsRaw())
|
112 |
|
113 | lex = _MakeTagLexer('<a href="?foo=1&bar=2" />')
|
114 | self.assertEqual([('href', '?foo=1&bar=2')], lex.AllAttrsRaw())
|
115 |
|
116 | def testEmptyMissingValues(self):
|
117 | # equivalent to <button disabled="">
|
118 | lex = _MakeTagLexer('<button disabled>')
|
119 | all_attrs = lex.AllAttrsRaw()
|
120 | self.assertEqual([('disabled', '')], all_attrs)
|
121 |
|
122 | slices = lex.AllAttrsRawSlice()
|
123 | log('slices %s', slices)
|
124 |
|
125 | lex = _MakeTagLexer(
|
126 | '''<p double="" single='' empty= value missing empty2=>''')
|
127 | all_attrs = lex.AllAttrsRaw()
|
128 | self.assertEqual([
|
129 | ('double', ''),
|
130 | ('single', ''),
|
131 | ('empty', 'value'),
|
132 | ('missing', ''),
|
133 | ('empty2', ''),
|
134 | ], all_attrs)
|
135 | # TODO: should have
|
136 | log('all %s', all_attrs)
|
137 |
|
138 | slices = lex.AllAttrsRawSlice()
|
139 | log('slices %s', slices)
|
140 |
|
141 | def testInvalidTag(self):
|
142 | try:
|
143 | lex = _MakeTagLexer('<a foo=bar !></a>')
|
144 | all_attrs = lex.AllAttrsRaw()
|
145 | except html.LexError as e:
|
146 | print(e)
|
147 | else:
|
148 | self.fail('Expected LexError')
|
149 |
|
150 |
|
151 | def _MakeAttrValueLexer(s):
|
152 | lex = html.AttrValueLexer(s)
|
153 | lex.Reset(0, len(s))
|
154 | return lex
|
155 |
|
156 |
|
157 | class AttrValueLexerTest(unittest.TestCase):
|
158 |
|
159 | def testGood(self):
|
160 | lex = _MakeAttrValueLexer('?foo=42&bar=99')
|
161 | n = lex.NumTokens()
|
162 | self.assertEqual(3, n)
|
163 |
|
164 |
|
165 | def Lex(h, no_special_tags=False):
|
166 | print(repr(h))
|
167 | tokens = html.ValidTokenList(h, no_special_tags=no_special_tags)
|
168 | start_pos = 0
|
169 | for tok_id, end_pos in tokens:
|
170 | frag = h[start_pos:end_pos]
|
171 | log('%d %s %r', end_pos, html.TokenName(tok_id), frag)
|
172 | start_pos = end_pos
|
173 | return tokens
|
174 |
|
175 |
|
176 | class LexerTest(unittest.TestCase):
|
177 |
|
178 | # IndexLinker in devtools/make_help.py
|
179 | # <pre> sections in doc/html_help.py
|
180 | # TocExtractor in devtools/cmark.py
|
181 |
|
182 | def testPstrip(self):
|
183 | """Remove anything like this.
|
184 |
|
185 | <p><pstrip> </pstrip></p>
|
186 | """
|
187 | pass
|
188 |
|
189 | def testCommentParse(self):
|
190 | n = len(TEST_HTML)
|
191 | tokens = Lex(TEST_HTML)
|
192 |
|
193 | def testCommentParse2(self):
|
194 |
|
195 | Tok = html.Tok
|
196 | h = '''
|
197 | hi <!-- line 1
|
198 | line 2 --><br/>'''
|
199 | tokens = Lex(h)
|
200 |
|
201 | self.assertEqual(
|
202 | [
|
203 | (Tok.RawData, 12),
|
204 | (Tok.Comment, 50), # <? err ?>
|
205 | (Tok.StartEndTag, 55),
|
206 | (Tok.EndOfStream, 55),
|
207 | ],
|
208 | tokens)
|
209 |
|
210 | def testProcessingInstruction(self):
|
211 | # <?xml ?> header
|
212 | Tok = html.Tok
|
213 | h = 'hi <? err ?>'
|
214 | tokens = Lex(h)
|
215 |
|
216 | self.assertEqual(
|
217 | [
|
218 | (Tok.RawData, 3),
|
219 | (Tok.Processing, 12), # <? err ?>
|
220 | (Tok.EndOfStream, 12),
|
221 | ],
|
222 | tokens)
|
223 |
|
224 | def testScriptStyle(self):
|
225 | Tok = html.Tok
|
226 | h = '''
|
227 | hi <script src=""> if (x < 1 && y > 2 ) { console.log(""); }
|
228 | </script>
|
229 | '''
|
230 | tokens = Lex(h)
|
231 |
|
232 | self.assertEqual(
|
233 | [
|
234 | (Tok.RawData, 12),
|
235 | (Tok.StartTag, 27), # <script>
|
236 | (Tok.HtmlCData, 78), # JavaScript code is HTML CData
|
237 | (Tok.EndTag, 87), # </script>
|
238 | (Tok.RawData, 96), # \n
|
239 | (Tok.EndOfStream, 96), # \n
|
240 | ],
|
241 | tokens)
|
242 |
|
243 | def testScriptStyleXml(self):
|
244 | Tok = html.Tok
|
245 | h = 'hi <script src=""> < </script>'
|
246 | # XML mode
|
247 | tokens = Lex(h, no_special_tags=True)
|
248 |
|
249 | self.assertEqual(
|
250 | [
|
251 | (Tok.RawData, 3),
|
252 | (Tok.StartTag, 18), # <script>
|
253 | (Tok.RawData, 19), # space
|
254 | (Tok.CharEntity, 23), # </script>
|
255 | (Tok.RawData, 24), # \n
|
256 | (Tok.EndTag, 33), # \n
|
257 | (Tok.EndOfStream, 33), # \n
|
258 | ],
|
259 | tokens)
|
260 |
|
261 | def testCData(self):
|
262 | Tok = html.Tok
|
263 |
|
264 | # from
|
265 | # /home/andy/src/languages/Python-3.11.5/Lib/test/xmltestdata/c14n-20/inC14N4.xml
|
266 | h = '<compute><![CDATA[value>"0" && value<"10" ?"valid":"error"]]></compute>'
|
267 | tokens = Lex(h)
|
268 |
|
269 | self.assertEqual([
|
270 | (Tok.StartTag, 9),
|
271 | (Tok.CData, 61),
|
272 | (Tok.EndTag, 71),
|
273 | (Tok.EndOfStream, 71),
|
274 | ], tokens)
|
275 |
|
276 | def testEntity(self):
|
277 | Tok = html.Tok
|
278 |
|
279 | # from
|
280 | # /home/andy/src/Python-3.12.4/Lib/test/xmltestdata/c14n-20/inC14N5.xml
|
281 | h = '&ent1;, &ent2;!'
|
282 |
|
283 | tokens = Lex(h)
|
284 |
|
285 | self.assertEqual([
|
286 | (Tok.CharEntity, 6),
|
287 | (Tok.RawData, 8),
|
288 | (Tok.CharEntity, 14),
|
289 | (Tok.RawData, 15),
|
290 | (Tok.EndOfStream, 15),
|
291 | ], tokens)
|
292 |
|
293 | def testStartTag(self):
|
294 | Tok = html.Tok
|
295 |
|
296 | h = '<a>hi</a>'
|
297 | tokens = Lex(h)
|
298 |
|
299 | self.assertEqual([
|
300 | (Tok.StartTag, 3),
|
301 | (Tok.RawData, 5),
|
302 | (Tok.EndTag, 9),
|
303 | (Tok.EndOfStream, 9),
|
304 | ], tokens)
|
305 |
|
306 | # Make sure we don't consume too much
|
307 | h = '<a><source>1.7</source></a>'
|
308 |
|
309 | tokens = Lex(h)
|
310 |
|
311 | self.assertEqual([
|
312 | (Tok.StartTag, 3),
|
313 | (Tok.StartTag, 11),
|
314 | (Tok.RawData, 14),
|
315 | (Tok.EndTag, 23),
|
316 | (Tok.EndTag, 27),
|
317 | (Tok.EndOfStream, 27),
|
318 | ], tokens)
|
319 |
|
320 | return
|
321 |
|
322 | h = '''
|
323 | <configuration>
|
324 | <source>1.7</source>
|
325 | </configuration>'''
|
326 |
|
327 | tokens = Lex(h)
|
328 |
|
329 | self.assertEqual([
|
330 | (Tok.RawData, 9),
|
331 | (Tok.StartTag, 24),
|
332 | (Tok.RawData, 9),
|
333 | (Tok.EndOfStream, 9),
|
334 | ], tokens)
|
335 |
|
336 | def testInvalid(self):
|
337 | Tok = html.Tok
|
338 |
|
339 | for s in INVALID_LEX:
|
340 | try:
|
341 | tokens = html.ValidTokenList(s)
|
342 | except html.LexError as e:
|
343 | print(e)
|
344 | else:
|
345 | self.fail('Expected LexError %r' % s)
|
346 |
|
347 | def testValid(self):
|
348 | for s in VALID_LEX:
|
349 | tokens = Lex(s)
|
350 | print()
|
351 |
|
352 |
|
353 | VALID_LEX = [
|
354 | '<foo>',
|
355 | '<foo x=y>',
|
356 | '<foo x="&">',
|
357 |
|
358 | # Allowed with BadAmpersand
|
359 | '<p> x & y </p>',
|
360 | ]
|
361 |
|
362 | INVALID_LEX = [
|
363 | '<a><',
|
364 | '&<',
|
365 | '&<',
|
366 | # Hm > is allowed?
|
367 | #'a > b',
|
368 | 'a < b',
|
369 | '<!-- unfinished comment',
|
370 | '<? unfinished processing',
|
371 | '</div bad=attr> <a> <b>',
|
372 |
|
373 | # not allowed, but 3 > 4 is allowed
|
374 | '<a> 3 < 4 </a>',
|
375 | ]
|
376 |
|
377 | INVALID_PARSE = [
|
378 | '<a></b>',
|
379 | '<a>', # missing closing tag
|
380 | '<meta></meta>', # this is a self-closing tag
|
381 | ]
|
382 |
|
383 | VALID_PARSE = [
|
384 | '<!DOCTYPE html>\n',
|
385 | '<!DOCTYPE>',
|
386 |
|
387 | # empty strings
|
388 | '<p x=""></p>',
|
389 | "<p x=''></p>",
|
390 |
|
391 | # allowed, but 3 < 4 is not allowed
|
392 | '<a> 3 > 4 </a>',
|
393 | # allowed, but 3 > 4 is not allowed
|
394 | '<p x="3 < 4"></p>',
|
395 | '<b><a href="foo">link</a></b>',
|
396 | '<meta><a></a>',
|
397 | # no attribute
|
398 | '<button disabled></button>',
|
399 | '<button disabled=></button>',
|
400 | '<button disabled= ></button>',
|
401 |
|
402 | # single quoted is pretty common
|
403 | "<a href='single'></a>",
|
404 |
|
405 | # Conceding to reality - I used these myself
|
406 | '<a href=ble.sh></a>',
|
407 | '<a href=foo.html></a>',
|
408 | '<foo x="&"></foo>',
|
409 |
|
410 | # caps
|
411 | '<foo></FOO>',
|
412 | '<Foo></fOO>',
|
413 |
|
414 | # capital VOID tag
|
415 | '<META><a></a>',
|
416 |
|
417 | '<script><</script>',
|
418 | '<SCRipt><</script>',
|
419 |
|
420 | # Note: Python HTMLParser.py does DYNAMIC compilation of regex with re.I
|
421 | # flag to handle this! Gah I want something faster.
|
422 | #'<script><</SCRIPT>',
|
423 |
|
424 | # TODO: Test <svg> and <math> ?
|
425 | ]
|
426 |
|
427 | VALID_XML = [
|
428 | '<meta></meta>',
|
429 | ]
|
430 |
|
431 | INVALID_TAG_LEX = [
|
432 | # not allowed, but 3 < 4 is allowed
|
433 | '<p x="3 > 4"></p>',
|
434 | # same thing
|
435 | '<a href=">"></a>',
|
436 | '<a foo=bar !></a>', # bad attr
|
437 | ]
|
438 |
|
439 |
|
440 | class ValidateTest(unittest.TestCase):
|
441 |
|
442 | def testInvalid(self):
|
443 | counters = html.Counters()
|
444 | for s in INVALID_LEX + INVALID_TAG_LEX:
|
445 | try:
|
446 | html.Validate(s, html.BALANCED_TAGS, counters)
|
447 | except html.LexError as e:
|
448 | print(e)
|
449 | else:
|
450 | self.fail('Expected LexError %r' % s)
|
451 |
|
452 | for s in INVALID_PARSE:
|
453 | try:
|
454 | html.Validate(s, html.BALANCED_TAGS, counters)
|
455 | except html.ParseError as e:
|
456 | print(e)
|
457 | else:
|
458 | self.fail('Expected ParseError')
|
459 |
|
460 | def testValid(self):
|
461 | counters = html.Counters()
|
462 | for s in VALID_PARSE:
|
463 | html.Validate(s, html.BALANCED_TAGS, counters)
|
464 | print('HTML5 %r' % s)
|
465 | print('HTML5 attrs %r' % counters.debug_attrs)
|
466 |
|
467 | def testValidXml(self):
|
468 | counters = html.Counters()
|
469 | for s in VALID_XML:
|
470 | html.Validate(s, html.BALANCED_TAGS | html.NO_SPECIAL_TAGS,
|
471 | counters)
|
472 | print('XML %r' % s)
|
473 | print('XML attrs %r' % counters.debug_attrs)
|
474 |
|
475 |
|
476 | if __name__ == '__main__':
|
477 | unittest.main()
|