Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/python-wasm
Path: blob/main/python/pylang/test/generic.py
1396 views
1
# globals: assrt, ρσ_last_exception
2
3
import traceback
4
5
6
def throw_test(code):
7
def parse():
8
PyLang.parse(code, {'filename': code}).body[0]
9
10
assrt.throws(parse, PyLang.SyntaxError)
11
12
13
# unary operators
14
assrt.equal(-(1), -1)
15
assrt.equal(-(-1), 1)
16
assrt.equal(+(+1), 1)
17
18
# arithmetic
19
assrt.equal(3**4, Math.pow(3, 4))
20
assrt.equal(100**-2, Math.pow(100, -2))
21
assrt.equal(2 * 5**2 * 3, 150)
22
assrt.equal(-2**2, -4)
23
assrt.equal((-2)**2, 4)
24
assrt.equal(pow(2, 2, 2), 0)
25
assrt.equal(100 // 3, 33)
26
assrt.equal(-100 // 3, -34)
27
a = 100
28
a //= 3
29
assrt.equal(a, 33)
30
assrt.equal(0b11, 3)
31
assrt.ok(42 / "x" is NaN)
32
assrt.ok(42 is not NaN)
33
assrt.ok(NaN is parseInt('asd', 10))
34
assrt.ok('NaN' is not 42 / 'x')
35
36
# comparisons
37
assrt.ok(3 < 5 < 7)
38
assrt.equal(-1 < 0 == 1 < 0, False)
39
40
# Empty tuple
41
assrt.deepEqual((), [])
42
43
# Conditional operators
44
assrt.equal(1 if True else 2, 1)
45
assrt.equal(1 if True else 2, 1)
46
assrt.deepEqual([x for x in ("asd" if True else "xyz") if x], 'asd'.split(''))
47
assrt.deepEqual((1, [x for x in [2] if x]), [1, [2]])
48
49
# Comprehensions
50
assrt.deepEqual([a + 1 for a in [1, 2, 3] if a > 1], [3, 4])
51
assrt.deepEqual({a + 1: a + 2 for a in [1, 2, 3] if a > 1}, {3: 4, 4: 5})
52
assrt.deepEqual({a + 1 for a in [1, 2, 3] if a > 1}, set([3, 4]))
53
assrt.deepEqual([(a + 1, 1) for a in [1, 2, 3] if a > 1], [[3, 1], [4, 1]])
54
55
# Destructuring assignment
56
a, (b, (c, d)), e = [1, [2, [3, 4]], 5]
57
assrt.deepEqual([a, b, c, d, e], [1, 2, 3, 4, 5])
58
for x, (y, z) in [[1, [2, 3]]]:
59
assrt.deepEqual([x, y, z], [1, 2, 3])
60
assrt.deepEqual([[x, y, z, w] for ((x, y), (z, w)) in [[[1, 2], [3, 4]]]],
61
[[1, 2, 3, 4]])
62
assrt.deepEqual([[x, y, z] for x, (y, z) in [[1, [2, 3]]]], [[1, 2, 3]])
63
(a, b) = [1, 2]
64
assrt.deepEqual([a, b], [1, 2])
65
(a, (b, c)) = [1, [2, 3]]
66
assrt.deepEqual([a, b, c], [1, 2, 3])
67
68
# Chained assignment
69
a = b = 11
70
assrt.deepEqual([a, b], [11, 11])
71
72
73
def inc():
74
nonlocal a
75
a += 1
76
return a
77
78
79
a = b = inc()
80
assrt.deepEqual([a, b], [12, 12])
81
a, b = c, d = 1, 2
82
assrt.deepEqual([a, b, c, d], [1, 2, 1, 2])
83
(a, b) = [c, d] = 1, 2
84
assrt.deepEqual([a, b, c, d], [1, 2, 1, 2])
85
a, (x, b) = c, d = [1, [2, 3]]
86
assrt.deepEqual([a, x, b, c, d], [1, 2, 3, 1, [2, 3]])
87
a, b = [c, d] = [e, f] = [1, 2]
88
assrt.deepEqual([a, b, c, d, e, f], [1, 2, 1, 2, 1, 2])
89
a = b, c = 1, 2
90
assrt.deepEqual([a, b, c], [[1, 2], 1, 2])
91
92
throw_test('a += b += 1')
93
throw_test('a += 1, 2 += b')
94
throw_test('a += [1, 2] += b')
95
throw_test('function = 1')
96
throw_test('def function():\n pass')
97
throw_test('class function:\n pass')
98
throw_test('while 1:\npass')
99
throw_test('def f():\n while 1:\n pass')
100
throw_test('1 1')
101
throw_test('z = x y')
102
throw_test('while a = 1: pass')
103
throw_test('while 1\n pass')
104
throw_test('for a in [1]\n pass')
105
106
# object literals
107
{
108
1: 1
109
} # Check that arbitrary indentation is allowed after : for an object literal key
110
111
# strict equality
112
assrt.ok(1 == 1) # number vs number: ok
113
assrt.ok(True == True) # boolean vs boolean: ok
114
assrt.ok(not (1 == True)) # number vs boolean: NEVER equal
115
assrt.ok(1 != True) # number vs boolean: NEVER equal
116
assrt.ok(not ("" == False)) # string vs boolean: NEVER equal
117
assrt.ok(not ("0" == 0)) # string vs integer: NEVER equal
118
assrt.ok(not ("" == 0)) # string vs integer: NEVER equal
119
assrt.ok(bool(1) == True) # boolean conversion
120
assrt.ok(bool("") == False) # boolean conversion
121
assrt.ok(r'%js 1 == true') # javascript override
122
assrt.ok(not r'%js (1 != true)') # javascript override
123
assrt.ok(
124
r'%js String("test")' == "test"
125
) # this should do string conversion rather than creating a string object
126
assrt.ok(String("test") != "test") # this should create a string object
127
128
# raw JavaScript
129
r'%js var def = {}' # ability to bypass reserved keywords in declaration
130
r'%js def'.item = 3 # ability to use reserved keywords
131
assrt.ok(r'%js def.item' == 3)
132
133
n = 5
134
135
136
def sumit():
137
s = 0
138
for i in range(n + 1):
139
s += i
140
return s
141
142
143
assrt.equal(r"""%js
144
(function() {
145
var s = 0
146
for (var i=0; i<=n; i++) {
147
s += i
148
}
149
return s
150
})()
151
""", sumit()) # shared scoping and equivalent capability
152
a = []
153
for i in range(1):
154
a[i] = 1 # noqa: undef
155
assrt.deepEqual(a, [1])
156
157
# String literals
158
a = '\u00ad'
159
assrt.equal(a.charCodeAt(0), 0xad)
160
# String literal concatenation
161
162
assrt.equal('1' '2', '12')
163
assrt.equal('1' '2' '3', '123')
164
assrt.equal(u'a', 'a')
165
assrt.equal('a' * 5, 'aaaaa')
166
assrt.ok(isinstance('a', str))
167
168
# Various bits of miscellaneous code that caused parser infinite loops and other breakage
169
throw_test('for a in b:\\n 1+1')
170
171
172
def localvars_in_comprehension():
173
return {k: i for i, k in enumerate([1, 2])}
174
175
176
assrt.deepEqual(localvars_in_comprehension(), {'1': 0, '2': 1})
177
178
# Numbers
179
assrt.equal(1e2, 100)
180
assrt.equal(-1e2, -100)
181
assrt.equal(1e+2, 100)
182
assrt.equal(1E-1, 0.1)
183
184
# Equality operators
185
186
187
class D:
188
def __init__(self, data):
189
self.data = data
190
191
def __eq__(self, other):
192
return self.data == other.data
193
194
195
assrt.ok(D(1) == D(1))
196
assrt.ok(D(2) != D(1))
197
assrt.ok(D(1) == {'data': 1})
198
assrt.ok({'data': 1} == D(1))
199
200
arr = []
201
{} == arr.append(2)
202
assrt.ok(arr.length is 1)
203
204
call_count = 0
205
206
207
def cc():
208
nonlocal call_count
209
call_count += 1
210
return [1]
211
212
213
cc()[-1]
214
assrt.equal(call_count, 1)
215
216
# Test the del operator
217
218
# JS object
219
deleteme = {1: 1}
220
assrt.ok(Object.keys(deleteme).indexOf('1') is not -1)
221
del deleteme[1]
222
assrt.ok(Object.keys(deleteme).indexOf('1') is -1)
223
224
# list
225
deleteme = [1, 2]
226
del deleteme[0]
227
assrt.equal(deleteme.length, 1)
228
assrt.deepEqual(deleteme, [2])
229
deleteme = [1, 2, 3]
230
del deleteme[::2]
231
assrt.deepEqual(deleteme, [2])
232
deleteme = [1, 2, 3]
233
del deleteme[::1]
234
assrt.equal(deleteme.length, 0)
235
deleteme = [1, 2, 3]
236
del deleteme[1:2]
237
assrt.deepEqual(deleteme, [1, 3])
238
239
# global
240
del deleteme
241
242
# python dict
243
from __python__ import dict_literals, overload_getitem
244
245
deleteme = {1: 1, 2: 2}
246
assrt.ok(1 in deleteme)
247
del deleteme[1]
248
assrt.ok(1 not in deleteme)
249
assrt.equal(len(deleteme), 1)
250
251
252
# Asserts
253
def assert0():
254
assert 0
255
256
257
assrt.throws(assert0, AssertionError)
258
259
260
def assertxdx():
261
assert 0, 'xdx'
262
263
264
assrt.throws(assertxdx, r"%js: /xdx/")
265
266
# Exceptions
267
268
269
class MyException(Exception):
270
def __init__(self, message, val):
271
Exception.__init__(self, message)
272
self.val = val
273
274
275
try:
276
raise MyException('xxx', 3)
277
except MyException as e:
278
assrt.equal(e.name, 'MyException')
279
assrt.equal(e.message, 'xxx')
280
assrt.equal(e.val, 3)
281
assrt.equal(e.toString(), 'MyException: xxx')
282
assrt.ok(r'%js e instanceof MyException')
283
assrt.ok(r'%js e instanceof Error')
284
285
try:
286
raise Error('eee')
287
except Exception:
288
# Test that we can catch JS errors and that local variables in the except block are declared
289
xxlocalvar = 1
290
assrt.equal(xxlocalvar, 1)
291
292
293
def errf():
294
raise MyException()
295
296
297
try:
298
errf()
299
except MyException as e:
300
fe = traceback.format_exception()
301
assrt.ok(str.strip(fe[-2]).startsWith('at errf'))
302
303
304
def stackf():
305
return traceback.format_stack()
306
307
308
assrt.ok(str.strip(stackf()[-1]).startsWith('at stackf'))
309
310
311
def else_without_finally(fail):
312
ans = []
313
try:
314
if fail:
315
raise Exception('a')
316
ans.push('ok')
317
except:
318
ans.append('ex')
319
else:
320
ans.append('el')
321
return ans
322
323
324
def else_with_finally(fail):
325
ans = []
326
try:
327
if fail:
328
raise Exception('a')
329
ans.push('ok')
330
except:
331
ans.push('ex')
332
else:
333
ans.push('el')
334
finally:
335
ans.push('fi')
336
return ans
337
338
339
def exc_in_else():
340
ans = []
341
try:
342
try:
343
ans.push('ok')
344
except:
345
pass
346
else:
347
raise Exception('1')
348
finally:
349
ans.push('fi')
350
except:
351
ans.push('ex')
352
return ans
353
354
355
assrt.deepEqual(else_without_finally(), ['ok', 'el'])
356
assrt.deepEqual(else_without_finally(True), ['ex'])
357
assrt.deepEqual(else_with_finally(), ['ok', 'el', 'fi'])
358
assrt.deepEqual(else_with_finally(True), ['ex', 'fi'])
359
assrt.deepEqual(exc_in_else(), ['ok', 'fi', 'ex'])
360
361
# Existential operator
362
363
assrt.ok(not gfsgs?)
364
assrt.equal(gfsgs ? 1, 1)
365
assrt.equal(gfsgs?.b, undefined)
366
assrt.equal(gfsgs?(), undefined) # noqa: undef
367
undef = undefined
368
assrt.ok(not undef?)
369
undef = None
370
assrt.ok(not undef?)
371
undef = 0
372
assrt.ok(undef?)
373
assrt.equal(undef?(), undefined)
374
assrt.equal(undef?.xxx?(), undefined)
375
assrt.equal(undef.a, undefined)
376
assrt.equal(undef[1], undefined)
377
assrt.equal(undef ? 1, 0)
378
ml = 1, '''
379
'''
380
assrt.deepEqual(ml, [1, '\n'])
381
382
# localvars in conditions
383
384
gv = 1
385
386
387
def gvtest():
388
# This only changes the local version
389
gv = 2
390
assrt.equal(gv, 2)
391
392
gvtest()
393
assrt.equal(gv, 1)
394
395
def gvtest2():
396
global gv
397
# This only changes the global version
398
gv = 2
399
400
gvtest2()
401
assrt.equal(gv, 2)
402
403
404
405
assrt.ok(1 not in [2, 3])
406
assrt.ok(1 in [1, 2])
407
assrt.ok("1" + "2" in ["12", "x"])
408
assrt.ok("1" + "2" not in ["1", "2"])
409
if "1" + "2" not in ["1", "2"]:
410
assrt.ok(1)
411
else:
412
assrt.ok(0)
413
414