tensor-sensor
113 строк · 2.5 Кб
1"""
2MIT License
3
4Copyright (c) 2021 Terence Parr
5
6Permission is hereby granted, free of charge, to any person obtaining a copy
7of this software and associated documentation files (the "Software"), to deal
8in the Software without restriction, including without limitation the rights
9to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10copies of the Software, and to permit persons to whom the Software is
11furnished to do so, subject to the following conditions:
12
13The above copyright notice and this permission notice shall be included in all
14copies or substantial portions of the Software.
15
16THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22SOFTWARE.
23"""
24from tsensor.parsing import *
25import tsensor.ast
26import sys
27import numpy as np
28
29
30def check(s,expected):
31frame = sys._getframe()
32caller = frame.f_back
33p = PyExprParser(s)
34t = p.parse()
35result = t.eval(caller)
36assert str(result)==str(expected)
37
38
39def test_int():
40check("34", 34)
41
42def test_assign():
43check("a = 34", 34)
44
45def test_var():
46a = 34
47check("a", 34)
48
49def test_member_var():
50class A:
51def __init__(self):
52self.a = 34
53x = A()
54check("x.a", 34)
55
56def test_member_func():
57class A:
58def f(self, a):
59return a+4
60x = A()
61check("x.f(30)", 34)
62
63def test_index():
64a = [1,2,3]
65check("a[2]", 3)
66
67def test_add():
68a = 3
69b = 4
70c = 5
71check("a+b+c", 12)
72
73def test_add_mul():
74a = 3
75b = 4
76c = 5
77check("a+b*c", 23)
78
79def test_pow():
80a = 3
81b = 4
82check("a**b", 3**4)
83
84def test_pow2():
85a = 3
86b = 4
87c = 5
88check("a**(b+1)**c", 3**5**5)
89
90def test_parens():
91a = 3
92b = 4
93c = 5
94check("(a+b)*c", 35)
95
96def test_list_literal():
97a = [[1,2,3],[4,5,6]]
98check("a", """[[1, 2, 3], [4, 5, 6]]""")
99
100
101def test_np_literal():
102a = np.array([[1,2,3],[4,5,6]])
103check("a*2", """[[ 2 4 6]\n [ 8 10 12]]""")
104
105
106def test_np_add():
107a = np.array([[1,2,3],[4,5,6]])
108check("a+a", """[[ 2 4 6]\n [ 8 10 12]]""")
109
110
111def test_np_add2():
112a = np.array([[1,2,3],[4,5,6]])
113check("a+a+a", """[[ 3 6 9]\n [12 15 18]]""")
114