OILS / lazylex / html_test.py View on Github | oils.pub

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