Debian Codegraph @

src/c/test_c.py

raw
1 from __future__ import annotations
2
3 import contextlib
4 import traceback
5 import unittest.mock
6
7 import pytest
8 import sys
9 import typing as t
10
11 is_musl = False
12 if sys.platform == 'linux':
13 try:
14 from packaging.tags import platform_tags
15 is_musl = any(t.startswith('musllinux') for t in platform_tags())
16 del platform_tags
17 except ImportError:
18 pass
19
20 is_ios = sys.platform == 'ios'
21
22
23 def _setup_path():
24 import os, sys
25 sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
26 _setup_path()
27 from _cffi_backend import *
28 from _cffi_backend import _get_types, _get_common_types
29 try:
30 from _cffi_backend import _testfunc
31 except ImportError:
32 def _testfunc(num):
33 pytest.skip("_testunc() not available")
34 from _cffi_backend import __version__
35
36
37 @contextlib.contextmanager
38 def _assert_unraisable(error_type: type[Exception] | None, message: str = '', traceback_tokens: list[str] | None = None):
39 """Assert that a given sys.unraisablehook interaction occurred (or did not occur, if error_type is None) while this context was active"""
40 raised_errors: list[Exception] = []
41 raised_traceback: str = ''
42
43 # sys.unraisablehook is called more than once for chained exceptions; accumulate the errors and tracebacks for inspection
44 def _capture_unraisable_hook(ur_args):
45 nonlocal raised_traceback
46 raised_errors.append(ur_args.exc_value)
47
48 # NB: need to use the old etype/value/tb form until 3.10 is the minimum
49 raised_traceback += (ur_args.err_msg or '' + '\n') + ''.join(traceback.format_exception(None, ur_args.exc_value, ur_args.exc_traceback))
50
51
52 with pytest.MonkeyPatch.context() as mp:
53 mp.setattr(sys, 'unraisablehook', _capture_unraisable_hook)
54 yield
55
56 if error_type is None:
57 assert not raised_errors
58 assert not raised_traceback
59 return
60
61 assert any(type(raised_error) is error_type for raised_error in raised_errors)
62 assert any(message in str(raised_error) for raised_error in raised_errors)
63 for t in traceback_tokens or []:
64 assert t in raised_traceback
65
66 # ____________________________________________________________
67
68 import sys
69 assert __version__ == "2.1.1", ("This test_c.py file is for testing a version"
70 " of cffi that differs from the one that we"
71 " get from 'import _cffi_backend'")
72 if sys.version_info < (3,):
73 type_or_class = "type"
74 mandatory_b_prefix = ''
75 mandatory_u_prefix = 'u'
76 bytechr = chr
77 bitem2bchr = lambda x: x
78 class U:
79 def __add__(self, other):
80 return eval('u'+repr(other).replace(r'\\u', r'\u')
81 .replace(r'\\U', r'\U'))
82 u = U()
83 str2bytes = str
84 strict_compare = False
85 else:
86 type_or_class = "class"
87 long = int
88 unicode = str
89 unichr = chr
90 mandatory_b_prefix = 'b'
91 mandatory_u_prefix = ''
92 bytechr = lambda n: bytes([n])
93 bitem2bchr = bytechr
94 u = ""
95 str2bytes = lambda s: bytes(s, "ascii")
96 strict_compare = True
97
98 def size_of_int():
99 BInt = new_primitive_type("int")
100 return sizeof(BInt)
101
102 def size_of_long():
103 BLong = new_primitive_type("long")
104 return sizeof(BLong)
105
106 def size_of_ptr():
107 BInt = new_primitive_type("int")
108 BPtr = new_pointer_type(BInt)
109 return sizeof(BPtr)
110
111
112 def find_and_load_library(name, flags=RTLD_NOW):
113 import ctypes.util
114 if name is None:
115 path = None
116 else:
117 path = ctypes.util.find_library(name)
118 if path is None and sys.platform == 'darwin' and sys.version_info[:2] == (3, 8):
119 pytest.xfail("find_library usually broken on MacOS Python 3.8")
120 if path is None and name == 'c':
121 assert sys.platform == 'win32'
122 assert (sys.version_info >= (3,) or
123 '__pypy__' in sys.builtin_module_names)
124 pytest.skip("dlopen(None) cannot work on Windows "
125 "with PyPy or Python 3")
126 return load_library(path, flags)
127
128 def test_load_library():
129 x = find_and_load_library('c')
130 assert repr(x).startswith("<clibrary '")
131 x = find_and_load_library('c', RTLD_NOW | RTLD_GLOBAL)
132 assert repr(x).startswith("<clibrary '")
133 x = find_and_load_library('c', RTLD_LAZY)
134 assert repr(x).startswith("<clibrary '")
135
136 def test_all_rtld_symbols():
137 import sys
138 FFI_DEFAULT_ABI # these symbols must be defined
139 FFI_CDECL
140 RTLD_LAZY
141 RTLD_NOW
142 RTLD_GLOBAL
143 RTLD_LOCAL
144 if sys.platform.startswith("linux"):
145 RTLD_NODELETE
146 RTLD_NOLOAD
147 if not is_musl:
148 RTLD_DEEPBIND
149
150 def test_new_primitive_type():
151 pytest.raises(KeyError, new_primitive_type, "foo")
152 p = new_primitive_type("signed char")
153 assert repr(p) == "<ctype 'signed char'>"
154
155 def check_dir(p, expected):
156 got = [name for name in dir(p) if not name.startswith('_')]
157 assert got == sorted(expected)
158
159 def test_inspect_primitive_type():
160 p = new_primitive_type("signed char")
161 assert p.kind == "primitive"
162 assert p.cname == "signed char"
163 check_dir(p, ['cname', 'kind'])
164
165 def test_cast_to_signed_char():
166 p = new_primitive_type("signed char")
167 x = cast(p, -65 + 17*256)
168 assert repr(x) == "<cdata 'signed char' -65>"
169 assert repr(type(x)) == "<%s '_cffi_backend._CDataBase'>" % type_or_class
170 assert int(x) == -65
171 x = cast(p, -66 + (1<<199)*256)
172 assert repr(x) == "<cdata 'signed char' -66>"
173 assert int(x) == -66
174 assert (x == cast(p, -66)) is True
175 assert (x != cast(p, -66)) is False
176 q = new_primitive_type("short")
177 assert (x == cast(q, -66)) is True
178 assert (x != cast(q, -66)) is False
179
180 def test_sizeof_type():
181 pytest.raises(TypeError, sizeof, 42.5)
182 p = new_primitive_type("short")
183 assert sizeof(p) == 2
184
185 def test_integer_types():
186 for name in ['signed char', 'short', 'int', 'long', 'long long']:
187 p = new_primitive_type(name)
188 size = sizeof(p)
189 min = -(1 << (8*size-1))
190 max = (1 << (8*size-1)) - 1
191 assert int(cast(p, min)) == min
192 assert int(cast(p, max)) == max
193 assert int(cast(p, min - 1)) == max
194 assert int(cast(p, max + 1)) == min
195 pytest.raises(TypeError, cast, p, None)
196 assert long(cast(p, min - 1)) == max
197 assert int(cast(p, b'\x08')) == 8
198 assert int(cast(p, u+'\x08')) == 8
199 for name in ['char', 'short', 'int', 'long', 'long long']:
200 p = new_primitive_type('unsigned ' + name)
201 size = sizeof(p)
202 max = (1 << (8*size)) - 1
203 assert int(cast(p, 0)) == 0
204 assert int(cast(p, max)) == max
205 assert int(cast(p, -1)) == max
206 assert int(cast(p, max + 1)) == 0
207 assert long(cast(p, -1)) == max
208 assert int(cast(p, b'\xFE')) == 254
209 assert int(cast(p, u+'\xFE')) == 254
210
211 def test_no_float_on_int_types():
212 p = new_primitive_type('long')
213 pytest.raises(TypeError, float, cast(p, 42))
214 pytest.raises(TypeError, complex, cast(p, 42))
215
216 def test_float_types():
217 INF = 1E200 * 1E200
218 for name in ["float", "double"]:
219 p = new_primitive_type(name)
220 assert bool(cast(p, 0)) is False # since 1.7
221 assert bool(cast(p, -0.0)) is False # since 1.7
222 assert bool(cast(p, 1e-42)) is True
223 assert bool(cast(p, -1e-42)) is True
224 assert bool(cast(p, INF))
225 assert bool(cast(p, -INF))
226 assert bool(cast(p, float("nan")))
227 assert int(cast(p, -150)) == -150
228 assert int(cast(p, 61.91)) == 61
229 assert long(cast(p, 61.91)) == 61
230 assert type(int(cast(p, 61.91))) is int
231 assert type(int(cast(p, 1E22))) is long
232 assert type(long(cast(p, 61.91))) is long
233 assert type(long(cast(p, 1E22))) is long
234 pytest.raises(OverflowError, int, cast(p, INF))
235 pytest.raises(OverflowError, int, cast(p, -INF))
236 assert float(cast(p, 1.25)) == 1.25
237 assert float(cast(p, INF)) == INF
238 assert float(cast(p, -INF)) == -INF
239 if name == "float":
240 assert float(cast(p, 1.1)) != 1.1 # rounding error
241 assert float(cast(p, 1E200)) == INF # limited range
242
243 assert cast(p, -1.1) == cast(p, -1.1)
244 assert repr(float(cast(p, -0.0))) == '-0.0'
245 assert float(cast(p, b'\x09')) == 9.0
246 assert float(cast(p, u+'\x09')) == 9.0
247 assert float(cast(p, True)) == 1.0
248 pytest.raises(TypeError, cast, p, None)
249
250 def test_complex_types():
251 INF = 1E200 * 1E200
252 for name in ["float", "double"]:
253 p = new_primitive_type("_cffi_" + name + "_complex_t")
254 assert bool(cast(p, 0)) is False
255 assert bool(cast(p, INF))
256 assert bool(cast(p, -INF))
257 assert bool(cast(p, 0j)) is False
258 assert bool(cast(p, INF*1j))
259 assert bool(cast(p, -INF*1j))
260 # "can't convert complex to float", like CPython's "float(0j)"
261 pytest.raises(TypeError, int, cast(p, -150))
262 pytest.raises(TypeError, long, cast(p, -150))
263 pytest.raises(TypeError, float, cast(p, -150))
264 assert complex(cast(p, 1.25)) == 1.25
265 assert complex(cast(p, 1.25j)) == 1.25j
266 assert complex(cast(p, complex(0,INF))) == complex(0,INF)
267 assert complex(cast(p, -INF)) == -INF
268 if name == "float":
269 assert complex(cast(p, 1.1j)) != 1.1j # rounding error
270 assert complex(cast(p, 1E200+3j)) == INF+3j # limited range
271 assert complex(cast(p, complex(3,1E200))) == complex(3,INF) # limited range
272
273 assert cast(p, -1.1j) == cast(p, -1.1j)
274 assert repr(complex(cast(p, -0.0)).real) == '-0.0'
275 #assert repr(complex(cast(p, -0j))) == '-0j' # http://bugs.python.org/issue29602
276 assert complex(cast(p, b'\x09')) == 9.0 + 0j
277 assert complex(cast(p, u+'\x09')) == 9.0 + 0j
278 assert complex(cast(p, True)) == 1.0 + 0j
279 pytest.raises(TypeError, cast, p, None)
280 #
281 pytest.raises(TypeError, cast, new_primitive_type(name), 1+0j)
282 #
283 for basetype in ["char", "int", "uint64_t", "float",
284 "double", "long double"]:
285 baseobj = cast(new_primitive_type(basetype), 65)
286 pytest.raises(TypeError, complex, baseobj)
287 #
288 BArray = new_array_type(new_pointer_type(p), 10)
289 x = newp(BArray, None)
290 x[5] = 12.34 + 56.78j
291 assert type(x[5]) is complex
292 assert abs(x[5] - (12.34 + 56.78j)) < 1e-5
293 assert (x[5] == 12.34 + 56.78j) == (name == "double") # rounding error
294 #
295 class Foo:
296 def __complex__(self):
297 return 2 + 3j
298 assert complex(Foo()) == 2 + 3j
299 assert complex(cast(p, Foo())) == 2 + 3j
300 pytest.raises(TypeError, cast, new_primitive_type("int"), 1+0j)
301
302 def test_character_type():
303 p = new_primitive_type("char")
304 assert bool(cast(p, 'A')) is True
305 assert bool(cast(p, '\x00')) is False # since 1.7
306 assert cast(p, '\x00') == cast(p, -17*256)
307 assert int(cast(p, 'A')) == 65
308 assert long(cast(p, 'A')) == 65
309 assert type(int(cast(p, 'A'))) is int
310 assert type(long(cast(p, 'A'))) is long
311 assert str(cast(p, 'A')) == repr(cast(p, 'A'))
312 assert repr(cast(p, 'A')) == "<cdata 'char' %s'A'>" % mandatory_b_prefix
313 assert repr(cast(p, 255)) == r"<cdata 'char' %s'\xff'>" % mandatory_b_prefix
314 assert repr(cast(p, 0)) == r"<cdata 'char' %s'\x00'>" % mandatory_b_prefix
315
316 def test_pointer_type():
317 p = new_primitive_type("int")
318 assert repr(p) == "<ctype 'int'>"
319 p = new_pointer_type(p)
320 assert repr(p) == "<ctype 'int *'>"
321 p = new_pointer_type(p)
322 assert repr(p) == "<ctype 'int * *'>"
323 p = new_pointer_type(p)
324 assert repr(p) == "<ctype 'int * * *'>"
325
326 def test_inspect_pointer_type():
327 p1 = new_primitive_type("int")
328 p2 = new_pointer_type(p1)
329 assert p2.kind == "pointer"
330 assert p2.cname == "int *"
331 assert p2.item is p1
332 check_dir(p2, ['cname', 'kind', 'item'])
333 p3 = new_pointer_type(p2)
334 assert p3.item is p2
335
336 def test_pointer_to_int():
337 BInt = new_primitive_type("int")
338 pytest.raises(TypeError, newp, BInt)
339 pytest.raises(TypeError, newp, BInt, None)
340 BPtr = new_pointer_type(BInt)
341 p = newp(BPtr)
342 assert repr(p) == "<cdata 'int *' owning %d bytes>" % size_of_int()
343 p = newp(BPtr, None)
344 assert repr(p) == "<cdata 'int *' owning %d bytes>" % size_of_int()
345 p = newp(BPtr, 5000)
346 assert repr(p) == "<cdata 'int *' owning %d bytes>" % size_of_int()
347 q = cast(BPtr, p)
348 assert repr(q).startswith("<cdata 'int *' 0x")
349 assert p == q
350 assert hash(p) == hash(q)
351 e = pytest.raises(TypeError, newp, new_array_type(BPtr, None), None)
352 assert str(e.value) == (
353 "expected new array length or list/tuple/str, not NoneType")
354
355 def test_pointer_bool():
356 BInt = new_primitive_type("int")
357 BPtr = new_pointer_type(BInt)
358 p = cast(BPtr, 0)
359 assert bool(p) is False
360 p = cast(BPtr, 42)
361 assert bool(p) is True
362
363 def test_pointer_to_pointer():
364 BInt = new_primitive_type("int")
365 BPtr = new_pointer_type(BInt)
366 BPtrPtr = new_pointer_type(BPtr)
367 p = newp(BPtrPtr, None)
368 assert repr(p) == "<cdata 'int * *' owning %d bytes>" % size_of_ptr()
369
370 def test_reading_pointer_to_int():
371 BInt = new_primitive_type("int")
372 BPtr = new_pointer_type(BInt)
373 p = newp(BPtr, None)
374 assert p[0] == 0
375 p = newp(BPtr, 5000)
376 assert p[0] == 5000
377 with pytest.raises(IndexError):
378 p[1]
379 with pytest.raises(IndexError):
380 p[-1]
381
382 def test_reading_pointer_to_float():
383 BFloat = new_primitive_type("float")
384 pytest.raises(TypeError, newp, BFloat, None)
385 BPtr = new_pointer_type(BFloat)
386 p = newp(BPtr, None)
387 assert p[0] == 0.0 and type(p[0]) is float
388 p = newp(BPtr, 1.25)
389 assert p[0] == 1.25 and type(p[0]) is float
390 p = newp(BPtr, 1.1)
391 assert p[0] != 1.1 and abs(p[0] - 1.1) < 1E-5 # rounding errors
392
393 def test_cast_float_to_int():
394 for type in ["int", "unsigned int", "long", "unsigned long",
395 "long long", "unsigned long long"]:
396 p = new_primitive_type(type)
397 assert int(cast(p, 4.2)) == 4
398 pytest.raises(TypeError, newp, new_pointer_type(p), 4.2)
399
400 def test_newp_integer_types():
401 for name in ['signed char', 'short', 'int', 'long', 'long long']:
402 p = new_primitive_type(name)
403 pp = new_pointer_type(p)
404 size = sizeof(p)
405 min = -(1 << (8*size-1))
406 max = (1 << (8*size-1)) - 1
407 assert newp(pp, min)[0] == min
408 assert newp(pp, max)[0] == max
409 pytest.raises(OverflowError, newp, pp, min - 2 ** 32)
410 pytest.raises(OverflowError, newp, pp, min - 2 ** 64)
411 pytest.raises(OverflowError, newp, pp, max + 2 ** 32)
412 pytest.raises(OverflowError, newp, pp, max + 2 ** 64)
413 pytest.raises(OverflowError, newp, pp, min - 1)
414 pytest.raises(OverflowError, newp, pp, max + 1)
415 pytest.raises(OverflowError, newp, pp, min - 1 - 2 ** 32)
416 pytest.raises(OverflowError, newp, pp, min - 1 - 2 ** 64)
417 pytest.raises(OverflowError, newp, pp, max + 1)
418 pytest.raises(OverflowError, newp, pp, max + 1 + 2 ** 32)
419 pytest.raises(OverflowError, newp, pp, max + 1 + 2 ** 64)
420 pytest.raises(TypeError, newp, pp, 1.0)
421 for name in ['char', 'short', 'int', 'long', 'long long']:
422 p = new_primitive_type('unsigned ' + name)
423 pp = new_pointer_type(p)
424 size = sizeof(p)
425 max = (1 << (8*size)) - 1
426 assert newp(pp, 0)[0] == 0
427 assert newp(pp, max)[0] == max
428 pytest.raises(OverflowError, newp, pp, -1)
429 pytest.raises(OverflowError, newp, pp, max + 1)
430
431 def test_reading_pointer_to_char():
432 BChar = new_primitive_type("char")
433 pytest.raises(TypeError, newp, BChar, None)
434 BPtr = new_pointer_type(BChar)
435 p = newp(BPtr, None)
436 assert p[0] == b'\x00'
437 p = newp(BPtr, b'A')
438 assert p[0] == b'A'
439 pytest.raises(TypeError, newp, BPtr, 65)
440 pytest.raises(TypeError, newp, BPtr, b"foo")
441 pytest.raises(TypeError, newp, BPtr, u+"foo")
442 c = cast(BChar, b'A')
443 assert str(c) == repr(c)
444 assert int(c) == ord(b'A')
445 pytest.raises(TypeError, cast, BChar, b'foo')
446 pytest.raises(TypeError, cast, BChar, u+'foo')
447 e = pytest.raises(TypeError, newp, new_array_type(BPtr, None), 12.3)
448 assert str(e.value) == (
449 "expected new array length or list/tuple/str, not float")
450
451 def test_reading_pointer_to_pointer():
452 BVoidP = new_pointer_type(new_void_type())
453 BCharP = new_pointer_type(new_primitive_type("char"))
454 BInt = new_primitive_type("int")
455 BIntPtr = new_pointer_type(BInt)
456 BIntPtrPtr = new_pointer_type(BIntPtr)
457 q = newp(BIntPtr, 42)
458 assert q[0] == 42
459 p = newp(BIntPtrPtr, None)
460 assert p[0] is not None
461 assert p[0] == cast(BVoidP, 0)
462 assert p[0] == cast(BCharP, 0)
463 assert p[0] is not None
464 assert repr(p[0]) == "<cdata 'int *' NULL>"
465 p[0] = q
466 assert p[0] != cast(BVoidP, 0)
467 assert p[0] != cast(BCharP, 0)
468 assert p[0][0] == 42
469 q[0] += 1
470 assert p[0][0] == 43
471 p = newp(BIntPtrPtr, q)
472 assert p[0][0] == 43
473
474 def test_load_standard_library():
475 if sys.platform == "win32":
476 pytest.raises(OSError, find_and_load_library, None)
477 return
478 x = find_and_load_library(None)
479 BVoidP = new_pointer_type(new_void_type())
480 assert x.load_function(BVoidP, 'strcpy')
481 pytest.raises(AttributeError, x.load_function,
482 BVoidP, 'xxx_this_function_does_not_exist')
483 # the next one is from 'libm', not 'libc', but we assume
484 # that it is already loaded too, so it should work
485 assert x.load_function(BVoidP, 'sqrt')
486 #
487 x.close_lib()
488 pytest.raises(ValueError, x.load_function, BVoidP, 'sqrt')
489 x.close_lib()
490
491 def test_no_len_on_nonarray():
492 p = new_primitive_type("int")
493 pytest.raises(TypeError, len, cast(p, 42))
494
495 def test_cmp_none():
496 p = new_primitive_type("int")
497 x = cast(p, 42)
498 assert (x is None) is False
499 assert (x is not None) is True
500 assert (x == ["hello"]) is False
501 assert (x != ["hello"]) is True
502 y = cast(p, 0)
503 assert (y is None) is False
504
505 def test_invalid_indexing():
506 p = new_primitive_type("int")
507 x = cast(p, 42)
508 with pytest.raises(TypeError):
509 x[0]
510
511 def test_default_str():
512 BChar = new_primitive_type("char")
513 x = cast(BChar, 42)
514 assert str(x) == repr(x)
515 BInt = new_primitive_type("int")
516 x = cast(BInt, 42)
517 assert str(x) == repr(x)
518 BArray = new_array_type(new_pointer_type(BInt), 10)
519 x = newp(BArray, None)
520 assert str(x) == repr(x)
521
522 def test_default_unicode():
523 BInt = new_primitive_type("int")
524 x = cast(BInt, 42)
525 assert unicode(x) == unicode(repr(x))
526 BArray = new_array_type(new_pointer_type(BInt), 10)
527 x = newp(BArray, None)
528 assert unicode(x) == unicode(repr(x))
529
530 def test_cast_from_cdataint():
531 BInt = new_primitive_type("int")
532 x = cast(BInt, 0)
533 y = cast(new_pointer_type(BInt), x)
534 assert bool(y) is False
535 #
536 x = cast(BInt, 42)
537 y = cast(BInt, x)
538 assert int(y) == 42
539 y = cast(new_primitive_type("char"), x)
540 assert int(y) == 42
541 y = cast(new_primitive_type("float"), x)
542 assert float(y) == 42.0
543 #
544 z = cast(BInt, 42.5)
545 assert int(z) == 42
546 z = cast(BInt, y)
547 assert int(z) == 42
548
549 def test_void_type():
550 p = new_void_type()
551 assert p.kind == "void"
552 assert p.cname == "void"
553 check_dir(p, ['kind', 'cname'])
554
555 def test_array_type():
556 p = new_primitive_type("int")
557 assert repr(p) == "<ctype 'int'>"
558 #
559 pytest.raises(TypeError, new_array_type, new_pointer_type(p), "foo")
560 pytest.raises(ValueError, new_array_type, new_pointer_type(p), -42)
561 #
562 p1 = new_array_type(new_pointer_type(p), None)
563 assert repr(p1) == "<ctype 'int[]'>"
564 pytest.raises(ValueError, new_array_type, new_pointer_type(p1), 42)
565 #
566 p1 = new_array_type(new_pointer_type(p), 42)
567 p2 = new_array_type(new_pointer_type(p1), 25)
568 assert repr(p2) == "<ctype 'int[25][42]'>"
569 p2 = new_array_type(new_pointer_type(p1), None)
570 assert repr(p2) == "<ctype 'int[][42]'>"
571 #
572 pytest.raises(OverflowError,
573 new_array_type, new_pointer_type(p), sys.maxsize+1)
574 pytest.raises(OverflowError,
575 new_array_type, new_pointer_type(p), sys.maxsize // 3)
576
577 def test_inspect_array_type():
578 p = new_primitive_type("int")
579 p1 = new_array_type(new_pointer_type(p), None)
580 assert p1.kind == "array"
581 assert p1.cname == "int[]"
582 assert p1.item is p
583 assert p1.length is None
584 check_dir(p1, ['cname', 'kind', 'item', 'length'])
585 p1 = new_array_type(new_pointer_type(p), 42)
586 assert p1.kind == "array"
587 assert p1.cname == "int[42]"
588 assert p1.item is p
589 assert p1.length == 42
590 check_dir(p1, ['cname', 'kind', 'item', 'length'])
591
592 def test_array_instance():
593 LENGTH = 1423
594 p = new_primitive_type("int")
595 p1 = new_array_type(new_pointer_type(p), LENGTH)
596 a = newp(p1, None)
597 assert repr(a) == "<cdata 'int[%d]' owning %d bytes>" % (
598 LENGTH, LENGTH * size_of_int())
599 assert len(a) == LENGTH
600 for i in range(LENGTH):
601 assert a[i] == 0
602 with pytest.raises(IndexError):
603 a[LENGTH]
604 with pytest.raises(IndexError):
605 a[-1]
606 for i in range(LENGTH):
607 a[i] = i * i + 1
608 for i in range(LENGTH):
609 assert a[i] == i * i + 1
610 with pytest.raises(IndexError) as e:
611 a[LENGTH+100] = 500
612 assert ('(expected %d < %d)' % (LENGTH+100, LENGTH)) in str(e.value)
613 pytest.raises(TypeError, int, a)
614
615 def test_array_of_unknown_length_instance():
616 p = new_primitive_type("int")
617 p1 = new_array_type(new_pointer_type(p), None)
618 pytest.raises(TypeError, newp, p1, None)
619 pytest.raises(ValueError, newp, p1, -42)
620 a = newp(p1, 42)
621 assert len(a) == 42
622 for i in range(42):
623 a[i] -= i
624 for i in range(42):
625 assert a[i] == -i
626 with pytest.raises(IndexError):
627 a[42]
628 with pytest.raises(IndexError):
629 a[-1]
630 with pytest.raises(IndexError):
631 a[42] = 123
632 with pytest.raises(IndexError):
633 a[-1] = 456
634
635 def test_array_of_unknown_length_instance_with_initializer():
636 p = new_primitive_type("int")
637 p1 = new_array_type(new_pointer_type(p), None)
638 a = newp(p1, list(range(42)))
639 assert len(a) == 42
640 a = newp(p1, tuple(range(142)))
641 assert len(a) == 142
642
643 def test_array_initializer():
644 p = new_primitive_type("int")
645 p1 = new_array_type(new_pointer_type(p), None)
646 a = newp(p1, list(range(100, 142)))
647 for i in range(42):
648 assert a[i] == 100 + i
649 #
650 p2 = new_array_type(new_pointer_type(p), 43)
651 a = newp(p2, tuple(range(100, 142)))
652 for i in range(42):
653 assert a[i] == 100 + i
654 assert a[42] == 0 # extra uninitialized item
655
656 def test_array_add():
657 p = new_primitive_type("int")
658 p1 = new_array_type(new_pointer_type(p), 5) # int[5]
659 p2 = new_array_type(new_pointer_type(p1), 3) # int[3][5]
660 a = newp(p2, [list(range(n, n+5)) for n in [100, 200, 300]])
661 assert repr(a) == "<cdata 'int[3][5]' owning %d bytes>" % (
662 3*5*size_of_int(),)
663 assert repr(a + 0).startswith("<cdata 'int(*)[5]' 0x")
664 assert 0 + a == a + 0 != 1 + a == a + 1
665 assert repr(a[0]).startswith("<cdata 'int[5]' 0x")
666 assert repr((a + 0)[0]).startswith("<cdata 'int[5]' 0x")
667 assert repr(a[0] + 0).startswith("<cdata 'int *' 0x")
668 assert type(a[0][0]) is int
669 assert type((a[0] + 0)[0]) is int
670
671 def test_array_sub():
672 BInt = new_primitive_type("int")
673 BArray = new_array_type(new_pointer_type(BInt), 5) # int[5]
674 a = newp(BArray, None)
675 p = a + 1
676 assert p - a == 1
677 assert p - (a+0) == 1
678 assert a == (p - 1)
679 BPtr = new_pointer_type(new_primitive_type("short"))
680 q = newp(BPtr, None)
681 with pytest.raises(TypeError):
682 p - q
683 with pytest.raises(TypeError):
684 q - p
685 with pytest.raises(TypeError):
686 a - q
687 with pytest.raises(TypeError) as e:
688 q - a
689 assert str(e.value) == "cannot subtract cdata 'short *' and cdata 'int *'"
690
691 def test_ptr_sub_unaligned():
692 BInt = new_primitive_type("int")
693 BIntPtr = new_pointer_type(BInt)
694 a = cast(BIntPtr, 1240)
695 for bi in range(1430, 1438):
696 b = cast(BIntPtr, bi)
697 if ((bi - 1240) % size_of_int()) == 0:
698 assert b - a == (bi - 1240) // size_of_int()
699 assert a - b == (1240 - bi) // size_of_int()
700 else:
701 with pytest.raises(ValueError):
702 b - a
703 with pytest.raises(ValueError):
704 a - b
705
706 def test_cast_primitive_from_cdata():
707 p = new_primitive_type("int")
708 n = cast(p, cast(p, -42))
709 assert int(n) == -42
710 #
711 p = new_primitive_type("unsigned int")
712 n = cast(p, cast(p, 42))
713 assert int(n) == 42
714 #
715 p = new_primitive_type("long long")
716 n = cast(p, cast(p, -(1<<60)))
717 assert int(n) == -(1<<60)
718 #
719 p = new_primitive_type("unsigned long long")
720 n = cast(p, cast(p, 1<<63))
721 assert int(n) == 1<<63
722 #
723 p = new_primitive_type("float")
724 n = cast(p, cast(p, 42.5))
725 assert float(n) == 42.5
726 #
727 p = new_primitive_type("char")
728 n = cast(p, cast(p, "A"))
729 assert int(n) == ord("A")
730
731 def test_new_primitive_from_cdata():
732 p = new_primitive_type("int")
733 p1 = new_pointer_type(p)
734 n = newp(p1, cast(p, -42))
735 assert n[0] == -42
736 #
737 p = new_primitive_type("unsigned int")
738 p1 = new_pointer_type(p)
739 n = newp(p1, cast(p, 42))
740 assert n[0] == 42
741 #
742 p = new_primitive_type("float")
743 p1 = new_pointer_type(p)
744 n = newp(p1, cast(p, 42.5))
745 assert n[0] == 42.5
746 #
747 p = new_primitive_type("char")
748 p1 = new_pointer_type(p)
749 n = newp(p1, cast(p, "A"))
750 assert n[0] == b"A"
751
752 def test_cast_between_pointers():
753 BIntP = new_pointer_type(new_primitive_type("int"))
754 BIntA = new_array_type(BIntP, None)
755 a = newp(BIntA, [40, 41, 42, 43, 44])
756 BShortP = new_pointer_type(new_primitive_type("short"))
757 b = cast(BShortP, a)
758 c = cast(BIntP, b)
759 assert c[3] == 43
760 BLongLong = new_primitive_type("long long")
761 d = cast(BLongLong, c)
762 e = cast(BIntP, d)
763 assert e[3] == 43
764 f = cast(BIntP, int(d))
765 assert f[3] == 43
766 #
767 b = cast(BShortP, 0)
768 assert not b
769 c = cast(BIntP, b)
770 assert not c
771 assert int(cast(BLongLong, c)) == 0
772
773 def test_alignof():
774 BInt = new_primitive_type("int")
775 assert alignof(BInt) == sizeof(BInt)
776 BPtr = new_pointer_type(BInt)
777 assert alignof(BPtr) == sizeof(BPtr)
778 BArray = new_array_type(BPtr, None)
779 assert alignof(BArray) == alignof(BInt)
780
781 def test_new_struct_type():
782 BStruct = new_struct_type("foo")
783 assert repr(BStruct) == "<ctype 'foo'>"
784 BStruct = new_struct_type("struct foo")
785 assert repr(BStruct) == "<ctype 'struct foo'>"
786 BPtr = new_pointer_type(BStruct)
787 assert repr(BPtr) == "<ctype 'struct foo *'>"
788 pytest.raises(ValueError, sizeof, BStruct)
789 pytest.raises(ValueError, alignof, BStruct)
790
791 def test_new_union_type():
792 BUnion = new_union_type("union foo")
793 assert repr(BUnion) == "<ctype 'union foo'>"
794 BPtr = new_pointer_type(BUnion)
795 assert repr(BPtr) == "<ctype 'union foo *'>"
796
797 def test_complete_struct():
798 BLong = new_primitive_type("long")
799 BChar = new_primitive_type("char")
800 BShort = new_primitive_type("short")
801 BStruct = new_struct_type("struct foo")
802 assert BStruct.kind == "struct"
803 assert BStruct.cname == "struct foo"
804 assert BStruct.fields is None
805 check_dir(BStruct, ['cname', 'kind', 'fields'])
806 #
807 complete_struct_or_union(BStruct, [('a1', BLong, -1),
808 ('a2', BChar, -1),
809 ('a3', BShort, -1)])
810 d = BStruct.fields
811 assert len(d) == 3
812 assert d[0][0] == 'a1'
813 assert d[0][1].type is BLong
814 assert d[0][1].offset == 0
815 assert d[0][1].bitshift == -1
816 assert d[0][1].bitsize == -1
817 assert d[1][0] == 'a2'
818 assert d[1][1].type is BChar
819 assert d[1][1].offset == sizeof(BLong)
820 assert d[1][1].bitshift == -1
821 assert d[1][1].bitsize == -1
822 assert d[2][0] == 'a3'
823 assert d[2][1].type is BShort
824 assert d[2][1].offset == sizeof(BLong) + sizeof(BShort)
825 assert d[2][1].bitshift == -1
826 assert d[2][1].bitsize == -1
827 assert sizeof(BStruct) == 2 * sizeof(BLong)
828 assert alignof(BStruct) == alignof(BLong)
829
830 def test_complete_union():
831 BLong = new_primitive_type("long")
832 BChar = new_primitive_type("char")
833 BUnion = new_union_type("union foo")
834 assert BUnion.kind == "union"
835 assert BUnion.cname == "union foo"
836 assert BUnion.fields is None
837 complete_struct_or_union(BUnion, [('a1', BLong, -1),
838 ('a2', BChar, -1)])
839 d = BUnion.fields
840 assert len(d) == 2
841 assert d[0][0] == 'a1'
842 assert d[0][1].type is BLong
843 assert d[0][1].offset == 0
844 assert d[1][0] == 'a2'
845 assert d[1][1].type is BChar
846 assert d[1][1].offset == 0
847 assert sizeof(BUnion) == sizeof(BLong)
848 assert alignof(BUnion) == alignof(BLong)
849
850 def test_struct_instance():
851 BInt = new_primitive_type("int")
852 BStruct = new_struct_type("struct foo")
853 BStructPtr = new_pointer_type(BStruct)
854 p = cast(BStructPtr, 42)
855 with pytest.raises(AttributeError) as e:
856 p.a1 # opaque
857 assert str(e.value) == ("cdata 'struct foo *' points to an opaque type: "
858 "cannot read fields")
859 with pytest.raises(AttributeError) as e:
860 p.a1 = 10 # opaque
861 assert str(e.value) == ("cdata 'struct foo *' points to an opaque type: "
862 "cannot write fields")
863
864 complete_struct_or_union(BStruct, [('a1', BInt, -1),
865 ('a2', BInt, -1)])
866 p = newp(BStructPtr, None)
867 s = p[0]
868 assert s.a1 == 0
869 s.a2 = 123
870 assert s.a1 == 0
871 assert s.a2 == 123
872 with pytest.raises(OverflowError):
873 s.a1 = sys.maxsize+1
874 assert s.a1 == 0
875 with pytest.raises(AttributeError) as e:
876 p.foobar
877 assert str(e.value) == "cdata 'struct foo *' has no field 'foobar'"
878 with pytest.raises(AttributeError) as e:
879 p.foobar = 42
880 assert str(e.value) == "cdata 'struct foo *' has no field 'foobar'"
881 with pytest.raises(AttributeError) as e:
882 s.foobar
883 assert str(e.value) == "cdata 'struct foo' has no field 'foobar'"
884 with pytest.raises(AttributeError) as e:
885 s.foobar = 42
886 assert str(e.value) == "cdata 'struct foo' has no field 'foobar'"
887 j = cast(BInt, 42)
888 with pytest.raises(AttributeError) as e:
889 j.foobar
890 assert str(e.value) == "cdata 'int' has no attribute 'foobar'"
891 with pytest.raises(AttributeError) as e:
892 j.foobar = 42
893 assert str(e.value) == "cdata 'int' has no attribute 'foobar'"
894 j = cast(new_pointer_type(BInt), 42)
895 with pytest.raises(AttributeError) as e:
896 j.foobar
897 assert str(e.value) == "cdata 'int *' has no attribute 'foobar'"
898 with pytest.raises(AttributeError) as e:
899 j.foobar = 42
900 assert str(e.value) == "cdata 'int *' has no attribute 'foobar'"
901 pp = newp(new_pointer_type(BStructPtr), p)
902 with pytest.raises(AttributeError) as e:
903 pp.a1
904 assert str(e.value) == "cdata 'struct foo * *' has no attribute 'a1'"
905 with pytest.raises(AttributeError) as e:
906 pp.a1 = 42
907 assert str(e.value) == "cdata 'struct foo * *' has no attribute 'a1'"
908
909 def test_union_instance():
910 BInt = new_primitive_type("int")
911 BUInt = new_primitive_type("unsigned int")
912 BUnion = new_union_type("union bar")
913 complete_struct_or_union(BUnion, [('a1', BInt, -1), ('a2', BUInt, -1)])
914 p = newp(new_pointer_type(BUnion), [-42])
915 bigval = -42 + (1 << (8*size_of_int()))
916 assert p.a1 == -42
917 assert p.a2 == bigval
918 p = newp(new_pointer_type(BUnion), {'a2': bigval})
919 assert p.a1 == -42
920 assert p.a2 == bigval
921 pytest.raises(OverflowError, newp, new_pointer_type(BUnion),
922 {'a1': bigval})
923 p = newp(new_pointer_type(BUnion), [])
924 assert p.a1 == p.a2 == 0
925
926 def test_struct_pointer():
927 BInt = new_primitive_type("int")
928 BStruct = new_struct_type("struct foo")
929 BStructPtr = new_pointer_type(BStruct)
930 complete_struct_or_union(BStruct, [('a1', BInt, -1),
931 ('a2', BInt, -1)])
932 p = newp(BStructPtr, None)
933 assert p.a1 == 0 # read/write via the pointer (C equivalent: '->')
934 p.a2 = 123
935 assert p.a1 == 0
936 assert p.a2 == 123
937
938 def test_struct_init_list():
939 BVoidP = new_pointer_type(new_void_type())
940 BInt = new_primitive_type("int")
941 BIntPtr = new_pointer_type(BInt)
942 BStruct = new_struct_type("struct foo")
943 BStructPtr = new_pointer_type(BStruct)
944 complete_struct_or_union(BStruct, [('a1', BInt, -1),
945 ('a2', BInt, -1),
946 ('a3', BInt, -1),
947 ('p4', BIntPtr, -1)])
948 s = newp(BStructPtr, [123, 456])
949 assert s.a1 == 123
950 assert s.a2 == 456
951 assert s.a3 == 0
952 assert s.p4 == cast(BVoidP, 0)
953 assert s.p4 != 0
954 #
955 s = newp(BStructPtr, {'a2': 41122, 'a3': -123})
956 assert s.a1 == 0
957 assert s.a2 == 41122
958 assert s.a3 == -123
959 assert s.p4 == cast(BVoidP, 0)
960 #
961 pytest.raises(KeyError, newp, BStructPtr, {'foobar': 0})
962 #
963 p = newp(BIntPtr, 14141)
964 s = newp(BStructPtr, [12, 34, 56, p])
965 assert s.p4 == p
966 assert s.p4
967 #
968 s = newp(BStructPtr, [12, 34, 56, cast(BVoidP, 0)])
969 assert s.p4 == cast(BVoidP, 0)
970 assert not s.p4
971 #
972 pytest.raises(TypeError, newp, BStructPtr, [12, 34, 56, None])
973
974 def test_array_in_struct():
975 BInt = new_primitive_type("int")
976 BStruct = new_struct_type("struct foo")
977 BArrayInt5 = new_array_type(new_pointer_type(BInt), 5)
978 complete_struct_or_union(BStruct, [('a1', BArrayInt5, -1)])
979 s = newp(new_pointer_type(BStruct), [[20, 24, 27, 29, 30]])
980 assert s.a1[2] == 27
981 assert repr(s.a1).startswith("<cdata 'int[5]' 0x")
982
983 def test_offsetof():
984 def offsetof(BType, fieldname):
985 return typeoffsetof(BType, fieldname)[1]
986 BInt = new_primitive_type("int")
987 BStruct = new_struct_type("struct foo")
988 pytest.raises(TypeError, offsetof, BInt, "abc")
989 pytest.raises(TypeError, offsetof, BStruct, "abc")
990 complete_struct_or_union(BStruct, [('abc', BInt, -1), ('def', BInt, -1)])
991 assert offsetof(BStruct, 'abc') == 0
992 assert offsetof(BStruct, 'def') == size_of_int()
993 pytest.raises(KeyError, offsetof, BStruct, "ghi")
994 assert offsetof(new_pointer_type(BStruct), "def") == size_of_int()
995
996 def test_function_type():
997 BInt = new_primitive_type("int")
998 BFunc = new_function_type((BInt, BInt), BInt, False)
999 assert repr(BFunc) == "<ctype 'int(*)(int, int)'>"
1000 BFunc2 = new_function_type((), BFunc, False)
1001 assert repr(BFunc2) == "<ctype 'int(*(*)())(int, int)'>"
1002
1003 def test_inspect_function_type():
1004 BInt = new_primitive_type("int")
1005 BFunc = new_function_type((BInt, BInt), BInt, False)
1006 assert BFunc.kind == "function"
1007 assert BFunc.cname == "int(*)(int, int)"
1008 assert BFunc.args == (BInt, BInt)
1009 assert BFunc.result is BInt
1010 assert BFunc.ellipsis is False
1011 assert BFunc.abi == FFI_DEFAULT_ABI
1012
1013 def test_function_type_taking_struct():
1014 BChar = new_primitive_type("char")
1015 BShort = new_primitive_type("short")
1016 BStruct = new_struct_type("struct foo")
1017 complete_struct_or_union(BStruct, [('a1', BChar, -1),
1018 ('a2', BShort, -1)])
1019 BFunc = new_function_type((BStruct,), BShort, False)
1020 assert repr(BFunc) == "<ctype 'short(*)(struct foo)'>"
1021
1022 def test_function_void_result():
1023 BVoid = new_void_type()
1024 BInt = new_primitive_type("int")
1025 BFunc = new_function_type((BInt, BInt), BVoid, False)
1026 assert repr(BFunc) == "<ctype 'void(*)(int, int)'>"
1027
1028 def test_function_void_arg():
1029 BVoid = new_void_type()
1030 BInt = new_primitive_type("int")
1031 pytest.raises(TypeError, new_function_type, (BVoid,), BInt, False)
1032
1033 def test_call_function_0():
1034 BSignedChar = new_primitive_type("signed char")
1035 BFunc0 = new_function_type((BSignedChar, BSignedChar), BSignedChar, False)
1036 f = cast(BFunc0, _testfunc(0))
1037 assert f(40, 2) == 42
1038 assert f(-100, -100) == -200 + 256
1039 pytest.raises(OverflowError, f, 128, 0)
1040 pytest.raises(OverflowError, f, 0, 128)
1041
1042 def test_call_function_0_pretend_bool_result():
1043 BSignedChar = new_primitive_type("signed char")
1044 BBool = new_primitive_type("_Bool")
1045 BFunc0 = new_function_type((BSignedChar, BSignedChar), BBool, False)
1046 f = cast(BFunc0, _testfunc(0))
1047 assert f(40, -39) is True
1048 assert f(40, -40) is False
1049 pytest.raises(ValueError, f, 40, 2)
1050
1051 def test_call_function_1():
1052 BInt = new_primitive_type("int")
1053 BLong = new_primitive_type("long")
1054 BFunc1 = new_function_type((BInt, BLong), BLong, False)
1055 f = cast(BFunc1, _testfunc(1))
1056 assert f(40, 2) == 42
1057 assert f(-100, -100) == -200
1058 int_max = (1 << (8*size_of_int()-1)) - 1
1059 long_max = (1 << (8*size_of_long()-1)) - 1
1060 if int_max == long_max:
1061 assert f(int_max, 1) == - int_max - 1
1062 else:
1063 assert f(int_max, 1) == int_max + 1
1064
1065 def test_call_function_2():
1066 BLongLong = new_primitive_type("long long")
1067 BFunc2 = new_function_type((BLongLong, BLongLong), BLongLong, False)
1068 f = cast(BFunc2, _testfunc(2))
1069 longlong_max = (1 << (8*sizeof(BLongLong)-1)) - 1
1070 assert f(longlong_max - 42, 42) == longlong_max
1071 assert f(43, longlong_max - 42) == - longlong_max - 1
1072
1073 def test_call_function_3():
1074 BFloat = new_primitive_type("float")
1075 BDouble = new_primitive_type("double")
1076 BFunc3 = new_function_type((BFloat, BDouble), BDouble, False)
1077 f = cast(BFunc3, _testfunc(3))
1078 assert f(1.25, 5.1) == 1.25 + 5.1 # exact
1079 res = f(1.3, 5.1)
1080 assert res != 6.4 and abs(res - 6.4) < 1E-5 # inexact
1081
1082 def test_call_function_4():
1083 BFloat = new_primitive_type("float")
1084 BDouble = new_primitive_type("double")
1085 BFunc4 = new_function_type((BFloat, BDouble), BFloat, False)
1086 f = cast(BFunc4, _testfunc(4))
1087 res = f(1.25, 5.1)
1088 assert res != 6.35 and abs(res - 6.35) < 1E-5 # inexact
1089
1090 def test_call_function_5():
1091 BVoid = new_void_type()
1092 BFunc5 = new_function_type((), BVoid, False)
1093 f = cast(BFunc5, _testfunc(5))
1094 f() # did not crash
1095
1096 @pytest.mark.thread_unsafe(reason="_testfunc6 uses global state")
1097 def test_call_function_6():
1098 BInt = new_primitive_type("int")
1099 BIntPtr = new_pointer_type(BInt)
1100 BFunc6 = new_function_type((BIntPtr,), BIntPtr, False)
1101 f = cast(BFunc6, _testfunc(6))
1102 x = newp(BIntPtr, 42)
1103 res = f(x)
1104 assert typeof(res) is BIntPtr
1105 assert res[0] == 42 - 1000
1106 #
1107 BIntArray = new_array_type(BIntPtr, None)
1108 BFunc6bis = new_function_type((BIntArray,), BIntPtr, False)
1109 f = cast(BFunc6bis, _testfunc(6))
1110 #
1111 res = f([142])
1112 assert typeof(res) is BIntPtr
1113 assert res[0] == 142 - 1000
1114 #
1115 res = f((143,))
1116 assert typeof(res) is BIntPtr
1117 assert res[0] == 143 - 1000
1118 #
1119 x = newp(BIntArray, [242])
1120 res = f(x)
1121 assert typeof(res) is BIntPtr
1122 assert res[0] == 242 - 1000
1123 #
1124 pytest.raises(TypeError, f, 123456)
1125 pytest.raises(TypeError, f, "foo")
1126 pytest.raises(TypeError, f, u+"bar")
1127
1128 def test_call_function_7():
1129 BChar = new_primitive_type("char")
1130 BShort = new_primitive_type("short")
1131 BStruct = new_struct_type("struct foo")
1132 BStructPtr = new_pointer_type(BStruct)
1133 complete_struct_or_union(BStruct, [('a1', BChar, -1),
1134 ('a2', BShort, -1)])
1135 BFunc7 = new_function_type((BStruct,), BShort, False)
1136 f = cast(BFunc7, _testfunc(7))
1137 res = f({'a1': b'A', 'a2': -4042})
1138 assert res == -4042 + ord(b'A')
1139 #
1140 x = newp(BStructPtr, {'a1': b'A', 'a2': -4042})
1141 res = f(x[0])
1142 assert res == -4042 + ord(b'A')
1143
1144 def test_call_function_20():
1145 BChar = new_primitive_type("char")
1146 BShort = new_primitive_type("short")
1147 BStruct = new_struct_type("struct foo")
1148 BStructPtr = new_pointer_type(BStruct)
1149 complete_struct_or_union(BStruct, [('a1', BChar, -1),
1150 ('a2', BShort, -1)])
1151 BFunc20 = new_function_type((BStructPtr,), BShort, False)
1152 f = cast(BFunc20, _testfunc(20))
1153 x = newp(BStructPtr, {'a1': b'A', 'a2': -4042})
1154 # can't pass a 'struct foo'
1155 pytest.raises(TypeError, f, x[0])
1156
1157 def test_call_function_21():
1158 BInt = new_primitive_type("int")
1159 BStruct = new_struct_type("struct foo")
1160 complete_struct_or_union(BStruct, [('a', BInt, -1),
1161 ('b', BInt, -1),
1162 ('c', BInt, -1),
1163 ('d', BInt, -1),
1164 ('e', BInt, -1),
1165 ('f', BInt, -1),
1166 ('g', BInt, -1),
1167 ('h', BInt, -1),
1168 ('i', BInt, -1),
1169 ('j', BInt, -1)])
1170 BFunc21 = new_function_type((BStruct,), BInt, False)
1171 f = cast(BFunc21, _testfunc(21))
1172 res = f(list(range(13, 3, -1)))
1173 lst = [(n << i) for (i, n) in enumerate(range(13, 3, -1))]
1174 assert res == sum(lst)
1175
1176 def test_call_function_22():
1177 BInt = new_primitive_type("int")
1178 BArray10 = new_array_type(new_pointer_type(BInt), 10)
1179 BStruct = new_struct_type("struct foo")
1180 BStructP = new_pointer_type(BStruct)
1181 complete_struct_or_union(BStruct, [('a', BArray10, -1)])
1182 BFunc22 = new_function_type((BStruct, BStruct), BStruct, False)
1183 f = cast(BFunc22, _testfunc(22))
1184 p1 = newp(BStructP, {'a': list(range(100, 110))})
1185 p2 = newp(BStructP, {'a': list(range(1000, 1100, 10))})
1186 res = f(p1[0], p2[0])
1187 for i in range(10):
1188 assert res.a[i] == p1.a[i] - p2.a[i]
1189
1190 def test_call_function_23():
1191 BVoid = new_void_type() # declaring the function as int(void*)
1192 BVoidP = new_pointer_type(BVoid)
1193 BInt = new_primitive_type("int")
1194 BFunc23 = new_function_type((BVoidP,), BInt, False)
1195 f = cast(BFunc23, _testfunc(23))
1196 res = f(b"foo")
1197 assert res == 1000 * ord(b'f')
1198 res = f(cast(BVoidP, 0)) # NULL
1199 assert res == -42
1200 pytest.raises(TypeError, f, None)
1201 pytest.raises(TypeError, f, 0)
1202 pytest.raises(TypeError, f, 0.0)
1203
1204 def test_call_function_23_bis():
1205 # declaring the function as int(unsigned char*)
1206 BUChar = new_primitive_type("unsigned char")
1207 BUCharP = new_pointer_type(BUChar)
1208 BInt = new_primitive_type("int")
1209 BFunc23 = new_function_type((BUCharP,), BInt, False)
1210 f = cast(BFunc23, _testfunc(23))
1211 res = f(b"foo")
1212 assert res == 1000 * ord(b'f')
1213
1214 def test_call_function_23_bool_array():
1215 # declaring the function as int(_Bool*)
1216 BBool = new_primitive_type("_Bool")
1217 BBoolP = new_pointer_type(BBool)
1218 BInt = new_primitive_type("int")
1219 BFunc23 = new_function_type((BBoolP,), BInt, False)
1220 f = cast(BFunc23, _testfunc(23))
1221 res = f(b"\x01\x01")
1222 assert res == 1000
1223 pytest.raises(ValueError, f, b"\x02\x02")
1224
1225 def test_cannot_pass_struct_with_array_of_length_0():
1226 BInt = new_primitive_type("int")
1227 BArray0 = new_array_type(new_pointer_type(BInt), 0)
1228 BStruct = new_struct_type("struct foo")
1229 BStructP = new_pointer_type(BStruct)
1230 complete_struct_or_union(BStruct, [('a', BArray0)])
1231 BFunc = new_function_type((BStruct,), BInt, False)
1232 pytest.raises(NotImplementedError, cast(BFunc, 123), cast(BStructP, 123))
1233 BFunc2 = new_function_type((BInt,), BStruct, False)
1234 pytest.raises(NotImplementedError, cast(BFunc2, 123), 123)
1235
1236 @pytest.mark.xfail(
1237 is_ios,
1238 reason="For an unknown reason f(1, cast(BInt, 42)) returns 36792864",
1239 raises=AssertionError,
1240 )
1241 def test_call_function_9():
1242 BInt = new_primitive_type("int")
1243 BFunc9 = new_function_type((BInt,), BInt, True) # vararg
1244 f = cast(BFunc9, _testfunc(9))
1245 assert f(0) == 0
1246 assert f(1, cast(BInt, 42)) == 42
1247 assert f(2, cast(BInt, 40), cast(BInt, 2)) == 42
1248 pytest.raises(TypeError, f, 1, 42)
1249 pytest.raises(TypeError, f, 2, None)
1250 # promotion of chars and shorts to ints
1251 BSChar = new_primitive_type("signed char")
1252 BUChar = new_primitive_type("unsigned char")
1253 BSShort = new_primitive_type("short")
1254 assert f(3, cast(BSChar, -3), cast(BUChar, 200), cast(BSShort, -5)) == 192
1255
1256 def test_call_function_24():
1257 BFloat = new_primitive_type("float")
1258 BFloatComplex = new_primitive_type("_cffi_float_complex_t")
1259 BFunc3 = new_function_type((BFloat, BFloat), BFloatComplex, False)
1260 if 0: # libffi returning nonsense silently, so logic disabled for now
1261 f = cast(BFunc3, _testfunc(24))
1262 result = f(1.25, 5.1)
1263 assert type(result) == complex
1264 assert result.real == 1.25 # exact
1265 assert (result.imag != 2*5.1) and (abs(result.imag - 2*5.1) < 1e-5) # inexact
1266 else:
1267 f = cast(BFunc3, _testfunc(9))
1268 pytest.raises(NotImplementedError, f, 12.3, 34.5)
1269
1270 def test_call_function_25():
1271 BDouble = new_primitive_type("double")
1272 BDoubleComplex = new_primitive_type("_cffi_double_complex_t")
1273 BFunc3 = new_function_type((BDouble, BDouble), BDoubleComplex, False)
1274 if 0: # libffi returning nonsense silently, so logic disabled for now
1275 f = cast(BFunc3, _testfunc(25))
1276 result = f(1.25, 5.1)
1277 assert type(result) == complex
1278 assert result.real == 1.25 # exact
1279 assert (result.imag != 2*5.1) and (abs(result.imag - 2*5.1) < 1e-10) # inexact
1280 else:
1281 f = cast(BFunc3, _testfunc(9))
1282 pytest.raises(NotImplementedError, f, 12.3, 34.5)
1283
1284 def test_cannot_call_with_a_autocompleted_struct():
1285 BSChar = new_primitive_type("signed char")
1286 BDouble = new_primitive_type("double")
1287 BStruct = new_struct_type("struct foo")
1288 BStructPtr = new_pointer_type(BStruct)
1289 complete_struct_or_union(BStruct, [('c', BDouble, -1, 8),
1290 ('a', BSChar, -1, 2),
1291 ('b', BSChar, -1, 0)])
1292 BFunc = new_function_type((BStruct,), BDouble) # internally not callable
1293 dummy_func = cast(BFunc, 42)
1294 e = pytest.raises(NotImplementedError, dummy_func, "?")
1295 msg = ("ctype 'struct foo' not supported as argument. It is a struct "
1296 'declared with "...;", but the C calling convention may depend '
1297 "on the missing fields; or, it contains anonymous struct/unions. "
1298 "Such structs are only supported as argument if the function is "
1299 "'API mode' and non-variadic (i.e. declared inside ffibuilder."
1300 "cdef()+ffibuilder.set_source() and not taking a final '...' "
1301 "argument)")
1302 assert str(e.value) == msg
1303
1304 def test_new_charp():
1305 BChar = new_primitive_type("char")
1306 BCharP = new_pointer_type(BChar)
1307 BCharA = new_array_type(BCharP, None)
1308 x = newp(BCharA, 42)
1309 assert len(x) == 42
1310 x = newp(BCharA, b"foobar")
1311 assert len(x) == 7
1312
1313 def test_load_and_call_function():
1314 BChar = new_primitive_type("char")
1315 BCharP = new_pointer_type(BChar)
1316 BLong = new_primitive_type("long")
1317 BFunc = new_function_type((BCharP,), BLong, False)
1318 ll = find_and_load_library('c')
1319 strlen = ll.load_function(BFunc, "strlen")
1320 input = newp(new_array_type(BCharP, None), b"foobar")
1321 assert strlen(input) == 6
1322 #
1323 assert strlen(b"foobarbaz") == 9
1324 #
1325 BVoidP = new_pointer_type(new_void_type())
1326 strlenaddr = ll.load_function(BVoidP, "strlen")
1327 assert strlenaddr == cast(BVoidP, strlen)
1328
1329 def test_read_variable():
1330 ## FIXME: this test assumes glibc specific behavior, it's not compliant with C standard
1331 ## https://bugs.pypy.org/issue1643
1332 if not sys.platform.startswith("linux"):
1333 pytest.skip("untested")
1334 BVoidP = new_pointer_type(new_void_type())
1335 ll = find_and_load_library('c')
1336 stderr = ll.read_variable(BVoidP, "stderr")
1337 assert stderr == cast(BVoidP, _testfunc(8))
1338 #
1339 ll.close_lib()
1340 pytest.raises(ValueError, ll.read_variable, BVoidP, "stderr")
1341
1342 def test_read_variable_as_unknown_length_array():
1343 ## FIXME: this test assumes glibc specific behavior, it's not compliant with C standard
1344 ## https://bugs.pypy.org/issue1643
1345 if not sys.platform.startswith("linux"):
1346 pytest.skip("untested")
1347 BCharP = new_pointer_type(new_primitive_type("char"))
1348 BArray = new_array_type(BCharP, None)
1349 ll = find_and_load_library('c')
1350 stderr = ll.read_variable(BArray, "stderr")
1351 assert repr(stderr).startswith("<cdata 'char *' 0x")
1352 # ^^ and not 'char[]', which is basically not allowed and would crash
1353
1354 @pytest.mark.thread_unsafe(reason="writes to global state")
1355 def test_write_variable():
1356 ## FIXME: this test assumes glibc specific behavior, it's not compliant with C standard
1357 ## https://bugs.pypy.org/issue1643
1358 if not sys.platform.startswith("linux") or is_musl:
1359 pytest.skip("untested")
1360 BVoidP = new_pointer_type(new_void_type())
1361 ll = find_and_load_library('c')
1362 stderr = ll.read_variable(BVoidP, "stderr")
1363 ll.write_variable(BVoidP, "stderr", cast(BVoidP, 0))
1364 assert ll.read_variable(BVoidP, "stderr") is not None
1365 assert not ll.read_variable(BVoidP, "stderr")
1366 ll.write_variable(BVoidP, "stderr", stderr)
1367 assert ll.read_variable(BVoidP, "stderr") == stderr
1368 #
1369 ll.close_lib()
1370 pytest.raises(ValueError, ll.write_variable, BVoidP, "stderr", stderr)
1371
1372
1373 @pytest.mark.skipif(is_ios, reason="Cannot allocate executable memory on iOS")
1374 def test_callback():
1375 BInt = new_primitive_type("int")
1376 def make_callback():
1377 def cb(n):
1378 return n + 1
1379 BFunc = new_function_type((BInt,), BInt, False)
1380 return callback(BFunc, cb, 42) # 'cb' and 'BFunc' go out of scope
1381 f = make_callback()
1382 assert f(-142) == -141
1383 assert repr(f).startswith(
1384 "<cdata 'int(*)(int)' calling <function ")
1385 assert "cb at 0x" in repr(f)
1386 e = pytest.raises(TypeError, f)
1387 assert str(e.value) == "'int(*)(int)' expects 1 arguments, got 0"
1388
1389
1390 @pytest.mark.skipif(is_ios, reason="Cannot allocate executable memory on iOS")
1391 @pytest.mark.thread_unsafe("mocks sys.unraiseablehook")
1392 def test_callback_exception():
1393 def check_value(x):
1394 if x == 10000:
1395 raise ValueError(42)
1396 def Zcb1(x):
1397 check_value(x)
1398 return x * 3
1399 BShort = new_primitive_type("short")
1400 BFunc = new_function_type((BShort,), BShort, False)
1401
1402 f = callback(BFunc, Zcb1, -42)
1403 seen = []
1404 oops_result = None
1405 def oops(*args):
1406 seen.append(args)
1407 return oops_result
1408 ff = callback(BFunc, Zcb1, -42, oops)
1409 with _assert_unraisable(None):
1410 assert f(100) == 300
1411 with _assert_unraisable(ValueError, '42', ['in Zcb1', 'in check_value']):
1412 assert f(10000) == -42
1413
1414 bigvalue = 20000
1415 with _assert_unraisable(OverflowError, "integer 60000 does not fit 'short'", ['callback', 'Zcb1']):
1416 assert f(bigvalue) == -42
1417 assert len(seen) == 0
1418
1419 with _assert_unraisable(None):
1420 assert ff(bigvalue) == -42
1421 assert len(seen) == 1
1422 exc, val, tb = seen[0]
1423 assert exc is OverflowError
1424 assert str(val) == "integer 60000 does not fit 'short'"
1425
1426 del seen[:]
1427 oops_result = 81
1428 with _assert_unraisable(None):
1429 assert ff(bigvalue) == 81
1430
1431 assert len(seen) == 1
1432 exc, val, tb = seen[0]
1433 assert exc is OverflowError
1434 assert str(val) == "integer 60000 does not fit 'short'"
1435
1436 del seen[:]
1437 oops_result = "xy" # not None and not an int!
1438
1439 with _assert_unraisable(TypeError, "an integer is required", ["integer 60000 does not fit 'short'"]):
1440 assert ff(bigvalue) == -42
1441
1442 seen = "not a list" # this makes the oops() function crash
1443 oops_result = None
1444 with _assert_unraisable(AttributeError, "'str' object has no attribute 'append", ['Zcb1', 'ff', 'oops']):
1445 assert ff(bigvalue) == -42
1446
1447
1448 @pytest.mark.skipif(is_ios, reason="Cannot allocate executable memory on iOS")
1449 def test_callback_return_type():
1450 for rettype in ["signed char", "short", "int", "long", "long long",
1451 "unsigned char", "unsigned short", "unsigned int",
1452 "unsigned long", "unsigned long long"]:
1453 BRet = new_primitive_type(rettype)
1454 def cb(n):
1455 return n + 1
1456 BFunc = new_function_type((BRet,), BRet)
1457 f = callback(BFunc, cb, 42)
1458 assert f(41) == 42
1459 if rettype.startswith("unsigned "):
1460 min = 0
1461 max = (1 << (8*sizeof(BRet))) - 1
1462 else:
1463 min = -(1 << (8*sizeof(BRet)-1))
1464 max = (1 << (8*sizeof(BRet)-1)) - 1
1465 assert f(min) == min + 1
1466 assert f(max - 1) == max
1467 assert f(max) == 42
1468
1469 @pytest.mark.skipif(is_ios, reason="Cannot allocate executable memory on iOS")
1470 def test_a_lot_of_callbacks():
1471 BIGNUM = 10000
1472 if 'PY_DOT_PY' in globals(): BIGNUM = 100 # tests on py.py
1473 #
1474 BInt = new_primitive_type("int")
1475 BFunc = new_function_type((BInt,), BInt, False)
1476 def make_callback(m):
1477 def cb(n):
1478 return n + m
1479 return callback(BFunc, cb, 42) # 'cb' goes out of scope
1480 #
1481 flist = [make_callback(i) for i in range(BIGNUM)]
1482 for i, f in enumerate(flist):
1483 assert f(-142) == -142 + i
1484
1485 @pytest.mark.skipif(is_ios, reason="Cannot allocate executable memory on iOS")
1486 def test_callback_receiving_tiny_struct():
1487 BSChar = new_primitive_type("signed char")
1488 BInt = new_primitive_type("int")
1489 BStruct = new_struct_type("struct foo")
1490 BStructPtr = new_pointer_type(BStruct)
1491 complete_struct_or_union(BStruct, [('a', BSChar, -1),
1492 ('b', BSChar, -1)])
1493 def cb(s):
1494 return s.a + 10 * s.b
1495 BFunc = new_function_type((BStruct,), BInt)
1496 f = callback(BFunc, cb)
1497 p = newp(BStructPtr, [-2, -4])
1498 n = f(p[0])
1499 assert n == -42
1500
1501 @pytest.mark.skipif(is_ios, reason="Cannot allocate executable memory on iOS")
1502 def test_callback_returning_tiny_struct():
1503 BSChar = new_primitive_type("signed char")
1504 BInt = new_primitive_type("int")
1505 BStruct = new_struct_type("struct foo")
1506 BStructPtr = new_pointer_type(BStruct)
1507 complete_struct_or_union(BStruct, [('a', BSChar, -1),
1508 ('b', BSChar, -1)])
1509 def cb(n):
1510 return newp(BStructPtr, [-n, -3*n])[0]
1511 BFunc = new_function_type((BInt,), BStruct)
1512 f = callback(BFunc, cb)
1513 s = f(10)
1514 assert typeof(s) is BStruct
1515 assert repr(s) == "<cdata 'struct foo' owning 2 bytes>"
1516 assert s.a == -10
1517 assert s.b == -30
1518
1519 @pytest.mark.skipif(is_ios, reason="Cannot allocate executable memory on iOS")
1520 def test_callback_receiving_struct():
1521 BSChar = new_primitive_type("signed char")
1522 BInt = new_primitive_type("int")
1523 BDouble = new_primitive_type("double")
1524 BStruct = new_struct_type("struct foo")
1525 BStructPtr = new_pointer_type(BStruct)
1526 complete_struct_or_union(BStruct, [('a', BSChar, -1),
1527 ('b', BDouble, -1)])
1528 def cb(s):
1529 return s.a + int(s.b)
1530 BFunc = new_function_type((BStruct,), BInt)
1531 f = callback(BFunc, cb)
1532 p = newp(BStructPtr, [-2, 44.444])
1533 n = f(p[0])
1534 assert n == 42
1535
1536 @pytest.mark.skipif(is_ios, reason="Cannot allocate executable memory on iOS")
1537 def test_callback_returning_struct():
1538 BSChar = new_primitive_type("signed char")
1539 BInt = new_primitive_type("int")
1540 BDouble = new_primitive_type("double")
1541 BStruct = new_struct_type("struct foo")
1542 BStructPtr = new_pointer_type(BStruct)
1543 complete_struct_or_union(BStruct, [('a', BSChar, -1),
1544 ('b', BDouble, -1)])
1545 def cb(n):
1546 return newp(BStructPtr, [-n, 1E-42])[0]
1547 BFunc = new_function_type((BInt,), BStruct)
1548 f = callback(BFunc, cb)
1549 s = f(10)
1550 assert typeof(s) is BStruct
1551 assert repr(s) in ["<cdata 'struct foo' owning 12 bytes>",
1552 "<cdata 'struct foo' owning 16 bytes>"]
1553 assert s.a == -10
1554 assert s.b == 1E-42
1555
1556 @pytest.mark.skipif(is_ios, reason="Cannot allocate executable memory on iOS")
1557 def test_callback_receiving_big_struct():
1558 BInt = new_primitive_type("int")
1559 BStruct = new_struct_type("struct foo")
1560 BStructPtr = new_pointer_type(BStruct)
1561 complete_struct_or_union(BStruct, [('a', BInt, -1),
1562 ('b', BInt, -1),
1563 ('c', BInt, -1),
1564 ('d', BInt, -1),
1565 ('e', BInt, -1),
1566 ('f', BInt, -1),
1567 ('g', BInt, -1),
1568 ('h', BInt, -1),
1569 ('i', BInt, -1),
1570 ('j', BInt, -1)])
1571 def cb(s):
1572 for i, name in enumerate("abcdefghij"):
1573 assert getattr(s, name) == 13 - i
1574 return 42
1575 BFunc = new_function_type((BStruct,), BInt)
1576 f = callback(BFunc, cb)
1577 p = newp(BStructPtr, list(range(13, 3, -1)))
1578 n = f(p[0])
1579 assert n == 42
1580
1581 @pytest.mark.skipif(is_ios, reason="Cannot allocate executable memory on iOS")
1582 def test_callback_returning_big_struct():
1583 BInt = new_primitive_type("int")
1584 BStruct = new_struct_type("struct foo")
1585 BStructPtr = new_pointer_type(BStruct)
1586 complete_struct_or_union(BStruct, [('a', BInt, -1),
1587 ('b', BInt, -1),
1588 ('c', BInt, -1),
1589 ('d', BInt, -1),
1590 ('e', BInt, -1),
1591 ('f', BInt, -1),
1592 ('g', BInt, -1),
1593 ('h', BInt, -1),
1594 ('i', BInt, -1),
1595 ('j', BInt, -1)])
1596 def cb():
1597 return newp(BStructPtr, list(range(13, 3, -1)))[0]
1598 BFunc = new_function_type((), BStruct)
1599 f = callback(BFunc, cb)
1600 s = f()
1601 assert typeof(s) is BStruct
1602 assert repr(s) in ["<cdata 'struct foo' owning 40 bytes>",
1603 "<cdata 'struct foo' owning 80 bytes>"]
1604 for i, name in enumerate("abcdefghij"):
1605 assert getattr(s, name) == 13 - i
1606
1607 @pytest.mark.skipif(is_ios, reason="Cannot allocate executable memory on iOS")
1608 def test_callback_returning_void():
1609 BVoid = new_void_type()
1610 BFunc = new_function_type((), BVoid, False)
1611 def cb():
1612 seen.append(42)
1613 f = callback(BFunc, cb)
1614 seen = []
1615 f()
1616 assert seen == [42]
1617 pytest.raises(TypeError, callback, BFunc, cb, -42)
1618
1619 def test_enum_type():
1620 BUInt = new_primitive_type("unsigned int")
1621 BEnum = new_enum_type("foo", (), (), BUInt)
1622 assert repr(BEnum) == "<ctype 'foo'>"
1623 assert BEnum.kind == "enum"
1624 assert BEnum.cname == "foo"
1625 assert BEnum.elements == {}
1626 #
1627 BInt = new_primitive_type("int")
1628 BEnum = new_enum_type("enum foo", ('def', 'c', 'ab'), (0, 1, -20), BInt)
1629 assert BEnum.kind == "enum"
1630 assert BEnum.cname == "enum foo"
1631 assert BEnum.elements == {-20: 'ab', 0: 'def', 1: 'c'}
1632 # 'elements' is not the real dict, but merely a copy
1633 BEnum.elements[2] = '??'
1634 assert BEnum.elements == {-20: 'ab', 0: 'def', 1: 'c'}
1635 #
1636 BEnum = new_enum_type("enum bar", ('ab', 'cd'), (5, 5), BUInt)
1637 assert BEnum.elements == {5: 'ab'}
1638 assert BEnum.relements == {'ab': 5, 'cd': 5}
1639
1640 def test_cast_to_enum():
1641 BInt = new_primitive_type("int")
1642 BEnum = new_enum_type("enum foo", ('def', 'c', 'ab'), (0, 1, -20), BInt)
1643 assert sizeof(BEnum) == sizeof(BInt)
1644 e = cast(BEnum, 0)
1645 assert repr(e) == "<cdata 'enum foo' 0: def>"
1646 assert repr(cast(BEnum, -42)) == "<cdata 'enum foo' -42>"
1647 assert repr(cast(BEnum, -20)) == "<cdata 'enum foo' -20: ab>"
1648 assert string(e) == 'def'
1649 assert string(cast(BEnum, -20)) == 'ab'
1650 assert int(cast(BEnum, 1)) == 1
1651 assert int(cast(BEnum, 0)) == 0
1652 assert int(cast(BEnum, -242 + 2**128)) == -242
1653 assert string(cast(BEnum, -242 + 2**128)) == '-242'
1654 #
1655 BUInt = new_primitive_type("unsigned int")
1656 BEnum = new_enum_type("enum bar", ('def', 'c', 'ab'), (0, 1, 20), BUInt)
1657 e = cast(BEnum, -1)
1658 assert repr(e) == "<cdata 'enum bar' 4294967295>" # unsigned int
1659 #
1660 BLong = new_primitive_type("long")
1661 BEnum = new_enum_type("enum baz", (), (), BLong)
1662 assert sizeof(BEnum) == sizeof(BLong)
1663 e = cast(BEnum, -1)
1664 assert repr(e) == "<cdata 'enum baz' -1>"
1665
1666 def test_enum_with_non_injective_mapping():
1667 BInt = new_primitive_type("int")
1668 BEnum = new_enum_type("enum foo", ('ab', 'cd'), (7, 7), BInt)
1669 e = cast(BEnum, 7)
1670 assert repr(e) == "<cdata 'enum foo' 7: ab>"
1671 assert string(e) == 'ab'
1672
1673 def test_enum_in_struct():
1674 BInt = new_primitive_type("int")
1675 BEnum = new_enum_type("enum foo", ('def', 'c', 'ab'), (0, 1, -20), BInt)
1676 BStruct = new_struct_type("struct bar")
1677 BStructPtr = new_pointer_type(BStruct)
1678 complete_struct_or_union(BStruct, [('a1', BEnum, -1)])
1679 p = newp(BStructPtr, [-20])
1680 assert p.a1 == -20
1681 p = newp(BStructPtr, [12])
1682 assert p.a1 == 12
1683 e = pytest.raises(TypeError, newp, BStructPtr, [None])
1684 msg = str(e.value)
1685 assert ("an integer is required" in msg or # CPython
1686 "unsupported operand type for int(): 'NoneType'" in msg or # old PyPys
1687 "expected integer, got NoneType object" in msg) # newer PyPys
1688 with pytest.raises(TypeError):
1689 p.a1 = "def"
1690 if sys.version_info < (3,):
1691 BEnum2 = new_enum_type(unicode("foo"), (unicode('abc'),), (5,), BInt)
1692 assert string(cast(BEnum2, 5)) == 'abc'
1693 assert type(string(cast(BEnum2, 5))) is str
1694
1695 def test_enum_overflow():
1696 max_uint = 2 ** (size_of_int()*8) - 1
1697 max_int = max_uint // 2
1698 max_ulong = 2 ** (size_of_long()*8) - 1
1699 max_long = max_ulong // 2
1700 for BPrimitive in [new_primitive_type("int"),
1701 new_primitive_type("unsigned int"),
1702 new_primitive_type("long"),
1703 new_primitive_type("unsigned long")]:
1704 for x in [max_uint, max_int, max_ulong, max_long]:
1705 for testcase in [x, x+1, -x-1, -x-2]:
1706 if int(cast(BPrimitive, testcase)) == testcase:
1707 # fits
1708 BEnum = new_enum_type("foo", ("AA",), (testcase,),
1709 BPrimitive)
1710 assert int(cast(BEnum, testcase)) == testcase
1711 else:
1712 # overflows
1713 pytest.raises(OverflowError, new_enum_type,
1714 "foo", ("AA",), (testcase,), BPrimitive)
1715
1716 @pytest.mark.skipif(is_ios, reason="Cannot allocate executable memory on iOS")
1717 def test_callback_returning_enum():
1718 BInt = new_primitive_type("int")
1719 BEnum = new_enum_type("foo", ('def', 'c', 'ab'), (0, 1, -20), BInt)
1720 def cb(n):
1721 if n & 1:
1722 return cast(BEnum, n)
1723 else:
1724 return n
1725 BFunc = new_function_type((BInt,), BEnum)
1726 f = callback(BFunc, cb)
1727 assert f(0) == 0
1728 assert f(1) == 1
1729 assert f(-20) == -20
1730 assert f(20) == 20
1731 assert f(21) == 21
1732
1733 @pytest.mark.skipif(is_ios, reason="Cannot allocate executable memory on iOS")
1734 def test_callback_returning_enum_unsigned():
1735 BInt = new_primitive_type("int")
1736 BUInt = new_primitive_type("unsigned int")
1737 BEnum = new_enum_type("foo", ('def', 'c', 'ab'), (0, 1, 20), BUInt)
1738 def cb(n):
1739 if n & 1:
1740 return cast(BEnum, n)
1741 else:
1742 return n
1743 BFunc = new_function_type((BInt,), BEnum)
1744 f = callback(BFunc, cb)
1745 assert f(0) == 0
1746 assert f(1) == 1
1747 assert f(-21) == 2**32 - 21
1748 assert f(20) == 20
1749 assert f(21) == 21
1750
1751 @pytest.mark.skipif(is_ios, reason="Cannot allocate executable memory on iOS")
1752 def test_callback_returning_char():
1753 BInt = new_primitive_type("int")
1754 BChar = new_primitive_type("char")
1755 def cb(n):
1756 return bytechr(n)
1757 BFunc = new_function_type((BInt,), BChar)
1758 f = callback(BFunc, cb)
1759 assert f(0) == b'\x00'
1760 assert f(255) == b'\xFF'
1761
1762 def _hacked_pypy_uni4():
1763 pyuni4 = {1: True, 2: False}[len(u+'\U00012345')]
1764 return 'PY_DOT_PY' in globals() and not pyuni4
1765
1766 @pytest.mark.skipif(is_ios, reason="Cannot allocate executable memory on iOS")
1767 def test_callback_returning_wchar_t():
1768 BInt = new_primitive_type("int")
1769 BWChar = new_primitive_type("wchar_t")
1770 def cb(n):
1771 if n == -1:
1772 return u+'\U00012345'
1773 if n == -2:
1774 raise ValueError
1775 return unichr(n)
1776 BFunc = new_function_type((BInt,), BWChar)
1777 f = callback(BFunc, cb)
1778 assert f(0) == unichr(0)
1779 assert f(255) == unichr(255)
1780 assert f(0x1234) == u+'\u1234'
1781 if sizeof(BWChar) == 4 and not _hacked_pypy_uni4():
1782 assert f(-1) == u+'\U00012345'
1783 assert f(-2) == u+'\x00' # and an exception printed to stderr
1784
1785 def test_struct_with_bitfields():
1786 BLong = new_primitive_type("long")
1787 BStruct = new_struct_type("struct foo")
1788 LONGBITS = 8 * sizeof(BLong)
1789 complete_struct_or_union(BStruct, [('a1', BLong, 1),
1790 ('a2', BLong, 2),
1791 ('a3', BLong, 3),
1792 ('a4', BLong, LONGBITS - 5)])
1793 d = BStruct.fields
1794 assert d[0][1].offset == d[1][1].offset == d[2][1].offset == 0
1795 assert d[3][1].offset == sizeof(BLong)
1796 def f(m, r):
1797 if sys.byteorder == 'little':
1798 return r
1799 else:
1800 return LONGBITS - m - r
1801 assert d[0][1].bitshift == f(1, 0)
1802 assert d[0][1].bitsize == 1
1803 assert d[1][1].bitshift == f(2, 1)
1804 assert d[1][1].bitsize == 2
1805 assert d[2][1].bitshift == f(3, 3)
1806 assert d[2][1].bitsize == 3
1807 assert d[3][1].bitshift == f(LONGBITS - 5, 0)
1808 assert d[3][1].bitsize == LONGBITS - 5
1809 assert sizeof(BStruct) == 2 * sizeof(BLong)
1810 assert alignof(BStruct) == alignof(BLong)
1811
1812 def test_bitfield_instance():
1813 BInt = new_primitive_type("int")
1814 BUnsignedInt = new_primitive_type("unsigned int")
1815 BStruct = new_struct_type("struct foo")
1816 complete_struct_or_union(BStruct, [('a1', BInt, 1),
1817 ('a2', BUnsignedInt, 2),
1818 ('a3', BInt, 3)])
1819 p = newp(new_pointer_type(BStruct), None)
1820 p.a1 = -1
1821 assert p.a1 == -1
1822 p.a1 = 0
1823 with pytest.raises(OverflowError):
1824 p.a1 = 2
1825 assert p.a1 == 0
1826 #
1827 p.a1 = -1
1828 p.a2 = 3
1829 p.a3 = -4
1830 with pytest.raises(OverflowError):
1831 p.a3 = 4
1832 with pytest.raises(OverflowError) as e:
1833 p.a3 = -5
1834 assert str(e.value) == ("value -5 outside the range allowed by the "
1835 "bit field width: -4 <= x <= 3")
1836 assert p.a1 == -1 and p.a2 == 3 and p.a3 == -4
1837 #
1838 # special case for convenience: "int x:1", while normally signed,
1839 # allows also setting the value "1" (it still gets read back as -1)
1840 p.a1 = 1
1841 assert p.a1 == -1
1842 with pytest.raises(OverflowError) as e:
1843 p.a1 = -2
1844 assert str(e.value) == ("value -2 outside the range allowed by the "
1845 "bit field width: -1 <= x <= 1")
1846
1847 def test_bitfield_instance_init():
1848 BInt = new_primitive_type("int")
1849 BStruct = new_struct_type("struct foo")
1850 complete_struct_or_union(BStruct, [('a1', BInt, 1)])
1851 p = newp(new_pointer_type(BStruct), [-1])
1852 assert p.a1 == -1
1853 p = newp(new_pointer_type(BStruct), {'a1': -1})
1854 assert p.a1 == -1
1855 #
1856 BUnion = new_union_type("union bar")
1857 complete_struct_or_union(BUnion, [('a1', BInt, 1)])
1858 p = newp(new_pointer_type(BUnion), [-1])
1859 assert p.a1 == -1
1860
1861 def test_weakref():
1862 import _weakref
1863 BInt = new_primitive_type("int")
1864 BPtr = new_pointer_type(BInt)
1865 rlist = [_weakref.ref(BInt),
1866 _weakref.ref(newp(BPtr, 42)),
1867 _weakref.ref(cast(BPtr, 42)),
1868 _weakref.ref(cast(BInt, 42)),
1869 _weakref.ref(buffer(newp(BPtr, 42))),
1870 ]
1871 for i in range(5):
1872 import gc; gc.collect()
1873 if [r() for r in rlist] == [None for r in rlist]:
1874 break
1875
1876 def test_no_inheritance():
1877 BInt = new_primitive_type("int")
1878 try:
1879 class foo(type(BInt)): pass
1880 except TypeError:
1881 pass
1882 else:
1883 raise AssertionError
1884 x = cast(BInt, 42)
1885 try:
1886 class foo(type(x)): pass
1887 except TypeError:
1888 pass
1889 else:
1890 raise AssertionError
1891
1892 def test_assign_string():
1893 BChar = new_primitive_type("char")
1894 BArray1 = new_array_type(new_pointer_type(BChar), 5)
1895 BArray2 = new_array_type(new_pointer_type(BArray1), 5)
1896 a = newp(BArray2, [b"abc", b"de", b"ghij"])
1897 assert string(a[1]) == b"de"
1898 assert string(a[2]) == b"ghij"
1899 a[2] = b"."
1900 assert string(a[2]) == b"."
1901 a[2] = b"12345"
1902 assert string(a[2]) == b"12345"
1903 with pytest.raises(IndexError) as e:
1904 a[2] = b"123456"
1905 assert 'char[5]' in str(e.value)
1906 assert 'got 6 characters' in str(e.value)
1907
1908 def test_add_error():
1909 x = cast(new_primitive_type("int"), 42)
1910 with pytest.raises(TypeError):
1911 x + 1
1912 with pytest.raises(TypeError):
1913 x - 1
1914
1915 def test_void_errors():
1916 pytest.raises(ValueError, alignof, new_void_type())
1917 pytest.raises(TypeError, newp, new_pointer_type(new_void_type()), None)
1918
1919 def test_too_many_items():
1920 BChar = new_primitive_type("char")
1921 BArray = new_array_type(new_pointer_type(BChar), 5)
1922 pytest.raises(IndexError, newp, BArray, tuple(b'123456'))
1923 pytest.raises(IndexError, newp, BArray, list(b'123456'))
1924 pytest.raises(IndexError, newp, BArray, b'123456')
1925 BStruct = new_struct_type("struct foo")
1926 complete_struct_or_union(BStruct, [])
1927 pytest.raises(TypeError, newp, new_pointer_type(BStruct), b'')
1928 pytest.raises(ValueError, newp, new_pointer_type(BStruct), [b'1'])
1929
1930 def test_more_type_errors():
1931 BInt = new_primitive_type("int")
1932 BChar = new_primitive_type("char")
1933 BArray = new_array_type(new_pointer_type(BChar), 5)
1934 pytest.raises(TypeError, newp, BArray, 12.34)
1935 BArray = new_array_type(new_pointer_type(BInt), 5)
1936 pytest.raises(TypeError, newp, BArray, 12.34)
1937 BFloat = new_primitive_type("float")
1938 pytest.raises(TypeError, cast, BFloat, newp(BArray, None))
1939
1940 def test_more_overflow_errors():
1941 BUInt = new_primitive_type("unsigned int")
1942 pytest.raises(OverflowError, newp, new_pointer_type(BUInt), -1)
1943 pytest.raises(OverflowError, newp, new_pointer_type(BUInt), 2**32)
1944
1945 def test_newp_copying():
1946 """Test that we can do newp(<type>, <cdata of the given type>) for most
1947 types, including same-type arrays.
1948 """
1949 BInt = new_primitive_type("int")
1950 p = newp(new_pointer_type(BInt), cast(BInt, 42))
1951 assert p[0] == 42
1952 #
1953 BUInt = new_primitive_type("unsigned int")
1954 p = newp(new_pointer_type(BUInt), cast(BUInt, 42))
1955 assert p[0] == 42
1956 #
1957 BChar = new_primitive_type("char")
1958 p = newp(new_pointer_type(BChar), cast(BChar, '!'))
1959 assert p[0] == b'!'
1960 #
1961 BFloat = new_primitive_type("float")
1962 p = newp(new_pointer_type(BFloat), cast(BFloat, 12.25))
1963 assert p[0] == 12.25
1964 #
1965 BStruct = new_struct_type("struct foo_s")
1966 BStructPtr = new_pointer_type(BStruct)
1967 complete_struct_or_union(BStruct, [('a1', BInt, -1)])
1968 s1 = newp(BStructPtr, [42])
1969 p1 = newp(new_pointer_type(BStructPtr), s1)
1970 assert p1[0] == s1
1971 #
1972 BArray = new_array_type(new_pointer_type(BInt), None)
1973 a1 = newp(BArray, [1, 2, 3, 4])
1974 pytest.raises(TypeError, newp, BArray, a1)
1975 BArray6 = new_array_type(new_pointer_type(BInt), 6)
1976 a1 = newp(BArray6, [10, 20, 30])
1977 a2 = newp(BArray6, a1)
1978 assert list(a2) == [10, 20, 30, 0, 0, 0]
1979 #
1980 s1 = newp(BStructPtr, [42])
1981 s2 = newp(BStructPtr, s1[0])
1982 assert s2.a1 == 42
1983 #
1984 BUnion = new_union_type("union foo_u")
1985 BUnionPtr = new_pointer_type(BUnion)
1986 complete_struct_or_union(BUnion, [('a1', BInt, -1)])
1987 u1 = newp(BUnionPtr, [42])
1988 u2 = newp(BUnionPtr, u1[0])
1989 assert u2.a1 == 42
1990 #
1991 BFunc = new_function_type((BInt,), BUInt)
1992 p1 = cast(BFunc, 42)
1993 p2 = newp(new_pointer_type(BFunc), p1)
1994 assert p2[0] == p1
1995
1996 def test_string():
1997 BChar = new_primitive_type("char")
1998 assert string(cast(BChar, 42)) == b'*'
1999 assert string(cast(BChar, 0)) == b'\x00'
2000 BCharP = new_pointer_type(BChar)
2001 BArray = new_array_type(BCharP, 10)
2002 a = newp(BArray, b"hello")
2003 assert len(a) == 10
2004 assert string(a) == b"hello"
2005 p = a + 2
2006 assert string(p) == b"llo"
2007 assert string(newp(new_array_type(BCharP, 4), b"abcd")) == b"abcd"
2008 pytest.raises(RuntimeError, string, cast(BCharP, 0))
2009 assert string(a, 4) == b"hell"
2010 assert string(a, 5) == b"hello"
2011 assert string(a, 6) == b"hello"
2012
2013 def test_string_byte():
2014 BByte = new_primitive_type("signed char")
2015 assert string(cast(BByte, 42)) == b'*'
2016 assert string(cast(BByte, 0)) == b'\x00'
2017 BArray = new_array_type(new_pointer_type(BByte), None)
2018 a = newp(BArray, [65, 66, 67])
2019 assert type(string(a)) is bytes and string(a) == b'ABC'
2020 #
2021 BByte = new_primitive_type("unsigned char")
2022 assert string(cast(BByte, 42)) == b'*'
2023 assert string(cast(BByte, 0)) == b'\x00'
2024 BArray = new_array_type(new_pointer_type(BByte), None)
2025 a = newp(BArray, [65, 66, 67])
2026 assert type(string(a)) is bytes and string(a) == b'ABC'
2027 if 'PY_DOT_PY' not in globals() and sys.version_info < (3,):
2028 assert string(a, 8).startswith(b'ABC') # may contain additional garbage
2029
2030 def test_string_wchar():
2031 for typename in ["wchar_t", "char16_t", "char32_t"]:
2032 _test_string_wchar_variant(typename)
2033
2034 def _test_string_wchar_variant(typename):
2035 BWChar = new_primitive_type(typename)
2036 assert string(cast(BWChar, 42)) == u+'*'
2037 assert string(cast(BWChar, 0x4253)) == u+'\u4253'
2038 assert string(cast(BWChar, 0)) == u+'\x00'
2039 BArray = new_array_type(new_pointer_type(BWChar), None)
2040 a = newp(BArray, [u+'A', u+'B', u+'C'])
2041 assert type(string(a)) is unicode and string(a) == u+'ABC'
2042 if 'PY_DOT_PY' not in globals() and sys.version_info < (3,):
2043 try:
2044 # may contain additional garbage
2045 assert string(a, 8).startswith(u+'ABC')
2046 except ValueError: # garbage contains values > 0x10FFFF
2047 assert sizeof(BWChar) == 4
2048
2049 def test_string_typeerror():
2050 BShort = new_primitive_type("short")
2051 BArray = new_array_type(new_pointer_type(BShort), None)
2052 a = newp(BArray, [65, 66, 67])
2053 pytest.raises(TypeError, string, a)
2054
2055 def test_bug_convert_to_ptr():
2056 BChar = new_primitive_type("char")
2057 BCharP = new_pointer_type(BChar)
2058 BDouble = new_primitive_type("double")
2059 x = cast(BDouble, 42)
2060 pytest.raises(TypeError, newp, new_pointer_type(BCharP), x)
2061
2062 def test_set_struct_fields():
2063 BChar = new_primitive_type("char")
2064 BCharP = new_pointer_type(BChar)
2065 BCharArray10 = new_array_type(BCharP, 10)
2066 BStruct = new_struct_type("struct foo")
2067 BStructPtr = new_pointer_type(BStruct)
2068 complete_struct_or_union(BStruct, [('a1', BCharArray10, -1)])
2069 p = newp(BStructPtr, None)
2070 assert string(p.a1) == b''
2071 p.a1 = b'foo'
2072 assert string(p.a1) == b'foo'
2073 assert list(p.a1) == [b'f', b'o', b'o'] + [b'\x00'] * 7
2074 p.a1 = [b'x', b'y']
2075 assert string(p.a1) == b'xyo'
2076
2077 def test_invalid_function_result_types():
2078 BFunc = new_function_type((), new_void_type())
2079 BArray = new_array_type(new_pointer_type(BFunc), 5) # works
2080 new_function_type((), BFunc) # works
2081 new_function_type((), new_primitive_type("int"))
2082 new_function_type((), new_pointer_type(BFunc))
2083 BUnion = new_union_type("union foo_u")
2084 complete_struct_or_union(BUnion, [])
2085 BFunc = new_function_type((), BUnion)
2086 pytest.raises(NotImplementedError, cast(BFunc, 123))
2087 pytest.raises(TypeError, new_function_type, (), BArray)
2088
2089 def test_struct_return_in_func():
2090 BChar = new_primitive_type("char")
2091 BShort = new_primitive_type("short")
2092 BFloat = new_primitive_type("float")
2093 BDouble = new_primitive_type("double")
2094 BInt = new_primitive_type("int")
2095 BStruct = new_struct_type("struct foo_s")
2096 complete_struct_or_union(BStruct, [('a1', BChar, -1),
2097 ('a2', BShort, -1)])
2098 BFunc10 = new_function_type((BInt,), BStruct)
2099 f = cast(BFunc10, _testfunc(10))
2100 s = f(40)
2101 assert repr(s) == "<cdata 'struct foo_s' owning 4 bytes>"
2102 assert s.a1 == bytechr(40)
2103 assert s.a2 == 40 * 40
2104 #
2105 BStruct11 = new_struct_type("struct test11")
2106 complete_struct_or_union(BStruct11, [('a1', BInt, -1),
2107 ('a2', BInt, -1)])
2108 BFunc11 = new_function_type((BInt,), BStruct11)
2109 f = cast(BFunc11, _testfunc(11))
2110 s = f(40)
2111 assert repr(s) == "<cdata 'struct test11' owning 8 bytes>"
2112 assert s.a1 == 40
2113 assert s.a2 == 40 * 40
2114 #
2115 BStruct12 = new_struct_type("struct test12")
2116 complete_struct_or_union(BStruct12, [('a1', BDouble, -1),
2117 ])
2118 BFunc12 = new_function_type((BInt,), BStruct12)
2119 f = cast(BFunc12, _testfunc(12))
2120 s = f(40)
2121 assert repr(s) == "<cdata 'struct test12' owning 8 bytes>"
2122 assert s.a1 == 40.0
2123 #
2124 BStruct13 = new_struct_type("struct test13")
2125 complete_struct_or_union(BStruct13, [('a1', BInt, -1),
2126 ('a2', BInt, -1),
2127 ('a3', BInt, -1)])
2128 BFunc13 = new_function_type((BInt,), BStruct13)
2129 f = cast(BFunc13, _testfunc(13))
2130 s = f(40)
2131 assert repr(s) == "<cdata 'struct test13' owning 12 bytes>"
2132 assert s.a1 == 40
2133 assert s.a2 == 40 * 40
2134 assert s.a3 == 40 * 40 * 40
2135 #
2136 BStruct14 = new_struct_type("struct test14")
2137 complete_struct_or_union(BStruct14, [('a1', BFloat, -1),
2138 ])
2139 BFunc14 = new_function_type((BInt,), BStruct14)
2140 f = cast(BFunc14, _testfunc(14))
2141 s = f(40)
2142 assert repr(s) == "<cdata 'struct test14' owning 4 bytes>"
2143 assert s.a1 == 40.0
2144 #
2145 BStruct15 = new_struct_type("struct test15")
2146 complete_struct_or_union(BStruct15, [('a1', BFloat, -1),
2147 ('a2', BInt, -1)])
2148 BFunc15 = new_function_type((BInt,), BStruct15)
2149 f = cast(BFunc15, _testfunc(15))
2150 s = f(40)
2151 assert repr(s) == "<cdata 'struct test15' owning 8 bytes>"
2152 assert s.a1 == 40.0
2153 assert s.a2 == 40 * 40
2154 #
2155 BStruct16 = new_struct_type("struct test16")
2156 complete_struct_or_union(BStruct16, [('a1', BFloat, -1),
2157 ('a2', BFloat, -1)])
2158 BFunc16 = new_function_type((BInt,), BStruct16)
2159 f = cast(BFunc16, _testfunc(16))
2160 s = f(40)
2161 assert repr(s) == "<cdata 'struct test16' owning 8 bytes>"
2162 assert s.a1 == 40.0
2163 assert s.a2 == -40.0
2164 #
2165 BStruct17 = new_struct_type("struct test17")
2166 complete_struct_or_union(BStruct17, [('a1', BInt, -1),
2167 ('a2', BFloat, -1)])
2168 BFunc17 = new_function_type((BInt,), BStruct17)
2169 f = cast(BFunc17, _testfunc(17))
2170 s = f(40)
2171 assert repr(s) == "<cdata 'struct test17' owning 8 bytes>"
2172 assert s.a1 == 40
2173 assert s.a2 == 40.0 * 40.0
2174 #
2175 BStruct17Ptr = new_pointer_type(BStruct17)
2176 BFunc18 = new_function_type((BStruct17Ptr,), BInt)
2177 f = cast(BFunc18, _testfunc(18))
2178 x = f([[40, 2.5]])
2179 assert x == 42
2180 x = f([{'a2': 43.1}])
2181 assert x == 43
2182
2183 def test_cast_with_functionptr():
2184 BFunc = new_function_type((), new_void_type())
2185 BFunc2 = new_function_type((), new_primitive_type("short"))
2186 BCharP = new_pointer_type(new_primitive_type("char"))
2187 BIntP = new_pointer_type(new_primitive_type("int"))
2188 BStruct = new_struct_type("struct foo")
2189 BStructPtr = new_pointer_type(BStruct)
2190 complete_struct_or_union(BStruct, [('a1', BFunc, -1)])
2191 newp(BStructPtr, [cast(BFunc, 0)])
2192 pytest.raises(TypeError, newp, BStructPtr, [cast(BCharP, 0)])
2193 pytest.raises(TypeError, newp, BStructPtr, [cast(BIntP, 0)])
2194 pytest.raises(TypeError, newp, BStructPtr, [cast(BFunc2, 0)])
2195
2196 def test_wchar():
2197 _test_wchar_variant("wchar_t")
2198 if sys.platform.startswith("linux"):
2199 BWChar = new_primitive_type("wchar_t")
2200 assert sizeof(BWChar) == 4
2201 # wchar_t is often signed on Linux, but not always (e.g. on ARM)
2202 assert int(cast(BWChar, -1)) in (-1, 4294967295)
2203
2204 def test_char16():
2205 BChar16 = new_primitive_type("char16_t")
2206 assert sizeof(BChar16) == 2
2207 _test_wchar_variant("char16_t")
2208 assert int(cast(BChar16, -1)) == 0xffff # always unsigned
2209
2210 def test_char32():
2211 BChar32 = new_primitive_type("char32_t")
2212 assert sizeof(BChar32) == 4
2213 _test_wchar_variant("char32_t")
2214 assert int(cast(BChar32, -1)) == 0xffffffff # always unsigned
2215
2216 def _test_wchar_variant(typename):
2217 BWChar = new_primitive_type(typename)
2218 BInt = new_primitive_type("int")
2219 pyuni4 = {1: True, 2: False}[len(u+'\U00012345')]
2220 wchar4 = {2: False, 4: True}[sizeof(BWChar)]
2221 assert str(cast(BWChar, 0x45)) == "<cdata '%s' %s'E'>" % (
2222 typename, mandatory_u_prefix)
2223 assert str(cast(BWChar, 0x1234)) == "<cdata '%s' %s'\u1234'>" % (
2224 typename, mandatory_u_prefix)
2225 if not _hacked_pypy_uni4():
2226 if wchar4:
2227 x = cast(BWChar, 0x12345)
2228 assert str(x) == "<cdata '%s' %s'\U00012345'>" % (
2229 typename, mandatory_u_prefix)
2230 assert int(x) == 0x12345
2231 else:
2232 x = cast(BWChar, 0x18345)
2233 assert str(x) == "<cdata '%s' %s'\u8345'>" % (
2234 typename, mandatory_u_prefix)
2235 assert int(x) == 0x8345
2236 #
2237 BWCharP = new_pointer_type(BWChar)
2238 BStruct = new_struct_type("struct foo_s")
2239 BStructPtr = new_pointer_type(BStruct)
2240 complete_struct_or_union(BStruct, [('a1', BWChar, -1),
2241 ('a2', BWCharP, -1)])
2242 s = newp(BStructPtr)
2243 s.a1 = u+'\x00'
2244 assert s.a1 == u+'\x00'
2245 with pytest.raises(TypeError):
2246 s.a1 = b'a'
2247 with pytest.raises(TypeError):
2248 s.a1 = bytechr(0xFF)
2249 s.a1 = u+'\u1234'
2250 assert s.a1 == u+'\u1234'
2251 if pyuni4:
2252 if wchar4:
2253 s.a1 = u+'\U00012345'
2254 assert s.a1 == u+'\U00012345'
2255 elif wchar4:
2256 if not _hacked_pypy_uni4():
2257 s.a1 = cast(BWChar, 0x12345)
2258 assert s.a1 == u+'\ud808\udf45'
2259 s.a1 = u+'\ud807\udf44'
2260 assert s.a1 == u+'\U00011f44'
2261 else:
2262 with pytest.raises(TypeError):
2263 s.a1 = u+'\U00012345'
2264 #
2265 BWCharArray = new_array_type(BWCharP, None)
2266 a = newp(BWCharArray, u+'hello \u1234 world')
2267 assert len(a) == 14 # including the final null
2268 assert string(a) == u+'hello \u1234 world'
2269 a[13] = u+'!'
2270 assert string(a) == u+'hello \u1234 world!'
2271 assert str(a) == repr(a)
2272 assert a[6] == u+'\u1234'
2273 a[6] = u+'-'
2274 assert string(a) == u+'hello - world!'
2275 assert str(a) == repr(a)
2276 #
2277 if wchar4 and not _hacked_pypy_uni4():
2278 u1 = u+'\U00012345\U00012346\U00012347'
2279 a = newp(BWCharArray, u1)
2280 assert len(a) == 4
2281 assert string(a) == u1
2282 assert len(list(a)) == 4
2283 expected = [u+'\U00012345', u+'\U00012346', u+'\U00012347', unichr(0)]
2284 assert list(a) == expected
2285 got = [a[i] for i in range(4)]
2286 assert got == expected
2287 with pytest.raises(IndexError):
2288 a[4]
2289 #
2290 w = cast(BWChar, 'a')
2291 assert repr(w) == "<cdata '%s' %s'a'>" % (typename, mandatory_u_prefix)
2292 assert str(w) == repr(w)
2293 assert string(w) == u+'a'
2294 assert int(w) == ord('a')
2295 w = cast(BWChar, 0x1234)
2296 assert repr(w) == "<cdata '%s' %s'\u1234'>" % (typename, mandatory_u_prefix)
2297 assert str(w) == repr(w)
2298 assert string(w) == u+'\u1234'
2299 assert int(w) == 0x1234
2300 w = cast(BWChar, u+'\u8234')
2301 assert repr(w) == "<cdata '%s' %s'\u8234'>" % (typename, mandatory_u_prefix)
2302 assert str(w) == repr(w)
2303 assert string(w) == u+'\u8234'
2304 assert int(w) == 0x8234
2305 w = cast(BInt, u+'\u1234')
2306 assert repr(w) == "<cdata 'int' 4660>"
2307 if wchar4 and not _hacked_pypy_uni4():
2308 w = cast(BWChar, u+'\U00012345')
2309 assert repr(w) == "<cdata '%s' %s'\U00012345'>" % (
2310 typename, mandatory_u_prefix)
2311 assert str(w) == repr(w)
2312 assert string(w) == u+'\U00012345'
2313 assert int(w) == 0x12345
2314 w = cast(BInt, u+'\U00012345')
2315 assert repr(w) == "<cdata 'int' 74565>"
2316 pytest.raises(TypeError, cast, BInt, u+'')
2317 pytest.raises(TypeError, cast, BInt, u+'XX')
2318 assert int(cast(BInt, u+'a')) == ord('a')
2319 #
2320 a = newp(BWCharArray, u+'hello - world')
2321 p = cast(BWCharP, a)
2322 assert string(p) == u+'hello - world'
2323 p[6] = u+'\u2345'
2324 assert string(p) == u+'hello \u2345 world'
2325 #
2326 s = newp(BStructPtr, [u+'\u1234', p])
2327 assert s.a1 == u+'\u1234'
2328 assert s.a2 == p
2329 assert str(s.a2) == repr(s.a2)
2330 assert string(s.a2) == u+'hello \u2345 world'
2331 #
2332 q = cast(BWCharP, 0)
2333 assert str(q) == repr(q)
2334 pytest.raises(RuntimeError, string, q)
2335 #
2336 if is_ios:
2337 return # cannot allocate executable memory for the callback() below
2338 def cb(p):
2339 assert repr(p).startswith("<cdata '%s *' 0x" % typename)
2340 return len(string(p))
2341 BFunc = new_function_type((BWCharP,), BInt, False)
2342 f = callback(BFunc, cb, -42)
2343 assert f(u+'a\u1234b') == 3
2344 #
2345 if wchar4 and not pyuni4 and not _hacked_pypy_uni4():
2346 # try out-of-range wchar_t values
2347 x = cast(BWChar, 1114112)
2348 pytest.raises(ValueError, string, x)
2349 x = cast(BWChar, -1)
2350 pytest.raises(ValueError, string, x)
2351
2352 def test_wchar_variants_mix():
2353 BWChar = new_primitive_type("wchar_t")
2354 BChar16 = new_primitive_type("char16_t")
2355 BChar32 = new_primitive_type("char32_t")
2356 assert int(cast(BChar32, cast(BChar16, -2))) == 0xfffe
2357 assert int(cast(BWChar, cast(BChar16, -2))) == 0xfffe
2358 assert int(cast(BChar16, cast(BChar32, 0x0001f345))) == 0xf345
2359 assert int(cast(BChar16, cast(BWChar, 0x0001f345))) == 0xf345
2360 #
2361 BChar16A = new_array_type(new_pointer_type(BChar16), None)
2362 BChar32A = new_array_type(new_pointer_type(BChar32), None)
2363 x = cast(BChar32, 'A')
2364 pytest.raises(TypeError, newp, BChar16A, [x])
2365 x = cast(BChar16, 'A')
2366 pytest.raises(TypeError, newp, BChar32A, [x])
2367 #
2368 a = newp(BChar16A, u+'\U00012345')
2369 assert len(a) == 3
2370 a = newp(BChar32A, u+'\U00012345')
2371 assert len(a) == 2 # even if the Python unicode string above is 2 chars
2372
2373 def test_keepalive_struct():
2374 # exception to the no-keepalive rule: p=newp(BStructPtr) returns a
2375 # pointer owning the memory, and p[0] returns a pointer to the
2376 # struct that *also* owns the memory
2377 BStruct = new_struct_type("struct foo")
2378 BStructPtr = new_pointer_type(BStruct)
2379 complete_struct_or_union(BStruct, [('a1', new_primitive_type("int"), -1),
2380 ('a2', new_primitive_type("int"), -1),
2381 ('a3', new_primitive_type("int"), -1)])
2382 p = newp(BStructPtr)
2383 assert repr(p) == "<cdata 'struct foo *' owning 12 bytes>"
2384 q = p[0]
2385 assert repr(q) == "<cdata 'struct foo' owning 12 bytes>"
2386 q.a1 = 123456
2387 assert p.a1 == 123456
2388 r = cast(BStructPtr, p)
2389 assert repr(r[0]).startswith("<cdata 'struct foo &' 0x")
2390 del p
2391 import gc; gc.collect()
2392 assert q.a1 == 123456
2393 assert repr(q) == "<cdata 'struct foo' owning 12 bytes>"
2394 assert q.a1 == 123456
2395
2396 def test_nokeepalive_struct():
2397 BStruct = new_struct_type("struct foo")
2398 BStructPtr = new_pointer_type(BStruct)
2399 BStructPtrPtr = new_pointer_type(BStructPtr)
2400 complete_struct_or_union(BStruct, [('a1', new_primitive_type("int"), -1)])
2401 p = newp(BStructPtr)
2402 pp = newp(BStructPtrPtr)
2403 pp[0] = p
2404 s = pp[0][0]
2405 assert repr(s).startswith("<cdata 'struct foo &' 0x")
2406
2407 def test_owning_repr():
2408 BInt = new_primitive_type("int")
2409 BArray = new_array_type(new_pointer_type(BInt), None) # int[]
2410 p = newp(BArray, 7)
2411 assert repr(p) == "<cdata 'int[]' owning 28 bytes>"
2412 assert sizeof(p) == 28
2413 #
2414 BArray = new_array_type(new_pointer_type(BInt), 7) # int[7]
2415 p = newp(BArray, None)
2416 assert repr(p) == "<cdata 'int[7]' owning 28 bytes>"
2417 assert sizeof(p) == 28
2418
2419 def test_cannot_dereference_void():
2420 BVoidP = new_pointer_type(new_void_type())
2421 p = cast(BVoidP, 123456)
2422 with pytest.raises(TypeError):
2423 p[0]
2424 p = cast(BVoidP, 0)
2425 with pytest.raises((TypeError, RuntimeError)):
2426 p[0]
2427
2428 def test_iter():
2429 BInt = new_primitive_type("int")
2430 BIntP = new_pointer_type(BInt)
2431 BArray = new_array_type(BIntP, None) # int[]
2432 p = newp(BArray, 7)
2433 assert list(p) == list(iter(p)) == [0] * 7
2434 #
2435 pytest.raises(TypeError, iter, cast(BInt, 5))
2436 pytest.raises(TypeError, iter, cast(BIntP, 123456))
2437
2438 def test_cmp():
2439 BInt = new_primitive_type("int")
2440 BIntP = new_pointer_type(BInt)
2441 BVoidP = new_pointer_type(new_void_type())
2442 p = newp(BIntP, 123)
2443 q = cast(BInt, 124)
2444 assert (p == q) is False
2445 assert (p != q) is True
2446 assert (q == p) is False
2447 assert (q != p) is True
2448 if strict_compare:
2449 with pytest.raises(TypeError): p < q
2450 with pytest.raises(TypeError): p <= q
2451 with pytest.raises(TypeError): q < p
2452 with pytest.raises(TypeError): q <= p
2453 with pytest.raises(TypeError): p > q
2454 with pytest.raises(TypeError): p >= q
2455 r = cast(BVoidP, p)
2456 assert (p < r) is False
2457 assert (p <= r) is True
2458 assert (p == r) is True
2459 assert (p != r) is False
2460 assert (p > r) is False
2461 assert (p >= r) is True
2462 s = newp(BIntP, 125)
2463 assert (p == s) is False
2464 assert (p != s) is True
2465 assert (p < s) is (p <= s) is (s > p) is (s >= p)
2466 assert (p > s) is (p >= s) is (s < p) is (s <= p)
2467 assert (p < s) ^ (p > s)
2468
2469 def test_buffer():
2470 try:
2471 import __builtin__
2472 except ImportError:
2473 import builtins as __builtin__
2474 BShort = new_primitive_type("short")
2475 s = newp(new_pointer_type(BShort), 100)
2476 assert sizeof(s) == size_of_ptr()
2477 assert sizeof(BShort) == 2
2478 assert len(buffer(s)) == 2
2479 #
2480 BChar = new_primitive_type("char")
2481 BCharArray = new_array_type(new_pointer_type(BChar), None)
2482 c = newp(BCharArray, b"hi there")
2483 #
2484 buf = buffer(c)
2485 assert repr(buf).startswith('<_cffi_backend.buffer object at 0x')
2486 assert bytes(buf) == b"hi there\x00"
2487 assert type(buf) is buffer
2488 if sys.version_info < (3,):
2489 assert str(buf) == "hi there\x00"
2490 assert unicode(buf) == u+"hi there\x00"
2491 else:
2492 assert str(buf) == repr(buf)
2493 # --mb_length--
2494 assert len(buf) == len(b"hi there\x00")
2495 # --mb_item--
2496 for i in range(-12, 12):
2497 try:
2498 expected = b"hi there\x00"[i]
2499 except IndexError:
2500 with pytest.raises(IndexError):
2501 buf[i]
2502 else:
2503 assert buf[i] == bitem2bchr(expected)
2504 # --mb_slice--
2505 assert buf[:] == b"hi there\x00"
2506 for i in range(-12, 12):
2507 assert buf[i:] == b"hi there\x00"[i:]
2508 assert buf[:i] == b"hi there\x00"[:i]
2509 for j in range(-12, 12):
2510 assert buf[i:j] == b"hi there\x00"[i:j]
2511 # --misc--
2512 assert list(buf) == list(map(bitem2bchr, b"hi there\x00"))
2513 # --mb_as_buffer--
2514 if hasattr(__builtin__, 'buffer'): # Python <= 2.7
2515 pytest.raises(TypeError, __builtin__.buffer, c)
2516 bf1 = __builtin__.buffer(buf)
2517 assert len(bf1) == len(buf) and bf1[3] == "t"
2518 if hasattr(__builtin__, 'memoryview'): # Python >= 2.7
2519 pytest.raises(TypeError, memoryview, c)
2520 mv1 = memoryview(buf)
2521 assert len(mv1) == len(buf) and mv1[3] in (b"t", ord(b"t"))
2522 # --mb_ass_item--
2523 expected = list(map(bitem2bchr, b"hi there\x00"))
2524 for i in range(-12, 12):
2525 try:
2526 expected[i] = bytechr(i & 0xff)
2527 except IndexError:
2528 with pytest.raises(IndexError):
2529 buf[i] = bytechr(i & 0xff)
2530 else:
2531 buf[i] = bytechr(i & 0xff)
2532 assert list(buf) == expected
2533 # --mb_ass_slice--
2534 buf[:] = b"hi there\x00"
2535 assert list(buf) == list(c) == list(map(bitem2bchr, b"hi there\x00"))
2536 with pytest.raises(ValueError):
2537 buf[:] = b"shorter"
2538 with pytest.raises(ValueError):
2539 buf[:] = b"this is much too long!"
2540 buf[4:2] = b"" # no effect, but should work
2541 assert buf[:] == b"hi there\x00"
2542 buf[:2] = b"HI"
2543 assert buf[:] == b"HI there\x00"
2544 buf[:2] = b"hi"
2545 expected = list(map(bitem2bchr, b"hi there\x00"))
2546 x = 0
2547 for i in range(-12, 12):
2548 for j in range(-12, 12):
2549 start = i if i >= 0 else i + len(buf)
2550 stop = j if j >= 0 else j + len(buf)
2551 start = max(0, min(len(buf), start))
2552 stop = max(0, min(len(buf), stop))
2553 sample = bytechr(x & 0xff) * (stop - start)
2554 x += 1
2555 buf[i:j] = sample
2556 expected[i:j] = map(bitem2bchr, sample)
2557 assert list(buf) == expected
2558
2559 def test_getcname():
2560 BUChar = new_primitive_type("unsigned char")
2561 BArray = new_array_type(new_pointer_type(BUChar), 123)
2562 assert getcname(BArray, "<-->") == "unsigned char<-->[123]"
2563
2564 def test_errno():
2565 BVoid = new_void_type()
2566 BFunc5 = new_function_type((), BVoid)
2567 f = cast(BFunc5, _testfunc(5))
2568 set_errno(50)
2569 f()
2570 assert get_errno() == 65
2571 f(); f()
2572 assert get_errno() == 95
2573
2574 @pytest.mark.skipif(is_ios, reason="Cannot allocate executable memory on iOS")
2575 def test_errno_callback():
2576 if globals().get('PY_DOT_PY'):
2577 pytest.skip("cannot run this test on py.py (e.g. fails on Windows)")
2578 set_errno(95)
2579 def cb():
2580 e = get_errno()
2581 set_errno(e - 6)
2582 BVoid = new_void_type()
2583 BFunc5 = new_function_type((), BVoid)
2584 f = callback(BFunc5, cb)
2585 f()
2586 assert get_errno() == 89
2587 f(); f()
2588 assert get_errno() == 77
2589
2590 def test_cast_to_array():
2591 # not valid in C! extension to get a non-owning <cdata 'int[3]'>
2592 BInt = new_primitive_type("int")
2593 BIntP = new_pointer_type(BInt)
2594 BArray = new_array_type(BIntP, 3)
2595 x = cast(BArray, 0)
2596 assert repr(x) == "<cdata 'int[3]' NULL>"
2597
2598 def test_cast_invalid():
2599 BStruct = new_struct_type("struct foo")
2600 complete_struct_or_union(BStruct, [])
2601 p = cast(new_pointer_type(BStruct), 123456)
2602 s = p[0]
2603 pytest.raises(TypeError, cast, BStruct, s)
2604
2605 def test_bug_float_convertion():
2606 BDouble = new_primitive_type("double")
2607 BDoubleP = new_pointer_type(BDouble)
2608 pytest.raises(TypeError, newp, BDoubleP, "foobar")
2609
2610 def test_bug_delitem():
2611 BChar = new_primitive_type("char")
2612 BCharP = new_pointer_type(BChar)
2613 x = newp(BCharP)
2614 with pytest.raises(TypeError):
2615 del x[0]
2616
2617 def test_bug_delattr():
2618 BLong = new_primitive_type("long")
2619 BStruct = new_struct_type("struct foo")
2620 complete_struct_or_union(BStruct, [('a1', BLong, -1)])
2621 x = newp(new_pointer_type(BStruct))
2622 with pytest.raises(AttributeError):
2623 del x.a1
2624
2625 def test_variable_length_struct():
2626 pytest.skip("later")
2627 BLong = new_primitive_type("long")
2628 BArray = new_array_type(new_pointer_type(BLong), None)
2629 BStruct = new_struct_type("struct foo")
2630 BStructP = new_pointer_type(BStruct)
2631 complete_struct_or_union(BStruct, [('a1', BLong, -1),
2632 ('a2', BArray, -1)])
2633 assert sizeof(BStruct) == size_of_long()
2634 assert alignof(BStruct) == alignof(BLong)
2635 #
2636 pytest.raises(TypeError, newp, BStructP, None)
2637 x = newp(BStructP, 5)
2638 assert sizeof(x) == 6 * size_of_long()
2639 x[4] = 123
2640 assert x[4] == 123
2641 with pytest.raises(IndexError):
2642 x[5]
2643 assert len(x.a2) == 5
2644 #
2645 pytest.raises(TypeError, newp, BStructP, [123])
2646 x = newp(BStructP, [123, 5])
2647 assert x.a1 == 123
2648 assert len(x.a2) == 5
2649 assert list(x.a2) == [0] * 5
2650 #
2651 x = newp(BStructP, {'a2': 5})
2652 assert x.a1 == 0
2653 assert len(x.a2) == 5
2654 assert list(x.a2) == [0] * 5
2655 #
2656 x = newp(BStructP, [123, (4, 5)])
2657 assert x.a1 == 123
2658 assert len(x.a2) == 2
2659 assert list(x.a2) == [4, 5]
2660 #
2661 x = newp(BStructP, {'a2': (4, 5)})
2662 assert x.a1 == 0
2663 assert len(x.a2) == 2
2664 assert list(x.a2) == [4, 5]
2665
2666 def test_autocast_int():
2667 BInt = new_primitive_type("int")
2668 BIntPtr = new_pointer_type(BInt)
2669 BLongLong = new_primitive_type("long long")
2670 BULongLong = new_primitive_type("unsigned long long")
2671 BULongLongPtr = new_pointer_type(BULongLong)
2672 x = newp(BIntPtr, cast(BInt, 42))
2673 assert x[0] == 42
2674 x = newp(BIntPtr, cast(BLongLong, 42))
2675 assert x[0] == 42
2676 x = newp(BIntPtr, cast(BULongLong, 42))
2677 assert x[0] == 42
2678 x = newp(BULongLongPtr, cast(BInt, 42))
2679 assert x[0] == 42
2680 pytest.raises(OverflowError, newp, BULongLongPtr, cast(BInt, -42))
2681 x = cast(BInt, cast(BInt, 42))
2682 assert int(x) == 42
2683 x = cast(BInt, cast(BLongLong, 42))
2684 assert int(x) == 42
2685 x = cast(BInt, cast(BULongLong, 42))
2686 assert int(x) == 42
2687 x = cast(BULongLong, cast(BInt, 42))
2688 assert int(x) == 42
2689 x = cast(BULongLong, cast(BInt, -42))
2690 assert int(x) == 2 ** 64 - 42
2691 x = cast(BIntPtr, cast(BInt, 42))
2692 assert int(cast(BInt, x)) == 42
2693
2694 def test_autocast_float():
2695 BFloat = new_primitive_type("float")
2696 BDouble = new_primitive_type("float")
2697 BFloatPtr = new_pointer_type(BFloat)
2698 x = newp(BFloatPtr, cast(BDouble, 12.5))
2699 assert x[0] == 12.5
2700 x = cast(BFloat, cast(BDouble, 12.5))
2701 assert float(x) == 12.5
2702
2703 def test_longdouble():
2704 py_py = 'PY_DOT_PY' in globals()
2705 BInt = new_primitive_type("int")
2706 BLongDouble = new_primitive_type("long double")
2707 BLongDoublePtr = new_pointer_type(BLongDouble)
2708 BLongDoubleArray = new_array_type(BLongDoublePtr, None)
2709 a = newp(BLongDoubleArray, 1)
2710 x = a[0]
2711 if not py_py:
2712 assert repr(x).startswith("<cdata 'long double' 0.0")
2713 assert float(x) == 0.0
2714 assert int(x) == 0
2715 #
2716 b = newp(BLongDoubleArray, [1.23])
2717 x = b[0]
2718 if not py_py:
2719 assert repr(x).startswith("<cdata 'long double' 1.23")
2720 assert float(x) == 1.23
2721 assert int(x) == 1
2722 #
2723 BFunc19 = new_function_type((BLongDouble, BInt), BLongDouble)
2724 f = cast(BFunc19, _testfunc(19))
2725 start = lstart = 1.5
2726 for i in range(107):
2727 start = 4 * start - start * start
2728 lstart = f(lstart, 1)
2729 lother = f(1.5, 107)
2730 if not py_py:
2731 assert float(lstart) == float(lother)
2732 assert repr(lstart) == repr(lother)
2733 if sizeof(BLongDouble) > sizeof(new_primitive_type("double")):
2734 assert float(lstart) != start
2735 assert repr(lstart).startswith("<cdata 'long double' ")
2736 #
2737 c = newp(BLongDoubleArray, [lstart])
2738 x = c[0]
2739 assert float(f(lstart, 107)) == float(f(x, 107))
2740
2741 def test_get_array_of_length_zero():
2742 for length in [0, 5, 10]:
2743 BLong = new_primitive_type("long")
2744 BLongP = new_pointer_type(BLong)
2745 BArray0 = new_array_type(BLongP, length)
2746 BStruct = new_struct_type("struct foo")
2747 BStructPtr = new_pointer_type(BStruct)
2748 complete_struct_or_union(BStruct, [('a1', BArray0, -1)])
2749 p = newp(BStructPtr, None)
2750 if length == 0:
2751 assert repr(p.a1).startswith("<cdata 'long *' 0x")
2752 else:
2753 assert repr(p.a1).startswith("<cdata 'long[%d]' 0x" % length)
2754
2755 def test_nested_anonymous_struct():
2756 BInt = new_primitive_type("int")
2757 BChar = new_primitive_type("char")
2758 BStruct = new_struct_type("struct foo")
2759 BInnerStruct = new_struct_type("struct foo")
2760 complete_struct_or_union(BInnerStruct, [('a1', BInt, -1),
2761 ('a2', BChar, -1)])
2762 complete_struct_or_union(BStruct, [('', BInnerStruct, -1),
2763 ('a3', BChar, -1)])
2764 assert sizeof(BInnerStruct) == sizeof(BInt) * 2 # with alignment
2765 assert sizeof(BStruct) == sizeof(BInt) * 3 # 'a3' is placed after
2766 d = BStruct.fields
2767 assert len(d) == 3
2768 assert d[0][0] == 'a1'
2769 assert d[0][1].type is BInt
2770 assert d[0][1].offset == 0
2771 assert d[0][1].bitshift == -1
2772 assert d[0][1].bitsize == -1
2773 assert d[1][0] == 'a2'
2774 assert d[1][1].type is BChar
2775 assert d[1][1].offset == sizeof(BInt)
2776 assert d[1][1].bitshift == -1
2777 assert d[1][1].bitsize == -1
2778 assert d[2][0] == 'a3'
2779 assert d[2][1].type is BChar
2780 assert d[2][1].offset == sizeof(BInt) * 2
2781 assert d[2][1].bitshift == -1
2782 assert d[2][1].bitsize == -1
2783
2784 def test_nested_anonymous_struct_2():
2785 BInt = new_primitive_type("int")
2786 BStruct = new_struct_type("struct foo")
2787 BInnerUnion = new_union_type("union bar")
2788 complete_struct_or_union(BInnerUnion, [('a1', BInt, -1),
2789 ('a2', BInt, -1)])
2790 complete_struct_or_union(BStruct, [('b1', BInt, -1),
2791 ('', BInnerUnion, -1),
2792 ('b2', BInt, -1)])
2793 assert sizeof(BInnerUnion) == sizeof(BInt)
2794 assert sizeof(BStruct) == sizeof(BInt) * 3
2795 fields = [(name, fld.offset, fld.flags) for (name, fld) in BStruct.fields]
2796 assert fields == [
2797 ('b1', 0 * sizeof(BInt), 0),
2798 ('a1', 1 * sizeof(BInt), 0),
2799 ('a2', 1 * sizeof(BInt), 1),
2800 ('b2', 2 * sizeof(BInt), 0),
2801 ]
2802
2803 def test_sizeof_union():
2804 # a union has the largest alignment of its members, and a total size
2805 # that is the largest of its items *possibly further aligned* if
2806 # another smaller item has a larger alignment...
2807 BChar = new_primitive_type("char")
2808 BShort = new_primitive_type("short")
2809 assert sizeof(BShort) == alignof(BShort) == 2
2810 BStruct = new_struct_type("struct foo")
2811 complete_struct_or_union(BStruct, [('a1', BChar),
2812 ('a2', BChar),
2813 ('a3', BChar)])
2814 assert sizeof(BStruct) == 3 and alignof(BStruct) == 1
2815 BUnion = new_union_type("union u")
2816 complete_struct_or_union(BUnion, [('s', BStruct),
2817 ('i', BShort)])
2818 assert sizeof(BUnion) == 4
2819 assert alignof(BUnion) == 2
2820
2821 def test_unaligned_struct():
2822 BInt = new_primitive_type("int")
2823 BStruct = new_struct_type("struct foo")
2824 complete_struct_or_union(BStruct, [('b', BInt, -1, 1)],
2825 None, 5, 1)
2826
2827 def test_CData_CType():
2828 CData, CType = _get_types()
2829 BChar = new_primitive_type("char")
2830 BCharP = new_pointer_type(BChar)
2831 nullchr = cast(BChar, 0)
2832 chrref = newp(BCharP, None)
2833 assert isinstance(nullchr, CData)
2834 assert isinstance(chrref, CData)
2835 assert not isinstance(BChar, CData)
2836 assert not isinstance(nullchr, CType)
2837 assert not isinstance(chrref, CType)
2838 assert isinstance(BChar, CType)
2839
2840 def test_no_cdata_float():
2841 BInt = new_primitive_type("int")
2842 BIntP = new_pointer_type(BInt)
2843 BUInt = new_primitive_type("unsigned int")
2844 BUIntP = new_pointer_type(BUInt)
2845 BFloat = new_primitive_type("float")
2846 pytest.raises(TypeError, newp, BIntP, cast(BFloat, 0.0))
2847 pytest.raises(TypeError, newp, BUIntP, cast(BFloat, 0.0))
2848
2849 def test_bool():
2850 BBool = new_primitive_type("_Bool")
2851 BBoolP = new_pointer_type(BBool)
2852 assert int(cast(BBool, False)) == 0
2853 assert int(cast(BBool, True)) == 1
2854 assert bool(cast(BBool, False)) is False # since 1.7
2855 assert bool(cast(BBool, True)) is True
2856 assert int(cast(BBool, 3)) == 1
2857 assert int(cast(BBool, long(3))) == 1
2858 assert int(cast(BBool, long(10)**4000)) == 1
2859 assert int(cast(BBool, -0.1)) == 1
2860 assert int(cast(BBool, -0.0)) == 0
2861 assert int(cast(BBool, '\x00')) == 0
2862 assert int(cast(BBool, '\xff')) == 1
2863 assert newp(BBoolP, False)[0] == 0
2864 assert newp(BBoolP, True)[0] == 1
2865 assert newp(BBoolP, 0)[0] == 0
2866 assert newp(BBoolP, 1)[0] == 1
2867 pytest.raises(TypeError, newp, BBoolP, 1.0)
2868 pytest.raises(TypeError, newp, BBoolP, '\x00')
2869 pytest.raises(OverflowError, newp, BBoolP, 2)
2870 pytest.raises(OverflowError, newp, BBoolP, -1)
2871 BCharP = new_pointer_type(new_primitive_type("char"))
2872 p = newp(BCharP, b'\x01')
2873 q = cast(BBoolP, p)
2874 assert q[0] is True
2875 p = newp(BCharP, b'\x00')
2876 q = cast(BBoolP, p)
2877 assert q[0] is False
2878 pytest.raises(TypeError, string, cast(BBool, False))
2879 BDouble = new_primitive_type("double")
2880 assert int(cast(BBool, cast(BDouble, 0.1))) == 1
2881 assert int(cast(BBool, cast(BDouble, 0.0))) == 0
2882 BBoolA = new_array_type(BBoolP, None)
2883 p = newp(BBoolA, b'\x01\x00')
2884 assert p[0] is True
2885 assert p[1] is False
2886
2887 def test_bool_forbidden_cases():
2888 BBool = new_primitive_type("_Bool")
2889 BBoolP = new_pointer_type(BBool)
2890 BBoolA = new_array_type(BBoolP, None)
2891 BCharP = new_pointer_type(new_primitive_type("char"))
2892 p = newp(BCharP, b'X')
2893 q = cast(BBoolP, p)
2894 with pytest.raises(ValueError):
2895 q[0]
2896 pytest.raises(TypeError, newp, BBoolP, b'\x00')
2897 assert newp(BBoolP, 0)[0] is False
2898 assert newp(BBoolP, 1)[0] is True
2899 pytest.raises(OverflowError, newp, BBoolP, 2)
2900 pytest.raises(OverflowError, newp, BBoolP, -1)
2901 pytest.raises(ValueError, newp, BBoolA, b'\x00\x01\x02')
2902 pytest.raises(OverflowError, newp, BBoolA, [0, 1, 2])
2903 pytest.raises(TypeError, string, newp(BBoolP, 1))
2904 pytest.raises(TypeError, string, newp(BBoolA, [1]))
2905
2906 def test_typeoffsetof():
2907 BChar = new_primitive_type("char")
2908 BStruct = new_struct_type("struct foo")
2909 BStructPtr = new_pointer_type(BStruct)
2910 complete_struct_or_union(BStruct, [('a1', BChar, -1),
2911 ('a2', BChar, -1),
2912 ('a3', BChar, -1)])
2913 pytest.raises(TypeError, typeoffsetof, BStructPtr, None)
2914 pytest.raises(TypeError, typeoffsetof, BStruct, None)
2915 assert typeoffsetof(BStructPtr, 'a1') == (BChar, 0)
2916 assert typeoffsetof(BStruct, 'a1') == (BChar, 0)
2917 assert typeoffsetof(BStructPtr, 'a2') == (BChar, 1)
2918 assert typeoffsetof(BStruct, 'a3') == (BChar, 2)
2919 assert typeoffsetof(BStructPtr, 'a2', 0) == (BChar, 1)
2920 assert typeoffsetof(BStruct, u+'a3') == (BChar, 2)
2921 pytest.raises(TypeError, typeoffsetof, BStructPtr, 'a2', 1)
2922 pytest.raises(KeyError, typeoffsetof, BStructPtr, 'a4')
2923 pytest.raises(KeyError, typeoffsetof, BStruct, 'a5')
2924 pytest.raises(TypeError, typeoffsetof, BStruct, 42)
2925 pytest.raises(TypeError, typeoffsetof, BChar, 'a1')
2926
2927 def test_typeoffsetof_array():
2928 BInt = new_primitive_type("int")
2929 BIntP = new_pointer_type(BInt)
2930 BArray = new_array_type(BIntP, None)
2931 pytest.raises(TypeError, typeoffsetof, BArray, None)
2932 pytest.raises(TypeError, typeoffsetof, BArray, 'a1')
2933 assert typeoffsetof(BArray, 51) == (BInt, 51 * size_of_int())
2934 assert typeoffsetof(BIntP, 51) == (BInt, 51 * size_of_int())
2935 assert typeoffsetof(BArray, -51) == (BInt, -51 * size_of_int())
2936 MAX = sys.maxsize // size_of_int()
2937 assert typeoffsetof(BArray, MAX) == (BInt, MAX * size_of_int())
2938 assert typeoffsetof(BIntP, MAX) == (BInt, MAX * size_of_int())
2939 pytest.raises(OverflowError, typeoffsetof, BArray, MAX + 1)
2940
2941 def test_typeoffsetof_no_bitfield():
2942 BInt = new_primitive_type("int")
2943 BStruct = new_struct_type("struct foo")
2944 complete_struct_or_union(BStruct, [('a1', BInt, 4)])
2945 pytest.raises(TypeError, typeoffsetof, BStruct, 'a1')
2946
2947 def test_rawaddressof():
2948 BChar = new_primitive_type("char")
2949 BCharP = new_pointer_type(BChar)
2950 BStruct = new_struct_type("struct foo")
2951 BStructPtr = new_pointer_type(BStruct)
2952 complete_struct_or_union(BStruct, [('a1', BChar, -1),
2953 ('a2', BChar, -1),
2954 ('a3', BChar, -1)])
2955 p = newp(BStructPtr)
2956 assert repr(p) == "<cdata 'struct foo *' owning 3 bytes>"
2957 s = p[0]
2958 assert repr(s) == "<cdata 'struct foo' owning 3 bytes>"
2959 a = rawaddressof(BStructPtr, s, 0)
2960 assert repr(a).startswith("<cdata 'struct foo *' 0x")
2961 pytest.raises(TypeError, rawaddressof, BStruct, s, 0)
2962 b = rawaddressof(BCharP, s, 0)
2963 assert b == cast(BCharP, p)
2964 c = rawaddressof(BStructPtr, a, 0)
2965 assert c == a
2966 pytest.raises(TypeError, rawaddressof, BStructPtr, cast(BChar, '?'), 0)
2967 #
2968 d = rawaddressof(BCharP, s, 1)
2969 assert d == cast(BCharP, p) + 1
2970 #
2971 e = cast(BCharP, 109238)
2972 f = rawaddressof(BCharP, e, 42)
2973 assert f == e + 42
2974 #
2975 BCharA = new_array_type(BCharP, None)
2976 e = newp(BCharA, 50)
2977 f = rawaddressof(BCharP, e, 42)
2978 assert f == e + 42
2979
2980 def test_newp_signed_unsigned_char():
2981 BCharArray = new_array_type(
2982 new_pointer_type(new_primitive_type("char")), None)
2983 p = newp(BCharArray, b"foo")
2984 assert len(p) == 4
2985 assert list(p) == [b"f", b"o", b"o", b"\x00"]
2986 #
2987 BUCharArray = new_array_type(
2988 new_pointer_type(new_primitive_type("unsigned char")), None)
2989 p = newp(BUCharArray, b"fo\xff")
2990 assert len(p) == 4
2991 assert list(p) == [ord("f"), ord("o"), 0xff, 0]
2992 #
2993 BSCharArray = new_array_type(
2994 new_pointer_type(new_primitive_type("signed char")), None)
2995 p = newp(BSCharArray, b"fo\xff")
2996 assert len(p) == 4
2997 assert list(p) == [ord("f"), ord("o"), -1, 0]
2998
2999 def test_newp_from_bytearray_doesnt_work():
3000 BCharArray = new_array_type(
3001 new_pointer_type(new_primitive_type("char")), None)
3002 pytest.raises(TypeError, newp, BCharArray, bytearray(b"foo"))
3003 p = newp(BCharArray, 5)
3004 buffer(p)[:] = bytearray(b"foo.\x00")
3005 assert len(p) == 5
3006 assert list(p) == [b"f", b"o", b"o", b".", b"\x00"]
3007 p[1:3] = bytearray(b"XY")
3008 assert list(p) == [b"f", b"X", b"Y", b".", b"\x00"]
3009
3010 def test_string_assignment_to_byte_array():
3011 BByteArray = new_array_type(
3012 new_pointer_type(new_primitive_type("unsigned char")), None)
3013 p = newp(BByteArray, 5)
3014 p[0:3] = bytearray(b"XYZ")
3015 assert list(p) == [ord("X"), ord("Y"), ord("Z"), 0, 0]
3016
3017 # XXX hack
3018 if sys.version_info >= (3,):
3019 try:
3020 import posix
3021 posix.fdopen = open
3022 except ImportError:
3023 pass # win32
3024
3025 @pytest.mark.skipif(
3026 is_ios,
3027 reason="For an unknown reason fscanf() doesn't read anything on 3.14"
3028 " and crashes on 3.13 (that's why it's not an xfail)",
3029 )
3030 def test_FILE():
3031 if sys.platform == "win32":
3032 pytest.skip("testing FILE not implemented")
3033 #
3034 BFILE = new_struct_type("struct _IO_FILE")
3035 BFILEP = new_pointer_type(BFILE)
3036 BChar = new_primitive_type("char")
3037 BCharP = new_pointer_type(BChar)
3038 BInt = new_primitive_type("int")
3039 BFunc = new_function_type((BCharP, BFILEP), BInt, False)
3040 BFunc2 = new_function_type((BFILEP, BCharP), BInt, True)
3041 ll = find_and_load_library('c')
3042 fputs = ll.load_function(BFunc, "fputs")
3043 fscanf = ll.load_function(BFunc2, "fscanf")
3044 #
3045 import posix
3046 fdr, fdw = posix.pipe()
3047 fr1 = posix.fdopen(fdr, 'rb', 256)
3048 fw1 = posix.fdopen(fdw, 'wb', 256)
3049 #
3050 fw1.write(b"X")
3051 res = fputs(b"hello world\n", fw1)
3052 assert res >= 0
3053 fw1.flush() # should not be needed
3054 #
3055 p = newp(new_array_type(BCharP, 100), None)
3056 res = fscanf(fr1, b"%s\n", p)
3057 assert res == 1
3058 assert string(p) == b"Xhello"
3059 fr1.close()
3060 fw1.close()
3061
3062 def test_FILE_only_for_FILE_arg():
3063 if sys.platform == "win32":
3064 pytest.skip("testing FILE not implemented")
3065 #
3066 B_NOT_FILE = new_struct_type("struct NOT_FILE")
3067 B_NOT_FILEP = new_pointer_type(B_NOT_FILE)
3068 BChar = new_primitive_type("char")
3069 BCharP = new_pointer_type(BChar)
3070 BInt = new_primitive_type("int")
3071 BFunc = new_function_type((BCharP, B_NOT_FILEP), BInt, False)
3072 ll = find_and_load_library('c')
3073 fputs = ll.load_function(BFunc, "fputs")
3074 #
3075 import posix
3076 fdr, fdw = posix.pipe()
3077 fr1 = posix.fdopen(fdr, 'r')
3078 fw1 = posix.fdopen(fdw, 'w')
3079 #
3080 e = pytest.raises(TypeError, fputs, b"hello world\n", fw1)
3081 assert str(e.value).startswith(
3082 "initializer for ctype 'struct NOT_FILE *' must "
3083 "be a cdata pointer, not ")
3084
3085 def test_FILE_object():
3086 if sys.platform == "win32":
3087 pytest.skip("testing FILE not implemented")
3088 #
3089 BFILE = new_struct_type("FILE")
3090 BFILEP = new_pointer_type(BFILE)
3091 BChar = new_primitive_type("char")
3092 BCharP = new_pointer_type(BChar)
3093 BInt = new_primitive_type("int")
3094 BFunc = new_function_type((BCharP, BFILEP), BInt, False)
3095 BFunc2 = new_function_type((BFILEP,), BInt, False)
3096 ll = find_and_load_library('c')
3097 fputs = ll.load_function(BFunc, "fputs")
3098 fileno = ll.load_function(BFunc2, "fileno")
3099 #
3100 import posix
3101 fdr, fdw = posix.pipe()
3102 fw1 = posix.fdopen(fdw, 'wb', 256)
3103 #
3104 fw1p = cast(BFILEP, fw1)
3105 fw1.write(b"X")
3106 fw1.flush()
3107 res = fputs(b"hello\n", fw1p)
3108 assert res >= 0
3109 res = fileno(fw1p)
3110 assert (res == fdw) == (sys.version_info < (3,))
3111 fw1.close()
3112 #
3113 data = posix.read(fdr, 256)
3114 assert data == b"Xhello\n"
3115 posix.close(fdr)
3116
3117 def test_errno_saved():
3118 set_errno(42)
3119 # a random function that will reset errno to 0 (at least on non-windows)
3120 import os; os.stat('.')
3121 #
3122 res = get_errno()
3123 assert res == 42
3124
3125 def test_GetLastError():
3126 if sys.platform != "win32":
3127 pytest.skip("GetLastError(): only for Windows")
3128 #
3129 lib = find_and_load_library('KERNEL32.DLL')
3130 BInt = new_primitive_type("int")
3131 BVoid = new_void_type()
3132 BFunc1 = new_function_type((BInt,), BVoid, False)
3133 BFunc2 = new_function_type((), BInt, False)
3134 SetLastError = lib.load_function(BFunc1, "SetLastError")
3135 GetLastError = lib.load_function(BFunc2, "GetLastError")
3136 #
3137 SetLastError(42)
3138 # a random function that will reset the real GetLastError() to 0
3139 import nt; nt.stat('.')
3140 #
3141 res = GetLastError()
3142 assert res == 42
3143 #
3144 SetLastError(2)
3145 code, message = getwinerror()
3146 assert code == 2
3147 assert message == "The system cannot find the file specified"
3148 #
3149 code, message = getwinerror(1155)
3150 assert code == 1155
3151 assert message == ("No application is associated with the "
3152 "specified file for this operation")
3153
3154 def test_nonstandard_integer_types():
3155 for typename in ['int8_t', 'uint8_t', 'int16_t', 'uint16_t', 'int32_t',
3156 'uint32_t', 'int64_t', 'uint64_t', 'intptr_t',
3157 'uintptr_t', 'ptrdiff_t', 'size_t', 'ssize_t',
3158 'int_least8_t', 'uint_least8_t',
3159 'int_least16_t', 'uint_least16_t',
3160 'int_least32_t', 'uint_least32_t',
3161 'int_least64_t', 'uint_least64_t',
3162 'int_fast8_t', 'uint_fast8_t',
3163 'int_fast16_t', 'uint_fast16_t',
3164 'int_fast32_t', 'uint_fast32_t',
3165 'int_fast64_t', 'uint_fast64_t',
3166 'intmax_t', 'uintmax_t']:
3167 new_primitive_type(typename) # works
3168
3169 def test_cannot_convert_unicode_to_charp():
3170 BCharP = new_pointer_type(new_primitive_type("char"))
3171 BCharArray = new_array_type(BCharP, None)
3172 pytest.raises(TypeError, newp, BCharArray, u+'foobar')
3173
3174 def test_buffer_keepalive():
3175 BCharP = new_pointer_type(new_primitive_type("char"))
3176 BCharArray = new_array_type(BCharP, None)
3177 buflist = []
3178 for i in range(20):
3179 c = newp(BCharArray, str2bytes("hi there %d" % i))
3180 buflist.append(buffer(c))
3181 import gc; gc.collect()
3182 for i in range(20):
3183 buf = buflist[i]
3184 assert buf[:] == str2bytes("hi there %d\x00" % i)
3185
3186 def test_slice():
3187 BIntP = new_pointer_type(new_primitive_type("int"))
3188 BIntArray = new_array_type(BIntP, None)
3189 c = newp(BIntArray, 5)
3190 assert len(c) == 5
3191 assert repr(c) == "<cdata 'int[]' owning 20 bytes>"
3192 d = c[1:4]
3193 assert len(d) == 3
3194 assert repr(d) == "<cdata 'int[]' sliced length 3>"
3195 d[0] = 123
3196 d[2] = 456
3197 assert c[1] == 123
3198 assert c[3] == 456
3199 assert d[2] == 456
3200 with pytest.raises(IndexError):
3201 d[3]
3202 with pytest.raises(IndexError):
3203 d[-1]
3204
3205 def test_slice_ptr():
3206 BIntP = new_pointer_type(new_primitive_type("int"))
3207 BIntArray = new_array_type(BIntP, None)
3208 c = newp(BIntArray, 5)
3209 d = (c+1)[0:2]
3210 assert len(d) == 2
3211 assert repr(d) == "<cdata 'int[]' sliced length 2>"
3212 d[1] += 50
3213 assert c[2] == 50
3214
3215 def test_slice_array_checkbounds():
3216 BIntP = new_pointer_type(new_primitive_type("int"))
3217 BIntArray = new_array_type(BIntP, None)
3218 c = newp(BIntArray, 5)
3219 c[0:5]
3220 assert len(c[5:5]) == 0
3221 with pytest.raises(IndexError):
3222 c[-1:1]
3223 cp = c + 0
3224 cp[-1:1]
3225
3226 def test_nonstandard_slice():
3227 BIntP = new_pointer_type(new_primitive_type("int"))
3228 BIntArray = new_array_type(BIntP, None)
3229 c = newp(BIntArray, 5)
3230 with pytest.raises(IndexError) as e:
3231 c[:5]
3232 assert str(e.value) == "slice start must be specified"
3233 with pytest.raises(IndexError) as e:
3234 c[4:]
3235 assert str(e.value) == "slice stop must be specified"
3236 with pytest.raises(IndexError) as e:
3237 c[1:2:3]
3238 assert str(e.value) == "slice with step not supported"
3239 with pytest.raises(IndexError) as e:
3240 c[1:2:1]
3241 assert str(e.value) == "slice with step not supported"
3242 with pytest.raises(IndexError) as e:
3243 c[4:2]
3244 assert str(e.value) == "slice start > stop"
3245 with pytest.raises(IndexError) as e:
3246 c[6:6]
3247 assert str(e.value) == "index too large (expected 6 <= 5)"
3248
3249 def test_setslice():
3250 BIntP = new_pointer_type(new_primitive_type("int"))
3251 BIntArray = new_array_type(BIntP, None)
3252 c = newp(BIntArray, 5)
3253 c[1:3] = [100, 200]
3254 assert list(c) == [0, 100, 200, 0, 0]
3255 cp = c + 3
3256 cp[-1:1] = [300, 400]
3257 assert list(c) == [0, 100, 300, 400, 0]
3258 cp[-1:1] = iter([500, 600])
3259 assert list(c) == [0, 100, 500, 600, 0]
3260 with pytest.raises(ValueError):
3261 cp[-1:1] = [1000]
3262 assert list(c) == [0, 100, 1000, 600, 0]
3263 with pytest.raises(ValueError):
3264 cp[-1:1] = (700, 800, 900)
3265 assert list(c) == [0, 100, 700, 800, 0]
3266
3267 def test_setslice_array():
3268 BIntP = new_pointer_type(new_primitive_type("int"))
3269 BIntArray = new_array_type(BIntP, None)
3270 c = newp(BIntArray, 5)
3271 d = newp(BIntArray, [10, 20, 30])
3272 c[1:4] = d
3273 assert list(c) == [0, 10, 20, 30, 0]
3274 #
3275 BShortP = new_pointer_type(new_primitive_type("short"))
3276 BShortArray = new_array_type(BShortP, None)
3277 d = newp(BShortArray, [40, 50])
3278 c[1:3] = d
3279 assert list(c) == [0, 40, 50, 30, 0]
3280
3281 def test_cdata_name_module_doc():
3282 p = new_primitive_type("signed char")
3283 x = cast(p, 17)
3284 assert x.__module__ == '_cffi_backend'
3285 assert x.__name__ == '<cdata>'
3286 assert hasattr(x, '__doc__')
3287
3288 def test_different_types_of_ptr_equality():
3289 BVoidP = new_pointer_type(new_void_type())
3290 BIntP = new_pointer_type(new_primitive_type("int"))
3291 x = cast(BVoidP, 12345)
3292 assert x == cast(BIntP, 12345)
3293 assert x != cast(BIntP, 12344)
3294 assert hash(x) == hash(cast(BIntP, 12345))
3295
3296 def test_new_handle():
3297 import _weakref
3298 BVoidP = new_pointer_type(new_void_type())
3299 BCharP = new_pointer_type(new_primitive_type("char"))
3300 class mylist(list):
3301 pass
3302 o = mylist([2, 3, 4])
3303 x = newp_handle(BVoidP, o)
3304 assert repr(x) == "<cdata 'void *' handle to [2, 3, 4]>"
3305 assert x
3306 assert from_handle(x) is o
3307 assert from_handle(cast(BCharP, x)) is o
3308 wr = _weakref.ref(o)
3309 del o
3310 import gc; gc.collect()
3311 assert wr() is not None
3312 assert from_handle(x) == list((2, 3, 4))
3313 assert from_handle(cast(BCharP, x)) == list((2, 3, 4))
3314 del x
3315 for i in range(3):
3316 if wr() is not None:
3317 import gc; gc.collect()
3318 assert wr() is None
3319 pytest.raises(RuntimeError, from_handle, cast(BCharP, 0))
3320
3321 def test_new_handle_cycle():
3322 import gc
3323 import _weakref
3324 BVoidP = new_pointer_type(new_void_type())
3325 class A:
3326 pass
3327 o = A()
3328 o.cycle = newp_handle(BVoidP, o)
3329 wr = _weakref.ref(o)
3330 del o
3331 # free-threading requires more iterations to clear weakref
3332 while wr() is not None:
3333 gc.collect()
3334 assert wr() is None
3335
3336 def _test_bitfield_details(flag):
3337 BChar = new_primitive_type("char")
3338 BShort = new_primitive_type("short")
3339 BInt = new_primitive_type("int")
3340 BUInt = new_primitive_type("unsigned int")
3341 BStruct = new_struct_type("struct foo1")
3342 complete_struct_or_union(BStruct, [('a', BChar, -1),
3343 ('b1', BInt, 9),
3344 ('b2', BUInt, 7),
3345 ('c', BChar, -1)], -1, -1, -1, flag)
3346 if not (flag & SF_MSVC_BITFIELDS): # gcc, any variant
3347 assert typeoffsetof(BStruct, 'c') == (BChar, 3)
3348 assert sizeof(BStruct) == 4
3349 else: # msvc
3350 assert typeoffsetof(BStruct, 'c') == (BChar, 8)
3351 assert sizeof(BStruct) == 12
3352 assert alignof(BStruct) == 4
3353 #
3354 p = newp(new_pointer_type(BStruct), None)
3355 p.a = b'A'
3356 p.b1 = -201
3357 p.b2 = 99
3358 p.c = b'\x9D'
3359 raw = buffer(p)[:]
3360 if sys.byteorder == 'little':
3361 if flag & SF_MSVC_BITFIELDS:
3362 assert raw == b'A\x00\x00\x007\xC7\x00\x00\x9D\x00\x00\x00'
3363 elif flag & SF_GCC_LITTLE_ENDIAN:
3364 assert raw == b'A7\xC7\x9D'
3365 elif flag & SF_GCC_BIG_ENDIAN:
3366 assert raw == b'A\xE3\x9B\x9D'
3367 else:
3368 raise AssertionError("bad flag")
3369 elif flag & SF_MSVC_BITFIELDS:
3370 assert raw == b'A\x00\x00\x00\x00\x00\xC77\x9D\x00\x00\x00'
3371 elif flag & SF_GCC_LITTLE_ENDIAN:
3372 assert raw == b'A\xC77\x9D'
3373 elif flag & SF_GCC_BIG_ENDIAN:
3374 assert raw == b'A\x9B\xE3\x9D'
3375 else:
3376 raise AssertionError("bad flag")
3377 #
3378 BStruct = new_struct_type("struct foo2")
3379 complete_struct_or_union(BStruct, [('a', BChar, -1),
3380 ('', BShort, 9),
3381 ('c', BChar, -1)], -1, -1, -1, flag)
3382 assert typeoffsetof(BStruct, 'c') == (BChar, 4)
3383 if flag & SF_MSVC_BITFIELDS:
3384 assert sizeof(BStruct) == 6
3385 assert alignof(BStruct) == 2
3386 elif flag & SF_GCC_X86_BITFIELDS:
3387 assert sizeof(BStruct) == 5
3388 assert alignof(BStruct) == 1
3389 elif flag & SF_GCC_ARM_BITFIELDS:
3390 assert sizeof(BStruct) == 6
3391 assert alignof(BStruct) == 2
3392 else:
3393 raise AssertionError("bad flag")
3394 #
3395 BStruct = new_struct_type("struct foo2")
3396 complete_struct_or_union(BStruct, [('a', BChar, -1),
3397 ('', BInt, 0),
3398 ('', BInt, 0),
3399 ('c', BChar, -1)], -1, -1, -1, flag)
3400 if flag & SF_MSVC_BITFIELDS:
3401 assert typeoffsetof(BStruct, 'c') == (BChar, 1)
3402 assert sizeof(BStruct) == 2
3403 assert alignof(BStruct) == 1
3404 elif flag & SF_GCC_X86_BITFIELDS:
3405 assert typeoffsetof(BStruct, 'c') == (BChar, 4)
3406 assert sizeof(BStruct) == 5
3407 assert alignof(BStruct) == 1
3408 elif flag & SF_GCC_ARM_BITFIELDS:
3409 assert typeoffsetof(BStruct, 'c') == (BChar, 4)
3410 assert sizeof(BStruct) == 8
3411 assert alignof(BStruct) == 4
3412 else:
3413 raise AssertionError("bad flag")
3414
3415
3416 SF_MSVC_BITFIELDS = 0x01
3417 SF_GCC_ARM_BITFIELDS = 0x02
3418 SF_GCC_X86_BITFIELDS = 0x10
3419
3420 SF_GCC_BIG_ENDIAN = 0x04
3421 SF_GCC_LITTLE_ENDIAN = 0x40
3422
3423 SF_PACKED = 0x08
3424
3425 def test_bitfield_as_x86_gcc():
3426 _test_bitfield_details(flag=SF_GCC_X86_BITFIELDS|SF_GCC_LITTLE_ENDIAN)
3427
3428 def test_bitfield_as_msvc():
3429 _test_bitfield_details(flag=SF_MSVC_BITFIELDS|SF_GCC_LITTLE_ENDIAN)
3430
3431 def test_bitfield_as_arm_gcc():
3432 _test_bitfield_details(flag=SF_GCC_ARM_BITFIELDS|SF_GCC_LITTLE_ENDIAN)
3433
3434 def test_bitfield_as_ppc_gcc():
3435 # PowerPC uses the same format as X86, but is big-endian
3436 _test_bitfield_details(flag=SF_GCC_X86_BITFIELDS|SF_GCC_BIG_ENDIAN)
3437
3438
3439 def buffer_warning(cdata):
3440 import warnings
3441 buf = buffer(cdata)
3442 bytes = len(buf)
3443 with warnings.catch_warnings(record=True) as w:
3444 warnings.simplefilter("always")
3445 buffer(cdata, bytes)
3446 assert len(w) == 0
3447 buffer(cdata, bytes + 1)
3448 assert len(w) <= 1
3449 return len(w) == 1
3450
3451 def test_struct_array_no_length():
3452 BInt = new_primitive_type("int")
3453 BIntP = new_pointer_type(BInt)
3454 BArray = new_array_type(BIntP, None)
3455 BStruct = new_struct_type("foo")
3456 pytest.raises(TypeError, complete_struct_or_union,
3457 BStruct, [('x', BArray),
3458 ('y', BInt)])
3459 #
3460 BStruct = new_struct_type("foo")
3461 complete_struct_or_union(BStruct, [('x', BInt),
3462 ('y', BArray)])
3463 assert sizeof(BStruct) == size_of_int()
3464 d = BStruct.fields
3465 assert len(d) == 2
3466 assert d[0][0] == 'x'
3467 assert d[0][1].type is BInt
3468 assert d[0][1].offset == 0
3469 assert d[0][1].bitshift == -1
3470 assert d[0][1].bitsize == -1
3471 assert d[1][0] == 'y'
3472 assert d[1][1].type is BArray
3473 assert d[1][1].offset == size_of_int()
3474 assert d[1][1].bitshift == -2
3475 assert d[1][1].bitsize == -1
3476 #
3477 p = newp(new_pointer_type(BStruct))
3478 p.x = 42
3479 assert p.x == 42
3480 assert typeof(p.y) is BArray
3481 assert len(p.y) == 0
3482 assert p.y == cast(BIntP, p) + 1
3483 #
3484 p = newp(new_pointer_type(BStruct), [100])
3485 assert p.x == 100
3486 assert len(p.y) == 0
3487 #
3488 # Tests for
3489 # ffi.new("struct_with_var_array *", [field.., [the_array_items..]])
3490 # ffi.new("struct_with_var_array *", [field.., array_size])
3491 plist = []
3492 for i in range(20):
3493 if i % 2 == 0:
3494 p = newp(new_pointer_type(BStruct), [100, [200, i, 400]])
3495 else:
3496 p = newp(new_pointer_type(BStruct), [100, 3])
3497 p.y[1] = i
3498 p.y[0] = 200
3499 assert p.y[2] == 0
3500 p.y[2] = 400
3501 assert len(p.y) == 3
3502 assert len(p[0].y) == 3
3503 assert len(buffer(p)) == sizeof(BInt) * 4
3504 assert sizeof(p[0]) == sizeof(BInt) * 4
3505 plist.append(p)
3506 for i in range(20):
3507 p = plist[i]
3508 assert p.x == 100
3509 assert p.y[0] == 200
3510 assert p.y[1] == i
3511 assert p.y[2] == 400
3512 assert list(p.y) == [200, i, 400]
3513 #
3514 # the following assignment works, as it normally would, for any array field
3515 p.y = [501, 601]
3516 assert list(p.y) == [501, 601, 400]
3517 p[0].y = [500, 600]
3518 assert list(p[0].y) == [500, 600, 400]
3519 assert repr(p) == "<cdata 'foo *' owning %d bytes>" % (
3520 sizeof(BStruct) + 3 * sizeof(BInt),)
3521 assert repr(p[0]) == "<cdata 'foo' owning %d bytes>" % (
3522 sizeof(BStruct) + 3 * sizeof(BInt),)
3523 assert sizeof(p[0]) == sizeof(BStruct) + 3 * sizeof(BInt)
3524 #
3525 # from a non-owning pointer, we can't get the length
3526 q = cast(new_pointer_type(BStruct), p)
3527 assert q.y[0] == 500
3528 assert q[0].y[0] == 500
3529 pytest.raises(TypeError, len, q.y)
3530 pytest.raises(TypeError, len, q[0].y)
3531 assert typeof(q.y) is BIntP
3532 assert typeof(q[0].y) is BIntP
3533 assert sizeof(q[0]) == sizeof(BStruct)
3534 #
3535 # error cases
3536 with pytest.raises(IndexError):
3537 p.y[4]
3538 with pytest.raises(TypeError):
3539 p.y = cast(BIntP, 0)
3540 with pytest.raises(TypeError):
3541 p.y = 15
3542 with pytest.raises(TypeError):
3543 p.y = None
3544 #
3545 # accepting this may be specified by the C99 standard,
3546 # or a GCC strangeness...
3547 BStruct2 = new_struct_type("bar")
3548 complete_struct_or_union(BStruct2, [('f', BStruct),
3549 ('n', BInt)])
3550 p = newp(new_pointer_type(BStruct2), {'n': 42})
3551 assert p.n == 42
3552 #
3553 # more error cases
3554 pytest.raises(TypeError, newp, new_pointer_type(BStruct), [100, None])
3555 BArray4 = new_array_type(BIntP, 4)
3556 BStruct4 = new_struct_type("test4")
3557 complete_struct_or_union(BStruct4, [('a', BArray4)]) # not varsized
3558 pytest.raises(TypeError, newp, new_pointer_type(BStruct4), [None])
3559 pytest.raises(TypeError, newp, new_pointer_type(BStruct4), [4])
3560 p = newp(new_pointer_type(BStruct4), [[10, 20, 30]])
3561 assert p.a[0] == 10
3562 assert p.a[1] == 20
3563 assert p.a[2] == 30
3564 assert p.a[3] == 0
3565 assert buffer_warning(p)
3566 #
3567 # struct of struct of varsized array
3568 BStruct2 = new_struct_type("bar")
3569 complete_struct_or_union(BStruct2, [('head', BInt),
3570 ('tail', BStruct)])
3571 for i in range(2): # try to detect heap overwrites
3572 p = newp(new_pointer_type(BStruct2), [100, [200, list(range(50))]])
3573 assert p.tail.y[49] == 49
3574 assert buffer_warning(p)
3575 assert not buffer_warning(cast(new_pointer_type(BStruct2), p))
3576 assert not buffer_warning(cast(BIntP, p))
3577
3578 def test_more_buffer_warning():
3579 BChar = new_primitive_type("unsigned char")
3580 BCharP = new_pointer_type(BChar)
3581 BArray = new_array_type(BCharP, 10) # char[10]
3582 p = newp(BArray)
3583 assert buffer_warning(p)
3584 assert not buffer_warning(cast(BCharP, p))
3585 p = newp(BCharP)
3586 assert buffer_warning(p)
3587 assert not buffer_warning(cast(BCharP, p))
3588
3589
3590 def test_struct_array_no_length_explicit_position():
3591 BInt = new_primitive_type("int")
3592 BIntP = new_pointer_type(BInt)
3593 BArray = new_array_type(BIntP, None)
3594 BStruct = new_struct_type("foo")
3595 complete_struct_or_union(BStruct, [('x', BArray, -1, 0), # actually 3 items
3596 ('y', BInt, -1, 12)])
3597 p = newp(new_pointer_type(BStruct), [[10, 20], 30])
3598 assert p.x[0] == 10
3599 assert p.x[1] == 20
3600 assert p.x[2] == 0
3601 assert p.y == 30
3602 p = newp(new_pointer_type(BStruct), {'x': [40], 'y': 50})
3603 assert p.x[0] == 40
3604 assert p.x[1] == 0
3605 assert p.x[2] == 0
3606 assert p.y == 50
3607 p = newp(new_pointer_type(BStruct), {'y': 60})
3608 assert p.x[0] == 0
3609 assert p.x[1] == 0
3610 assert p.x[2] == 0
3611 assert p.y == 60
3612 #
3613 # This "should" work too, allocating a larger structure
3614 # (a bit strange in this case, but useful in general)
3615 plist = []
3616 for i in range(20):
3617 p = newp(new_pointer_type(BStruct), [[10, 20, 30, 40, 50, 60, 70]])
3618 plist.append(p)
3619 for i in range(20):
3620 p = plist[i]
3621 assert p.x[0] == 10
3622 assert p.x[1] == 20
3623 assert p.x[2] == 30
3624 assert p.x[3] == 40 == p.y
3625 assert p.x[4] == 50
3626 assert p.x[5] == 60
3627 assert p.x[6] == 70
3628
3629 def test_struct_array_not_aligned():
3630 # struct a { int x; char y; char z[]; };
3631 # ends up of size 8, but 'z' is at offset 5
3632 BChar = new_primitive_type("char")
3633 BInt = new_primitive_type("int")
3634 BCharP = new_pointer_type(BChar)
3635 BArray = new_array_type(BCharP, None)
3636 BStruct = new_struct_type("foo")
3637 complete_struct_or_union(BStruct, [('x', BInt),
3638 ('y', BChar),
3639 ('z', BArray)])
3640 assert sizeof(BStruct) == 2 * size_of_int()
3641 def offsetof(BType, fieldname):
3642 return typeoffsetof(BType, fieldname)[1]
3643 base = offsetof(BStruct, 'z')
3644 assert base == size_of_int() + 1
3645 #
3646 p = newp(new_pointer_type(BStruct), {'z': 3})
3647 assert sizeof(p[0]) == base + 3
3648 q = newp(new_pointer_type(BStruct), {'z': size_of_int()})
3649 assert sizeof(q) == size_of_ptr()
3650 assert sizeof(q[0]) == base + size_of_int()
3651 assert len(p.z) == 3
3652 assert len(p[0].z) == 3
3653 assert len(q.z) == size_of_int()
3654 assert len(q[0].z) == size_of_int()
3655
3656 def test_ass_slice():
3657 BChar = new_primitive_type("char")
3658 BArray = new_array_type(new_pointer_type(BChar), None)
3659 p = newp(BArray, b"foobar")
3660 p[2:5] = [b"*", b"Z", b"T"]
3661 p[1:3] = b"XY"
3662 assert list(p) == [b"f", b"X", b"Y", b"Z", b"T", b"r", b"\x00"]
3663 with pytest.raises(TypeError):
3664 p[1:5] = u+'XYZT'
3665 with pytest.raises(TypeError):
3666 p[1:5] = [1, 2, 3, 4]
3667 #
3668 for typename in ["wchar_t", "char16_t", "char32_t"]:
3669 BUniChar = new_primitive_type(typename)
3670 BArray = new_array_type(new_pointer_type(BUniChar), None)
3671 p = newp(BArray, u+"foobar")
3672 p[2:5] = [u+"*", u+"Z", u+"T"]
3673 p[1:3] = u+"XY"
3674 assert list(p) == [u+"f", u+"X", u+"Y", u+"Z", u+"T", u+"r", u+"\x00"]
3675 with pytest.raises(TypeError):
3676 p[1:5] = b'XYZT'
3677 with pytest.raises(TypeError):
3678 p[1:5] = [1, 2, 3, 4]
3679
3680 def test_void_p_arithmetic():
3681 BVoid = new_void_type()
3682 BInt = new_primitive_type("intptr_t")
3683 p = cast(new_pointer_type(BVoid), 100000)
3684 assert int(cast(BInt, p)) == 100000
3685 assert int(cast(BInt, p + 42)) == 100042
3686 assert int(cast(BInt, p - (-42))) == 100042
3687 assert (p + 42) - p == 42
3688 q = cast(new_pointer_type(new_primitive_type("char")), 100000)
3689 with pytest.raises(TypeError):
3690 p - q
3691 with pytest.raises(TypeError):
3692 q - p
3693 with pytest.raises(TypeError):
3694 p + cast(new_primitive_type('int'), 42)
3695 with pytest.raises(TypeError):
3696 p - cast(new_primitive_type('int'), 42)
3697
3698 def test_sizeof_sliced_array():
3699 BInt = new_primitive_type("int")
3700 BArray = new_array_type(new_pointer_type(BInt), 10)
3701 p = newp(BArray, None)
3702 assert sizeof(p[2:9]) == 7 * sizeof(BInt)
3703
3704 def test_packed():
3705 BLong = new_primitive_type("long")
3706 BChar = new_primitive_type("char")
3707 BShort = new_primitive_type("short")
3708 for extra_args in [(SF_PACKED,), (0, 1)]:
3709 BStruct = new_struct_type("struct foo")
3710 complete_struct_or_union(BStruct, [('a1', BLong, -1),
3711 ('a2', BChar, -1),
3712 ('a3', BShort, -1)],
3713 None, -1, -1, *extra_args)
3714 d = BStruct.fields
3715 assert len(d) == 3
3716 assert d[0][0] == 'a1'
3717 assert d[0][1].type is BLong
3718 assert d[0][1].offset == 0
3719 assert d[0][1].bitshift == -1
3720 assert d[0][1].bitsize == -1
3721 assert d[1][0] == 'a2'
3722 assert d[1][1].type is BChar
3723 assert d[1][1].offset == sizeof(BLong)
3724 assert d[1][1].bitshift == -1
3725 assert d[1][1].bitsize == -1
3726 assert d[2][0] == 'a3'
3727 assert d[2][1].type is BShort
3728 assert d[2][1].offset == sizeof(BLong) + sizeof(BChar)
3729 assert d[2][1].bitshift == -1
3730 assert d[2][1].bitsize == -1
3731 assert sizeof(BStruct) == sizeof(BLong) + sizeof(BChar) + sizeof(BShort)
3732 assert alignof(BStruct) == 1
3733 #
3734 BStruct2 = new_struct_type("struct foo")
3735 complete_struct_or_union(BStruct2, [('b1', BChar, -1),
3736 ('b2', BLong, -1)],
3737 None, -1, -1, 0, 2)
3738 d = BStruct2.fields
3739 assert len(d) == 2
3740 assert d[0][0] == 'b1'
3741 assert d[0][1].type is BChar
3742 assert d[0][1].offset == 0
3743 assert d[0][1].bitshift == -1
3744 assert d[0][1].bitsize == -1
3745 assert d[1][0] == 'b2'
3746 assert d[1][1].type is BLong
3747 assert d[1][1].offset == 2
3748 assert d[1][1].bitshift == -1
3749 assert d[1][1].bitsize == -1
3750 assert sizeof(BStruct2) == 2 + sizeof(BLong)
3751 assert alignof(BStruct2) == 2
3752
3753 def test_packed_with_bitfields():
3754 if sys.platform == "win32":
3755 pytest.skip("testing gcc behavior")
3756 BLong = new_primitive_type("long")
3757 BChar = new_primitive_type("char")
3758 BStruct = new_struct_type("struct foo")
3759 pytest.raises(NotImplementedError,
3760 complete_struct_or_union,
3761 BStruct, [('a1', BLong, 30),
3762 ('a2', BChar, 5)],
3763 None, -1, -1, SF_PACKED)
3764
3765 def test_from_buffer():
3766 import array
3767 a = array.array('H', [10000, 20000, 30000])
3768 BChar = new_primitive_type("char")
3769 BCharP = new_pointer_type(BChar)
3770 BCharA = new_array_type(BCharP, None)
3771 c = from_buffer(BCharA, a)
3772 assert typeof(c) is BCharA
3773 assert len(c) == 6
3774 assert repr(c) == "<cdata 'char[]' buffer len 6 from 'array.array' object>"
3775 p = new_pointer_type(new_primitive_type("unsigned short"))
3776 cast(p, c)[1] += 500
3777 assert list(a) == [10000, 20500, 30000]
3778
3779 def test_from_buffer_not_str_unicode():
3780 BChar = new_primitive_type("char")
3781 BCharP = new_pointer_type(BChar)
3782 BCharA = new_array_type(BCharP, None)
3783 p1 = from_buffer(BCharA, b"foo")
3784 assert p1 == from_buffer(BCharA, b"foo")
3785 import gc; gc.collect()
3786 assert p1 == from_buffer(BCharA, b"foo")
3787 pytest.raises(TypeError, from_buffer, BCharA, u+"foo")
3788 try:
3789 from __builtin__ import buffer
3790 except ImportError:
3791 pass
3792 else:
3793 # Python 2 only
3794 contents = from_buffer(BCharA, buffer(b"foo"))
3795 assert len(contents) == len(p1)
3796 for i in range(len(contents)):
3797 assert contents[i] == p1[i]
3798 p4 = buffer(u+"foo")
3799 contents = from_buffer(BCharA, buffer(u+"foo"))
3800 assert len(contents) == len(p4)
3801 for i in range(len(contents)):
3802 assert contents[i] == p4[i]
3803 try:
3804 from __builtin__ import memoryview
3805 except ImportError:
3806 pass
3807 else:
3808 contents = from_buffer(BCharA, memoryview(b"foo"))
3809 assert len(contents) == len(p1)
3810 for i in range(len(contents)):
3811 assert contents[i] == p1[i]
3812
3813
3814 def test_from_buffer_bytearray():
3815 a = bytearray(b"xyz")
3816 BChar = new_primitive_type("char")
3817 BCharP = new_pointer_type(BChar)
3818 BCharA = new_array_type(BCharP, None)
3819 p = from_buffer(BCharA, a)
3820 assert typeof(p) is BCharA
3821 assert len(p) == 3
3822 assert repr(p) == "<cdata 'char[]' buffer len 3 from 'bytearray' object>"
3823 assert p[2] == b"z"
3824 p[2] = b"."
3825 assert a[2] == ord(".")
3826 a[2] = ord("?")
3827 assert p[2] == b"?"
3828
3829 def test_from_buffer_more_cases():
3830 try:
3831 from _cffi_backend import _testbuff
3832 except ImportError:
3833 pytest.skip("not for pypy")
3834 BChar = new_primitive_type("char")
3835 BCharP = new_pointer_type(BChar)
3836 BCharA = new_array_type(BCharP, None)
3837 #
3838 def check1(bufobj, expected):
3839 c = from_buffer(BCharA, bufobj)
3840 assert typeof(c) is BCharA
3841 if sys.version_info >= (3,):
3842 expected = [bytes(c, "ascii") for c in expected]
3843 assert list(c) == list(expected)
3844 #
3845 def check(methods, expected, expected_for_memoryview=None):
3846 if sys.version_info >= (3,):
3847 if methods <= 7:
3848 return
3849 if expected_for_memoryview is not None:
3850 expected = expected_for_memoryview
3851 class X:
3852 pass
3853 _testbuff(X, methods)
3854 bufobj = X()
3855 check1(bufobj, expected)
3856 try:
3857 from __builtin__ import buffer
3858 bufobjb = buffer(bufobj)
3859 except (TypeError, ImportError):
3860 pass
3861 else:
3862 check1(bufobjb, expected)
3863 try:
3864 bufobjm = memoryview(bufobj)
3865 except (TypeError, NameError):
3866 pass
3867 else:
3868 check1(bufobjm, expected_for_memoryview or expected)
3869 #
3870 check(1, "RDB")
3871 check(2, "WRB")
3872 check(4, "CHB")
3873 check(8, "GTB")
3874 check(16, "ROB")
3875 #
3876 check(1 | 2, "RDB")
3877 check(1 | 4, "RDB")
3878 check(2 | 4, "CHB")
3879 check(1 | 8, "RDB", "GTB")
3880 check(1 | 16, "RDB", "ROB")
3881 check(2 | 8, "WRB", "GTB")
3882 check(2 | 16, "WRB", "ROB")
3883 check(4 | 8, "CHB", "GTB")
3884 check(4 | 16, "CHB", "ROB")
3885
3886 def test_from_buffer_require_writable():
3887 BChar = new_primitive_type("char")
3888 BCharP = new_pointer_type(BChar)
3889 BCharA = new_array_type(BCharP, None)
3890 p1 = from_buffer(BCharA, b"foo", False)
3891 assert p1 == from_buffer(BCharA, b"foo", False)
3892 pytest.raises((TypeError, BufferError), from_buffer, BCharA, b"foo", True)
3893 ba = bytearray(b"foo")
3894 p1 = from_buffer(BCharA, ba, True)
3895 p1[0] = b"g"
3896 assert ba == b"goo"
3897
3898 def test_from_buffer_types():
3899 BInt = new_primitive_type("int")
3900 BIntP = new_pointer_type(BInt)
3901 BIntA = new_array_type(BIntP, None)
3902 lst = [-12345678, 87654321, 489148]
3903 bytestring = bytearray(buffer(newp(BIntA, lst))[:] + b'XYZ')
3904 lst2 = lst + [42, -999999999]
3905 bytestring2 = bytearray(buffer(newp(BIntA, lst2))[:] + b'XYZ')
3906 #
3907 p1 = from_buffer(BIntA, bytestring) # int[]
3908 assert typeof(p1) is BIntA
3909 assert len(p1) == 3
3910 assert p1[0] == lst[0]
3911 assert p1[1] == lst[1]
3912 assert p1[2] == lst[2]
3913 with pytest.raises(IndexError):
3914 p1[3]
3915 with pytest.raises(IndexError):
3916 p1[-1]
3917 #
3918 pytest.raises(TypeError, from_buffer, BInt, bytestring)
3919 #
3920 p2 = from_buffer(BIntP, bytestring) # int *
3921 assert p2 == p1 or 'PY_DOT_PY' in globals()
3922 # note: on py.py ^^^, bytearray buffers are not emulated well enough
3923 assert typeof(p2) is BIntP
3924 assert p2[0] == lst[0]
3925 assert p2[1] == lst[1]
3926 assert p2[2] == lst[2]
3927 # hopefully does not crash, but doesn't raise an exception:
3928 p2[3]
3929 p2[-1]
3930 # not enough data even for one, but this is not enforced:
3931 from_buffer(BIntP, b"")
3932 #
3933 BIntA2 = new_array_type(BIntP, 2)
3934 p2 = from_buffer(BIntA2, bytestring) # int[2]
3935 assert typeof(p2) is BIntA2
3936 assert len(p2) == 2
3937 assert p2[0] == lst[0]
3938 assert p2[1] == lst[1]
3939 with pytest.raises(IndexError):
3940 p2[2]
3941 with pytest.raises(IndexError):
3942 p2[-1]
3943 assert p2 == p1 or 'PY_DOT_PY' in globals()
3944 #
3945 BIntA4 = new_array_type(BIntP, 4) # int[4]: too big
3946 pytest.raises(ValueError, from_buffer, BIntA4, bytestring)
3947 #
3948 BStruct = new_struct_type("foo")
3949 complete_struct_or_union(BStruct, [('a1', BInt, -1),
3950 ('a2', BInt, -1)])
3951 BStructP = new_pointer_type(BStruct)
3952 BStructA = new_array_type(BStructP, None)
3953 p1 = from_buffer(BStructA, bytestring2) # struct[]
3954 assert len(p1) == 2
3955 assert typeof(p1) is BStructA
3956 assert p1[0].a1 == lst2[0]
3957 assert p1[0].a2 == lst2[1]
3958 assert p1[1].a1 == lst2[2]
3959 assert p1[1].a2 == lst2[3]
3960 with pytest.raises(IndexError):
3961 p1[2]
3962 with pytest.raises(IndexError):
3963 p1[-1]
3964 assert repr(p1) == "<cdata 'foo[]' buffer len 2 from 'bytearray' object>"
3965 #
3966 p2 = from_buffer(BStructP, bytestring2) # 'struct *'
3967 assert p2 == p1 or 'PY_DOT_PY' in globals()
3968 assert typeof(p2) is BStructP
3969 assert p2.a1 == lst2[0]
3970 assert p2.a2 == lst2[1]
3971 assert p2[0].a1 == lst2[0]
3972 assert p2[0].a2 == lst2[1]
3973 assert p2[1].a1 == lst2[2]
3974 assert p2[1].a2 == lst2[3]
3975 # does not crash:
3976 p2[2]
3977 p2[-1]
3978 # not enough data even for one, but this is not enforced:
3979 from_buffer(BStructP, b"")
3980 from_buffer(BStructP, b"1234567")
3981 #
3982 release(p1)
3983 assert repr(p1) == "<cdata 'foo[]' buffer RELEASED>"
3984 #
3985 BEmptyStruct = new_struct_type("empty")
3986 complete_struct_or_union(BEmptyStruct, [], Ellipsis, 0)
3987 assert sizeof(BEmptyStruct) == 0
3988 BEmptyStructP = new_pointer_type(BEmptyStruct)
3989 BEmptyStructA = new_array_type(BEmptyStructP, None)
3990 pytest.raises(ZeroDivisionError, from_buffer, # empty[]
3991 BEmptyStructA, bytestring)
3992 #
3993 BEmptyStructA5 = new_array_type(BEmptyStructP, 5)
3994 p1 = from_buffer(BEmptyStructA5, bytestring) # struct empty[5]
3995 assert typeof(p1) is BEmptyStructA5
3996 assert len(p1) == 5
3997 assert (cast(BIntP, p1) == from_buffer(BIntA, bytestring)
3998 or 'PY_DOT_PY' in globals())
3999 #
4000 BVarStruct = new_struct_type("varfoo")
4001 BVarStructP = new_pointer_type(BVarStruct)
4002 complete_struct_or_union(BVarStruct, [('a1', BInt, -1),
4003 ('va', BIntA, -1)])
4004 with pytest.raises(TypeError):
4005 from_buffer(BVarStruct, bytestring)
4006 pv = from_buffer(BVarStructP, bytestring) # varfoo *
4007 assert pv.a1 == lst[0]
4008 assert pv.va[0] == lst[1]
4009 assert pv.va[1] == lst[2]
4010 assert sizeof(pv[0]) == 1 * size_of_int()
4011 with pytest.raises(TypeError):
4012 len(pv.va)
4013 # hopefully does not crash, but doesn't raise an exception:
4014 pv.va[2]
4015 pv.va[-1]
4016 # not enough data even for one, but this is not enforced:
4017 from_buffer(BVarStructP, b"")
4018 assert repr(pv) == "<cdata 'varfoo *' buffer from 'bytearray' object>"
4019 assert repr(pv[0]).startswith("<cdata 'varfoo &' ")
4020 #
4021 release(pv)
4022 assert repr(pv) == "<cdata 'varfoo *' buffer RELEASED>"
4023 assert repr(pv[0]).startswith("<cdata 'varfoo &' ")
4024 #
4025 pv = from_buffer(BVarStructP, bytestring) # make a fresh one
4026 with pytest.raises(ValueError):
4027 release(pv[0])
4028
4029 def test_issue483():
4030 BInt = new_primitive_type("int")
4031 BIntP = new_pointer_type(BInt)
4032 BIntA = new_array_type(BIntP, None)
4033 lst = list(range(25))
4034 bytestring = bytearray(buffer(newp(BIntA, lst))[:] + b'XYZ')
4035 p1 = from_buffer(BIntA, bytestring) # int[]
4036 assert len(buffer(p1)) == 25 * size_of_int()
4037 assert sizeof(p1) == 25 * size_of_int()
4038 #
4039 p2 = from_buffer(BIntP, bytestring)
4040 assert sizeof(p2) == size_of_ptr()
4041 assert len(buffer(p2)) == size_of_int() # first element only, by default
4042
4043 def test_memmove():
4044 Short = new_primitive_type("short")
4045 ShortA = new_array_type(new_pointer_type(Short), None)
4046 Char = new_primitive_type("char")
4047 CharA = new_array_type(new_pointer_type(Char), None)
4048 p = newp(ShortA, [-1234, -2345, -3456, -4567, -5678])
4049 memmove(p, p + 1, 4)
4050 assert list(p) == [-2345, -3456, -3456, -4567, -5678]
4051 p[2] = 999
4052 memmove(p + 2, p, 6)
4053 assert list(p) == [-2345, -3456, -2345, -3456, 999]
4054 memmove(p + 4, newp(CharA, b"\x71\x72"), 2)
4055 if sys.byteorder == 'little':
4056 assert list(p) == [-2345, -3456, -2345, -3456, 0x7271]
4057 else:
4058 assert list(p) == [-2345, -3456, -2345, -3456, 0x7172]
4059
4060 def test_memmove_buffer():
4061 import array
4062 Short = new_primitive_type("short")
4063 ShortA = new_array_type(new_pointer_type(Short), None)
4064 a = array.array('H', [10000, 20000, 30000])
4065 p = newp(ShortA, 5)
4066 memmove(p, a, 6)
4067 assert list(p) == [10000, 20000, 30000, 0, 0]
4068 memmove(p + 1, a, 6)
4069 assert list(p) == [10000, 10000, 20000, 30000, 0]
4070 b = array.array('h', [-1000, -2000, -3000])
4071 memmove(b, a, 4)
4072 assert b.tolist() == [10000, 20000, -3000]
4073 assert a.tolist() == [10000, 20000, 30000]
4074 p[0] = 999
4075 p[1] = 998
4076 p[2] = 997
4077 p[3] = 996
4078 p[4] = 995
4079 memmove(b, p, 2)
4080 assert b.tolist() == [999, 20000, -3000]
4081 memmove(b, p + 2, 4)
4082 assert b.tolist() == [997, 996, -3000]
4083 p[2] = -p[2]
4084 p[3] = -p[3]
4085 memmove(b, p + 2, 6)
4086 assert b.tolist() == [-997, -996, 995]
4087
4088 def test_memmove_readonly_readwrite():
4089 SignedChar = new_primitive_type("signed char")
4090 SignedCharA = new_array_type(new_pointer_type(SignedChar), None)
4091 p = newp(SignedCharA, 5)
4092 memmove(p, b"abcde", 3)
4093 assert list(p) == [ord("a"), ord("b"), ord("c"), 0, 0]
4094 memmove(p, bytearray(b"ABCDE"), 2)
4095 assert list(p) == [ord("A"), ord("B"), ord("c"), 0, 0]
4096 pytest.raises((TypeError, BufferError), memmove, b"abcde", p, 3)
4097 ba = bytearray(b"xxxxx")
4098 memmove(dest=ba, src=p, n=3)
4099 assert ba == bytearray(b"ABcxx")
4100 memmove(ba, b"EFGH", 4)
4101 assert ba == bytearray(b"EFGHx")
4102
4103 def test_memmove_sign_check():
4104 SignedChar = new_primitive_type("signed char")
4105 SignedCharA = new_array_type(new_pointer_type(SignedChar), None)
4106 p = newp(SignedCharA, 5)
4107 pytest.raises(ValueError, memmove, p, p + 1, -1) # not segfault
4108
4109 def test_memmove_bad_cdata():
4110 BInt = new_primitive_type("int")
4111 p = cast(BInt, 42)
4112 pytest.raises(TypeError, memmove, p, bytearray(b'a'), 1)
4113 pytest.raises(TypeError, memmove, bytearray(b'a'), p, 1)
4114
4115 def test_dereference_null_ptr():
4116 BInt = new_primitive_type("int")
4117 BIntPtr = new_pointer_type(BInt)
4118 p = cast(BIntPtr, 0)
4119 with pytest.raises(RuntimeError):
4120 p[0]
4121 with pytest.raises(RuntimeError):
4122 p[0] = 42
4123 with pytest.raises(RuntimeError):
4124 p[42]
4125 with pytest.raises(RuntimeError):
4126 p[42] = -1
4127
4128 def test_mixup():
4129 BStruct1 = new_struct_type("foo")
4130 BStruct2 = new_struct_type("foo") # <= same name as BStruct1
4131 BStruct3 = new_struct_type("bar")
4132 BStruct1Ptr = new_pointer_type(BStruct1)
4133 BStruct2Ptr = new_pointer_type(BStruct2)
4134 BStruct3Ptr = new_pointer_type(BStruct3)
4135 BStruct1PtrPtr = new_pointer_type(BStruct1Ptr)
4136 BStruct2PtrPtr = new_pointer_type(BStruct2Ptr)
4137 BStruct3PtrPtr = new_pointer_type(BStruct3Ptr)
4138 pp1 = newp(BStruct1PtrPtr)
4139 pp2 = newp(BStruct2PtrPtr)
4140 pp3 = newp(BStruct3PtrPtr)
4141 pp1[0] = pp1[0]
4142 with pytest.raises(TypeError) as e:
4143 pp3[0] = pp1[0]
4144 assert str(e.value).startswith("initializer for ctype 'bar *' must be a ")
4145 assert str(e.value).endswith(", not cdata 'foo *'")
4146 with pytest.raises(TypeError) as e:
4147 pp2[0] = pp1[0]
4148 assert str(e.value) == ("initializer for ctype 'foo *' appears indeed to "
4149 "be 'foo *', but the types are different (check "
4150 "that you are not e.g. mixing up different ffi "
4151 "instances)")
4152
4153 def test_stdcall_function_type():
4154 assert FFI_CDECL == FFI_DEFAULT_ABI
4155 try:
4156 stdcall = FFI_STDCALL
4157 except NameError:
4158 stdcall = FFI_DEFAULT_ABI
4159 BInt = new_primitive_type("int")
4160 BFunc = new_function_type((BInt, BInt), BInt, False, stdcall)
4161 if stdcall != FFI_DEFAULT_ABI:
4162 assert repr(BFunc) == "<ctype 'int(__stdcall *)(int, int)'>"
4163 else:
4164 assert repr(BFunc) == "<ctype 'int(*)(int, int)'>"
4165
4166 def test_get_common_types():
4167 d = {}
4168 _get_common_types(d)
4169 assert d['bool'] == '_Bool'
4170
4171 def test_unpack():
4172 BChar = new_primitive_type("char")
4173 BArray = new_array_type(new_pointer_type(BChar), 10) # char[10]
4174 p = newp(BArray, b"abc\x00def")
4175 p0 = p
4176 assert unpack(p, 10) == b"abc\x00def\x00\x00\x00"
4177 assert unpack(p+1, 5) == b"bc\x00de"
4178
4179 for typename in ["wchar_t", "char16_t", "char32_t"]:
4180 BWChar = new_primitive_type(typename)
4181 BArray = new_array_type(new_pointer_type(BWChar), 10) # wchar_t[10]
4182 p = newp(BArray, "abc\x00def")
4183 assert unpack(p, 10) == "abc\x00def\x00\x00\x00"
4184
4185 for typename, samples in [
4186 ("uint8_t", [0, 2**8-1]),
4187 ("uint16_t", [0, 2**16-1]),
4188 ("uint32_t", [0, 2**32-1]),
4189 ("uint64_t", [0, 2**64-1]),
4190 ("int8_t", [-2**7, 2**7-1]),
4191 ("int16_t", [-2**15, 2**15-1]),
4192 ("int32_t", [-2**31, 2**31-1]),
4193 ("int64_t", [-2**63, 2**63-1]),
4194 ("_Bool", [False, True]),
4195 ("float", [0.0, 10.5]),
4196 ("double", [12.34, 56.78]),
4197 ]:
4198 BItem = new_primitive_type(typename)
4199 BArray = new_array_type(new_pointer_type(BItem), 10)
4200 p = newp(BArray, samples)
4201 result = unpack(p, len(samples))
4202 assert result == samples
4203 for i in range(len(samples)):
4204 assert result[i] == p[i] and type(result[i]) is type(p[i])
4205 assert (type(result[i]) is bool) == (type(samples[i]) is bool)
4206 #
4207 BInt = new_primitive_type("int")
4208 pytest.raises(TypeError, unpack, p)
4209 pytest.raises(TypeError, unpack, b"foobar", 6)
4210 pytest.raises(TypeError, unpack, cast(BInt, 42), 1)
4211 #
4212 BPtr = new_pointer_type(BInt)
4213 random_ptr = cast(BPtr, -424344)
4214 other_ptr = cast(BPtr, 54321)
4215 BArray = new_array_type(new_pointer_type(BPtr), None)
4216 lst = unpack(newp(BArray, [random_ptr, other_ptr]), 2)
4217 assert lst == [random_ptr, other_ptr]
4218 #
4219 BFunc = new_function_type((BInt, BInt), BInt, False)
4220 BFuncPtr = new_pointer_type(BFunc)
4221 lst = unpack(newp(new_array_type(BFuncPtr, None), 2), 2)
4222 assert len(lst) == 2
4223 assert not lst[0] and not lst[1]
4224 assert typeof(lst[0]) is BFunc
4225 #
4226 BStruct = new_struct_type("foo")
4227 BStructPtr = new_pointer_type(BStruct)
4228 e = pytest.raises(ValueError, unpack, cast(BStructPtr, 42), 5)
4229 assert str(e.value) == "'foo *' points to items of unknown size"
4230 complete_struct_or_union(BStruct, [('a1', BInt, -1),
4231 ('a2', BInt, -1)])
4232 array_of_structs = newp(new_array_type(BStructPtr, None), [[4,5], [6,7]])
4233 lst = unpack(array_of_structs, 2)
4234 assert typeof(lst[0]) is BStruct
4235 assert lst[0].a1 == 4 and lst[1].a2 == 7
4236 #
4237 pytest.raises(RuntimeError, unpack, cast(new_pointer_type(BChar), 0), 0)
4238 pytest.raises(RuntimeError, unpack, cast(new_pointer_type(BChar), 0), 10)
4239 #
4240 pytest.raises(ValueError, unpack, p0, -1)
4241 pytest.raises(ValueError, unpack, p, -1)
4242
4243 def test_cdata_dir():
4244 BInt = new_primitive_type("int")
4245 p = cast(BInt, 42)
4246 check_dir(p, [])
4247 p = newp(new_array_type(new_pointer_type(BInt), None), 5)
4248 check_dir(p, [])
4249 BStruct = new_struct_type("foo")
4250 p = cast(new_pointer_type(BStruct), 0)
4251 check_dir(p, []) # opaque
4252 complete_struct_or_union(BStruct, [('a2', BInt, -1),
4253 ('a1', BInt, -1)])
4254 check_dir(p, ['a1', 'a2']) # always sorted
4255 p = newp(new_pointer_type(BStruct), None)
4256 check_dir(p, ['a1', 'a2'])
4257 check_dir(p[0], ['a1', 'a2'])
4258 pp = newp(new_pointer_type(new_pointer_type(BStruct)), p)
4259 check_dir(pp, [])
4260 check_dir(pp[0], ['a1', 'a2'])
4261 check_dir(pp[0][0], ['a1', 'a2'])
4262
4263 def test_char_pointer_conversion():
4264 import warnings
4265 BCharP = new_pointer_type(new_primitive_type("char"))
4266 BIntP = new_pointer_type(new_primitive_type("int"))
4267 BVoidP = new_pointer_type(new_void_type())
4268 BUCharP = new_pointer_type(new_primitive_type("unsigned char"))
4269 z1 = cast(BCharP, 0)
4270 z2 = cast(BIntP, 0)
4271 z3 = cast(BVoidP, 0)
4272 z4 = cast(BUCharP, 0)
4273 with pytest.raises(TypeError) as e1:
4274 newp(new_pointer_type(BIntP), z1)
4275 newp(new_pointer_type(BVoidP), z1) # fine
4276 with pytest.raises(TypeError) as e2:
4277 newp(new_pointer_type(BCharP), z2)
4278 newp(new_pointer_type(BVoidP), z2) # fine
4279 newp(new_pointer_type(BCharP), z3) # fine
4280 newp(new_pointer_type(BIntP), z3) # fine
4281 newp(new_pointer_type(BCharP), z4) # fine (ignore signedness here)
4282 newp(new_pointer_type(BUCharP), z1) # fine (ignore signedness here)
4283 newp(new_pointer_type(BUCharP), z3) # fine
4284
4285 def test_primitive_comparison():
4286 def assert_eq(a, b):
4287 assert (a == b) is True
4288 assert (b == a) is True
4289 assert (a != b) is False
4290 assert (b != a) is False
4291 assert (a < b) is False
4292 assert (a <= b) is True
4293 assert (a > b) is False
4294 assert (a >= b) is True
4295 assert (b < a) is False
4296 assert (b <= a) is True
4297 assert (b > a) is False
4298 assert (b >= a) is True
4299 assert hash(a) == hash(b)
4300 def assert_lt(a, b, check_hash=True):
4301 assert (a == b) is False
4302 assert (b == a) is False
4303 assert (a != b) is True
4304 assert (b != a) is True
4305 assert (a < b) is True
4306 assert (a <= b) is True
4307 assert (a > b) is False
4308 assert (a >= b) is False
4309 assert (b < a) is False
4310 assert (b <= a) is False
4311 assert (b > a) is True
4312 assert (b >= a) is True
4313 if check_hash:
4314 assert hash(a) != hash(b) # (or at least, it is unlikely)
4315 def assert_gt(a, b, check_hash=True):
4316 assert_lt(b, a, check_hash)
4317 def assert_ne(a, b):
4318 assert (a == b) is False
4319 assert (b == a) is False
4320 assert (a != b) is True
4321 assert (b != a) is True
4322 if strict_compare:
4323 with pytest.raises(TypeError): a < b
4324 with pytest.raises(TypeError): a <= b
4325 with pytest.raises(TypeError): a > b
4326 with pytest.raises(TypeError): a >= b
4327 with pytest.raises(TypeError): b < a
4328 with pytest.raises(TypeError): b <= a
4329 with pytest.raises(TypeError): b > a
4330 with pytest.raises(TypeError): b >= a
4331 elif a < b:
4332 assert_lt(a, b)
4333 else:
4334 assert_lt(b, a)
4335 assert_eq(5, 5)
4336 assert_lt(3, 5)
4337 assert_ne('5', 5)
4338 #
4339 t1 = new_primitive_type("char")
4340 t2 = new_primitive_type("int")
4341 t3 = new_primitive_type("unsigned char")
4342 t4 = new_primitive_type("unsigned int")
4343 t5 = new_primitive_type("float")
4344 t6 = new_primitive_type("double")
4345 assert_eq(cast(t1, 65), b'A')
4346 assert_lt(cast(t1, 64), b'\x99')
4347 assert_gt(cast(t1, 200), b'A')
4348 assert_ne(cast(t1, 65), 65)
4349 assert_eq(cast(t2, -25), -25)
4350 assert_lt(cast(t2, -25), -24)
4351 assert_gt(cast(t2, -25), -26)
4352 assert_eq(cast(t3, 65), 65)
4353 assert_ne(cast(t3, 65), b'A')
4354 assert_ne(cast(t3, 65), cast(t1, 65))
4355 assert_gt(cast(t4, -1), -1, check_hash=False)
4356 assert_gt(cast(t4, -1), cast(t2, -1), check_hash=False)
4357 assert_gt(cast(t4, -1), 99999)
4358 assert_eq(cast(t4, -1), 256 ** size_of_int() - 1)
4359 assert_eq(cast(t5, 3.0), 3)
4360 assert_eq(cast(t5, 3.5), 3.5)
4361 assert_lt(cast(t5, 3.3), 3.3) # imperfect rounding
4362 assert_eq(cast(t6, 3.3), 3.3)
4363 assert_eq(cast(t5, 3.5), cast(t6, 3.5))
4364 assert_lt(cast(t5, 3.1), cast(t6, 3.1)) # imperfect rounding
4365 assert_eq(cast(t5, 7.0), cast(t3, 7))
4366 assert_lt(cast(t5, 3.1), 3.101)
4367 assert_gt(cast(t5, 3.1), 3)
4368
4369 def test_explicit_release_new():
4370 # release() on a ffi.new() object has no effect on CPython, but
4371 # really releases memory on PyPy. We can't test that effect
4372 # though, because a released cdata is not marked.
4373 BIntP = new_pointer_type(new_primitive_type("int"))
4374 p = newp(BIntP)
4375 p[0] = 42
4376 with pytest.raises(IndexError):
4377 p[1]
4378 release(p)
4379 # here, reading p[0] might give garbage or segfault...
4380 release(p) # no effect
4381 #
4382 BStruct = new_struct_type("struct foo")
4383 BStructP = new_pointer_type(BStruct)
4384 complete_struct_or_union(BStruct, [('p', BIntP, -1)])
4385 pstruct = newp(BStructP)
4386 assert pstruct.p == cast(BIntP, 0)
4387 release(pstruct)
4388 # here, reading pstruct.p might give garbage or segfault...
4389 release(pstruct) # no effect
4390
4391 def test_explicit_release_new_contextmgr():
4392 BIntP = new_pointer_type(new_primitive_type("int"))
4393 with newp(BIntP) as p:
4394 p[0] = 42
4395 assert p[0] == 42
4396 # here, reading p[0] might give garbage or segfault...
4397 release(p) # no effect
4398
4399 def test_explicit_release_badtype():
4400 BIntP = new_pointer_type(new_primitive_type("int"))
4401 p = cast(BIntP, 12345)
4402 pytest.raises(ValueError, release, p)
4403 pytest.raises(ValueError, release, p)
4404 BStruct = new_struct_type("struct foo")
4405 BStructP = new_pointer_type(BStruct)
4406 complete_struct_or_union(BStruct, [('p', BIntP, -1)])
4407 pstruct = newp(BStructP)
4408 pytest.raises(ValueError, release, pstruct[0])
4409
4410 def test_explicit_release_badtype_contextmgr():
4411 BIntP = new_pointer_type(new_primitive_type("int"))
4412 p = cast(BIntP, 12345)
4413 with pytest.raises(ValueError):
4414 with p:
4415 pass
4416 with pytest.raises(ValueError):
4417 with p:
4418 pass
4419
4420 def test_explicit_release_gc():
4421 BIntP = new_pointer_type(new_primitive_type("int"))
4422 seen = []
4423 intp1 = newp(BIntP, 12345)
4424 p1 = cast(BIntP, intp1)
4425 p = gcp(p1, seen.append)
4426 assert seen == []
4427 release(p)
4428 assert seen == [p1]
4429 assert p1[0] == 12345
4430 assert p[0] == 12345 # true so far, but might change to raise RuntimeError
4431 release(p) # no effect
4432
4433 def test_explicit_release_gc_contextmgr():
4434 BIntP = new_pointer_type(new_primitive_type("int"))
4435 seen = []
4436 intp1 = newp(BIntP, 12345)
4437 p1 = cast(BIntP, intp1)
4438 p = gcp(p1, seen.append)
4439 with p:
4440 assert p[0] == 12345
4441 assert seen == []
4442 assert seen == [p1]
4443 assert p1[0] == 12345
4444 assert p[0] == 12345 # true so far, but might change to raise RuntimeError
4445 release(p) # no effect
4446
4447 def test_explicit_release_from_buffer():
4448 a = bytearray(b"xyz")
4449 BChar = new_primitive_type("char")
4450 BCharP = new_pointer_type(BChar)
4451 BCharA = new_array_type(BCharP, None)
4452 p = from_buffer(BCharA, a)
4453 assert p[2] == b"z"
4454 assert repr(p) == "<cdata 'char[]' buffer len 3 from 'bytearray' object>"
4455 release(p)
4456 assert p[2] == b"z" # true so far, but might change to raise RuntimeError
4457 assert repr(p) == "<cdata 'char[]' buffer RELEASED>"
4458 release(p) # no effect
4459
4460 def test_explicit_release_from_buffer_contextmgr():
4461 a = bytearray(b"xyz")
4462 BChar = new_primitive_type("char")
4463 BCharP = new_pointer_type(BChar)
4464 BCharA = new_array_type(BCharP, None)
4465 p = from_buffer(BCharA, a)
4466 with p:
4467 assert p[2] == b"z"
4468 assert p[2] == b"z" # true so far, but might change to raise RuntimeError
4469 assert repr(p) == "<cdata 'char[]' buffer RELEASED>"
4470 release(p) # no effect
4471
4472 def test_explicit_release_bytearray_on_cpython():
4473 if '__pypy__' in sys.builtin_module_names:
4474 pytest.skip("pypy's bytearray are never locked")
4475 a = bytearray(b"xyz")
4476 BChar = new_primitive_type("char")
4477 BCharP = new_pointer_type(BChar)
4478 BCharA = new_array_type(BCharP, None)
4479 a += b't' * 10
4480 p = from_buffer(BCharA, a)
4481 with pytest.raises(BufferError):
4482 a += b'u' * 100
4483 release(p)
4484 a += b'v' * 100
4485 release(p) # no effect
4486 a += b'w' * 1000
4487 assert a == bytearray(b"xyz" + b't' * 10 + b'v' * 100 + b'w' * 1000)
4488
4489 def test_int_doesnt_give_bool():
4490 BBool = new_primitive_type("_Bool")
4491 x = int(cast(BBool, 42))
4492 assert type(x) is int and x == 1
4493 x = long(cast(BBool, 42))
4494 assert type(x) is long and x == 1
4495 with pytest.raises(TypeError):
4496 float(cast(BBool, 42))
4497 with pytest.raises(TypeError):
4498 complex(cast(BBool, 42))
4499
4500 def test_cannot_call_null_function_pointer():
4501 BInt = new_primitive_type("int")
4502 BFunc = new_function_type((BInt, BInt), BInt, False)
4503 f = cast(BFunc, 0)
4504 with pytest.raises(RuntimeError):
4505 f(40, 2)
4506
4507 def test_huge_structure():
4508 BChar = new_primitive_type("char")
4509 BArray = new_array_type(new_pointer_type(BChar), sys.maxsize)
4510 assert sizeof(BArray) == sys.maxsize
4511 BStruct = new_struct_type("struct foo")
4512 complete_struct_or_union(BStruct, [('a1', BArray, -1)])
4513 assert sizeof(BStruct) == sys.maxsize
4514
4515 def test_get_types():
4516 import _cffi_backend
4517 CData, CType = _get_types()
4518 assert CData is _cffi_backend._CDataBase
4519 assert CType is _cffi_backend.CType
4520
4521 def test_type_available_with_correct_names():
4522 import _cffi_backend
4523 check_names = [
4524 'CType',
4525 'CField',
4526 'CLibrary',
4527 '_CDataBase',
4528 'FFI',
4529 'Lib',
4530 'buffer',
4531 ]
4532 if '__pypy__' in sys.builtin_module_names:
4533 check_names += [
4534 '__CData_iterator',
4535 '__FFIGlobSupport',
4536 '__FFIAllocator',
4537 '__FFIFunctionWrapper',
4538 ]
4539 else:
4540 check_names += [
4541 '__CDataOwn',
4542 '__CDataOwnGC',
4543 '__CDataFromBuf',
4544 '__CDataGCP',
4545 '__CData_iterator',
4546 '__FFIGlobSupport',
4547 ]
4548 for name in check_names:
4549 tp = getattr(_cffi_backend, name)
4550 assert isinstance(tp, type)
4551 assert (tp.__module__, tp.__name__) == ('_cffi_backend', name)
4552
4553 def test_unaligned_types():
4554 BByteArray = new_array_type(
4555 new_pointer_type(new_primitive_type("unsigned char")), None)
4556 pbuf = newp(BByteArray, 40)
4557 buf = buffer(pbuf)
4558 #
4559 for name in ['short', 'int', 'long', 'long long', 'float', 'double',
4560 '_cffi_float_complex_t', '_cffi_double_complex_t']:
4561 p = new_primitive_type(name)
4562 if name.endswith('_complex_t'):
4563 num = cast(p, 1.23 - 4.56j)
4564 else:
4565 num = cast(p, 0x0123456789abcdef)
4566 size = sizeof(p)
4567 buf[0:40] = b"\x00" * 40
4568 pbuf1 = cast(new_pointer_type(p), pbuf + 1)
4569 pbuf1[0] = num
4570 assert pbuf1[0] == num
4571 assert buf[0] == b'\x00'
4572 assert buf[1 + size] == b'\x00'