OILS / frontend / match_test.py View on Github | oilshell.org

113 lines, 81 significant
1#!/usr/bin/env python2
2"""
3match_test.py: Tests for match.py
4"""
5from __future__ import print_function
6
7import unittest
8
9from _devbuild.gen.id_kind_asdl import Id, Id_str
10from mycpp.mylib import log
11from frontend import match # module under test
12
13
14def _PrintTokens(lex):
15 for id_, val in lex.Tokens():
16 log(' %s %r', Id_str(id_), val)
17 if id_ == Id.Eol_Tok:
18 break
19
20
21class MatchTest(unittest.TestCase):
22
23 def testShouldHijack(self):
24 self.assertEqual(False, match.ShouldHijack('# comment\n[line 2]'))
25 self.assertEqual(False, match.ShouldHijack('#!/usr/bin/python\n'))
26 self.assertEqual(False, match.ShouldHijack(''))
27 self.assertEqual(False, match.ShouldHijack('\n'))
28
29 self.assertEqual(True, match.ShouldHijack('#!/usr/bin/env bash\n'))
30
31 self.assertEqual(True, match.ShouldHijack('#!/bin/bash\n[line 2]'))
32 self.assertEqual(True, match.ShouldHijack('#!/bin/bash -e\n[line 2]'))
33 self.assertEqual(True, match.ShouldHijack('#!/bin/sh\n[line 2]\n'))
34 self.assertEqual(True, match.ShouldHijack('#!/bin/sh -e\n[line 2]\n'))
35
36 # Unlikely but OK
37 self.assertEqual(True, match.ShouldHijack('#!/usr/bin/env sh\n'))
38
39 # fastlex bug: should not allow \0
40 self.assertEqual(False, match.ShouldHijack('#!/usr/bin/env \0 sh\n'))
41
42 def testBraceRangeLexer(self):
43 lex = match.BraceRangeLexer('1..3')
44 _PrintTokens(lex)
45
46 def testJ8Lexer(self):
47 cases = [
48 '00',
49 '[]',
50 '[3.14, 4, true]',
51 'truez',
52 'false\t',
53 'bad',
54 ]
55
56 for s in cases:
57 log('---')
58 log('J8 CASE %r', s)
59 lex = match.SimpleLexer(match.MatchJ8Token, s)
60 _PrintTokens(lex)
61
62 def testJ8StrLexer(self):
63 cases = [
64 '"hi"',
65 # Newlines in strings are control chars, not accepted
66 '"hi\n"',
67 '"hi\\n"',
68 r'"\yff \xff \u1234 \u{123456} \\ \" "',
69
70 # This points at \ as Id.Unknown_Tok, which I suppose is OK
71 r'"\a \z \/ \b "',
72 ]
73
74 for s in cases:
75 log('---')
76 log('J8 STR CASE %r', s)
77 lex = match.SimpleLexer(match.MatchJ8StrToken, s)
78 _PrintTokens(lex)
79
80 def testLooksLike(self):
81 INTS = [
82 (False, ''),
83 (False, 'foo'),
84 (True, '3'),
85 (True, '-3'),
86 (False, '-'),
87 (False, '.'),
88 (True, '\t12 '),
89 (True, '\t-12 '),
90 (False, ' - 12 '),
91 ]
92
93 MORE_INTS = [
94 (True, ' 3_000 '),
95 ]
96
97 for expected, s in INTS + MORE_INTS:
98 self.assertEqual(expected, match.LooksLikeInteger(s))
99
100 FLOATS = [
101 (True, '3.0'),
102 (True, '-3.0'),
103 (True, '\t3.0 '),
104 (True, '\t-3.0 '),
105 (False, ' - 3.0 '),
106 ]
107
108 for expected, s in INTS + FLOATS: # Use BOTH test cases
109 self.assertEqual(expected, match.LooksLikeFloat(s), s)
110
111
112if __name__ == '__main__':
113 unittest.main()