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

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

#countcontent
1n/aimport unittest
2n/afrom test import support
3n/aimport ctypes
4n/aimport gc
5n/a
6n/aMyCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int)
7n/aOtherCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_ulonglong)
8n/a
9n/aimport _ctypes_test
10n/adll = ctypes.CDLL(_ctypes_test.__file__)
11n/a
12n/aclass RefcountTestCase(unittest.TestCase):
13n/a
14n/a @support.refcount_test
15n/a def test_1(self):
16n/a from sys import getrefcount as grc
17n/a
18n/a f = dll._testfunc_callback_i_if
19n/a f.restype = ctypes.c_int
20n/a f.argtypes = [ctypes.c_int, MyCallback]
21n/a
22n/a def callback(value):
23n/a #print "called back with", value
24n/a return value
25n/a
26n/a self.assertEqual(grc(callback), 2)
27n/a cb = MyCallback(callback)
28n/a
29n/a self.assertGreater(grc(callback), 2)
30n/a result = f(-10, cb)
31n/a self.assertEqual(result, -18)
32n/a cb = None
33n/a
34n/a gc.collect()
35n/a
36n/a self.assertEqual(grc(callback), 2)
37n/a
38n/a
39n/a @support.refcount_test
40n/a def test_refcount(self):
41n/a from sys import getrefcount as grc
42n/a def func(*args):
43n/a pass
44n/a # this is the standard refcount for func
45n/a self.assertEqual(grc(func), 2)
46n/a
47n/a # the CFuncPtr instance holds at least one refcount on func:
48n/a f = OtherCallback(func)
49n/a self.assertGreater(grc(func), 2)
50n/a
51n/a # and may release it again
52n/a del f
53n/a self.assertGreaterEqual(grc(func), 2)
54n/a
55n/a # but now it must be gone
56n/a gc.collect()
57n/a self.assertEqual(grc(func), 2)
58n/a
59n/a class X(ctypes.Structure):
60n/a _fields_ = [("a", OtherCallback)]
61n/a x = X()
62n/a x.a = OtherCallback(func)
63n/a
64n/a # the CFuncPtr instance holds at least one refcount on func:
65n/a self.assertGreater(grc(func), 2)
66n/a
67n/a # and may release it again
68n/a del x
69n/a self.assertGreaterEqual(grc(func), 2)
70n/a
71n/a # and now it must be gone again
72n/a gc.collect()
73n/a self.assertEqual(grc(func), 2)
74n/a
75n/a f = OtherCallback(func)
76n/a
77n/a # the CFuncPtr instance holds at least one refcount on func:
78n/a self.assertGreater(grc(func), 2)
79n/a
80n/a # create a cycle
81n/a f.cycle = f
82n/a
83n/a del f
84n/a gc.collect()
85n/a self.assertEqual(grc(func), 2)
86n/a
87n/aclass AnotherLeak(unittest.TestCase):
88n/a def test_callback(self):
89n/a import sys
90n/a
91n/a proto = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int)
92n/a def func(a, b):
93n/a return a * b * 2
94n/a f = proto(func)
95n/a
96n/a a = sys.getrefcount(ctypes.c_int)
97n/a f(1, 2)
98n/a self.assertEqual(sys.getrefcount(ctypes.c_int), a)
99n/a
100n/aif __name__ == '__main__':
101n/a unittest.main()