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

567 lines, 350 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
215 Tok = html.Tok
216 h = '''
217 hi <!-- line 1
218 line 2 --><br/>'''
219 tokens = Lex(h)
220
221 self.assertEqual(
222 [
223 (h8_id.RawData, 12),
224 (h8_id.Comment, 50), # <? err ?>
225 (h8_id.StartEndTag, 55),
226 (h8_id.EndOfStream, 55),
227 ],
228 tokens)
229
230 def testProcessingInstruction(self):
231 # type: () -> None
232 # <?xml ?> header
233 Tok = html.Tok
234 h = 'hi <? err ?>'
235 tokens = Lex(h)
236
237 self.assertEqual(
238 [
239 (h8_id.RawData, 3),
240 (h8_id.Processing, 12), # <? err ?>
241 (h8_id.EndOfStream, 12),
242 ],
243 tokens)
244
245 def testScriptStyle(self):
246 # type: () -> None
247 Tok = html.Tok
248 h = '''
249 hi <script src=""> if (x < 1 && y > 2 ) { console.log(""); }
250 </script>
251 '''
252 tokens = Lex(h)
253
254 expected = [
255 (h8_id.RawData, 12),
256 (h8_id.StartTag, 27), # <script>
257 (h8_id.HtmlCData, 78), # JavaScript code is HTML CData
258 (h8_id.EndTag, 87), # </script>
259 (h8_id.RawData, 96), # \n
260 (h8_id.EndOfStream, 96), # \n
261 ]
262 self.assertEqual(expected, tokens)
263
264 # Test case matching
265 tokens = Lex(h.replace('script', 'scrIPT'))
266 self.assertEqual(expected, tokens)
267
268 def testScriptStyleXml(self):
269 # type: () -> None
270 Tok = html.Tok
271 h = 'hi <script src=""> &lt; </script>'
272 # XML mode
273 tokens = Lex(h, no_special_tags=True)
274
275 self.assertEqual(
276 [
277 (h8_id.RawData, 3),
278 (h8_id.StartTag, 18), # <script>
279 (h8_id.RawData, 19), # space
280 (h8_id.CharEntity, 23), # </script>
281 (h8_id.RawData, 24), # \n
282 (h8_id.EndTag, 33), # \n
283 (h8_id.EndOfStream, 33), # \n
284 ],
285 tokens)
286
287 def testCData(self):
288 # type: () -> None
289 Tok = html.Tok
290
291 # from
292 # /home/andy/src/languages/Python-3.11.5/Lib/test/xmltestdata/c14n-20/inC14N4.xml
293 h = '<compute><![CDATA[value>"0" && value<"10" ?"valid":"error"]]></compute>'
294 tokens = Lex(h)
295
296 self.assertEqual([
297 (h8_id.StartTag, 9),
298 (h8_id.CData, 61),
299 (h8_id.EndTag, 71),
300 (h8_id.EndOfStream, 71),
301 ], tokens)
302
303 def testEntity(self):
304 # type: () -> None
305 Tok = html.Tok
306
307 # from
308 # /home/andy/src/Python-3.12.4/Lib/test/xmltestdata/c14n-20/inC14N5.xml
309 h = '&ent1;, &ent2;!'
310
311 tokens = Lex(h)
312
313 self.assertEqual([
314 (h8_id.CharEntity, 6),
315 (h8_id.RawData, 8),
316 (h8_id.CharEntity, 14),
317 (h8_id.RawData, 15),
318 (h8_id.EndOfStream, 15),
319 ], tokens)
320
321 def testStartTag(self):
322 # type: () -> None
323 Tok = html.Tok
324
325 h = '<a>hi</a>'
326 tokens = Lex(h)
327
328 self.assertEqual([
329 (h8_id.StartTag, 3),
330 (h8_id.RawData, 5),
331 (h8_id.EndTag, 9),
332 (h8_id.EndOfStream, 9),
333 ], tokens)
334
335 # Make sure we don't consume too much
336 h = '<a><source>1.7</source></a>'
337
338 tokens = Lex(h)
339
340 self.assertEqual([
341 (h8_id.StartTag, 3),
342 (h8_id.StartTag, 11),
343 (h8_id.RawData, 14),
344 (h8_id.EndTag, 23),
345 (h8_id.EndTag, 27),
346 (h8_id.EndOfStream, 27),
347 ], tokens)
348
349 return
350
351 h = '''
352 <configuration>
353 <source>1.7</source>
354 </configuration>'''
355
356 tokens = Lex(h)
357
358 self.assertEqual([
359 (h8_id.RawData, 9),
360 (h8_id.StartTag, 24),
361 (h8_id.RawData, 9),
362 (h8_id.EndOfStream, 9),
363 ], tokens)
364
365 def testBad(self):
366 # type: () -> None
367 Tok = html.Tok
368
369 h = '&'
370 tokens = Lex(h)
371
372 self.assertEqual([
373 (h8_id.BadAmpersand, 1),
374 (h8_id.EndOfStream, 1),
375 ], tokens)
376
377 h = '>'
378 tokens = Lex(h)
379
380 self.assertEqual([
381 (h8_id.BadGreaterThan, 1),
382 (h8_id.EndOfStream, 1),
383 ], tokens)
384
385 def testInvalid(self):
386 # type: () -> None
387 Tok = html.Tok
388
389 for s in INVALID_LEX:
390 try:
391 tokens = html.ValidTokenList(s)
392 except html.LexError as e:
393 print(e)
394 else:
395 self.fail('Expected LexError %r' % s)
396
397 def testValid(self):
398 # type: () -> None
399 for s, _ in VALID_LEX:
400 tokens = Lex(s)
401 print()
402
403
404INVALID_LEX = [
405 '<a><',
406 '&amp<',
407 '&<',
408 # Hm > is allowed?
409 #'a > b',
410 'a < b',
411 '<!-- unfinished comment',
412 '<? unfinished processing',
413 '</div bad=attr> <a> <b>',
414
415 # not allowed, but 3 > 4 is allowed
416 '<a> 3 < 4 </a>',
417 # Not a CDATA tag
418 '<STYLEz><</STYLEz>',
419]
420
421SKIP = 0
422UNCHANGED = 1
423
424VALID_LEX = [
425 # TODO: convert these to XML
426 ('<foo></foo>', UNCHANGED),
427 ('<foo x=y></foo>', ''),
428 #('<foo x="&"></foo>', '<foo x="&amp;"></foo>'),
429 ('<foo x="&"></foo>', ''),
430
431 # Allowed with BadAmpersand
432 ('<p> x & y </p>', '<p> x &amp; y </p>'),
433]
434
435INVALID_PARSE = [
436 '<a></b>',
437 '<a>', # missing closing tag
438 '<meta></meta>', # this is a self-closing tag
439]
440
441VALID_PARSE = [
442 ('<!DOCTYPE html>\n', ''),
443 ('<!DOCTYPE>', ''),
444
445 # empty strings
446 ('<p x=""></p>', UNCHANGED),
447 ("<p x=''></p>", UNCHANGED),
448 ('<self-closing a="b" />', UNCHANGED),
449
450 # We could also normalize CDATA?
451 # Note that CDATA has an escaping problem: you need to handle it ]]> with
452 # concatenation. It just "pushes the problem around".
453 # So I think it's better to use ONE kind of escaping, which is &lt;
454 ('<script><![CDATA[ <wtf> >< ]]></script>', UNCHANGED),
455
456 # allowed, but 3 < 4 is not allowed
457 ('<a> 3 > 4 </a>', '<a> 3 &gt; 4 </a>'),
458 # allowed, but 3 > 4 is not allowed
459 ('<p x="3 < 4"></p>', ''),
460 ('<b><a href="foo">link</a></b>', UNCHANGED),
461
462 # TODO: should be self-closing
463 #('<meta><a></a>', '<meta/><a></a>'),
464 ('<meta><a></a>', ''),
465
466 # no attribute
467 ('<button disabled></button>', ''),
468 ('<button disabled=></button>', ''),
469 ('<button disabled= ></button>', ''),
470
471 # single quoted is pretty common
472 ("<a href='single'></a>", ''),
473
474 # Conceding to reality - I used these myself
475 ('<a href=ble.sh></a>', ''),
476 ('<a href=foo.html></a>', ''),
477 ('<foo x="&"></foo>', ''),
478
479 # caps
480 ('<foo></FOO>', ''),
481 ('<Foo></fOO>', ''),
482
483 # capital VOID tag
484 ('<META><a></a>', ''),
485 ('<script><</script>', ''),
486 # matching
487 ('<SCRipt><</SCRipt>', ''),
488 ('<SCRIPT><</SCRIPT>', ''),
489 ('<STYLE><</STYLE>', ''),
490 #'<SCRipt><</script>',
491
492 # Note: Python HTMLParser.py does DYNAMIC compilation of regex with re.I
493 # flag to handle this! Gah I want something faster.
494 #'<script><</SCRIPT>',
495
496 # TODO: Test <svg> and <math> ?
497]
498
499VALID_XML = [
500 '<meta></meta>',
501]
502
503INVALID_TAG_LEX = [
504 # not allowed, but 3 < 4 is allowed
505 '<p x="3 > 4"></p>',
506 # same thing
507 '<a href=">"></a>',
508 '<a foo=bar !></a>', # bad attr
509]
510
511
512class ValidateTest(unittest.TestCase):
513
514 def testInvalid(self):
515 # type: () -> None
516 counters = html.Counters()
517 for s in INVALID_LEX + INVALID_TAG_LEX:
518 try:
519 html.Validate(s, html.BALANCED_TAGS, counters)
520 except html.LexError as e:
521 print(e)
522 else:
523 self.fail('Expected LexError %r' % s)
524
525 for s in INVALID_PARSE:
526 try:
527 html.Validate(s, html.BALANCED_TAGS, counters)
528 except html.ParseError as e:
529 print(e)
530 else:
531 self.fail('Expected ParseError')
532
533 def testValid(self):
534 # type: () -> None
535 counters = html.Counters()
536 for s, _ in VALID_PARSE:
537 html.Validate(s, html.BALANCED_TAGS, counters)
538 print('HTML5 %r' % s)
539 print('HTML5 attrs %r' % counters.debug_attrs)
540
541 def testValidXml(self):
542 # type: () -> None
543 counters = html.Counters()
544 for s in VALID_XML:
545 html.Validate(s, html.BALANCED_TAGS | html.NO_SPECIAL_TAGS,
546 counters)
547 print('XML %r' % s)
548 print('XML attrs %r' % counters.debug_attrs)
549
550
551class XmlTest(unittest.TestCase):
552
553 def testValid(self):
554 # type: () -> None
555 counters = html.Counters()
556 for h, expected_xml in VALID_LEX + VALID_PARSE:
557 actual = html.ToXml(h)
558 if expected_xml == UNCHANGED: # Unchanged
559 self.assertEqual(h, actual)
560 elif expected_xml == '': # Skip
561 pass
562 else:
563 self.assertEqual(expected_xml, actual)
564
565
566if __name__ == '__main__':
567 unittest.main()