-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathbuiltin.py
472 lines (413 loc) · 10 KB
/
builtin.py
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
# Copyright 2019 The go-python Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
from libtest import assertRaises
doc="abs"
assert abs(0) == 0
assert abs(-0) == 0
assert abs(0.0) == 0.0
assert abs(-0.0) == 0.0
assert abs(10) == 10
assert abs(-10) == 10
assert abs(12.3) == 12.3
assert abs(-12.3) == 12.3
assert abs(1 << 63) == 1 << 63
assert abs(-1 << 63) == 1 << 63
assert abs(-(1 << 63)) == 1 << 63
assert abs(1 << 66) == 1 << 66
assert abs(-1 << 66) == 1 << 66
assert abs(-(1 << 66)) == 1 << 66
doc="all"
assert all((0,0,0)) == False
assert all((1,1,0)) == False
assert all(["hello", "world"]) == True
assert all([]) == True
doc="any"
assert any((0,0,0)) == False
assert any((1,1,0)) == True
assert any(["hello", "world"]) == True
assert any([]) == False
doc="ascii"
assert ascii('hello world') == "'hello world'"
assert ascii('안녕 세상') == "'\\uc548\\ub155 \\uc138\\uc0c1'"
assert ascii(chr(0x10001)) == "'\\U00010001'"
assert ascii('안녕 gpython') == "'\\uc548\\ub155 gpython'"
doc="bin"
assert bin(False) == '0b0'
assert bin(True) == '0b1'
assert bin(0) == '0b0'
assert bin(1) == '0b1'
assert bin(-1) == '-0b1'
assert bin(10) == '0b1010'
assert bin(-10) == '-0b1010'
assert bin(2**32) == '0b100000000000000000000000000000000'
assert bin(2**32-1) == '0b11111111111111111111111111111111'
assert bin(-(2**32)) == '-0b100000000000000000000000000000000'
assert bin(-(2**32-1)) == '-0b11111111111111111111111111111111'
doc="chr"
assert chr(65) == "A"
assert chr(163) == "£"
assert chr(0x263A) == "☺"
doc="compile"
code = compile("pass", "<string>", "exec")
assert code is not None
# FIXME
doc="divmod"
assert divmod(34,7) == (4, 6)
doc="enumerate"
a = [3, 4, 5, 6, 7]
for idx, value in enumerate(a):
assert value == a[idx]
doc="eval"
# smoke test only - see vm/tests/builtin.py for more tests
assert eval("1+2") == 3
doc="exec"
# smoke test only - see vm/tests/builtin.py for more tests
glob = {"a":100}
assert exec("b = a+100", glob) == None
assert glob["b"] == 200
doc="getattr"
class C:
def __init__(self):
self.potato = 42
c = C()
assert getattr(c, "potato") == 42
assert getattr(c, "potato", 43) == 42
assert getattr(c, "sausage", 43) == 43
doc="globals"
a = 1
assert globals()["a"] == 1
doc="hasattr"
assert hasattr(c, "potato")
assert not hasattr(c, "sausage")
doc="len"
assert len(()) == 0
assert len((1,2,3)) == 3
assert len("hello") == 5
assert len("£☺") == 2
doc="locals"
def fn(x):
assert locals()["x"] == 1
fn(1)
def func(p):
return p[1]
doc="min"
values = (1,2,3)
v = min(values)
assert v == 1
v = min(4,5,6)
assert v == 4
v = min((), default=-1)
assert v == -1
v = min([], default=-1)
assert v == -1
v = min([], key=func, default=(1,3))
assert v == (1,3)
v = min([(1,3), (2,1)], key=func)
assert v == (2,1)
ok = False
try:
min([(1,3), (2,1)], key=3)
except TypeError:
ok = True
assert ok, "TypeError not raised"
ok = False
try:
min([])
except ValueError:
ok = True
assert ok, "ValueError not raised"
doc="max"
values = (1,2,3)
v = max(values)
assert v == 3
v = max(4,5,6)
assert v == 6
v = max((), default=-1)
assert v == -1
v = max([], default=-1)
assert v == -1
v = max([], key=func, default=(1,3))
assert v == (1,3)
v = max([(1,3), (2,1)], key=func)
assert v == (1,3)
ok = False
try:
max([(1,3), (2,1)], key=3)
except TypeError:
ok = True
assert ok, "TypeError not raised"
ok = False
try:
max([])
except ValueError:
ok = True
assert ok, "ValueError not raised"
doc="hex"
assert hex( 0)=="0x0", "hex(0)"
assert hex( 1)=="0x1", "hex(1)"
assert hex(42)=="0x2a", "hex(42)"
assert hex( -0)=="0x0", "hex(-0)"
assert hex( -1)=="-0x1", "hex(-1)"
assert hex(-42)=="-0x2a", "hex(-42)"
assert hex( 1<<64) == "0x10000000000000000", "hex(1<<64)"
assert hex(-1<<64) == "-0x10000000000000000", "hex(-1<<64)"
assert hex( 1<<128) == "0x100000000000000000000000000000000", "hex(1<<128)"
assert hex(-1<<128) == "-0x100000000000000000000000000000000", "hex(-1<<128)"
assertRaises(TypeError, hex, 10.0) ## TypeError: 'float' object cannot be interpreted as an integer
assertRaises(TypeError, hex, float(0)) ## TypeError: 'float' object cannot be interpreted as an integer
doc="isinstance"
class A:
pass
a = A()
assert isinstance(1, (str, tuple, int))
assert isinstance(a, (str, (tuple, (A, ))))
assertRaises(TypeError, isinstance, 1, (A, ), "foo")
assertRaises(TypeError, isinstance, 1, [A, "foo"])
doc="iter"
cnt = 0
def f():
global cnt
cnt += 1
return cnt
l = list(iter(f,20))
assert len(l) == 19
for idx, v in enumerate(l):
assert idx + 1 == v
words1 = ['g', 'p', 'y', 't', 'h', 'o', 'n']
words2 = list(iter(words1))
for w1, w2 in zip(words1, words2):
assert w1 == w2
ok = False
try:
iter()
except TypeError:
ok = True
finally:
assert ok, "TypeError not raised"
ok = False
try:
l = [1, 2, 3]
iter(l, 2)
except TypeError:
ok = True
finally:
assert ok, "TypeError not raised"
ok = False
try:
iter(f, 2, 3)
except TypeError:
ok = True
finally:
assert ok, "TypeError not raised"
ok = False
doc="next no default"
def gen():
yield 1
yield 2
g = gen()
assert next(g) == 1
assert next(g) == 2
ok = False
try:
next(g)
except StopIteration:
ok = True
assert ok, "StopIteration not raised"
doc="next with default"
g = gen()
assert next(g, 42) == 1
assert next(g, 42) == 2
assert next(g, 42) == 42
assert next(g, 42) == 42
doc="next no default with exception"
def gen2():
yield 1
raise ValueError("potato")
g = gen2()
assert next(g) == 1
ok = False
try:
next(g)
except ValueError:
ok = True
assert ok, "ValueError not raised"
doc="next with default and exception"
g = gen2()
assert next(g, 42) == 1
ok = False
try:
next(g)
except ValueError:
ok = True
assert ok, "ValueError not raised"
doc="oct"
assert oct(0) == '0o0'
assert oct(100) == '0o144'
assert oct(-100) == '-0o144'
assertRaises(TypeError, oct, ())
doc="ord"
assert 65 == ord("A")
assert 163 == ord("£")
assert 0x263A == ord("☺")
assert 65 == ord(b"A")
ok = False
try:
ord("AA")
except TypeError as e:
if e.args[0] != "ord() expected a character, but string of length 2 found":
raise
ok = True
assert ok, "TypeError not raised"
try:
ord(None)
except TypeError as e:
if e.args[0] != "ord() expected string of length 1, but NoneType found":
raise
ok = True
assert ok, "TypeError not raised"
doc="open"
assert open(__file__) is not None
doc="pow"
assert pow(2, 10) == 1024
assert pow(2, 10, 17) == 4
doc="repr"
assert repr(5) == "5"
assert repr("hello") == "'hello'"
doc="print"
ok = False
try:
print("hello", sep=1, end="!")
except TypeError as e:
if e.args[0] != "print() argument 1 must be str, not int":
raise
ok = True
assert ok, "TypeError not raised"
try:
print("hello", sep=",", end=1)
except TypeError as e:
if e.args[0] != "print() argument 2 must be str, not int":
raise
ok = True
assert ok, "TypeError not raised"
try:
print("hello", sep=",", end="!", file=1)
except AttributeError as e:
if e.args[0] != "'int' has no attribute 'write'":
raise
ok = True
assert ok, "AttributeError not raised"
with open("testfile", "w") as f:
print("hello", "world", end="!\n", file=f, sep=", ")
print("hells", "bells", end="...", file=f)
print(" ~", "Brother ", "Foo", "bar", file=f, end="", sep="")
with open("testfile", "r") as f:
assert f.read() == "hello, world!\nhells bells... ~Brother Foobar"
with open("testfile", "w") as f:
print(1,2,3,sep=",", flush=False, end=",\n", file=f)
print("4",5, file=f, end="!", flush=True, sep=",")
with open("testfile", "r") as f:
assert f.read() == "1,2,3,\n4,5!"
doc="round"
assert round(1.1) == 1.0
doc="setattr"
class C: pass
c = C()
assert not hasattr(c, "potato")
setattr(c, "potato", "spud")
assert getattr(c, "potato") == "spud"
assert c.potato == "spud"
delattr(c, "potato")
assert not hasattr(c, "potato")
ok = False
try:
delattr(c, "potato")
except AttributeError as e:
ok = True
finally:
assert ok
doc="sorted"
a = [3, 1.1, 1, 2]
assert sorted(a) == [1, 1.1, 2, 3]
assert sorted(sorted(a)) == [1, 1.1, 2, 3]
assert sorted(a, reverse=True) == [3, 2, 1.1, 1]
assert sorted(a, key=lambda l: l+1) == [1, 1.1, 2, 3]
s = [2.0, 2, 1, 1.0]
assert sorted(s, key=lambda l: 0) == [2.0, 2, 1, 1.0]
assert [type(t) for t in sorted(s, key=lambda l: 0)] == [float, int, int, float]
assert sorted(s) == [1, 1.0, 2.0, 2]
assert [type(t) for t in sorted(s)] == [int, float, float, int]
try:
sorted([2.0, "abc"])
except TypeError:
pass
else:
assert False
assert sorted([]) == []
assert sorted([0]) == [0]
s = [0, 1]
try:
# Sorting a list of len >= 2 with uncallable key must fail on all Python implementations.
sorted(s, key=1)
except TypeError:
pass
else:
assert False
try:
sorted(1)
except TypeError:
pass
else:
assert False
try:
sorted()
except TypeError:
pass
else:
assert False
doc="sum"
assert sum([1,2,3]) == 6
assert sum([1,2,3], 3) == 9
assert sum((1,2,3)) == 6
assert sum((1,2,3), 3) == 9
assert sum((1, 2.5, 3)) == 6.5
assert sum((1, 2.5, 3), 3) == 9.5
try:
sum([1,2,3], 'hi')
except TypeError as e:
if e.args[0] != "sum() can't sum strings [use ''.join(seq) instead]":
raise
ok = True
assert ok, "TypeError not raised"
try:
sum([1,2,3], b'hi')
except TypeError as e:
if e.args[0] != "sum() can't sum bytes [use b''.join(seq) instead]":
raise
ok = True
assert ok, "TypeError not raised"
try:
sum(['h', 'i'])
except TypeError as e:
if e.args[0] != "unsupported operand type(s) for +: 'int' and 'str'":
raise
ok = True
assert ok, "TypeError not raised"
doc="zip"
ok = False
a = [3, 4, 5, 6, 7]
b = [8, 9, 10, 11, 12]
assert [e for e in zip(a, b)] == [(3,8), (4,9), (5,10), (6,11), (7,12)]
try:
zip(1,2,3)
except TypeError as e:
if e.args[0] != "zip argument #1 must support iteration":
raise
ok = True
assert ok, "TypeError not raised"
doc="__import__"
lib = __import__("lib")
assert lib.libfn() == 42
assert lib.libvar == 43
assert lib.libclass().method() == 44
doc="finished"