Debian Codegraph @

extra_tests/cffi_tests/cffi1/test_ffi_obj.py

raw symbols SCIP
1 # Generated by pypy/tool/import_cffi.py
2 import sys
3 import pytest
4 import _cffi_backend as _cffi1_backend
5
6
7 def test_ffi_new():
8 ffi = _cffi1_backend.FFI()
9 p = ffi.new("int *")
10 p[0] = -42
11 assert p[0] == -42
12 assert type(ffi) is ffi.__class__ is _cffi1_backend.FFI
13
14 def test_ffi_subclass():
15 class FOO(_cffi1_backend.FFI):
16 def __init__(self, x):
17 self.x = x
18 foo = FOO(42)
19 assert foo.x == 42
20 p = foo.new("int *")
21 assert p[0] == 0
22 assert type(foo) is foo.__class__ is FOO
23
24 def test_ffi_no_argument():
25 pytest.raises(TypeError, _cffi1_backend.FFI, 42)
26
27 def test_ffi_cache_type():
28 ffi = _cffi1_backend.FFI()
29 t1 = ffi.typeof("int **")
30 t2 = ffi.typeof("int *")
31 assert t2.item is t1.item.item
32 assert t2 is t1.item
33 assert ffi.typeof("int[][10]") is ffi.typeof("int[][10]")
34 assert ffi.typeof("int(*)()") is ffi.typeof("int(*)()")
35
36 def test_ffi_type_not_immortal():
37 import weakref, gc
38 ffi = _cffi1_backend.FFI()
39 # this test can fail on free-threaded builds lazier GC if the type was used by another test
40 t1 = ffi.typeof("unsigned short int **")
41 t2 = ffi.typeof("unsigned short int *")
42 w1 = weakref.ref(t1)
43 w2 = weakref.ref(t2)
44 del t1, ffi
45 gc.collect()
46 assert w1() is None
47 assert w2() is t2
48 ffi = _cffi1_backend.FFI()
49 assert ffi.typeof(ffi.new("unsigned short int **")[0]) is t2
50 #
51 ffi = _cffi1_backend.FFI()
52 t1 = ffi.typeof("int ***")
53 t2 = ffi.typeof("int **")
54 w1 = weakref.ref(t1)
55 w2 = weakref.ref(t2)
56 del t2, ffi
57 gc.collect()
58 assert w1() is t1
59 assert w2() is not None # kept alive by t1
60 ffi = _cffi1_backend.FFI()
61 assert ffi.typeof("int * *") is t1.item
62
63 def test_ffi_cache_type_globally():
64 ffi1 = _cffi1_backend.FFI()
65 ffi2 = _cffi1_backend.FFI()
66 t1 = ffi1.typeof("int *")
67 t2 = ffi2.typeof("int *")
68 assert t1 is t2
69
70 def test_ffi_invalid():
71 ffi = _cffi1_backend.FFI()
72 # array of 10 times an "int[]" is invalid
73 pytest.raises(ValueError, ffi.typeof, "int[10][]")
74
75 def test_ffi_docstrings():
76 # check that all methods of the FFI class have a docstring.
77 check_type = type(_cffi1_backend.FFI.new)
78 for methname in dir(_cffi1_backend.FFI):
79 if not methname.startswith('_'):
80 method = getattr(_cffi1_backend.FFI, methname)
81 if isinstance(method, check_type):
82 assert method.__doc__, "method FFI.%s() has no docstring" % (
83 methname,)
84
85 def test_ffi_NULL():
86 NULL = _cffi1_backend.FFI.NULL
87 assert _cffi1_backend.FFI().typeof(NULL).cname == "void *"
88
89 def test_ffi_no_attr():
90 ffi = _cffi1_backend.FFI()
91 with pytest.raises(AttributeError):
92 ffi.no_such_name
93 with pytest.raises(AttributeError):
94 ffi.no_such_name = 42
95 with pytest.raises(AttributeError):
96 del ffi.no_such_name
97
98 def test_ffi_string():
99 ffi = _cffi1_backend.FFI()
100 p = ffi.new("char[]", init=b"foobar\x00baz")
101 assert ffi.string(p) == b"foobar"
102 assert ffi.string(cdata=p, maxlen=3) == b"foo"
103
104 def test_ffi_errno():
105 # xxx not really checking errno, just checking that we can read/write it
106 ffi = _cffi1_backend.FFI()
107 ffi.errno = 42
108 assert ffi.errno == 42
109
110 def test_ffi_alignof():
111 ffi = _cffi1_backend.FFI()
112 assert ffi.alignof("int") == 4
113 assert ffi.alignof("int[]") == 4
114 assert ffi.alignof("int[41]") == 4
115 assert ffi.alignof("short[41]") == 2
116 assert ffi.alignof(ffi.new("int[41]")) == 4
117 assert ffi.alignof(ffi.new("int[]", 41)) == 4
118
119 def test_ffi_sizeof():
120 ffi = _cffi1_backend.FFI()
121 assert ffi.sizeof("int") == 4
122 pytest.raises(ffi.error, ffi.sizeof, "int[]")
123 assert ffi.sizeof("int[41]") == 41 * 4
124 assert ffi.sizeof(ffi.new("int[41]")) == 41 * 4
125 assert ffi.sizeof(ffi.new("int[]", 41)) == 41 * 4
126
127 def test_ffi_callback():
128 ffi = _cffi1_backend.FFI()
129 assert ffi.callback("int(int)", lambda x: x + 42)(10) == 52
130 assert ffi.callback("int(*)(int)", lambda x: x + 42)(10) == 52
131 assert ffi.callback("int(int)", lambda x: x + "", -66)(10) == -66
132 assert ffi.callback("int(int)", lambda x: x + "", error=-66)(10) == -66
133
134 def test_ffi_callback_decorator():
135 ffi = _cffi1_backend.FFI()
136 assert ffi.callback(ffi.typeof("int(*)(int)"))(lambda x: x + 42)(10) == 52
137 deco = ffi.callback("int(int)", error=-66)
138 assert deco(lambda x: x + "")(10) == -66
139 assert deco(lambda x: x + 42)(10) == 52
140
141 def test_ffi_callback_onerror():
142 ffi = _cffi1_backend.FFI()
143 seen = []
144 def oops(*args):
145 seen.append(args)
146
147 @ffi.callback("int(int)", onerror=oops)
148 def fn1(x):
149 return x + ""
150 assert fn1(10) == 0
151
152 @ffi.callback("int(int)", onerror=oops, error=-66)
153 def fn2(x):
154 return x + ""
155 assert fn2(10) == -66
156
157 assert len(seen) == 2
158 exc, val, tb = seen[0]
159 assert exc is TypeError
160 assert isinstance(val, TypeError)
161 assert tb.tb_frame.f_code.co_name == "fn1"
162 exc, val, tb = seen[1]
163 assert exc is TypeError
164 assert isinstance(val, TypeError)
165 assert tb.tb_frame.f_code.co_name == "fn2"
166 #
167 pytest.raises(TypeError, ffi.callback, "int(int)",
168 lambda x: x, onerror=42) # <- not callable
169
170 def test_ffi_getctype():
171 ffi = _cffi1_backend.FFI()
172 assert ffi.getctype("int") == "int"
173 assert ffi.getctype("int", 'x') == "int x"
174 assert ffi.getctype("int*") == "int *"
175 assert ffi.getctype("int*", '') == "int *"
176 assert ffi.getctype("int*", 'x') == "int * x"
177 assert ffi.getctype("int", '*') == "int *"
178 assert ffi.getctype("int", replace_with=' * x ') == "int * x"
179 assert ffi.getctype(ffi.typeof("int*"), '*') == "int * *"
180 assert ffi.getctype("int", '[5]') == "int[5]"
181 assert ffi.getctype("int[5]", '[6]') == "int[6][5]"
182 assert ffi.getctype("int[5]", '(*)') == "int(*)[5]"
183 # special-case for convenience: automatically put '()' around '*'
184 assert ffi.getctype("int[5]", '*') == "int(*)[5]"
185 assert ffi.getctype("int[5]", '*foo') == "int(*foo)[5]"
186 assert ffi.getctype("int[5]", ' ** foo ') == "int(** foo)[5]"
187
188 def test_addressof():
189 ffi = _cffi1_backend.FFI()
190 a = ffi.new("int[10]")
191 b = ffi.addressof(a, 5)
192 b[2] = -123
193 assert a[7] == -123
194
195 def test_handle():
196 ffi = _cffi1_backend.FFI()
197 x = [2, 4, 6]
198 xp = ffi.new_handle(x)
199 assert ffi.typeof(xp) == ffi.typeof("void *")
200 assert ffi.from_handle(xp) is x
201 yp = ffi.new_handle([6, 4, 2])
202 assert ffi.from_handle(yp) == [6, 4, 2]
203
204 def test_handle_unique():
205 ffi = _cffi1_backend.FFI()
206 assert ffi.new_handle(None) is not ffi.new_handle(None)
207 assert ffi.new_handle(None) != ffi.new_handle(None)
208
209 def test_ffi_cast():
210 ffi = _cffi1_backend.FFI()
211 assert ffi.cast("int(*)(int)", 0) == ffi.NULL
212 ffi.callback("int(int)") # side-effect of registering this string
213 pytest.raises(ffi.error, ffi.cast, "int(int)", 0)
214
215 def test_ffi_invalid_type():
216 ffi = _cffi1_backend.FFI()
217 e = pytest.raises(ffi.error, ffi.cast, "", 0)
218 assert str(e.value) == ("identifier expected\n"
219 "\n"
220 "^")
221 e = pytest.raises(ffi.error, ffi.cast, "struct struct", 0)
222 assert str(e.value) == ("struct or union name expected\n"
223 "struct struct\n"
224 " ^")
225 e = pytest.raises(ffi.error, ffi.cast, "struct never_heard_of_s", 0)
226 assert str(e.value) == ("undefined struct/union name\n"
227 "struct never_heard_of_s\n"
228 " ^")
229 e = pytest.raises(ffi.error, ffi.cast, "\t\n\x01\x1f~\x7f\x80\xff", 0)
230 marks = "?" if sys.version_info < (3,) else "??"
231 assert str(e.value) == ("identifier expected\n"
232 " ??~?%s%s\n"
233 " ^" % (marks, marks))
234 e = pytest.raises(ffi.error, ffi.cast, "X" * 600, 0)
235 assert str(e.value) == ("undefined type name")
236
237 def test_ffi_buffer():
238 ffi = _cffi1_backend.FFI()
239 a = ffi.new("signed char[]", [5, 6, 7])
240 assert ffi.buffer(a)[:] == b'\x05\x06\x07'
241 assert ffi.buffer(cdata=a, size=2)[:] == b'\x05\x06'
242 assert type(ffi.buffer(a)) is ffi.buffer
243
244 def test_ffi_from_buffer():
245 import array
246 ffi = _cffi1_backend.FFI()
247 a = array.array('H', [10000, 20000, 30000, 40000])
248 c = ffi.from_buffer(a)
249 assert ffi.typeof(c) is ffi.typeof("char[]")
250 assert len(c) == 8
251 ffi.cast("unsigned short *", c)[1] += 500
252 assert list(a) == [10000, 20500, 30000, 40000]
253 pytest.raises(TypeError, ffi.from_buffer, a, True)
254 assert c == ffi.from_buffer("char[]", a, True)
255 assert c == ffi.from_buffer(a, require_writable=True)
256 #
257 c = ffi.from_buffer("unsigned short[]", a)
258 assert len(c) == 4
259 assert c[1] == 20500
260 #
261 c = ffi.from_buffer("unsigned short[2][2]", a)
262 assert len(c) == 2
263 assert len(c[0]) == 2
264 assert c[0][1] == 20500
265 #
266 p = ffi.from_buffer(b"abcd")
267 assert p[2] == b"c"
268 #
269 assert p == ffi.from_buffer(b"abcd", require_writable=False)
270 pytest.raises((TypeError, BufferError), ffi.from_buffer,
271 "char[]", b"abcd", True)
272 pytest.raises((TypeError, BufferError), ffi.from_buffer, b"abcd",
273 require_writable=True)
274
275 def test_memmove():
276 ffi = _cffi1_backend.FFI()
277 p = ffi.new("short[]", [-1234, -2345, -3456, -4567, -5678])
278 ffi.memmove(p, p + 1, 4)
279 assert list(p) == [-2345, -3456, -3456, -4567, -5678]
280 p[2] = 999
281 ffi.memmove(p + 2, p, 6)
282 assert list(p) == [-2345, -3456, -2345, -3456, 999]
283 ffi.memmove(p + 4, ffi.new("char[]", b"\x71\x72"), 2)
284 if sys.byteorder == 'little':
285 assert list(p) == [-2345, -3456, -2345, -3456, 0x7271]
286 else:
287 assert list(p) == [-2345, -3456, -2345, -3456, 0x7172]
288
289 def test_memmove_buffer():
290 import array
291 ffi = _cffi1_backend.FFI()
292 a = array.array('H', [10000, 20000, 30000])
293 p = ffi.new("short[]", 5)
294 ffi.memmove(p, a, 6)
295 assert list(p) == [10000, 20000, 30000, 0, 0]
296 ffi.memmove(p + 1, a, 6)
297 assert list(p) == [10000, 10000, 20000, 30000, 0]
298 b = array.array('h', [-1000, -2000, -3000])
299 ffi.memmove(b, a, 4)
300 assert b.tolist() == [10000, 20000, -3000]
301 assert a.tolist() == [10000, 20000, 30000]
302 p[0] = 999
303 p[1] = 998
304 p[2] = 997
305 p[3] = 996
306 p[4] = 995
307 ffi.memmove(b, p, 2)
308 assert b.tolist() == [999, 20000, -3000]
309 ffi.memmove(b, p + 2, 4)
310 assert b.tolist() == [997, 996, -3000]
311 p[2] = -p[2]
312 p[3] = -p[3]
313 ffi.memmove(b, p + 2, 6)
314 assert b.tolist() == [-997, -996, 995]
315
316 def test_memmove_readonly_readwrite():
317 ffi = _cffi1_backend.FFI()
318 p = ffi.new("signed char[]", 5)
319 ffi.memmove(p, b"abcde", 3)
320 assert list(p) == [ord("a"), ord("b"), ord("c"), 0, 0]
321 ffi.memmove(p, bytearray(b"ABCDE"), 2)
322 assert list(p) == [ord("A"), ord("B"), ord("c"), 0, 0]
323 pytest.raises((TypeError, BufferError), ffi.memmove, b"abcde", p, 3)
324 ba = bytearray(b"xxxxx")
325 ffi.memmove(dest=ba, src=p, n=3)
326 assert ba == bytearray(b"ABcxx")
327
328 def test_ffi_types():
329 CData = _cffi1_backend.FFI.CData
330 CType = _cffi1_backend.FFI.CType
331 ffi = _cffi1_backend.FFI()
332 assert isinstance(ffi.cast("int", 42), CData)
333 assert isinstance(ffi.typeof("int"), CType)
334
335 def test_ffi_getwinerror():
336 if sys.platform != "win32":
337 pytest.skip("for windows")
338 ffi = _cffi1_backend.FFI()
339 n = (1 << 29) + 42
340 code, message = ffi.getwinerror(code=n)
341 assert code == n
342
343 def test_ffi_new_allocator_1():
344 ffi = _cffi1_backend.FFI()
345 alloc1 = ffi.new_allocator()
346 alloc2 = ffi.new_allocator(should_clear_after_alloc=False)
347 for retry in range(400):
348 p1 = alloc1("int[10]")
349 p2 = alloc2("int[]", 10 + retry * 13)
350 combination = 0
351 for i in range(10):
352 assert p1[i] == 0
353 combination |= p2[i]
354 p1[i] = -42
355 p2[i] = -43
356 if combination != 0:
357 break
358 else:
359 raise AssertionError("cannot seem to get an int[10] not "
360 "completely cleared")
361
362 def test_ffi_new_allocator_2():
363 ffi = _cffi1_backend.FFI()
364 seen = []
365 def myalloc(size):
366 seen.append(size)
367 return ffi.new("char[]", b"X" * size)
368 def myfree(raw):
369 seen.append(raw)
370 alloc1 = ffi.new_allocator(myalloc, myfree)
371 alloc2 = ffi.new_allocator(alloc=myalloc, free=myfree,
372 should_clear_after_alloc=False)
373 p1 = alloc1("int[10]")
374 p2 = alloc2("int[]", 10)
375 assert seen == [40, 40]
376 assert ffi.typeof(p1) == ffi.typeof("int[10]")
377 assert ffi.sizeof(p1) == 40
378 assert ffi.typeof(p2) == ffi.typeof("int[]")
379 assert ffi.sizeof(p2) == 40
380 assert p1[5] == 0
381 assert p2[6] == ord('X') * 0x01010101
382 raw1 = ffi.cast("char *", p1)
383 raw2 = ffi.cast("char *", p2)
384 del p1, p2
385 retries = 0
386 while len(seen) != 4:
387 retries += 1
388 assert retries <= 5
389 import gc; gc.collect()
390 assert (seen == [40, 40, raw1, raw2] or
391 seen == [40, 40, raw2, raw1])
392 assert repr(seen[2]) == "<cdata 'char[]' owning 41 bytes>"
393 assert repr(seen[3]) == "<cdata 'char[]' owning 41 bytes>"
394
395 def test_ffi_new_allocator_3():
396 ffi = _cffi1_backend.FFI()
397 seen = []
398 def myalloc(size):
399 seen.append(size)
400 return ffi.new("char[]", b"X" * size)
401 alloc1 = ffi.new_allocator(myalloc) # no 'free'
402 p1 = alloc1("int[10]")
403 assert seen == [40]
404 assert ffi.typeof(p1) == ffi.typeof("int[10]")
405 assert ffi.sizeof(p1) == 40
406 assert p1[5] == 0
407
408 def test_ffi_new_allocator_4():
409 ffi = _cffi1_backend.FFI()
410 pytest.raises(TypeError, ffi.new_allocator, free=lambda x: None)
411 #
412 def myalloc2(size):
413 raise LookupError
414 alloc2 = ffi.new_allocator(myalloc2)
415 pytest.raises(LookupError, alloc2, "int[5]")
416 #
417 def myalloc3(size):
418 return 42
419 alloc3 = ffi.new_allocator(myalloc3)
420 e = pytest.raises(TypeError, alloc3, "int[5]")
421 assert str(e.value) == "alloc() must return a cdata object (got int)"
422 #
423 def myalloc4(size):
424 return ffi.cast("int", 42)
425 alloc4 = ffi.new_allocator(myalloc4)
426 e = pytest.raises(TypeError, alloc4, "int[5]")
427 assert str(e.value) == "alloc() must return a cdata pointer, not 'int'"
428 #
429 def myalloc5(size):
430 return ffi.NULL
431 alloc5 = ffi.new_allocator(myalloc5)
432 pytest.raises(MemoryError, alloc5, "int[5]")
433
434 def test_bool_issue228():
435 ffi = _cffi1_backend.FFI()
436 fntype = ffi.typeof("int(*callback)(bool is_valid)")
437 assert repr(fntype.args[0]) == "<ctype '_Bool'>"
438
439 def test_FILE_issue228():
440 fntype1 = _cffi1_backend.FFI().typeof("FILE *")
441 fntype2 = _cffi1_backend.FFI().typeof("FILE *")
442 assert repr(fntype1) == "<ctype 'FILE *'>"
443 assert fntype1 is fntype2
444
445 def test_cast_from_int_type_to_bool():
446 ffi = _cffi1_backend.FFI()
447 for basetype in ['char', 'short', 'int', 'long', 'long long']:
448 for sign in ['signed', 'unsigned']:
449 type = '%s %s' % (sign, basetype)
450 assert int(ffi.cast("_Bool", ffi.cast(type, 42))) == 1
451 assert int(ffi.cast("bool", ffi.cast(type, 42))) == 1
452 assert int(ffi.cast("_Bool", ffi.cast(type, 0))) == 0
453
454 def test_init_once():
455 def do_init():
456 seen.append(1)
457 return 42
458 ffi = _cffi1_backend.FFI()
459 seen = []
460 for i in range(3):
461 res = ffi.init_once(do_init, "tag1")
462 assert res == 42
463 assert seen == [1]
464 for i in range(3):
465 res = ffi.init_once(do_init, "tag2")
466 assert res == 42
467 assert seen == [1, 1]
468
469 def test_init_once_multithread():
470 if sys.version_info < (3,):
471 import thread
472 else:
473 import _thread as thread
474 import time
475 #
476 def do_init():
477 print('init!')
478 seen.append('init!')
479 time.sleep(1)
480 seen.append('init done')
481 print('init done')
482 return 7
483 ffi = _cffi1_backend.FFI()
484 seen = []
485 for i in range(6):
486 def f():
487 res = ffi.init_once(do_init, "tag")
488 seen.append(res)
489 thread.start_new_thread(f, ())
490 time.sleep(1.5)
491 assert seen == ['init!', 'init done'] + 6 * [7]
492
493 def test_init_once_failure():
494 def do_init():
495 seen.append(1)
496 raise ValueError
497 ffi = _cffi1_backend.FFI()
498 seen = []
499 for i in range(5):
500 pytest.raises(ValueError, ffi.init_once, do_init, "tag")
501 assert seen == [1] * (i + 1)
502
503 def test_init_once_multithread_failure():
504 if sys.version_info < (3,):
505 import thread
506 else:
507 import _thread as thread
508 import time
509 def do_init():
510 seen.append('init!')
511 time.sleep(1)
512 seen.append('oops')
513 raise ValueError
514 ffi = _cffi1_backend.FFI()
515 seen = []
516 for i in range(3):
517 def f():
518 pytest.raises(ValueError, ffi.init_once, do_init, "tag")
519 thread.start_new_thread(f, ())
520 i = 0
521 while len(seen) < 6:
522 i += 1
523 assert i < 20
524 time.sleep(0.51)
525 assert seen == ['init!', 'oops'] * 3
526
527 def test_unpack():
528 ffi = _cffi1_backend.FFI()
529 p = ffi.new("char[]", b"abc\x00def")
530 assert ffi.unpack(p+1, 7) == b"bc\x00def\x00"
531 p = ffi.new("int[]", [-123456789])
532 assert ffi.unpack(p, 1) == [-123456789]
533
534 def test_negative_array_size():
535 ffi = _cffi1_backend.FFI()
536 pytest.raises(ffi.error, ffi.cast, "int[-5]", 0)
537