Debian Codegraph @

Lib/test/test_capi/test_number.py

raw
1 import itertools
2 import operator
3 import unittest
4 import warnings
5
6 from test.support import import_helper
7
8 _testcapi = import_helper.import_module('_testcapi')
9 from _testcapi import PY_SSIZE_T_MAX, PY_SSIZE_T_MIN
10
11 try:
12 from _testbuffer import ndarray
13 except ImportError:
14 ndarray = None
15
16 NULL = None
17
18 class BadDescr:
19 def __get__(self, obj, objtype=None):
20 raise RuntimeError
21
22 class WithDunder:
23 def _meth(self, *args):
24 if self.val:
25 return self.val
26 if self.exc:
27 raise self.exc
28 @classmethod
29 def with_val(cls, val):
30 obj = super().__new__(cls)
31 obj.val = val
32 obj.exc = None
33 setattr(cls, cls.methname, cls._meth)
34 return obj
35
36 @classmethod
37 def with_exc(cls, exc):
38 obj = super().__new__(cls)
39 obj.val = None
40 obj.exc = exc
41 setattr(cls, cls.methname, cls._meth)
42 return obj
43
44 class HasBadAttr:
45 def __new__(cls):
46 obj = super().__new__(cls)
47 setattr(cls, cls.methname, BadDescr())
48 return obj
49
50
51 class IndexLike(WithDunder):
52 methname = '__index__'
53
54 class IntLike(WithDunder):
55 methname = '__int__'
56
57 class FloatLike(WithDunder):
58 methname = '__float__'
59
60
61 def subclassof(base):
62 return type(base.__name__ + 'Subclass', (base,), {})
63
64
65 class SomeError(Exception):
66 pass
67
68 class OtherError(Exception):
69 pass
70
71
72 class CAPITest(unittest.TestCase):
73 def test_check(self):
74 # Test PyNumber_Check()
75 check = _testcapi.number_check
76
77 self.assertTrue(check(1))
78 self.assertTrue(check(IndexLike.with_val(1)))
79 self.assertTrue(check(IntLike.with_val(99)))
80 self.assertTrue(check(0.5))
81 self.assertTrue(check(FloatLike.with_val(4.25)))
82 self.assertTrue(check(1+2j))
83
84 self.assertFalse(check([]))
85 self.assertFalse(check("abc"))
86 self.assertFalse(check(object()))
87 self.assertFalse(check(NULL))
88
89 def test_unary_ops(self):
90 methmap = {'__neg__': _testcapi.number_negative, # PyNumber_Negative()
91 '__pos__': _testcapi.number_positive, # PyNumber_Positive()
92 '__abs__': _testcapi.number_absolute, # PyNumber_Absolute()
93 '__invert__': _testcapi.number_invert} # PyNumber_Invert()
94
95 for name, func in methmap.items():
96 # Generic object, has no tp_as_number structure
97 self.assertRaises(TypeError, func, object())
98
99 # C-API function accepts NULL
100 self.assertRaises(SystemError, func, NULL)
101
102 # Behave as corresponding unary operation
103 op = getattr(operator, name)
104 for x in [0, 42, -1, 3.14, 1+2j]:
105 try:
106 op(x)
107 except TypeError:
108 self.assertRaises(TypeError, func, x)
109 else:
110 self.assertEqual(func(x), op(x))
111
112 def test_binary_ops(self):
113 methmap = {'__add__': _testcapi.number_add, # PyNumber_Add()
114 '__sub__': _testcapi.number_subtract, # PyNumber_Subtract()
115 '__mul__': _testcapi.number_multiply, # PyNumber_Multiply()
116 '__matmul__': _testcapi.number_matrixmultiply, # PyNumber_MatrixMultiply()
117 '__floordiv__': _testcapi.number_floordivide, # PyNumber_FloorDivide()
118 '__truediv__': _testcapi.number_truedivide, # PyNumber_TrueDivide()
119 '__mod__': _testcapi.number_remainder, # PyNumber_Remainder()
120 '__divmod__': _testcapi.number_divmod, # PyNumber_Divmod()
121 '__lshift__': _testcapi.number_lshift, # PyNumber_Lshift()
122 '__rshift__': _testcapi.number_rshift, # PyNumber_Rshift()
123 '__and__': _testcapi.number_and, # PyNumber_And()
124 '__xor__': _testcapi.number_xor, # PyNumber_Xor()
125 '__or__': _testcapi.number_or, # PyNumber_Or()
126 '__pow__': _testcapi.number_power, # PyNumber_Power()
127 '__iadd__': _testcapi.number_inplaceadd, # PyNumber_InPlaceAdd()
128 '__isub__': _testcapi.number_inplacesubtract, # PyNumber_InPlaceSubtract()
129 '__imul__': _testcapi.number_inplacemultiply, # PyNumber_InPlaceMultiply()
130 '__imatmul__': _testcapi.number_inplacematrixmultiply, # PyNumber_InPlaceMatrixMultiply()
131 '__ifloordiv__': _testcapi.number_inplacefloordivide, # PyNumber_InPlaceFloorDivide()
132 '__itruediv__': _testcapi.number_inplacetruedivide, # PyNumber_InPlaceTrueDivide()
133 '__imod__': _testcapi.number_inplaceremainder, # PyNumber_InPlaceRemainder()
134 '__ilshift__': _testcapi.number_inplacelshift, # PyNumber_InPlaceLshift()
135 '__irshift__': _testcapi.number_inplacershift, # PyNumber_InPlaceRshift()
136 '__iand__': _testcapi.number_inplaceand, # PyNumber_InPlaceAnd()
137 '__ixor__': _testcapi.number_inplacexor, # PyNumber_InPlaceXor()
138 '__ior__': _testcapi.number_inplaceor, # PyNumber_InPlaceOr()
139 '__ipow__': _testcapi.number_inplacepower, # PyNumber_InPlacePower()
140 }
141
142 for name, func in methmap.items():
143 cases = [0, 42, 3.14, -1, 123, 1+2j]
144
145 # Generic object, has no tp_as_number structure
146 for x in cases:
147 self.assertRaises(TypeError, func, object(), x)
148 self.assertRaises(TypeError, func, x, object())
149
150 # Behave as corresponding binary operation
151 op = getattr(operator, name, divmod)
152 for x, y in itertools.combinations(cases, 2):
153 try:
154 op(x, y)
155 except (TypeError, ValueError, ZeroDivisionError) as exc:
156 self.assertRaises(exc.__class__, func, x, y)
157 else:
158 self.assertEqual(func(x, y), op(x, y))
159
160 # CRASHES func(NULL, object())
161 # CRASHES func(object(), NULL)
162
163 @unittest.skipIf(ndarray is None, "needs _testbuffer")
164 def test_misc_add(self):
165 # PyNumber_Add(), PyNumber_InPlaceAdd()
166 add = _testcapi.number_add
167 inplaceadd = _testcapi.number_inplaceadd
168
169 # test sq_concat/sq_inplace_concat slots
170 a, b, r = [1, 2], [3, 4], [1, 2, 3, 4]
171 self.assertEqual(add(a, b), r)
172 self.assertEqual(a, [1, 2])
173 self.assertRaises(TypeError, add, ndarray([1], (1,)), 2)
174 a, b, r = [1, 2], [3, 4], [1, 2, 3, 4]
175 self.assertEqual(inplaceadd(a, b), r)
176 self.assertEqual(a, r)
177 self.assertRaises(TypeError, inplaceadd, ndarray([1], (1,)), 2)
178
179 @unittest.skipIf(ndarray is None, "needs _testbuffer")
180 def test_misc_multiply(self):
181 # PyNumber_Multiply(), PyNumber_InPlaceMultiply()
182 multiply = _testcapi.number_multiply
183 inplacemultiply = _testcapi.number_inplacemultiply
184
185 # test sq_repeat/sq_inplace_repeat slots
186 a, b, r = [1], 2, [1, 1]
187 self.assertEqual(multiply(a, b), r)
188 self.assertEqual((a, b), ([1], 2))
189 self.assertEqual(multiply(b, a), r)
190 self.assertEqual((a, b), ([1], 2))
191 self.assertEqual(multiply([1], -1), [])
192 self.assertRaises(TypeError, multiply, ndarray([1], (1,)), 2)
193 self.assertRaises(TypeError, multiply, [1], 0.5)
194 self.assertRaises(OverflowError, multiply, [1], PY_SSIZE_T_MAX + 1)
195 self.assertRaises(MemoryError, multiply, [1, 2], PY_SSIZE_T_MAX//2 + 1)
196 a, b, r = [1], 2, [1, 1]
197 self.assertEqual(inplacemultiply(a, b), r)
198 self.assertEqual((a, b), (r, 2))
199 a = [1]
200 self.assertEqual(inplacemultiply(b, a), r)
201 self.assertEqual((a, b), ([1], 2))
202 self.assertRaises(TypeError, inplacemultiply, ndarray([1], (1,)), 2)
203 self.assertRaises(OverflowError, inplacemultiply, [1], PY_SSIZE_T_MAX + 1)
204 self.assertRaises(MemoryError, inplacemultiply, [1, 2], PY_SSIZE_T_MAX//2 + 1)
205
206 def test_misc_power(self):
207 # PyNumber_Power(), PyNumber_InPlacePower()
208 power = _testcapi.number_power
209 inplacepower = _testcapi.number_inplacepower
210
211 class HasPow(WithDunder):
212 methname = '__pow__'
213
214 # ternary op
215 self.assertEqual(power(4, 11, 5), pow(4, 11, 5))
216 self.assertRaises(TypeError, power, 4, 11, 1.25)
217 self.assertRaises(TypeError, power, 4, 11, HasPow.with_val(NotImplemented))
218 self.assertRaises(TypeError, power, 4, 11, object())
219 self.assertEqual(inplacepower(4, 11, 5), pow(4, 11, 5))
220 self.assertRaises(TypeError, inplacepower, 4, 11, 1.25)
221 self.assertRaises(TypeError, inplacepower, 4, 11, object())
222
223 class X:
224 def __pow__(*args):
225 return args
226
227 x = X()
228 self.assertEqual(power(x, 11), (x, 11))
229 self.assertEqual(inplacepower(x, 11), (x, 11))
230 self.assertEqual(power(x, 11, 5), (x, 11, 5))
231 self.assertEqual(inplacepower(x, 11, 5), (x, 11, 5))
232
233 class X:
234 def __rpow__(*args):
235 return args
236
237 x = X()
238 self.assertEqual(power(4, x), (x, 4))
239 self.assertEqual(inplacepower(4, x), (x, 4))
240 self.assertEqual(power(4, x, 5), (x, 4, 5))
241 self.assertEqual(inplacepower(4, x, 5), (x, 4, 5))
242
243 class X:
244 def __ipow__(*args):
245 return args
246
247 x = X()
248 self.assertEqual(inplacepower(x, 11), (x, 11))
249 # XXX: In-place power doesn't pass the third arg to __ipow__.
250 self.assertEqual(inplacepower(x, 11, 5), (x, 11))
251
252 def test_long(self):
253 # Test PyNumber_Long()
254 long = _testcapi.number_long
255
256 self.assertEqual(long(42), 42)
257 self.assertEqual(long(1.25), 1)
258 self.assertEqual(long("42"), 42)
259 self.assertEqual(long(b"42"), 42)
260 self.assertEqual(long(bytearray(b"42")), 42)
261 self.assertEqual(long(memoryview(b"42")), 42)
262 self.assertEqual(long(IndexLike.with_val(99)), 99)
263 self.assertEqual(long(IntLike.with_val(99)), 99)
264
265 self.assertRaises(TypeError, long, IntLike.with_val(1.0))
266 with warnings.catch_warnings():
267 warnings.simplefilter("error", DeprecationWarning)
268 self.assertRaises(DeprecationWarning, long, IntLike.with_val(True))
269 with self.assertWarns(DeprecationWarning):
270 self.assertEqual(long(IntLike.with_val(True)), 1)
271 self.assertRaises(RuntimeError, long, IntLike.with_exc(RuntimeError))
272
273 self.assertRaises(TypeError, long, 1j)
274 self.assertRaises(TypeError, long, object())
275 self.assertRaises(SystemError, long, NULL)
276
277 def test_float(self):
278 # Test PyNumber_Float()
279 float_ = _testcapi.number_float
280
281 self.assertEqual(float_(1.25), 1.25)
282 self.assertEqual(float_(123), 123.)
283 self.assertEqual(float_("1.25"), 1.25)
284
285 self.assertEqual(float_(FloatLike.with_val(4.25)), 4.25)
286 self.assertEqual(float_(IndexLike.with_val(99)), 99.0)
287 self.assertEqual(float_(IndexLike.with_val(-1)), -1.0)
288
289 self.assertRaises(TypeError, float_, FloatLike.with_val(687))
290 with warnings.catch_warnings():
291 warnings.simplefilter("error", DeprecationWarning)
292 self.assertRaises(DeprecationWarning, float_, FloatLike.with_val(subclassof(float)(4.25)))
293 with self.assertWarns(DeprecationWarning):
294 self.assertEqual(float_(FloatLike.with_val(subclassof(float)(4.25))), 4.25)
295 self.assertRaises(RuntimeError, float_, FloatLike.with_exc(RuntimeError))
296
297 self.assertRaises(TypeError, float_, IndexLike.with_val(1.25))
298 self.assertRaises(OverflowError, float_, IndexLike.with_val(2**2000))
299
300 self.assertRaises(TypeError, float_, 1j)
301 self.assertRaises(TypeError, float_, object())
302 self.assertRaises(SystemError, float_, NULL)
303
304 def test_index(self):
305 # Test PyNumber_Index()
306 index = _testcapi.number_index
307
308 self.assertEqual(index(11), 11)
309
310 with warnings.catch_warnings():
311 warnings.simplefilter("error", DeprecationWarning)
312 self.assertRaises(DeprecationWarning, index, IndexLike.with_val(True))
313 with self.assertWarns(DeprecationWarning):
314 self.assertEqual(index(IndexLike.with_val(True)), 1)
315 self.assertRaises(TypeError, index, IndexLike.with_val(1.0))
316 self.assertRaises(RuntimeError, index, IndexLike.with_exc(RuntimeError))
317
318 self.assertRaises(TypeError, index, 1.25)
319 self.assertRaises(TypeError, index, "42")
320 self.assertRaises(TypeError, index, object())
321 self.assertRaises(SystemError, index, NULL)
322
323 def test_tobase(self):
324 # Test PyNumber_ToBase()
325 tobase = _testcapi.number_tobase
326
327 self.assertEqual(tobase(10, 2), bin(10))
328 self.assertEqual(tobase(11, 8), oct(11))
329 self.assertEqual(tobase(16, 10), str(16))
330 self.assertEqual(tobase(13, 16), hex(13))
331
332 self.assertRaises(SystemError, tobase, NULL, 2)
333 self.assertRaises(SystemError, tobase, 2, 3)
334 self.assertRaises(TypeError, tobase, 1.25, 2)
335 self.assertRaises(TypeError, tobase, "42", 2)
336
337 def test_asssizet(self):
338 # Test PyNumber_AsSsize_t()
339 asssizet = _testcapi.number_asssizet
340
341 for n in [*range(-6, 7), PY_SSIZE_T_MIN, PY_SSIZE_T_MAX]:
342 self.assertEqual(asssizet(n, OverflowError), n)
343 self.assertEqual(asssizet(PY_SSIZE_T_MAX+10, NULL), PY_SSIZE_T_MAX)
344 self.assertEqual(asssizet(PY_SSIZE_T_MIN-10, NULL), PY_SSIZE_T_MIN)
345
346 self.assertRaises(OverflowError, asssizet, PY_SSIZE_T_MAX + 10, OverflowError)
347 self.assertRaises(RuntimeError, asssizet, PY_SSIZE_T_MAX + 10, RuntimeError)
348 self.assertRaises(SystemError, asssizet, NULL, TypeError)
349
350
351 if __name__ == "__main__":
352 unittest.main()