OILS / pyext / fastlex_test.py View on Github | oilshell.org

83 lines, 48 significant
1#!/usr/bin/env python2
2# Copyright 2016 Andy Chu. All rights reserved.
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8"""
9fastlex_test.py: Tests for fastlex
10"""
11from __future__ import print_function
12
13import unittest
14
15from mycpp.mylib import log
16from _devbuild.gen.id_kind_asdl import Id
17from _devbuild.gen.types_asdl import lex_mode_e
18
19import fastlex # module under test
20
21
22# NOTE: This is just like _MatchOshToken_Fast in frontend/match.py
23def MatchOshToken(lex_mode, line, start_pos):
24 tok_type, end_pos = fastlex.MatchOshToken(lex_mode, line, start_pos)
25 #log('tok_type = %d, id = %s', tok_type, tok_type)
26 return tok_type, end_pos
27
28
29def TokenizeLineOuter(line):
30 start_pos = 0
31 while True:
32 tok_type, end_pos = MatchOshToken(lex_mode_e.ShCommand, line, start_pos)
33 tok_val = line[start_pos:end_pos]
34 print('TOK: %s %r\n' % (tok_type, tok_val))
35 start_pos = end_pos
36
37 if tok_type == Id.Eol_Tok:
38 break
39
40
41class LexTest(unittest.TestCase):
42
43 def testMatchOshToken(self):
44 print(dir(fastlex))
45 print(MatchOshToken(lex_mode_e.Comment, 'line', 3))
46 print()
47
48 # Need to be able to pass NUL bytes for EOF.
49 line = 'end of line\n'
50 TokenizeLineOuter(line)
51 line = 'end of file\0'
52 TokenizeLineOuter(line)
53
54 def testOutOfBounds(self):
55 print(MatchOshToken(lex_mode_e.ShCommand, 'line', 3))
56 # It's an error to point to the end of the buffer! Have to be one behind
57 # it.
58 return
59 print(MatchOshToken(lex_mode_e.ShCommand, 'line', 4))
60 print(MatchOshToken(lex_mode_e.ShCommand, 'line', 5))
61
62 def testBug(self):
63 code_str = '-n'
64 expected = Id.BoolUnary_n
65
66 tok_type, end_pos = MatchOshToken(lex_mode_e.DBracket, code_str, 0)
67 print('--- %s expected, got %s' % (expected, tok_type))
68
69 self.assertEqual(expected, tok_type)
70
71 def testIsValidVarName(self):
72 self.assertEqual(True, fastlex.IsValidVarName('abc'))
73 self.assertEqual(True, fastlex.IsValidVarName('foo_bar'))
74 self.assertEqual(True, fastlex.IsValidVarName('_'))
75
76 self.assertEqual(False, fastlex.IsValidVarName(''))
77 self.assertEqual(False, fastlex.IsValidVarName('-x'))
78 self.assertEqual(False, fastlex.IsValidVarName('x-'))
79 self.assertEqual(False, fastlex.IsValidVarName('var_name-foo'))
80
81
82if __name__ == '__main__':
83 unittest.main()