Debian Codegraph @

extra_tests/ctypes_tests/test_buffers.py

raw symbols SCIP
1 import pytest
2 import sys
3 from ctypes import *
4
5 def test_buffer():
6 b = create_string_buffer(32)
7 assert len(b) == 32
8 assert sizeof(b) == 32 * sizeof(c_char)
9 assert type(b[0]) is bytes
10
11 b = create_string_buffer(b"abc")
12 assert len(b) == 4 # trailing nul char
13 assert sizeof(b) == 4 * sizeof(c_char)
14 assert type(b[0]) is bytes
15 assert b[0] == b"a"
16 assert b[:] == b"abc\0"
17
18 def test_from_buffer():
19 b1 = bytearray(b"abcde")
20 b = (c_char * 5).from_buffer(b1)
21 assert b[2] == b"c"
22 #
23 b1 = bytearray(b"abcd")
24 b = c_int.from_buffer(b1)
25 assert b.value in (1684234849, # little endian
26 1633837924) # big endian
27
28 def test_from_buffer_keepalive():
29 # Issue #2878
30 b1 = bytearray(b"ab")
31 array = (c_uint16 * 32)()
32 array[6] = c_uint16.from_buffer(b1)
33 # this is also what we get on CPython. I don't think it makes
34 # sense because the array contains just a copy of the number.
35 assert array._objects == {'6': b1}
36
37 def normalize(fmt):
38 if sys.byteorder == "big":
39 return fmt.replace('<', '>')
40 else:
41 return fmt
42
43 s_long = {4: 'l', 8: 'q'}[sizeof(c_long)]
44 s_ulong = {4: 'L', 8: 'Q'}[sizeof(c_long)]
45
46 @pytest.mark.parametrize("tp, fmt", [
47 ## simple types
48 (c_char, "<c"),
49 (c_byte, "<b"),
50 (c_ubyte, "<B"),
51 (c_short, "<h"),
52 (c_ushort, "<H"),
53 (c_long, f"<{s_long}"),
54 (c_ulong, f"<{s_ulong}"),
55 (c_float, "<f"),
56 (c_double, "<d"),
57 (c_bool, "<?"),
58 (py_object, "<O"),
59 ## pointers
60 (POINTER(c_byte), "&<b"),
61 (POINTER(POINTER(c_long)), f"&&<{s_long}"),
62 ## arrays and pointers
63 (c_double * 4, "<d"),
64 (c_float * 4 * 3 * 2, "<f"),
65 (POINTER(c_short) * 2, "&<h"),
66 (POINTER(c_short) * 2 * 3, "&<h"),
67 (POINTER(c_short * 2), "&(2)<h"),
68 ])
69 def test_memoryview_format(tp, fmt):
70 assert memoryview(tp()).format == normalize(fmt)