forked from Distributive-Network/PythonMonkey
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_pythonmonkey_eval.py
More file actions
241 lines (206 loc) · 8.74 KB
/
test_pythonmonkey_eval.py
File metadata and controls
241 lines (206 loc) · 8.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import pytest
import pythonmonkey as pm
import random
from datetime import datetime, timedelta
import math
def test_passes():
assert True
def test_eval_numbers_floats():
for _ in range(10):
py_number = random.uniform(-1000000,1000000)
js_number = pm.eval(repr(py_number))
assert py_number == js_number
def test_eval_numbers_floats_nan():
jsNaN = pm.eval("NaN")
assert math.isnan(jsNaN)
def test_eval_numbers_floats_negative_zero():
jsNegZero = pm.eval("-0")
assert jsNegZero == 0
assert jsNegZero == 0.0 # expected that -0.0 == 0.0 == 0
# https://docs.python.org/3/library/math.html#math.copysign
assert math.copysign(1.0, jsNegZero) == -1.0
def test_eval_numbers_floats_inf():
jsPosInf = pm.eval("Infinity")
jsNegInf = pm.eval("-Infinity")
assert jsPosInf == float("+inf")
assert jsNegInf == float("-inf")
def test_eval_numbers_integers():
for _ in range(10):
py_number = random.randint(-1000000,1000000)
js_number = pm.eval(repr(py_number))
assert py_number == js_number
def test_eval_booleans():
py_bool = True
js_bool = pm.eval('true')
assert py_bool == js_bool
py_bool = False
js_bool = pm.eval('false')
assert py_bool == js_bool
def test_eval_dates():
MIN_YEAR = 1 # https://docs.python.org/3/library/datetime.html#datetime.MINYEAR
MAX_YEAR = 2023
start = datetime(MIN_YEAR, 1, 1, 00, 00, 00)
years = MAX_YEAR - MIN_YEAR + 1
end = start + timedelta(days=365 * years)
for _ in range(10):
py_date = start + (end - start) * random.random()
# round to milliseconds precision because the smallest unit for js Date is 1ms
py_date = py_date.replace(microsecond=min(round(py_date.microsecond, -3), 999000)) # microsecond must be in 0..999999, but it would be rounded to 1000000 if >= 999500
js_date = pm.eval(f'new Date("{py_date.isoformat()}")')
assert py_date == js_date
def test_eval_boxed_booleans():
py_bool = True
js_bool = pm.eval('new Boolean(true)')
assert py_bool == js_bool
py_bool = False
js_bool = pm.eval('new Boolean(false)')
assert py_bool == js_bool
def test_eval_boxed_numbers_floats():
for _ in range(10):
py_number = random.uniform(-1000000,1000000)
js_number = pm.eval(f'new Number({repr(py_number)})')
assert py_number == js_number
def test_eval_boxed_numbers_integers():
for _ in range(10):
py_number = random.randint(-1000000,1000000)
js_number = pm.eval(f'new Number({repr(py_number)})')
assert py_number == js_number
def test_eval_exceptions():
# should print out the correct error messages
with pytest.raises(pm.SpiderMonkeyError, match='SyntaxError: "" literal not terminated before end of script'):
pm.eval('"123')
with pytest.raises(pm.SpiderMonkeyError, match="SyntaxError: missing } in compound statement"):
pm.eval('{')
with pytest.raises(pm.SpiderMonkeyError, match="TypeError: can't convert BigInt to number"):
pm.eval('1n + 1')
with pytest.raises(pm.SpiderMonkeyError, match="ReferenceError: RANDOM_VARIABLE is not defined"):
pm.eval('RANDOM_VARIABLE')
with pytest.raises(pm.SpiderMonkeyError, match="RangeError: invalid array length"):
pm.eval('new Array(-1)')
with pytest.raises(pm.SpiderMonkeyError, match="Error: abc"):
# manually by the `throw` statement
pm.eval('throw new Error("abc")')
# ANYTHING can be thrown in JS
with pytest.raises(pm.SpiderMonkeyError, match="uncaught exception: 9007199254740993"):
pm.eval('throw 9007199254740993n') # 2**53+1
with pytest.raises(pm.SpiderMonkeyError, match="uncaught exception: null"):
pm.eval('throw null')
with pytest.raises(pm.SpiderMonkeyError, match="uncaught exception: undefined"):
pm.eval('throw undefined')
with pytest.raises(pm.SpiderMonkeyError, match="uncaught exception: something from toString"):
# (side effect) calls the `toString` method if an object is thrown
pm.eval('throw { toString() { return "something from toString" } }')
# convert JS Error object to a Python Exception object for later use (in a `raise` statement)
js_err = pm.eval("new RangeError('to be raised in Python')")
assert isinstance(js_err, BaseException)
assert isinstance(js_err, Exception)
assert type(js_err) == pm.SpiderMonkeyError
with pytest.raises(pm.SpiderMonkeyError, match="RangeError: to be raised in Python"):
raise js_err
# convert Python Exception object to a JS Error object
get_err_msg = pm.eval("(err) => err.message")
assert "Python BufferError: ttt" == get_err_msg(BufferError("ttt"))
js_rethrow = pm.eval("(err) => { throw err }")
with pytest.raises(pm.SpiderMonkeyError, match="Error: Python BaseException: 123"):
js_rethrow(BaseException("123"))
def test_eval_undefined():
x = pm.eval("undefined")
assert x == None
def test_eval_null():
x = pm.eval("null")
assert x == pm.null
def test_eval_functions():
f = pm.eval("() => { return undefined }")
assert f() == None
g = pm.eval("() => { return null}")
assert g() == pm.null
h = pm.eval("(a, b) => {return a + b}")
n = 10
for _ in range(n):
a = random.randint(-1000, 1000)
b = random.randint(-1000, 1000)
assert h(a, b) == (a + b)
for _ in range (n):
a = random.uniform(-1000.0, 1000.0)
b = random.uniform(-1000.0, 1000.0)
assert h(a, b) == (a + b)
assert math.isnan(h(float("nan"), 1))
assert math.isnan(h(float("+inf"), float("-inf")))
def test_eval_functions_latin1_string_args():
concatenate = pm.eval("(a, b) => { return a + b}")
n = 10
for i in range(n):
length1 = random.randint(0x0000, 0xFFFF)
length2 = random.randint(0x0000, 0xFFFF)
string1 = ''
string2 = ''
for j in range(length1):
codepoint = random.randint(0x00, 0xFFFF)
string1 += chr(codepoint) # add random chr in ucs2 range
for j in range(length2):
codepoint = random.randint(0x00, 0xFFFF)
string2 += chr(codepoint)
assert concatenate(string1, string2) == (string1 + string2)
def test_eval_functions_ucs2_string_args():
concatenate = pm.eval("(a, b) => { return a + b}")
n = 10
for i in range(n):
length1 = random.randint(0x0000, 0xFFFF)
length2 = random.randint(0x0000, 0xFFFF)
string1 = ''
string2 = ''
for j in range(length1):
codepoint = random.randint(0x00, 0xFF)
string1 += chr(codepoint) # add random chr in latin1 range
for j in range(length2):
codepoint = random.randint(0x00, 0xFF)
string2 += chr(codepoint)
assert concatenate(string1, string2) == (string1 + string2)
def test_eval_functions_ucs4_string_args():
concatenate = pm.eval("(a, b) => { return a + b}")
n = 10
for i in range(n):
length1 = random.randint(0x0000, 0xFFFF)
length2 = random.randint(0x0000, 0xFFFF)
string1 = ''
string2 = ''
for j in range(length1):
codepoint = random.randint(0x010000, 0x10FFFF)
string1 += chr(codepoint) # add random chr outside BMP
for j in range(length2):
codepoint = random.randint(0x010000, 0x10FFFF)
string2 += chr(codepoint)
assert pm.asUCS4(concatenate(string1, string2)) == (string1 + string2)
def test_eval_functions_roundtrip():
# BF-60 https://github.com/Distributive-Network/PythonMonkey/pull/18
def ident(x):
return x
js_fn_back = pm.eval("(py_fn) => py_fn(()=>{ return 'YYZ' })")(ident)
# pm.collect() # TODO: to be fixed in BF-59
assert "YYZ" == js_fn_back()
def test_eval_functions_pyfunctions_ints():
caller = pm.eval("(func, param1, param2) => { return func(param1, param2) }")
def add(a, b):
return a + b
n = 10
for i in range(n):
int1 = random.randint(0x0000, 0xFFFF)
int2 = random.randint(0x0000, 0xFFFF)
assert caller(add, int1, int2) == int1 + int2
def test_eval_functions_pyfunctions_strs():
caller = pm.eval("(func, param1, param2) => { return func(param1, param2) }")
def concatenate(a, b):
return a + b
n = 10
for i in range(n):
length1 = random.randint(0x0000, 0xFFFF)
length2 = random.randint(0x0000, 0xFFFF)
string1 = ''
string2 = ''
for j in range(length1):
codepoint = random.randint(0x0000, 0xFFFF)
string1 += chr(codepoint) # add random chr
for j in range(length2):
codepoint = random.randint(0x0000, 0xFFFF)
string2 += chr(codepoint)
assert caller(concatenate, string1, string2) == string1 + string2