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

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