OILS / osh / sh_expr_eval_test.py View on Github | oilshell.org

101 lines, 86 significant
1#!/usr/bin/env python2
2from __future__ import print_function
3
4import unittest
5
6from _devbuild.gen.syntax_asdl import loc
7from _devbuild.gen.id_kind_asdl import Id_str
8from core import error
9from frontend import match
10from mycpp import mops
11from osh import sh_expr_eval
12
13
14class ParsingTest(unittest.TestCase):
15
16 def testMatchFunction(self):
17 id_, pos = match.MatchShNumberToken('2#1010', 0)
18 if 0:
19 print('id = %r' % id_)
20 print('id = %r' % Id_str(id_))
21 print('pos = %r' % pos)
22
23 def checkCases(self, cases):
24 for s, expected in cases:
25 stripped = s.strip() # also done in caller
26 try:
27 ok, actual = sh_expr_eval._MaybeParseInt(stripped, loc.Missing)
28 except error.Strict:
29 ok = False
30
31 if not ok:
32 actual = None
33
34 if 0:
35 print('s %r' % s)
36 print('expected', expected and expected.i)
37 print('actual', actual and actual.i)
38 print()
39 self.assertEqual(actual, expected)
40
41 def testDecimalConst(self):
42 CASES = [
43 ('0', mops.BigInt(0)),
44 ('42042', mops.BigInt(42042)),
45 (' 2 ', mops.BigInt(2)),
46 (' 2\t', mops.BigInt(2)),
47 ('\r\n2\r\n', mops.BigInt(2)),
48 ('1F', None),
49 ('011', mops.BigInt(9)), # Parsed as an octal
50 ('1_1', None),
51 ('1 1', None),
52 ]
53 self.checkCases(CASES)
54
55 def testOctalConst(self):
56 CASES = [
57 ('0777', mops.BigInt(511)),
58 ('00012', mops.BigInt(10)),
59 (' 010\t', mops.BigInt(8)),
60 ('\n010\r\n', mops.BigInt(8)),
61 ('019', None),
62 ('0_9', None),
63 ('0 9', None),
64 ('0F0', None),
65 ]
66 self.checkCases(CASES)
67
68 def testHexConst(self):
69 CASES = [
70 ('0xFF', mops.BigInt(255)),
71 ('0xff', mops.BigInt(255)),
72 ('0x0010', mops.BigInt(16)),
73 (' 0x1A ', mops.BigInt(26)),
74 ('\t0x1A\r\n', mops.BigInt(26)),
75 ('FF', None),
76 ('0xG', None),
77 ('0x1_0', None),
78 ('0x1 0', None),
79 ('0X12', None),
80 ]
81 self.checkCases(CASES)
82
83 def testArbitraryBaseConst(self):
84 CASES = [
85 ('2#0110', mops.BigInt(6)),
86 ('8#777', mops.BigInt(511)),
87 ('16#ff', mops.BigInt(255)),
88 (' 16#ff\r ', mops.BigInt(255)),
89 ('\t16#ff\n', mops.BigInt(255)),
90 ('64#123abcABC@_', mops.BigInt(1189839476434038719)),
91 ('16#FF', None), # F != f, so F is out of range of the base
92 ('010#42', None), # Base cannot start with 0
93 ('65#1', None), # Base too large
94 ('0#1', None), # Base too small
95 ('1#1', None), # Base too small
96 ]
97 self.checkCases(CASES)
98
99
100if __name__ == '__main__':
101 unittest.main()