-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathlang-test.lisp
More file actions
1743 lines (1627 loc) · 39.3 KB
/
Copy pathlang-test.lisp
File metadata and controls
1743 lines (1627 loc) · 39.3 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
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CLPYTHON.TEST; Readtable: PY-USER-READTABLE -*-
;;
;; This software is Copyright (c) Franz Inc. and Willem Broekema.
;; Franz Inc. and Willem Broekema grant you the rights to
;; distribute and use this software as governed by the terms
;; of the Lisp Lesser GNU Public License
;; (http://opensource.franz.com/preamble.html),
;; known as the LLGPL.
;;;; Python language semantics test
(in-package :clpython.test)
(in-syntax *ast-user-readtable*)
(defun run-lang-test ()
(with-subtest (:name "CLPython-Lang")
(dolist (node '(:assert-stmt :assign-stmt :attributeref-expr :augassign-stmt
:backticks-expr :binary-expr :binary-lazy-expr :break-stmt
:call-expr :classdef-stmt :comparison-expr :continue-stmt
:del-stmt :dict-expr :exec-stmt :for-in-stmt :funcdef-stmt
:generator-expr :global-stmt :identifier-expr :if-expr :if-stmt
:import-stmt :import-from-stmt :lambda-expr :listcompr-expr
:list-expr :module-stmt :print-stmt :return-stmt :slice-expr
:subscription-expr :suite-stmt :return-stmt :raise-stmt
:try-except-stmt :try-finally-stmt :tuple-expr :unary-expr
:while-stmt :with-stmt :yield-expr :yield-stmt
:attribute-semantics :number-method-lookups :getitem-methods))
(test-lang node))))
(defmacro with-all-compiler-variants-tried (&body body)
(let ((g1 (gensym))
(g2 (gensym)))
`(dolist (,g1 (clpython.util::all-use-environment-accessor-values))
(dolist (,g2 '(t nil))
(let ((clpython.util::*use-environment-acccessors* ,g1)
(clpython:*compile-python-ast-before-running* ,g2))
,@body)))))
(defmacro run-error (string condtype &rest options)
`(with-all-compiler-variants-tried
(test-error (run ,string) :condition-type ',condtype ,@options)))
(defmacro run-no-error (string &rest options)
`(with-all-compiler-variants-tried
(test-no-error (run ,string) ,@options)))
(defmacro run-test (val string &rest options)
`(with-all-compiler-variants-tried
(test ,val (run ,string) ,@options)))
(defgeneric test-lang (kind))
(defmethod test-lang :around (kind)
(with-subtest (:name (format nil "CLPython-Lang-~A" kind))
(assert (next-method-p))
(call-next-method)))
(defmethod test-lang ((kind (eql :assert-stmt)))
(declare (ignorable kind))
(run-error "assert 0" {AssertionError} )
(run-no-error "assert 1")
(run-error "assert \"\"" {AssertionError})
(run-no-error "assert \"s\"")
(run-error "assert []" {AssertionError})
(run-no-error "assert [1,2]")
(run-no-error "assert True")
(run-error "assert not True" {AssertionError})
(run-no-error "assert not not True")
(run-no-error "assert not False")
(run-no-error "assert 1 < 2")
(run-no-error "assert not 1 > 2")
(multiple-value-bind (x err)
(ignore-errors (run "assert 0, 'abc'"))
(test-false x)
(test-true err)
(test-true (string= (pop (exception-args err)) "abc")
:fail-info (format nil "~A = ~A" 'clpython:*exceptions-are-python-objects*
clpython:*exceptions-are-python-objects*))))
(defmethod test-lang ((kind (eql :assign-stmt)))
(declare (ignorable kind))
(run-test 3 "a = 3; a")
(run-test 3 "a, = 3,; a")
(run-test 3 "[a] = [3]; a")
(run-test 3 "(a,) = (3,); a")
(run-test 3 "a,b = 3,4; a")
(run-test 3 "a,b = [3,4]; a")
(run-error "a,b = 3" {TypeError} :fail-info "Iteration over non-sequence.")
(run-error "a,b = 3,4,5" {ValueError})
(run-error "a,b = [3,4,5]" {ValueError})
(run-no-error "def f(): pass")
(run-no-error "
g = 3
def f():
global g
g = 2
f()
assert g == 2"))
(defmethod test-lang ((kind (eql :attributeref-expr)))
(declare (ignorable kind))
(run-no-error "class C: pass
x = C()
C.a = 3
assert (x.a == 3)
x.a = 4
assert (x.a == 4)
del x.a
assert (x.a == 3)
del C.a
assert not hasattr(C, 'a')"))
(defmethod test-lang ((kind (eql :augassign-stmt)))
(declare (ignorable kind))
(run-no-error "x = 3; x+= 2; assert x == 5")
(run-no-error "x = 3; x*= 2; assert x == 6")
(run-no-error "x = [1,2]; x[1] -= 2; assert x[1] == 0")
(run-error "x,y += 3" {SyntaxError})
(run-no-error "x = 3; x **= 3; assert x == 27"))
(defmethod test-lang ((kind (eql :backticks-expr)))
(declare (ignorable kind))
(run-no-error "x = `3`; assert x == '3'")
(run-no-error "x = `(1,3)`; assert x == '(1, 3)'")
(run-no-error "
class C:
def __repr__(self): return 'r'
def __str__(self): return 'str'
x = C()
assert `x` == 'r'"))
(defmethod test-lang ((kind (eql :binary-expr)))
(declare (ignorable kind))
(run-no-error "assert 1 + 2 == 3")
(run-no-error "assert 1 - 2 * 3 == -5")
(run-no-error "assert 1 ^ 3 == 2")
(run-no-error "assert 1 | 2 == 3")
(run-no-error "assert 4 * 'ax' == 'axaxaxax'")
(run-no-error "assert -4 * 'ax' == ''")
(run-no-error "
# https://codespeak.net/issue/pypy-dev/issue412
class Base(object):
'''analogous to sympy.core.basic.Basic'''
def __init__(self, value):
self.value = value
def __mul__(self, other):
return self.value * other.value
def __rmul__(self, other):
return other.value * self.value
class Doubler(Base):
'''analogous to sympy.core.numbers.Rational'''
def __mul__(self, other):
return 2 * (self.value * other.value)
class AnotherDoubler(Doubler):
'''analogous to sympy.core.numbers.Half'''
a = Doubler(2)
b = AnotherDoubler(3)
assert a * b == 12"
:fail-info "Wrong lookup logic for __r...__ methods"
)
(run-no-error "(1,2,3) * 2 == (1,2,3,1,2,3)"))
(defmethod test-lang ((kind (eql :binary-lazy-expr)))
(declare (ignorable kind))
(run-no-error "assert not (0 or 0)")
(run-no-error "assert not (0 and 0)")
(run-no-error "1 or 3 / 0")
(run-no-error "0 and 3/0")
(run-no-error "assert ([] or '') == ''")
(run-no-error "assert (1 or '') == 1")
(run-no-error "assert ('' or 1) == 1")
(run-no-error "assert (1 or 2) == 1")
(run-no-error "assert (1 and 2) == 2")
(run-no-error "assert (0 and 2) == 0")
(run-no-error "assert (1 and []) == []"))
(defmethod test-lang ((kind (eql :break-stmt)))
(declare (ignorable kind))
(run-error "break" {SyntaxError})
(run-no-error "
for i in [1,2]:
break
assert i == 1"))
(defmethod test-lang ((kind (eql :call-expr)))
(declare (ignorable kind))
(run-no-error "def f(x,y,z=3,*arg,**kw): return x,y,z,arg,kw
assert (1,2,3,(),{}) == f(1,2)")
(run-no-error "
class C:
def __call__(self, *args):
return args
x = C()
x(1,2,3) == (1,2,3)"))
(defmethod test-lang ((kind (eql :classdef-stmt)))
(declare (ignorable kind))
(run-no-error "
class C:
def m(self): return 'C.m'
assert C().m() == 'C.m'
assert C.__mro__ == (C, object)")
(run-no-error "
class C: pass
class D(C): pass
assert D.__mro__ == (D, C, object)")
(run-no-error "
class C:
x = 3 # this variable X can not be closed over by methods
def g(self):
return x # so this should give an error
try:
print C().g()
assert False
except NameError:
'ok'
")
(run-no-error "
def f():
class C:
x = 3 # this variable X can not be closed over by methods
def g(self):
return x # so this should give an error
return C().g
try:
print f()()
assert False
except NameError:
'ok'
")
(run-no-error "
class M(type): pass
class C:
__metaclass__ = M
assert type.__class__ == type
assert M.__class__ == type
assert M.__class__.__class__ == type
assert C.__class__ == M")
(let ((clpython::*mro-filter-implementation-classes* t))
(run-no-error "
class C(int):
pass
x = C()
assert x.__class__ == C
assert C.__class__ == type
assert C.__mro__ == (C, int, object)"))
(run-no-error "
class C( type(1+2)): pass
assert C() == 0")
(run-no-error "
x = []
class Meta(type):
def __init__(cls,*args,**kw):
Meta ## check no name error
x.append(cls)
type.__init__(cls, *args, **kw)
class C():
__metaclass__ = Meta
assert len(x) == 1
assert x[0] == C")
(run-no-error "
class C:
a = 3
assert locals()['a'] == 3")
(run-no-error "
class C:
def __init__(self):
self.__a = 3
x = C()
assert x._C__a == 3
try:
x.__a
assert False
except:
pass")
(run-no-error "
class C:
__b = 4
x = C()
assert x._C__b == 4
try:
x.__b
assert False
except:
pass")
(run-no-error "
class C:
def __init__(self):
self.__dict__['a'] = 3
x = C()
assert x.a == 3"))
(defmethod test-lang ((kind (eql :comparison-expr)))
(declare (ignorable kind))
;; Ensure py-list.__eq__ can handle non-lists, etc.
(run-no-error "assert [] != ()")
(run-no-error "assert () != []")
(run-no-error "assert [] == []")
(run-no-error "assert [] != {}")
(run-no-error "assert {} != []")
(run-no-error "assert [] != None")
(run-no-error "assert '' != None")
(run-no-error "assert [] != 3")
(run-no-error "assert 3 != None")
(run-no-error "assert (1 < 2 < 3)")
(run-no-error "assert 1 < 2 < 3")
(run-no-error "assert (3 > 2 > 1)")
(run-no-error "assert 3 >=3 > 2 > 1 < 2 <= 2 < 3 > 2 >= 1")
(run-no-error "
for x in range(5):
for y in range(5):
for z in range(5):
assert (x == y == z) == ((x == y) and (y == z)) == (x == y and y == z)
assert (x <= y <= z) == ((x <= y) and (y <= z)) == (x <= y and y <= z)
assert (x < y > z) == ((x < y) and (y > z)) == (x < y and y > z)")
(run-no-error "
for x in range(5):
for y in range(5):
for z in range(5):
if x < y:
assert ((x < y) < z) == (1 < z)
else:
assert ((x < y) < z) == (0 < z)")
(run-no-error "
le = 0
class C:
def __le__(self, other):
global le
le += 1
return []
x, y = C(), C()
assert (x <= y) == []
assert le > 0" :known-failure t :fail-info "<= should use __le__, not __cmp__."))
(defmethod test-lang ((kind (eql :continue-stmt)))
(declare (ignorable kind))
(run-error "break" {SyntaxError})
(run-no-error "for i in []: continue")
(run-no-error "
for i in [1]: continue
assert i == 1")
(run-no-error "
for i in [1,2,3]:
continue
1 / 0")
(run-no-error "
sum = 0
for i in [0,1,2,3]:
if i == 0:
continue
sum += i
continue
i / 0
assert sum == 1 + 2 + 3
assert i == 3"))
(defmethod test-lang ((kind (eql :del-stmt)))
(declare (ignorable kind))
(run-error "del x" {NameError})
(run-no-error "x = 3; del x")
(run-error "x = 3; del x; x" {NameError})
(run-no-error "x,y,z = 3,4,5; del x,y; z")
(run-error "x,y,z = 3,4,5; del x,y; y" {NameError})
(run-no-error "
x,y,z = 3,4,5
del x,y,z
try:
z
assert False
except NameError:
pass")
(run-no-error "
def f():
global x,y,z
del x,y,z" :fail-info "Should not warn about unused local vars.")
(run-no-error "
x = [1,2,3,4,5]
del x[-2:]
assert x == [1,2,3]
")
(run-no-error "
x = range(10)
del x[1:8:2]
assert x == [0, 2, 4, 6, 8, 9]")
(run-no-error "
x = range(10)
del x[-1:-6:-2]
assert x == [0, 1, 2, 3, 4, 6, 8]"))
(defmethod test-lang ((kind (eql :dict-expr)))
(declare (ignorable kind))
(run-no-error "{}")
(run-no-error "{1: 3}")
(run-no-error "{1+2: 3+4}")
(run-no-error "assert {1: 3}[1] == 3")
(run-no-error "assert {1: 3, 2: 4}[1] == 3")
(run-no-error "{} == {}")
(run-no-error "{'a': 1, 'b': 2} == {'b': 2, 'a': 1}")
(run-no-error "
d = {}
d[3] = 1
assert d[3] == 1
del d[3]
assert d == {}
d[3] = 2
assert d[3] == 2")
(run-no-error "
# make sure user-defined subclasses of string work okay as key
class C(str): pass
x = C('a')
d = {}
d[x] = 3
assert d['a'] == 3
y = C('b')
assert d.get(y) == None
d[y] = 42
assert d[y] == 42
assert d['b'] == 42")
(run-no-error "assert {None: 3}[None] == 3"))
(defmethod test-lang ((kind (eql :exec-stmt)))
(declare (ignorable kind))
(run-no-error "
def f():
x = (1,2)
exec 'print x'" :fail-info "Make sure tuple `(1 2) is quoted in code generated for `exec'")
(run-no-error "exec 'assert x == 3' in {'x': 3}")
(run-no-error "
glo = {'x': 3}
loc = {'x': 4}
exec 'assert x == 4' in glo, loc" :fail-info "Locals higher priority than globals.")
(run-no-error "
exec \"
try:
1/0
assert 0
except ZeroDivisionError:
'ok'\"")
(run-no-error "
x = 3
exec 'assert x == 3'")
(run-no-error "
x = 3
def f():
x = 4
exec 'assert x == 4'
f()")
(run-no-error "
x = 3
def f():
x = 4
def g():
exec 'assert x == 3'
g()
f()")
(run-no-error "# http://mail.python.org/pipermail/python-dev/2008-October/082951.html
class C:
a = 3
assert locals().has_key('a')
exec 'b = 4'
assert locals().has_key('b')
assert C.a == 3
assert C.b == 4")
(run-no-error "
exec 'def f(): return 3'
assert f() == 3")
(run-no-error "# not quite exec-stmt, but implementation of eval is much the same
a = eval('2+3')
assert a == 5"))
(defmethod test-lang ((kind (eql :for-in-stmt)))
(declare (ignorable kind))
(run-no-error "for i in []: 1/0")
(run-no-error "for i in '': 1/0")
(run-no-error "
for k in {1: 3}:
x = k
assert k == 1")
(run-no-error "
for x in []:
pass
else:
x = 3
assert x == 3")
(run-no-error "
for x in [1]:
break
else:
x = 3
assert x == 1")
(run-no-error "
def f():
for x in [1]:
break
else:
x = 3
assert x == 1
yield x
g = f()
assert g.next() == 1")
(run-no-error "
def f():
for x in []:
pass
else:
x = 3
yield x
g = f()
assert g.next() == 3")
(run-no-error "
def f():
yield 1
yield 2
raise StopIteration('stop')
res = [x for x in f()]
assert res == [1,2]"))
(defmethod test-lang ((kind (eql :funcdef-stmt)))
(declare (ignorable kind))
;; *-arg, **-arg
(run-no-error "
def f(a, b, c=13, d=14, *e, **f): return [a,b,c,d,e,f]
x = f(1,2,3,4,5,6)
assert x == [1,2,3,4,(5,6),{}], 'x = %s' % x"
)
(run-no-error "
def f(a, b, c=13, d=14, *e, **f): return [a,b,c,d,e,f]
x = f(a=1,b=2,c=3,d=4,e=5,f=6)
assert x == [1,2,3,4,(),{'e': 5, 'f': 6}], 'x = %s' % x"
)
(run-no-error "
def f(): return f
f()
assert f() == f")
(run-no-error "
def f((x,y)=[1,2]): return x+y
assert f() == 3
assert f((1,2)) == 3
x = (1,2)
assert f(x) == 3")
(run-no-error "
def f(x, **kw): return x, kw
assert f(1,a=3) == (1, {'a': 3})")
;; todo: check evaluation order of decorators vs. keyword argument default values.
(run-no-error "
def f():
pass
f.__name__ = 'g'
assert f.__name__ == 'g'"))
(defmethod test-lang ((kind (eql :generator-expr)))
(declare (ignorable kind))
)
(defmethod test-lang ((kind (eql :global-stmt)))
(declare (ignorable kind))
(test-some-warning (run "global x")) ;; useless at toplevel
(run-error "
def f():
x = 3
global x" {SyntaxError}) ;; global decl must be before first usage
(run-error "def f(x): global x" {SyntaxError})
(run-no-error "
def f(y):
global x
x = y
f(3)
assert x == 3")
(run-no-error "
def f():
global x
def g(y):
x = y
return g
f()(4)
assert x == 4" :fail-info "Global decl is also valid for nested functions")
(test-some-warning (run "
global y # bogus declaration; check it does not leak into f
def f(a):
y = a
f(3)
try:
print y
assert False
except NameError:
pass"
))
(run-no-error "
def f():
x = 'fl'
class C:
global x # does not hold for method m
y = x
def m(self):
return x
return C().m()
x = 'gl'
assert f() == 'fl'" :fail-info "`global' in a class def must not leak into the methods within")
(run-no-error "
a = 'global'
def f():
a = 'af'
def g():
global a
def h():
assert a == 'global'
return h()
return g()
f()")
(run-no-error "
x = 0
def f():
x = 'local'
def g():
global x
print x
x += 1
g()
f()
assert x == 1"))
(defmethod test-lang ((kind (eql :identifier-expr)))
(declare (ignorable kind))
(run-no-error "
def f():
x = 3
class C:
assert x == 3")
(run-no-error "
def f():
x = 1
def g():
y = 2
def h():
return (x,y)
return h
return g
assert f()()() == (1,2)")
(run-no-error "
ok = ''
class C:
x = 1
class D:
y = 2
class E:
global ok
try:
x
except NameError:
ok += 'x'
try:
y
except NameError:
ok += 'y'
assert ok == 'xy'"))
(defmethod test-lang ((kind (eql :if-expr)))
(declare (ignorable kind))
(run-no-error "x = (1 if True else 0); assert x == 1")
(run-no-error "x = 1 if True else 0; assert x == 1")
(run-no-error "x = 1 if False else 0; assert x == 0")
(progn
;; Grammar test cases from PEP http://www.python.org/dev/peps/pep-0308/.
(run-no-error "
[a, b] = [f for f in (1, lambda x: x if x >= 0 else -1)]
assert a == 1
assert b(1) == 1
assert b(-2) == -1")
(run-no-error "
[a, b] = [f for f in 1, lambda x: (x if x >= 0 else -1)]
assert a == 1
assert b(1) == 1
assert b(-2) == -1")
(run-no-error "
[a, b] = [f for f in 1, (lambda x: x if x >= 0 else -1)]
assert a == 1
assert b(1) == 1
assert b(-2) == -1")
(run-error "[f for f in 1, lambda x: x if x >= 0 else -1]" {SyntaxError})))
(defmethod test-lang ((kind (eql :if-stmt)))
(declare (ignorable kind))
(run-no-error "def f(): pass
if f(): pass" :fail-info "Functions inherit __nonzero__ from object."))
(defmethod test-lang ((kind (eql :import-stmt)))
(declare (ignorable kind))
#.(progn (unless (string= (pathname-name (or *compile-file-truename*
*load-truename*))
"lang-test")
(error "Compile file lang-test.lisp using compile-file (or asdf), not using temp file, ~
otherwise import paths are incorrect: ~A." *compile-file-truename*))
nil)
(let* ((new-dir #.(directory-namestring (clpython.util:derive-pathname
(or *compile-file-truename* *load-truename*)
:type nil :name nil)))
(prefix (concatenate 'string "
import sys
sys.path.append('" (coerce (loop for c across new-dir if (char= c #\\) collect #\\ and collect #\\ else collect c) 'string) "data')" (string #\Newline))))
(format t "prefix: ~S~%" prefix)
(clpython::%reset-import-state)
(run-no-error "import sys
assert sys" :fail-info "Should work in both ANSI and Modern mode.")
(clpython::%reset-import-state)
;; run compilation outside run-no-error, to prevent allegro style warning from failing the test
#+ecl
(test-true nil :known-failure t :fail-info "ECL: reload() tests skipped due to segmentation fault")
#-ecl
(progn
(clpython:run (concatenate 'string prefix "
print 'import'
import bar
assert bar.i
print 'reload'
reload(bar)
print 'del bar.i'
del bar.i"))
(clpython::%reset-import-state)
;; When importing a module, the conditions of type clpython::module-import-pre
;; make run-no-error fail. Therefore rely on statements returning nil (?!) by using test-false.
(test-true (prog1 t
(run `,(concatenate 'string prefix "
import bar
for i in xrange(3):
print 'bar.i=', bar.i, 'i=', i
assert bar.i == i+1
reload(bar)"))))
(clpython::%reset-import-state)
;; run outside run-no-error
(clpython:run (concatenate 'string prefix "
print '4a'
import zut.bla
print '4b'"))
(clpython::%reset-import-state)
(test-true (prog1 t
(run `,(concatenate 'string prefix "
print '5a'
for i in xrange(3):
import zut.bla
assert zut.bla.x
print '5b'")))))))
(defmethod test-lang ((kind (eql :import-from-stmt)))
(declare (ignorable kind))
(run-no-error "from sys import path; path.append('/foo'); del path[-1]"))
(defmethod test-lang ((kind (eql :lambda-expr)))
(declare (ignorable kind))
(run-no-error "lambda: None")
(run-no-error "lambda: 3*x")
(run-error "(lambda: 3*x)()" {NameError})
(run-no-error "assert (lambda x: x)(0) == 0")
(run-no-error "
f = lambda x, y=3: x+y
assert f(1) == 4
assert f(1,2) == 3")
(run-no-error "
f = lambda x, y=lambda: 42: x + y()
assert f(1) == 1 + 42")
(run-no-error "
f = lambda x, y=lambda: 42: x + y()
assert f(1, lambda: 2) == 1 + 2")
(run-no-error "assert (lambda x, y: x+y)(x=3, y=4) == 7")
(run-no-error "print (lambda:42).func_globals" :known-failure t))
(defmethod test-lang ((kind (eql :listcompr-expr)))
(declare (ignorable kind))
(run-no-error "assert [x for x in [1,2] if x > 1] == [2]")
(run-no-error "assert [(x,y) for x in [1,2] for y in [x]] == [(1,1), (2,2)]"))
(defmethod test-lang ((kind (eql :list-expr)))
(declare (ignorable kind))
(run-no-error "
x = []
y = x
x += [2,3]
assert x == [2,3]
assert y == [2,3]")
(run-no-error "
x = []
x += '12'
assert x == ['1', '2']"))
(defmethod test-lang ((kind (eql :module-stmt)))
(declare (ignorable kind))
)
(defmethod test-lang ((kind (eql :print-stmt)))
(declare (ignorable kind))
)
(defmethod test-lang ((kind (eql :return-stmt)))
(declare (ignorable kind))
(run-error "
def f():
class C:
return
f()" {SyntaxError} :fail-info "return outside function"))
(defmethod test-lang ((kind (eql :slice-expr)))
(declare (ignorable kind))
(run-no-error "
x = range(10)
x[1:10:2] = [0,0,0,0,0]
assert x == [0, 0, 2, 0, 4, 0, 6, 0, 8, 0]")
(run-no-error "
x = range(10)
x[1:3] = []
assert x == [0, 3, 4, 5, 6, 7, 8, 9]")
(run-no-error "
x = [1,2]
x[:0] = 'abc'
assert x == ['a', 'b', 'c', 1, 2]"))
(defmethod test-lang ((kind (eql :subscription-expr)))
(declare (ignorable kind)))
(defmethod test-lang ((kind (eql :suite-stmt)))
(declare (ignorable kind)))
(defmethod test-lang ((kind (eql :raise-stmt)))
(declare (ignorable kind)))
(defmethod test-lang ((kind (eql :try-except-stmt)))
(declare (ignorable kind)))
(defmethod test-lang ((kind (eql :try-finally-stmt)))
(declare (ignorable kind))
(progn
;; These two test cases taken from Mike Stall,
;; http://blogs.msdn.com/jmstall/archive/2007/12/16/return-vs-finally-2.aspx
(run-no-error "
def f1():
try:
return 10
finally:
return 5
assert f1() == 5")
(run-no-error "
def f2():
try:
raise Exception # like 'throw'
finally:
return 5
assert f2() == 5")))
(defmethod test-lang ((kind (eql :tuple-expr)))
(declare (ignorable kind))
(run-no-error "assert (1,2,3)[0:1] == (1,)"))
(defmethod test-lang ((kind (eql :unary-expr)))
(declare (ignorable kind))
(run-no-error "x = 3; +x; -x")
(run-no-error "assert +3 == 3")
(run-no-error "x = 3; assert +x == 3")
(run-no-error "x = 3; assert -x == -3")
(run-no-error "x = 3; assert ++x == 3")
(run-no-error "x = 3; assert --x == 3")
)
(defmethod test-lang ((kind (eql :while-stmt)))
(declare (ignorable kind))
(run-no-error "while 0: 1/0")
(run-no-error "while 1: break")
(run-no-error "
x = 3
while x > 0:
x -= 1
if x == 1:
break
assert x == 1"
)
(run-no-error "
x = 3
while x > 0:
x -= 1
if x == 1:
break
else:
x = 42
assert x == 1"
)
(run-no-error "
x = 3
while x > 0:
x -= 1
else:
x = 42
assert x == 42"
)
(run-no-error "
def f():
x = 3
while x > 0:
x -= 1
else:
x = 42
assert x == 42
f()")
(run-no-error "
def f():
x = 3
while x > 0:
x -= 1
else:
x = 42
assert x == 42
yield 42
g = f()
assert g.next() == 42"))
(defmethod test-lang ((kind (eql :with-stmt)))
(declare (ignorable kind))
(run-no-error "
x = []
class C:
def __enter__(self):
x.append('enter')
return 42
def __exit__(self, _x,_y,_z):
x.append('exit')
with C() as y:
x.append(y)
assert x == ['enter', 42, 'exit']")
(run-error "
x = []
class C:
def __enter__(self):
x.append('enter')
return 42
def __exit__(self, _x,_y,_z):
x.append('exit')
with C() as y:
x.append(y)
1/0
" {ZeroDivisionError})
(run-no-error "
def f():
yield 1
try:
yield 2
raise NameError
finally:
yield 3
g = f()
assert g.next() == 1
assert g.next() == 2
assert g.next() == 3
try:
g.next()
assert False
except NameError:
pass
")
(run-no-error "
x = None
def f():
yield 1
try:
yield 2
finally:
global x
x = 3
g = f()
assert list(f()) == [1,2]
assert x == 3")
(run-error "
x = []
class C:
def __enter__(self):
x.append('enter')