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

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

#countcontent
1n/aimport unittest
2n/afrom test import support
3n/afrom ctypes import *
4n/a
5n/aimport _ctypes_test
6n/a
7n/alib = CDLL(_ctypes_test.__file__)
8n/a
9n/aclass StringPtrTestCase(unittest.TestCase):
10n/a
11n/a @support.refcount_test
12n/a def test__POINTER_c_char(self):
13n/a class X(Structure):
14n/a _fields_ = [("str", POINTER(c_char))]
15n/a x = X()
16n/a
17n/a # NULL pointer access
18n/a self.assertRaises(ValueError, getattr, x.str, "contents")
19n/a b = c_buffer(b"Hello, World")
20n/a from sys import getrefcount as grc
21n/a self.assertEqual(grc(b), 2)
22n/a x.str = b
23n/a self.assertEqual(grc(b), 3)
24n/a
25n/a # POINTER(c_char) and Python string is NOT compatible
26n/a # POINTER(c_char) and c_buffer() is compatible
27n/a for i in range(len(b)):
28n/a self.assertEqual(b[i], x.str[i])
29n/a
30n/a self.assertRaises(TypeError, setattr, x, "str", "Hello, World")
31n/a
32n/a def test__c_char_p(self):
33n/a class X(Structure):
34n/a _fields_ = [("str", c_char_p)]
35n/a x = X()
36n/a
37n/a # c_char_p and Python string is compatible
38n/a # c_char_p and c_buffer is NOT compatible
39n/a self.assertEqual(x.str, None)
40n/a x.str = b"Hello, World"
41n/a self.assertEqual(x.str, b"Hello, World")
42n/a b = c_buffer(b"Hello, World")
43n/a self.assertRaises(TypeError, setattr, x, b"str", b)
44n/a
45n/a
46n/a def test_functions(self):
47n/a strchr = lib.my_strchr
48n/a strchr.restype = c_char_p
49n/a
50n/a # c_char_p and Python string is compatible
51n/a # c_char_p and c_buffer are now compatible
52n/a strchr.argtypes = c_char_p, c_char
53n/a self.assertEqual(strchr(b"abcdef", b"c"), b"cdef")
54n/a self.assertEqual(strchr(c_buffer(b"abcdef"), b"c"), b"cdef")
55n/a
56n/a # POINTER(c_char) and Python string is NOT compatible
57n/a # POINTER(c_char) and c_buffer() is compatible
58n/a strchr.argtypes = POINTER(c_char), c_char
59n/a buf = c_buffer(b"abcdef")
60n/a self.assertEqual(strchr(buf, b"c"), b"cdef")
61n/a self.assertEqual(strchr(b"abcdef", b"c"), b"cdef")
62n/a
63n/a # XXX These calls are dangerous, because the first argument
64n/a # to strchr is no longer valid after the function returns!
65n/a # So we must keep a reference to buf separately
66n/a
67n/a strchr.restype = POINTER(c_char)
68n/a buf = c_buffer(b"abcdef")
69n/a r = strchr(buf, b"c")
70n/a x = r[0], r[1], r[2], r[3], r[4]
71n/a self.assertEqual(x, (b"c", b"d", b"e", b"f", b"\000"))
72n/a del buf
73n/a # x1 will NOT be the same as x, usually:
74n/a x1 = r[0], r[1], r[2], r[3], r[4]
75n/a
76n/aif __name__ == '__main__':
77n/a unittest.main()