Debian Codegraph @

extra_tests/test_binop_overriding.py

raw symbols SCIP
1 # test about the binop operation rule, see issue 412
2
3 class Base(object):
4 def __init__(self, name):
5 self.name = name
6
7 def lookup_where(obj, name):
8 mro = type(obj).__mro__
9 for t in mro:
10 if name in t.__dict__:
11 return t.__dict__[name], t
12 return None, None
13
14 def refop(x, y, opname, ropname):
15 # this has been validated by running the tests on top of cpython
16 # so for the space of possibilities that the tests touch it is known
17 # to behave like cpython as long as the latter doesn't change its own
18 # algorithm
19 t1 = type(x)
20 t2 = type(y)
21 op, where1 = lookup_where(x, opname)
22 rop, where2 = lookup_where(y, ropname)
23 if op is None and rop is not None:
24 return rop(y, x)
25 if rop and where1 is not where2:
26 if (issubclass(t2, t1) and not issubclass(where1, where2)
27 and not issubclass(t1, where2)
28 ):
29 return rop(y, x)
30 if op is None:
31 return "TypeError"
32 return op(x,y)
33
34 def do_test(X, Y, name, impl):
35 x = X('x')
36 y = Y('y')
37 opname = '__%s__' % name
38 ropname = '__r%s__' % name
39
40 count = [0]
41 fail = []
42
43 def check(z1, z2):
44 ref = refop(z1, z2, opname, ropname)
45 try:
46 v = impl(z1, z2)
47 except TypeError:
48 v = "TypeError"
49 if v != ref:
50 fail.append(count[0])
51
52 def override_in_hier(n=6):
53 if n == 0:
54 count[0] += 1
55 check(x, y)
56 check(y, x)
57 return
58
59 f = lambda self, other: (n, self.name, other.name)
60 if n%2 == 0:
61 name = opname
62 else:
63 name = ropname
64
65 for C in Y.__mro__:
66 if name in C.__dict__:
67 continue
68 if C is not object:
69 setattr(C, name, f)
70 override_in_hier(n-1)
71 if C is not object:
72 delattr(C, name)
73
74 override_in_hier()
75 #print count[0]
76 return fail
77
78 def test_binop_combinations_mul():
79 class X(Base):
80 pass
81 class Y(X):
82 pass
83
84 fail = do_test(X, Y, 'mul', lambda x,y: x*y)
85 #print len(fail)
86 assert not fail
87
88
89
90 def test_binop_combinations_sub():
91 class X(Base):
92 pass
93 class Y(X):
94 pass
95
96 fail = do_test(X, Y, 'sub', lambda x,y: x-y)
97 #print len(fail)
98 assert not fail
99
100
101 def test_binop_combinations_pow():
102 class X(Base):
103 pass
104 class Y(X):
105 pass
106
107 fail = do_test(X, Y, 'pow', lambda x,y: x**y)
108 #print len(fail)
109 assert not fail
110
111 def test_binop_combinations_more_exhaustive():
112 class X(Base):
113 pass
114
115 class B1(object):
116 pass
117
118 class B2(object):
119 pass
120
121 class X1(B1, X, B2):
122 pass
123
124 class C1(object):
125 pass
126
127 class C2(object):
128 pass
129
130 class Y(C1, X1, C2):
131 pass
132
133 fail = do_test(X, Y, 'sub', lambda x,y: x-y)
134 #print len(fail)
135 assert not fail