Debian Codegraph @

pypy/module/cpyext/test/test_longobject.py

raw symbols SCIP
1 import pytest
2 import struct
3 import sys
4 from pypy.interpreter.error import OperationError
5 from rpython.rtyper.lltypesystem import rffi, lltype
6 from rpython.rlib.rarithmetic import maxint
7 from pypy.objspace.std.longobject import W_LongObject
8 from pypy.module.cpyext.test.test_api import BaseApiTest
9 from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
10 from pypy.module.cpyext.longobject import (PyLong_Check, PyLong_CheckExact,
11 PyLong_FromLong, PyLong_AsLong, PyLong_AsUnsignedLong, PyLong_AsLongLong,
12 PyLong_AsUnsignedLongLong, PyLong_AsUnsignedLongLongMask)
13
14 maxlong = int(2 ** (struct.calcsize('l') * 8 - 1) - 1)
15
16 class TestLongObject(BaseApiTest):
17 def test_FromLong(self, space, api):
18 w_value = api.PyLong_FromLong(3)
19 assert space.unwrap(w_value) == 3
20
21 w_value = api.PyLong_FromLong(maxlong)
22 assert space.unwrap(w_value) == maxlong
23
24 def test_aslong(self, space):
25 w_value = PyLong_FromLong(space, (maxlong - 1) // 2)
26
27 w_value = space.mul(w_value, space.wrap(2))
28 value = PyLong_AsLong(space, w_value)
29 assert value == (maxlong - 1)
30
31 w_value = space.mul(w_value, space.wrap(2))
32 with pytest.raises(OperationError) as excinfo:
33 PyLong_AsLong(space, w_value)
34 assert excinfo.value.w_type is space.w_OverflowError
35 msg = "Python int too large to convert to C long"
36 print(space.text_w(excinfo.value.get_w_value(space)))
37 assert space.text_w(excinfo.value.get_w_value(space)) == msg
38 value = PyLong_AsUnsignedLong(space, w_value)
39 assert value == (maxlong - 1) * 2
40
41 def test_as_ssize_t(self, space, api):
42 w_value = space.newlong(2)
43 value = api.PyLong_AsSsize_t(w_value)
44 assert value == 2
45 w_val2 = api.PyLong_FromSsize_t(2)
46 assert space.eq_w(w_value, w_val2)
47
48 def test_fromdouble(self, space, api):
49 w_value = api.PyLong_FromDouble(-12.74)
50 assert space.isinstance_w(w_value, space.w_int)
51 assert space.unwrap(w_value) == -12
52 assert api.PyLong_AsDouble(w_value) == -12
53
54 def test_type_check(self, space, api):
55 w_l = space.wrap(sys.maxint + 1)
56 assert PyLong_Check(space, w_l)
57 assert PyLong_CheckExact(space, w_l)
58
59 w_i = space.wrap(sys.maxint)
60 assert PyLong_Check(space, w_i)
61 assert PyLong_CheckExact(space, w_i)
62
63 L = space.appexec([], """():
64 class L(int):
65 pass
66 return L
67 """)
68 l = space.call_function(L)
69 assert PyLong_Check(space, l)
70 assert not PyLong_CheckExact(space, l)
71
72 def test_as_longlong(self, space):
73 assert PyLong_AsLongLong(space, space.wrap(1 << 62)) == 1 << 62
74 with pytest.raises(OperationError) as excinfo:
75 PyLong_AsLongLong(space, space.wrap(1 << 63))
76 assert excinfo.value.w_type is space.w_OverflowError
77
78 assert PyLong_AsUnsignedLongLong(space, space.wrap(1 << 63)) == 1 << 63
79 with pytest.raises(OperationError) as excinfo:
80 PyLong_AsUnsignedLongLong(space, space.wrap(1 << 64))
81 assert excinfo.value.w_type is space.w_OverflowError
82
83 assert PyLong_AsUnsignedLongLongMask(space, space.wrap(1 << 64)) == 0
84
85 with pytest.raises(OperationError) as excinfo:
86 PyLong_AsUnsignedLongLongMask(space, None)
87 assert excinfo.value.w_type is space.w_SystemError
88
89 def test_as_long_and_overflow(self, space, api):
90 overflow = lltype.malloc(rffi.CArrayPtr(rffi.INT_real).TO, 1, flavor='raw')
91 overflow[0] = rffi.cast(rffi.INT_real, 123)
92 assert api.PyLong_AsLongAndOverflow(
93 space.wrap(maxlong), overflow) == maxlong
94 assert not api.PyErr_Occurred()
95 assert overflow[0] == 0
96 assert api.PyLong_AsLongAndOverflow(
97 space.wrap(maxlong + 1), overflow) == -1
98 assert not api.PyErr_Occurred()
99 assert overflow[0] == 1
100 assert api.PyLong_AsLongAndOverflow(
101 space.wrap(-maxlong - 2), overflow) == -1
102 assert not api.PyErr_Occurred()
103 assert overflow[0] == -1
104 lltype.free(overflow, flavor='raw')
105
106 def test_as_voidptr(self, space, api):
107 w_l = api.PyLong_FromVoidPtr(lltype.nullptr(rffi.VOIDP.TO))
108 assert space.is_w(space.type(w_l), space.w_int)
109 assert space.unwrap(w_l) == 0
110 assert api.PyLong_AsVoidPtr(w_l) == lltype.nullptr(rffi.VOIDP.TO)
111
112 p = rffi.cast(rffi.VOIDP, maxint)
113 w_l = api.PyLong_FromVoidPtr(p)
114 assert space.is_w(space.type(w_l), space.w_int)
115 assert space.unwrap(w_l) == maxint
116 assert api.PyLong_AsVoidPtr(w_l) == p
117
118 p = rffi.cast(rffi.VOIDP, -maxint-1)
119 w_l = api.PyLong_FromVoidPtr(p)
120 assert space.is_w(space.type(w_l), space.w_int)
121 assert space.unwrap(w_l) == maxint+1
122 assert api.PyLong_AsVoidPtr(w_l) == p
123
124 def test_sign_and_bits(self, space, api):
125 assert api._PyLong_Sign(space.wraplong(0L)) == 0
126 assert api._PyLong_Sign(space.wraplong(2L)) == 1
127 assert api._PyLong_Sign(space.wraplong(-2L)) == -1
128 assert api._PyLong_Sign(space.wrap(0)) == 0
129 assert api._PyLong_Sign(space.wrap(42)) == 1
130 assert api._PyLong_Sign(space.wrap(-42)) == -1
131
132 assert api._PyLong_NumBits(space.wrap(0)) == 0
133 assert api._PyLong_NumBits(space.wrap(1)) == 1
134 assert api._PyLong_NumBits(space.wrap(-1)) == 1
135 assert api._PyLong_NumBits(space.wrap(2)) == 2
136 assert api._PyLong_NumBits(space.wrap(-2)) == 2
137 assert api._PyLong_NumBits(space.wrap(3)) == 2
138 assert api._PyLong_NumBits(space.wrap(-3)) == 2
139
140 def test_as_ulongmask(self, space, api):
141 assert api.PyLong_AsUnsignedLongMask(
142 space.wrap(maxlong * 2 + 1)) == maxlong * 2 + 1
143 assert api.PyLong_AsUnsignedLongMask(
144 space.wrap(maxlong * 2 + 2)) == 0
145
146 class AppTestLongObject(AppTestCpythonExtensionBase):
147 def test_fromunsignedlong(self):
148 module = self.import_extension('foo', [
149 ("from_unsignedlong", "METH_NOARGS",
150 """
151 PyObject * obj;
152 obj = PyLong_FromUnsignedLong((unsigned long)-1);
153 if (obj->ob_type != &PyLong_Type)
154 {
155 Py_DECREF(obj);
156 PyErr_SetString(PyExc_ValueError,
157 "PyLong_FromLongLong did not return PyLongObject");
158 return NULL;
159 }
160 return obj;
161 """),
162 ])
163 import struct
164 max_ul = struct.unpack_from('L', b'\xff'*8)[0]
165 assert module.from_unsignedlong() == max_ul
166
167 def test_fromlonglong(self):
168 module = self.import_extension('foo', [
169 ("from_longlong", "METH_VARARGS",
170 """
171 int val;
172 PyObject * obj;
173 if (!PyArg_ParseTuple(args, "i", &val))
174 return NULL;
175 obj = PyLong_FromLongLong((long long)val);
176 if (obj->ob_type != &PyLong_Type)
177 {
178 Py_DECREF(obj);
179 PyErr_SetString(PyExc_ValueError,
180 "PyLong_FromLongLong did not return PyLongObject");
181 return NULL;
182 }
183 return obj;
184 """),
185 ("from_unsignedlonglong", "METH_VARARGS",
186 """
187 int val;
188 PyObject * obj;
189 if (!PyArg_ParseTuple(args, "i", &val))
190 return NULL;
191 obj = PyLong_FromUnsignedLongLong((long long)val);
192 if (obj->ob_type != &PyLong_Type)
193 {
194 Py_DECREF(obj);
195 PyErr_SetString(PyExc_ValueError,
196 "PyLong_FromLongLong did not return PyLongObject");
197 return NULL;
198 }
199 return obj;
200 """)])
201 assert module.from_longlong(-1) == -1
202 assert module.from_longlong(0) == 0
203 assert module.from_unsignedlonglong(0) == 0
204 assert module.from_unsignedlonglong(-1) == (1<<64) - 1
205
206 def test_from_size_t(self):
207 module = self.import_extension('foo', [
208 ("from_unsignedlong", "METH_NOARGS",
209 """
210 return PyLong_FromSize_t((size_t)-1);
211 """)])
212 import sys
213 assert module.from_unsignedlong() == 2 * sys.maxsize + 1
214
215 def test_from_long(self):
216 module = self.import_extension('foo', [
217 ("asunsignedlong", "METH_O",
218 """
219 unsigned long n = PyLong_AsUnsignedLong(args);
220 if ((long)n == -1 && PyErr_Occurred()) {
221 return NULL;
222 }
223 return PyLong_FromUnsignedLong(n);
224 """),
225 ("assize_t", "METH_O",
226 """
227 size_t n = PyLong_AsSize_t(args);
228 if ((long)n == -1 && PyErr_Occurred()) {
229 return NULL;
230 }
231 return PyLong_FromSize_t(n);
232 """),
233 ("asunsignedlonglong", "METH_O",
234 """
235 unsigned long n = PyLong_AsUnsignedLongLong(args);
236 if ((long)n == -1 && PyErr_Occurred()) {
237 return NULL;
238 }
239 return PyLong_FromUnsignedLongLong(n);
240 """)])
241 with raises(OverflowError):
242 module.asunsignedlong(-1)
243 with raises(OverflowError):
244 module.asunsignedlonglong(-1)
245 assert module.assize_t(100) == 100
246
247 def test_fromstring(self):
248 module = self.import_extension('foo', [
249 ("from_string", "METH_NOARGS",
250 """
251 return PyLong_FromString("0x1234", NULL, 0);
252 """),
253 ])
254 assert module.from_string() == 0x1234
255
256 def test_frombytearray(self):
257 module = self.import_extension('foo', [
258 ("from_bytearray", "METH_VARARGS",
259 """
260 int little_endian, is_signed;
261 if (!PyArg_ParseTuple(args, "ii", &little_endian, &is_signed))
262 return NULL;
263 return _PyLong_FromByteArray((unsigned char*)"\\x9A\\xBC", 2,
264 little_endian, is_signed);
265 """),
266 ])
267 assert module.from_bytearray(True, False) == 0xBC9A
268 assert module.from_bytearray(True, True) == -0x4366
269 assert module.from_bytearray(False, False) == 0x9ABC
270 assert module.from_bytearray(False, True) == -0x6544
271
272 def test_frombytearray_2(self):
273 module = self.import_extension('foo', [
274 ("from_bytearray", "METH_VARARGS",
275 """
276 int little_endian, is_signed;
277 if (!PyArg_ParseTuple(args, "ii", &little_endian, &is_signed))
278 return NULL;
279 return _PyLong_FromByteArray((unsigned char*)"\\x9A\\xBC\\x41", 3,
280 little_endian, is_signed);
281 """),
282 ])
283 assert module.from_bytearray(True, False) == 0x41BC9A
284 assert module.from_bytearray(True, True) == 0x41BC9A
285 assert module.from_bytearray(False, False) == 0x9ABC41
286 assert module.from_bytearray(False, True) == -0x6543BF
287
288 def test_asbytearray(self):
289 module = self.import_extension('foo', [
290 ("as_bytearray", "METH_VARARGS",
291 """
292 PyObject *result;
293 PyLongObject *o;
294 int n, little_endian, is_signed;
295 unsigned char *bytes;
296 if (!PyArg_ParseTuple(args, "O!iii", &PyLong_Type, &o, &n,
297 &little_endian, &is_signed))
298 return NULL;
299 bytes = malloc(n);
300 if (_PyLong_AsByteArray(o, bytes, (size_t)n,
301 little_endian, is_signed) != 0)
302 {
303 free(bytes);
304 return NULL;
305 }
306 result = PyBytes_FromStringAndSize((const char *)bytes, n);
307 free(bytes);
308 return result;
309 """),
310 ])
311 s = module.as_bytearray(0x41BC9A, 4, True, False)
312 assert s == b"\x9A\xBC\x41\x00"
313 s = module.as_bytearray(0x41BC9A, 4, False, False)
314 assert s == b"\x00\x41\xBC\x9A"
315 s = module.as_bytearray(0x41BC9A, 3, True, False)
316 assert s == b"\x9A\xBC\x41"
317 s = module.as_bytearray(0x41BC9A, 3, True, True)
318 assert s == b"\x9A\xBC\x41"
319 s = module.as_bytearray(0x9876, 2, True, False)
320 assert s == b"\x76\x98"
321 s = module.as_bytearray(0x9876 - 0x10000, 2, True, True)
322 assert s == b"\x76\x98"
323 raises(OverflowError, module.as_bytearray,
324 0x9876, 2, False, True)
325 raises(OverflowError, module.as_bytearray,
326 -1, 2, True, False)
327 raises(OverflowError, module.as_bytearray,
328 0x1234567, 3, True, False)
329
330 def test_fromunicode(self):
331 module = self.import_extension('foo', [
332 ("from_unicode", "METH_O",
333 """
334 _Py_COMP_DIAG_PUSH
335 _Py_COMP_DIAG_IGNORE_DEPR_DECLS
336 Py_UNICODE* u = PyUnicode_AsUnicode(args);
337 _Py_COMP_DIAG_POP
338 return Py_BuildValue("NN",
339 PyLong_FromUnicode(u, 6, 10),
340 PyLong_FromUnicode(u, 6, 16));
341 """),
342 ])
343 # A string with arabic digits. 'BAD' is after the 6th character.
344 assert module.from_unicode(u' 1\u0662\u0663\u0664BAD') == (1234, 4660)
345
346 def test_fromunicodeobject(self):
347 module = self.import_extension('foo', [
348 ("from_unicodeobject", "METH_O",
349 """
350 return Py_BuildValue("NN",
351 PyLong_FromUnicodeObject(args, 10),
352 PyLong_FromUnicodeObject(args, 16));
353 """),
354 ])
355 # A string with arabic digits.
356 assert (module.from_unicodeobject(u' 1\u0662\u0663\u0664')
357 == (1234, 4660))
358
359 def test_aslong(self):
360 module = self.import_extension('foo', [
361 ("as_long", "METH_O",
362 """
363 long n = PyLong_AsLong(args);
364 if (n == -1 && PyErr_Occurred()) {
365 return NULL;
366 }
367 return PyLong_FromLong(n);
368 """),
369 ("as_int", "METH_O",
370 """
371 int n = _PyLong_AsInt(args);
372 if (n == -1 && PyErr_Occurred()) {
373 return NULL;
374 }
375 return PyLong_FromLong(n);
376 """),
377 ("long_max", "METH_NOARGS",
378 """
379 return PyLong_FromLong(LONG_MAX);
380 """
381 ),
382 ("long_min", "METH_NOARGS",
383 """
384 return PyLong_FromLong(LONG_MIN);
385 """
386 ),
387 ("int_max", "METH_NOARGS",
388 """
389 return PyLong_FromLong(INT_MAX);
390 """
391 ),
392 ("int_min", "METH_NOARGS",
393 """
394 return PyLong_FromLong(INT_MIN);
395 """
396 ),
397 ("as_unsignedlongmask", "METH_O",
398 """
399 unsigned long n = PyLong_AsUnsignedLongMask(args);
400 if (n == (unsigned long)-1 && PyErr_Occurred()) {
401 return NULL;
402 }
403 return PyLong_FromLong(n);
404 """),
405 ])
406 module.as_long(123) == 123
407 assert module.as_long(-1) == -1
408 with raises(TypeError):
409 module.as_long(1.23) == 1
410 LONG_MAX = module.long_max()
411 LONG_MIN = module.long_min()
412 assert module.as_long(LONG_MAX) == LONG_MAX
413 raises(OverflowError, module.as_long, LONG_MAX+ 1)
414 assert module.as_long(LONG_MIN) == LONG_MIN
415 raises(OverflowError, module.as_long, LONG_MIN - 1)
416 # does not raise
417 module.as_unsignedlongmask(LONG_MAX * 10)
418
419 class A:
420 def __index__(self):
421 return 42
422
423 def __int__(self):
424 return 21
425
426 class B():
427 def __int__(self):
428 return 21
429
430 a = A()
431 b = B()
432 assert int(a) == 21
433 # new for python3.8: first try __index__
434 assert module.as_long(a) == 42
435 assert module.as_unsignedlongmask(a) == 42
436 with raises(TypeError):
437 module.as_long(b)
438 with raises(TypeError):
439 module.as_unsignedlongmask(b)
440 assert module.as_int(123) == 123
441 assert module.as_int(-1) == -1
442 with raises(TypeError):
443 module.as_int(1.23) == 1
444 INT_MAX = module.int_max()
445 INT_MIN = module.int_min()
446 assert module.as_int(INT_MAX) == INT_MAX
447 raises(OverflowError, module.as_int, INT_MAX+ 1)
448 assert module.as_int(INT_MIN) == INT_MIN
449 raises(OverflowError, module.as_int, INT_MIN - 1)
450 assert int(a) == 21
451 # new for python3.8: first try __index__
452 assert module.as_int(a) == 42
453
454 def test_strtol(self):
455 module = self.import_extension('foo', [
456 ("from_str", "METH_NOARGS",
457 """
458 const char *str =" 400";
459 char * end;
460 if (400 != PyOS_strtoul(str, &end, 10))
461 return PyLong_FromLong(1);
462 if (str + strlen(str) != end)
463 return PyLong_FromLong(2);
464 if (400 != PyOS_strtol(str, &end, 10))
465 return PyLong_FromLong(3);
466 if (str + strlen(str) != end)
467 return PyLong_FromLong(4);
468 return PyLong_FromLong(0);
469 """)])
470 assert module.from_str() == 0
471
472 def test_slots(self):
473 module = self.import_extension('foo', [
474 ("has_sub", "METH_NOARGS",
475 """
476 PyObject *ret, *obj = PyLong_FromLong(42);
477 if (obj->ob_type != &PyLong_Type)
478 ret = PyLong_FromLong(-2);
479 else
480 {
481 if (obj->ob_type->tp_as_number->nb_subtract)
482 ret = obj->ob_type->tp_as_number->nb_subtract(obj, obj);
483 else
484 ret = PyLong_FromLong(-1);
485 }
486 Py_DECREF(obj);
487 return ret;
488 """),
489 ("has_pow", "METH_NOARGS",
490 """
491 PyObject *ret, *obj = PyLong_FromLong(42);
492 PyObject *one = PyLong_FromLong(1);
493 if (obj->ob_type->tp_as_number->nb_power)
494 ret = obj->ob_type->tp_as_number->nb_power(obj, one, one);
495 else
496 ret = PyLong_FromLong(-1);
497 Py_DECREF(one);
498 Py_DECREF(obj);
499 return ret;
500 """)])
501 assert module.has_sub() == 0
502 assert module.has_pow() == 0
503
504 def test_PyLong_AsUnsignedLongLongMask(self):
505 module = self.import_extension('foo', [
506 ("aslongmask", "METH_O",
507 """
508 uint64_t ret = PyLong_AsUnsignedLongMask(args);
509 if (!ret) return NULL;
510 return PyLong_FromLong(ret);
511 """),
512 ])
513 assert module.aslongmask(3) == 3
514
515 def test_as_longlong_and_overflow(self):
516 module = self.import_extension('foo', [
517 ("aslonglong_overflow", "METH_O",
518 """
519 int overflow=0;
520 long long ret = PyLong_AsLongLongAndOverflow(args, &overflow);
521 return PyTuple_Pack(2, PyLong_FromLongLong(ret), PyLong_FromLong(overflow));
522 """),
523 ])
524 assert module.aslonglong_overflow(1<<62) == (1<<62, 0)
525 assert module.aslonglong_overflow(1<<63) == (-1, 1)
526 assert module.aslonglong_overflow(-1<<64) == (-1, -1)