Repository navigation
Expand file tree
/
Copy pathtest_class.py
More file actions
3271 lines (2427 loc) · 98.3 KB
/
Copy pathtest_class.py
File metadata and controls
3271 lines (2427 loc) · 98.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
# Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information.
# from iptest.type_util import *
import os
import sys
import unittest
from iptest import IronPythonTestCase, is_cli, is_mono, myint, big, run_test, skipUnlessIronPython
GETATTRIBUTE_CALLED = False
class ClassTest(IronPythonTestCase):
def test_common_attributes(self):
builtin_type_instances = [None, object(), big(1), "Hello", [0,1], {"a":0}, 0]
builtin_hashable_type_instances = [None, object(), 1, "Hello"]
builtin_types = [type(None), object, int, str, list, dict]
for i in builtin_type_instances:
# Read-only attribute
self.assertRaises(AttributeError, i.__delattr__, "__doc__")
# Non-existent attribute
self.assertRaises(AttributeError, i.__delattr__, "foo")
# Modifying __class__ causes a TypeError
self.assertRaises(TypeError, i.__delattr__, "__class__")
# Read-only attribute
self.assertRaises(TypeError, i.__setattr__, "__doc__")
# Non-existent attribute
self.assertRaises(AttributeError, i.__setattr__, "foo", "foovalue")
# Modifying __class__ causes a TypeError
self.assertRaises(TypeError, i.__setattr__, "__class__")
self.assertEqual(type(i), i.__getattribute__("__class__"))
# Non-existent attribute
self.assertRaises(AttributeError, i.__getattribute__, "foo")
if not i: # !!! Need to expose __reduce__ on all types
self.assertRaises(TypeError, i.__reduce__)
self.assertRaises(TypeError, i.__reduce_ex__)
for i in builtin_hashable_type_instances:
self.assertEqual(hash(i), i.__hash__())
for i in builtin_types:
# __init__ and __new__ are implemented by IronPython.Runtime.Operations.InstanceOps
# We do repr to ensure that we can map back the functions properly
repr(getattr(i, "__init__"))
repr(getattr(i, "__new__"))
def test_attrs(self):
class C:pass
C.v = 10
self.assertTrue(C.v == 10)
success = 0
try:
x = C.x
except AttributeError:
success = 1
self.assertTrue(success == 1)
def test_type_in(self):
self.assertEqual(type in (None, True, False, 1, {}, [], (), 1.0, big(1), (1+0j)), False)
def test_init_defaults(self):
class A:
def __init__(self, height=20, width=30):
self.area = height * width
a = A()
self.assertTrue(a.area == 600)
a = A(2,3)
self.assertTrue(a.area == 6)
a = A(2)
self.assertTrue(a.area == 60)
a = A(width = 2)
self.assertTrue(a.area == 40)
def test_getattr(self):
class C:
def __init__(self, name, flag):
self.f = open(name, flag)
def __getattr__(self, name):
return getattr(self.f, name)
tmpfile = "tmpfile_%d.txt" % os.getpid()
c=C(tmpfile, "w")
c.write("Hello\n")
c.close()
c=C(tmpfile, "r")
self.assertTrue(c.readline() == "Hello\n")
c.close()
try:
os.unlink(tmpfile)
except:
pass
# new-style
class C(object):
def __getattr__(self, name):
raise AttributeError(name)
# old-style
class D:
def __getattr__(self, name):
raise AttributeError(name)
# new-style __getattribute__
class E(object):
def __getattribute__(self, name):
if name == 'xyz':
raise AttributeError(name)
if name == 'x':
return 42
return object.__getattribute__(self, name)
# derived new-style type
class F(E):
pass
# verify that base class' __getattribute__ is called.
self.assertEqual(F().x, 42)
# exception shouldn't propagate out
for cls in [C, D, E, F]:
self.assertEqual(getattr(cls(), 'xyz', 'DNE'), 'DNE')
self.assertEqual(hasattr(cls(), 'xyz'), False)
# removing & adding back on __getattribute__ should work
class foo(object):
def __getattribute__(self, name): return 42
x = foo.__getattribute__
del foo.__getattribute__
self.assertRaises(AttributeError, getattr, foo(), 'x')
foo.__getattribute__ = x
self.assertEqual(foo().x, 42)
del foo.__getattribute__
self.assertRaises(AttributeError, getattr, foo(), 'x')
# check getattr when the property raises
class C(object):
def throw(self):
raise AttributeError
foo = property(throw)
self.assertEqual(getattr(C(), 'foo', 'abc'), 'abc')
def count_elem(self,d,n):
count = 0
for e in d:
if e == n:
count += 1
return count
############################################################
def test_newstyle_oldstyle_dict(self):
"""Dictionary and new style classes"""
class class_n(object):
val1 = "Value"
def __init__(self):
self.val2 = self.val1
inst_n = class_n()
self.assertTrue(inst_n.val2 == "Value")
self.assertTrue(not 'val2' in dir(class_n))
self.assertTrue('val1' in dir(class_n))
self.assertTrue('val2' in dir(inst_n))
self.assertTrue('val1' in dir(inst_n))
self.assertTrue('val2' in inst_n.__dict__)
self.assertTrue(inst_n.__dict__['val2'] == "Value")
self.assertTrue(self.count_elem(dir(inst_n), "val1") == 1)
inst_n.val1 = 20
self.assertTrue(self.count_elem(dir(inst_n), "val1") == 1)
# old style classes:
class class_o:
val1 = "Value"
def __init__(self):
self.val2 = self.val1
inst_o = class_o()
self.assertTrue('val1' in dir(class_o))
self.assertTrue(not 'val2' in dir(class_o))
self.assertTrue('val1' in dir(inst_o))
self.assertTrue('val2' in dir(inst_o))
self.assertTrue('val2' in inst_o.__dict__)
self.assertTrue(inst_o.__dict__['val2'] == "Value")
self.assertTrue(self.count_elem(dir(inst_o), "val1") == 1)
inst_n.val1 = 20
self.assertTrue(self.count_elem(dir(inst_o), "val1") == 1)
self.assertTrue(isinstance(class_o, object))
self.assertTrue(isinstance(inst_o, object))
self.assertTrue(isinstance(None, object))
def test_misc(self):
class B: pass
class C(B):
def x(self):
return 'C.x'
def y(self):
return 'C.y'
class D:
def z(self):
return 'D.z'
c = C()
self.assertEqual(c.x(), "C.x")
self.assertEqual(c.y(), "C.y")
# verify repr and str on old-style class objects have the right format:
# bug# 795
self.assertEqual(str(C), "<class '{}{}.C'>".format(__name__, "" if is_cli else ".ClassTest.test_misc.<locals>"))
self.assertTrue(repr(C), str(C))
with self.assertRaises(AttributeError):
c.z()
self.assertEqual(C.__bases__, (B,))
C.__bases__ += (D,)
self.assertEqual(c.z(), "D.z")
class C:
def m(self):
return "IronPython"
def n(self, parm):
return parm
c = C()
y = c.m
y = c.n
y = C.m
y = C.n
self.assertTrue('__dict__' not in str.__dict__)
class E: pass
class F: pass
if is_cli:
F.__bases__ = (E,)
else:
with self.assertRaises(TypeError):
F.__bases__ = (E,)
def test_dir_in_init(self):
# both of these shouldn't throw
class DirInInit(object):
def __init__(self):
dir(self)
a = DirInInit()
def test_priv_class(self):
class _PrivClass(object):
def __Mangled(self):
pass
def __init__(self):
a = self.__Mangled
a = _PrivClass()
def test_inheritance_attrs_dir(self):
class foo:
def foofunc(self):
return "foofunc"
class bar(foo):
def barfunc(self):
return "barfunc"
class baz(bar, foo):
def bazfunc(self):
return "bazfunc"
self.assertIn('foofunc', dir(foo))
self.assertEqual(dir(foo).count('__doc__'), 1)
self.assertEqual(dir(foo).count('__module__'), 1)
self.assertEqual(len(dir(foo)) - len(dir(object)), 4)
self.assertIn('foofunc', dir(bar))
self.assertIn('barfunc', dir(bar))
self.assertEqual(dir(bar).count('__doc__'), 1)
self.assertEqual(dir(bar).count('__module__'), 1)
self.assertEqual(len(dir(bar)) - len(dir(object)), 5)
self.assertIn('foofunc', dir(baz))
self.assertIn('barfunc', dir(baz))
self.assertIn('bazfunc', dir(baz))
self.assertEqual(dir(baz).count('__doc__'), 1)
self.assertEqual(dir(baz).count('__module__'), 1)
self.assertEqual(len(dir(baz)) - len(dir(object)), 6)
bz = baz()
self.assertIn('foofunc', dir(bz))
self.assertIn('barfunc', dir(bz))
self.assertIn('bazfunc', dir(bz))
self.assertEqual(dir(bz).count('__doc__'), 1)
self.assertEqual(dir(bz).count('__module__'), 1)
self.assertEqual(len(dir(bz)) - len(dir(object)), 6)
bz.__module__ = "MODULE"
self.assertEqual(bz.__module__, "MODULE")
bz.__module__ = "SOMEOTHERMODULE"
self.assertEqual(bz.__module__, "SOMEOTHERMODULE")
bz.__module__ = 33
self.assertEqual(bz.__module__, 33)
bz.__module__ = [2, 3, 4]
self.assertEqual(bz.__module__, [2, 3, 4])
def test_oldstyle_setattr(self):
global called
class C:
def __setattr__(self, name, value):
global called
called = (self, name, value)
a = C()
a.abc = 'def'
self.assertEqual(called, (a, 'abc', 'def'))
del C.__setattr__
a.qrt = 'abc'
self.assertEqual(called, (a, 'abc', 'def'))
def setattr(self, name, value):
global called
called = (self, name, value)
C.__setattr__ = setattr
a.qrt = 'abc'
self.assertEqual(called, (a, 'qrt', 'abc'))
def test_oldstyle_getattr(self):
"""verify we don't access __getattr__ while creating an old
style class."""
class C:
def __getattr__(self,name):
return globals()[name]
a = C()
def test_oldstyle_eq(self):
"""old style __eq__ shouldn't call __cmp__"""
class x: pass
inst = type(x())
global cmpCalled
cmpCalled = False
class C:
def __init__(self, value):
self.value = value
def __cmp__(self, other):
global cmpCalled
cmpCalled = True
return self.value - other.value
class D:
def __init__(self, value):
self.value = value
def __cmp__(self, other):
global cmpCalled
cmpCalled = True
return self.value - other.value
class C2(C): pass
class D2(D): pass
self.assertEqual(inst.__eq__(C(3.0), C(4.5)), NotImplemented)
self.assertEqual(inst.__eq__(C(3.0), C2(4.5)), NotImplemented)
self.assertEqual(inst.__eq__(C(3.0), D(4.5)), NotImplemented)
self.assertEqual(cmpCalled, False)
def test_raise_attrerror(self):
"""raising AttributeError from __getattr__ should be ok,
and shouldn't be seen by the user"""
class A:
def __getattr__(self, name):
raise AttributeError('get outta here')
def __repr__(self):
return 'foo'
class B:
def __getattr__(self, name):
raise AttributeError('get outta here')
def __str__(self):
return 'foo'
self.assertEqual(str(A()), 'foo')
self.assertEqual(repr(A()), 'foo')
self.assertEqual(str(B()), 'foo')
self.assertIn('B object', repr(B()))
# use exec to define methods on classes:
def test_exec_namespace(self):
class oldclasswithexec:
exec("def oldexecmethod(self): return 'result of oldexecmethod'")
self.assertTrue('oldexecmethod' in dir(oldclasswithexec))
self.assertEqual(oldclasswithexec().oldexecmethod(), 'result of oldexecmethod')
class newclasswithexec(object):
exec("def newexecmethod(self): return 'result of newexecmethod'")
self.assertTrue('newexecmethod' in dir(newclasswithexec))
self.assertEqual(newclasswithexec().newexecmethod(), 'result of newexecmethod')
def test_module_name(self):
global __name__
mod = sys.modules[__name__]
name = __name__
mod.__name__ = None
class C: pass
self.assertEqual(C.__module__, None)
def func1():
__name__ = "wrong"
class C: pass
return C()
def func2():
class C: pass
return C()
def func3():
global __name__
__name__ = "right"
class C: pass
return C()
self.assertEqual(func1().__module__, func2().__module__)
__name__ = "fake"
self.assertEqual(func1().__module__, "fake")
self.assertEqual(func3().__module__, "right")
mod.__name__ = name
def f(x): x.__module__
def g(x): getattr(x, '__module__')
import errno
for thing in "", 1, errno, big(1), 1+2j, (), [], {}:
self.assertEqual(getattr(thing, '__module__', 'does_not_exist'), 'does_not_exist')
self.assertEqual(hasattr(thing, '__module__'), False)
self.assertRaises(AttributeError, f, thing)
self.assertRaises(AttributeError, g, thing)
self.assertRaisesMessage(TypeError, "can't set function.__module__", type(type(f)).__dict__['__module__'].__set__, type(f), 42)
class x(object): pass
type(type(x())).__dict__['__module__'].__set__(x, 'fooz')
self.assertEqual(x.__module__, 'fooz')
self.assertRaisesMessage(TypeError, "can't delete x.__module__", type(type(x())).__dict__['__module__'].__delete__, x)
def test_check_dictionary(self):
"""tests to verify that Symbol dictionaries do the right thing in dynamic scenarios"""
class C(object):
def __init__(self): pass
# add a new attribute to the type...
C.newClassAttr = 'xyz'
self.assertEqual(C.newClassAttr, 'xyz')
# add non-string index into the class and instance dictionary
a = C()
a.__dict__[1] = '1'
if object in C.__bases__:
with self.assertRaises(TypeError):
C.__dict__[2] = '2'
self.assertEqual(2 in C.__dict__, False)
self.assertEqual(1 in a.__dict__, True)
with self.assertRaises(TypeError): # TypeError: unorderable types: str() < int()
dir(a)
self.assertEqual(repr(a.__dict__), "{1: '1'}")
# replace a class dictionary (containing non-string keys) w/ a normal dictionary
C.newTypeAttr = 1
self.assertEqual(hasattr(C, 'newTypeAttr'), True)
with self.assertRaises(AttributeError):
C.__dict__ = {}
# replace an instance dictionary (containing non-string keys) w/ a new one.
a.newInstanceAttr = 1
self.assertEqual(hasattr(a, 'newInstanceAttr'), True)
a.__dict__ = dict(a.__dict__)
self.assertEqual(hasattr(a, 'newInstanceAttr'), True)
a.abc = 'xyz'
self.assertEqual(hasattr(a, 'abc'), True)
self.assertEqual(getattr(a, 'abc'), 'xyz')
def test_call_type_call(self):
for stuff in [object, int, str, bool, float]:
self.assertEqual(type(type.__call__(stuff)), stuff)
self.assertEqual(type.__call__(int, 5), 5)
self.assertEqual(type.__call__(int), 0)
self.assertEqual(type.__call__(bool, True), True)
self.assertEqual(type.__call__(bool), False)
#User-defined old/new style classes
call_mapper = {}
class KNew0(object):
def __call__(self):
return 2
call_mapper[KNew0] = lambda: [type(KNew0()).__call__(KNew0())]
class KNew1(object):
def __call__(self, p):
return 2
call_mapper[KNew1] = lambda: [type(KNew1()).__call__(KNew1(), 3.14),
type(KNew1()).__call__(KNew1(), p=3.14),
type(KNew1()).__call__(KNew1(), **{"p":3.14}),
type(KNew1()).__call__(KNew1(), (1, 2, 3)),
]
class KNewArgs(object):
def __call__(self, *args):
return 2
call_mapper[KNewArgs] = lambda: [type(KNewArgs()).__call__(KNewArgs()) ]
class KNewKwargs(object):
def __call__(self, **kwargs):
return 2
call_mapper[KNewKwargs] = lambda: [type(KNewKwargs()).__call__(KNewKwargs())]
class KNewArgsKwargs(object):
def __call__(self, *args, **kwargs):
return 2
call_mapper[KNewArgsKwargs] = lambda: [type(KNewArgsKwargs()).__call__(KNewArgsKwargs())]
for K in list(call_mapper.keys()):
for ret_val in call_mapper[K]():
self.assertEqual(ret_val, 2)
def test_cp8246(self):
#...
class K(object):
def __call__(self):
return ((), {})
self.assertEqual(K()(), ((), {}))
#...
class K(object):
def __call__(self, **kwargs):
return ((), kwargs)
self.assertEqual(K()(), ((), {}))
self.assertEqual(K()(**{}), ((), {}))
self.assertEqual(K()(**{'a':None}), ((), {'a':None}))
#...
class K(object):
def __call__(self, *args):
return (args, {})
self.assertEqual(K()(), ((), {}))
self.assertEqual(K()(*()), ((), {}))
self.assertEqual(K()(*(None,)), ((None,), {}))
#...
class K(object):
def __call__(self, *args, **kwargs):
return (args, kwargs)
self.assertEqual(K()(), ((), {}))
self.assertEqual(K()(*()), ((), {}))
self.assertEqual(K()(**{}), ((), {}))
self.assertEqual(K()(*(), **{}), ((), {}))
self.assertEqual(K()(*(None,)), ((None,), {}))
self.assertEqual(K()(**{'a':None}), ((), {'a':None}))
self.assertEqual(K()(*(None,), **{'a':None}), ((None,), {'a':None}))
def test_mixed_inheritance(self):
"""inheritance from both old & new style classes..."""
class foo: pass
class bar(object): pass
class baz1(foo, bar): pass
class baz2(bar, foo): pass
self.assertEqual(baz1.__bases__, (foo, bar))
self.assertEqual(baz2.__bases__, (bar, foo))
class foo:
abc = 3
class bar(object):
def get_abc():
return 42
def set_abc():
pass
abc = property(fget=get_abc, fset=set_abc)
class baz(foo, bar): pass
self.assertEqual(baz().abc, 3)
def test_newstyle_unbound_inheritance(self):
"""verify calling unbound method w/ new-style class on subclass which
new-style also inherits from works."""
class foo:
def func(self): return self
class bar(foo):
def barfunc(self):
return foo.func(self)
a = bar()
self.assertEqual(a.barfunc(), a)
def test_mro(self):
"""mro (method resolution order) support"""
class A(object): pass
self.assertEqual(A.__mro__, (A, object))
class B(object): pass
self.assertEqual(B.__mro__, (B, object))
class C(B): pass
self.assertEqual(C.__mro__, (C, B, object))
class N(C,B,A): pass
self.assertEqual(N.__mro__, (N, C, B, A, object))
with self.assertRaises(TypeError, msg="impossible MRO created"):
class N(A, B,C): pass
with self.assertRaises(TypeError, msg="can't derive from the same base type twice"):
class N(A, A): pass
def test_mro_bases(self):
"""verify replacing base classes also updates MRO"""
class C(object):
def __getattribute__(self, name):
if(name == 'xyz'): return 'C'
return super(C, self).__getattribute__(name)
class C1(C):
def __getattribute__(self, name):
if(name == 'xyz'): return 'C1'
return super(C1, self).__getattribute__(name)
class A(object): pass
class B(object):
def __getattribute__(self, name):
if(name == 'xyz'): return 'B'
return super(B, self).__getattribute__(name)
a = C1()
self.assertEqual(a.xyz, 'C1')
C1.__bases__ = (A,B)
self.assertEqual(a.xyz, 'C1')
del(C1.__getattribute__)
self.assertEqual(a.xyz, 'B')
def test_dynamic_mro_bases(self):
class C(object):
pass
def __getattribute__(self, name):
if (name == 'xyz'):
return 'C'
return super(C, self).__getattribute__(name)
C.__getattribute__ = __getattribute__
class C1(C):
pass
def __getattribute__(self, name):
if (name == 'xyz'):
return 'C1'
return super(C1, self).__getattribute__(name)
C1.__getattribute__ = __getattribute__
class B(object):
pass
def __getattribute__(self, name):
if (name == 'xyz'):
return 'B'
return super(B, self).__getattribute__(name)
B.__getattribute__ = __getattribute__
C1.__bases__ = (B, )
self.assertEqual(C1().xyz, 'C1')
def test_builtin_mro(self):
"""int mro shouldn't include ValueType"""
self.assertEqual(int.__mro__, (int, object))
def test_mixed_inheritance_mro(self):
"""mixed inheritance from old-style & new-style classes"""
# we should use old-style MRO when inheriting w/ a single old-style class
class A: pass
class B(A): pass
class C(A): pass
class D(B, C):pass
class E(D): pass
# old-style MRO of D is D, B, A, C, which should
# be present in E's mro
self.assertEqual(E.__mro__, (E, D, B, C, A, object))
class F(B, C): pass
# but when inheriting from multiple old-style classes we switch
# to new-style MRO, and respect local ordering of classes in the MRO
self.assertEqual(F.__mro__, (F, B, C, A, object))
class G(B, C): pass
self.assertEqual(G.__mro__, (G, B, C, A, object))
class H(E): pass
self.assertEqual(H.__mro__, (H, E, D, B, C, A, object))
with self.assertRaises(TypeError):
class H(A,B,E): pass
class H(E,B,A): pass
self.assertEqual(H.__mro__, (H, E, D, B, C, A, object))
def test_depth_first_mro_mixed(self):
"""Verify given two large, independent class hierarchies
that we favor them in the order listed.
w/ old-style
"""
class A: pass
class B(A): pass
class C(A): pass
class D(B,C): pass
class E(D, object): pass
class G: pass
class H(G): pass
class I(G): pass
class K(H,I, object): pass
class L(K,E): pass
self.assertEqual(L.__mro__, (L, K, H, I, G, E, D, B, C, A, object))
def test_depth_first_mro(self):
"""w/o old-style"""
class A(object): pass
class B(A): pass
class C(A): pass
class D(B,C): pass
class E(D, object): pass
class G(object): pass
class H(G): pass
class I(G): pass
class K(H,I, object): pass
class L(K,E): pass
self.assertEqual(L.__mro__, (L, K, H, I, G, E, D, B, C, A, object))
def test_class_args(self):
class A1: pass
class A2: pass
class A3: pass
class B1(A1, *(A2, A3)): pass
self.assertEqual(B1.__mro__, (B1, A1, A2, A3, object))
clist = [A1, A2]
with self.assertRaisesMessage(TypeError, "duplicate base class A1"):
class B2(A1, *clist): pass
def foo(x): return x
class B3(foo(A1), clist[1], A3): pass
self.assertEqual(B3.__mro__, (B3, A1, A2, A3, object))
class B4(A1, *foo([A2, A3])): pass
self.assertEqual(B4.__mro__, (B4, A1, A2, A3, object))
with self.assertRaisesMessage(UnboundLocalError, "local variable 'A4' referenced before assignment"):
class B5(A1, *(A4,)): pass
class A4: pass
def test_newstyle_lookup(self):
"""new-style classes should only lookup methods from the class, not from the instance"""
class Strange(object):
def uselessMethod(self): pass
global obj
obj = Strange()
obj.__nonzero__ = lambda: False
self.assertEqual(bool(obj), True)
def twoargs(self, other):
global twoArgsCalled
twoArgsCalled = True
return self
def onearg(self):
return self
def onearg_str(self):
return 'abc'
class ForwardAndReverseTests:
testCases = [
#forward versions
('__add__', 'obj + obj'),
('__sub__', 'obj - obj'),
('__mul__', 'obj * obj'),
('__floordiv__', 'obj // obj'),
('__mod__', 'obj % obj'),
('__divmod__', 'divmod(obj,obj)'),
('__pow__', 'pow(obj, obj)'),
('__lshift__', 'obj << obj'),
('__rshift__', 'obj >> obj'),
('__and__', 'obj & obj'),
('__xor__', 'obj ^ obj'),
('__or__', 'obj | obj'),
# reverse versions
('__radd__', '1 + obj'),
('__rsub__', '1 - obj'),
('__rmul__', '1 * obj'),
('__rfloordiv__', '1 // obj'),
('__rmod__', '1 % obj'),
#('__rdivmod__', '1 % obj'), #bug 975
('__rpow__', 'pow(1, obj)'),
('__rlshift__', '1 << obj'),
('__rrshift__', '1 >> obj'),
('__rand__', '1 & obj'),
('__rxor__', '1 ^ obj'),
('__ror__', '1 | obj'),
]
@staticmethod
def NegativeTest(method, testCase):
setattr(obj, method, twoargs)
with self.assertRaises(TypeError):
eval(testCase)
delattr(obj, method)
@staticmethod
def PositiveTest(method, testCase):
setattr(Strange, method, twoargs)
self.assertEqual(eval(testCase), obj)
delattr(Strange, method)
class InPlaceTests:
# in-place versions require exec instead of eval
testCases = [
# inplace versions
('__iadd__', 'obj += obj'),
('__isub__', 'obj -= obj'),
('__imul__', 'obj *= obj'),
('__ifloordiv__', 'obj //= obj'),
('__imod__', 'obj %= obj'),
('__ipow__', 'obj **= obj'),
('__ilshift__', 'obj <<= obj'),
('__irshift__', 'obj >>= obj'),
('__iand__', 'obj &= obj'),
('__ixor__', 'obj ^= obj'),
('__ior__', 'obj |= obj'),
]
@staticmethod
def NegativeTest(method, testCase):
setattr(obj, method, twoargs)
with self.assertRaises(TypeError):
exec(testCase, globals(), locals())
delattr(obj, method)
@staticmethod
def PositiveTest(method, testCase):
setattr(Strange, method, twoargs)
global twoArgsCalled
twoArgsCalled = False
exec(testCase, globals(), locals())
self.assertEqual(twoArgsCalled, True)
delattr(Strange, method)
class SingleArgTests:
testCases = [
# one-argument versions
('__neg__', '-obj'),
('__pos__', '+obj'),
('__abs__', 'abs(obj)'),
('__invert__', '~obj'),
]
@staticmethod
def NegativeTest(method, testCase):
setattr(obj, method, onearg)
with self.assertRaises(TypeError):
eval(testCase)
delattr(obj, method)
@staticmethod
def PositiveTest(method, testCase):
setattr(Strange, method, onearg)
try:
self.assertEqual(eval(testCase), obj)
except TypeError:
self.assertTrue(method == '__oct__' or method == '__hex__')