ยปCore Development>Code coverage>Lib/ctypes/test/test_array_in_pointer.py

Python code coverage for Lib/ctypes/test/test_array_in_pointer.py

#countcontent
1n/aimport unittest
2n/afrom ctypes import *
3n/afrom binascii import hexlify
4n/aimport re
5n/a
6n/adef dump(obj):
7n/a # helper function to dump memory contents in hex, with a hyphen
8n/a # between the bytes.
9n/a h = hexlify(memoryview(obj)).decode()
10n/a return re.sub(r"(..)", r"\1-", h)[:-1]
11n/a
12n/a
13n/aclass Value(Structure):
14n/a _fields_ = [("val", c_byte)]
15n/a
16n/aclass Container(Structure):
17n/a _fields_ = [("pvalues", POINTER(Value))]
18n/a
19n/aclass Test(unittest.TestCase):
20n/a def test(self):
21n/a # create an array of 4 values
22n/a val_array = (Value * 4)()
23n/a
24n/a # create a container, which holds a pointer to the pvalues array.
25n/a c = Container()
26n/a c.pvalues = val_array
27n/a
28n/a # memory contains 4 NUL bytes now, that's correct
29n/a self.assertEqual("00-00-00-00", dump(val_array))
30n/a
31n/a # set the values of the array through the pointer:
32n/a for i in range(4):
33n/a c.pvalues[i].val = i + 1
34n/a
35n/a values = [c.pvalues[i].val for i in range(4)]
36n/a
37n/a # These are the expected results: here s the bug!
38n/a self.assertEqual(
39n/a (values, dump(val_array)),
40n/a ([1, 2, 3, 4], "01-02-03-04")
41n/a )
42n/a
43n/a def test_2(self):
44n/a
45n/a val_array = (Value * 4)()
46n/a
47n/a # memory contains 4 NUL bytes now, that's correct
48n/a self.assertEqual("00-00-00-00", dump(val_array))
49n/a
50n/a ptr = cast(val_array, POINTER(Value))
51n/a # set the values of the array through the pointer:
52n/a for i in range(4):
53n/a ptr[i].val = i + 1
54n/a
55n/a values = [ptr[i].val for i in range(4)]
56n/a
57n/a # These are the expected results: here s the bug!
58n/a self.assertEqual(
59n/a (values, dump(val_array)),
60n/a ([1, 2, 3, 4], "01-02-03-04")
61n/a )
62n/a
63n/aif __name__ == "__main__":
64n/a unittest.main()