Debian Codegraph @

lib-python/3/ctypes/test/test_callbacks.py

raw symbols SCIP
1 import functools
2 import unittest
3 from test import support
4
5 from ctypes import *
6 from ctypes.test import need_symbol
7 from _ctypes import CTYPES_MAX_ARGCOUNT
8 import _ctypes_test
9 try:
10 from sys import getrefcount as grc
11 except ImportError:
12 grc = None # e.g. PyPy
13
14 class Callbacks(unittest.TestCase):
15 functype = CFUNCTYPE
16
17 ## def tearDown(self):
18 ## import gc
19 ## gc.collect()
20
21 def callback(self, *args):
22 self.got_args = args
23 return args[-1]
24
25 def check_type(self, typ, arg):
26 PROTO = self.functype.__func__(typ, typ)
27 result = PROTO(self.callback)(arg)
28 if typ == c_float:
29 self.assertAlmostEqual(result, arg, places=5)
30 else:
31 self.assertEqual(self.got_args, (arg,))
32 self.assertEqual(result, arg)
33
34 PROTO = self.functype.__func__(typ, c_byte, typ)
35 result = PROTO(self.callback)(-3, arg)
36 if typ == c_float:
37 self.assertAlmostEqual(result, arg, places=5)
38 else:
39 self.assertEqual(self.got_args, (-3, arg))
40 self.assertEqual(result, arg)
41
42 ################
43
44 def test_byte(self):
45 self.check_type(c_byte, 42)
46 self.check_type(c_byte, -42)
47
48 def test_ubyte(self):
49 self.check_type(c_ubyte, 42)
50
51 def test_short(self):
52 self.check_type(c_short, 42)
53 self.check_type(c_short, -42)
54
55 def test_ushort(self):
56 self.check_type(c_ushort, 42)
57
58 def test_int(self):
59 self.check_type(c_int, 42)
60 self.check_type(c_int, -42)
61
62 def test_uint(self):
63 self.check_type(c_uint, 42)
64
65 def test_long(self):
66 self.check_type(c_long, 42)
67 self.check_type(c_long, -42)
68
69 def test_ulong(self):
70 self.check_type(c_ulong, 42)
71
72 @need_symbol('c_longlong')
73 def test_longlong(self):
74 self.check_type(c_longlong, 42)
75 self.check_type(c_longlong, -42)
76
77 @need_symbol('c_ulonglong')
78 def test_ulonglong(self):
79 self.check_type(c_ulonglong, 42)
80
81 def test_float(self):
82 # only almost equal: double -> float -> double
83 import math
84 self.check_type(c_float, math.e)
85 self.check_type(c_float, -math.e)
86
87 def test_double(self):
88 self.check_type(c_double, 3.14)
89 self.check_type(c_double, -3.14)
90
91 @need_symbol('c_longdouble')
92 def test_longdouble(self):
93 self.check_type(c_longdouble, 3.14)
94 self.check_type(c_longdouble, -3.14)
95
96 def test_char(self):
97 self.check_type(c_char, b"x")
98 self.check_type(c_char, b"a")
99
100 def test_pyobject(self):
101 if grc is None:
102 return unittest.skip("no sys.getrefcount()")
103 o = ()
104 for o in (), [], object():
105 initial = grc(o)
106 # This call leaks a reference to 'o'...
107 self.check_type(py_object, o)
108 before = grc(o)
109 # ...but this call doesn't leak any more. Where is the refcount?
110 self.check_type(py_object, o)
111 after = grc(o)
112 self.assertEqual((after, o), (before, o))
113
114 def test_unsupported_restype_1(self):
115 # Only "fundamental" result types are supported for callback
116 # functions, the type must have a non-NULL stgdict->setfunc.
117 # POINTER(c_double), for example, is not supported.
118
119 prototype = self.functype.__func__(POINTER(c_double))
120 # The type is checked when the prototype is called
121 self.assertRaises(TypeError, prototype, lambda: None)
122
123 def test_unsupported_restype_2(self):
124 prototype = self.functype.__func__(object)
125 self.assertRaises(TypeError, prototype, lambda: None)
126
127 def test_issue_7959(self):
128 proto = self.functype.__func__(None)
129
130 class X:
131 def func(self): pass
132 def __init__(self):
133 self.v = proto(self.func)
134
135 import gc
136 for i in range(32):
137 X()
138 gc.collect()
139 live = [x for x in gc.get_objects()
140 if isinstance(x, X)]
141 self.assertEqual(len(live), 0)
142
143 def test_issue12483(self):
144 import gc
145 class Nasty:
146 def __del__(self):
147 gc.collect()
148 CFUNCTYPE(None)(lambda x=Nasty(): None)
149
150
151 @need_symbol('WINFUNCTYPE')
152 class StdcallCallbacks(Callbacks):
153 try:
154 functype = WINFUNCTYPE
155 except NameError:
156 pass
157
158 ################################################################
159
160 class SampleCallbacksTestCase(unittest.TestCase):
161
162 def test_integrate(self):
163 # Derived from some then non-working code, posted by David Foster
164 dll = CDLL(_ctypes_test.__file__)
165
166 # The function prototype called by 'integrate': double func(double);
167 CALLBACK = CFUNCTYPE(c_double, c_double)
168
169 # The integrate function itself, exposed from the _ctypes_test dll
170 integrate = dll.integrate
171 integrate.argtypes = (c_double, c_double, CALLBACK, c_long)
172 integrate.restype = c_double
173
174 def func(x):
175 return x**2
176
177 result = integrate(0.0, 1.0, CALLBACK(func), 10)
178 diff = abs(result - 1./3.)
179
180 self.assertLess(diff, 0.01, "%s not less than 0.01" % diff)
181
182 def test_issue_8959_a(self):
183 from ctypes.util import find_library
184 libc_path = find_library("c")
185 if not libc_path:
186 self.skipTest('could not find libc')
187 libc = CDLL(libc_path)
188
189 @CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
190 def cmp_func(a, b):
191 return a[0] - b[0]
192
193 array = (c_int * 5)(5, 1, 99, 7, 33)
194
195 libc.qsort(array, len(array), sizeof(c_int), cmp_func)
196 self.assertEqual(array[:], [1, 5, 7, 33, 99])
197
198 @need_symbol('WINFUNCTYPE')
199 def test_issue_8959_b(self):
200 from ctypes.wintypes import BOOL, HWND, LPARAM
201 global windowCount
202 windowCount = 0
203
204 @WINFUNCTYPE(BOOL, HWND, LPARAM)
205 def EnumWindowsCallbackFunc(hwnd, lParam):
206 global windowCount
207 windowCount += 1
208 return True #Allow windows to keep enumerating
209
210 windll.user32.EnumWindows(EnumWindowsCallbackFunc, 0)
211
212 def test_callback_register_int(self):
213 # Issue #8275: buggy handling of callback args under Win64
214 # NOTE: should be run on release builds as well
215 dll = CDLL(_ctypes_test.__file__)
216 CALLBACK = CFUNCTYPE(c_int, c_int, c_int, c_int, c_int, c_int)
217 # All this function does is call the callback with its args squared
218 func = dll._testfunc_cbk_reg_int
219 func.argtypes = (c_int, c_int, c_int, c_int, c_int, CALLBACK)
220 func.restype = c_int
221
222 def callback(a, b, c, d, e):
223 return a + b + c + d + e
224
225 result = func(2, 3, 4, 5, 6, CALLBACK(callback))
226 self.assertEqual(result, callback(2*2, 3*3, 4*4, 5*5, 6*6))
227
228 def test_callback_register_double(self):
229 # Issue #8275: buggy handling of callback args under Win64
230 # NOTE: should be run on release builds as well
231 dll = CDLL(_ctypes_test.__file__)
232 CALLBACK = CFUNCTYPE(c_double, c_double, c_double, c_double,
233 c_double, c_double)
234 # All this function does is call the callback with its args squared
235 func = dll._testfunc_cbk_reg_double
236 func.argtypes = (c_double, c_double, c_double,
237 c_double, c_double, CALLBACK)
238 func.restype = c_double
239
240 def callback(a, b, c, d, e):
241 return a + b + c + d + e
242
243 result = func(1.1, 2.2, 3.3, 4.4, 5.5, CALLBACK(callback))
244 self.assertEqual(result,
245 callback(1.1*1.1, 2.2*2.2, 3.3*3.3, 4.4*4.4, 5.5*5.5))
246
247 def test_callback_large_struct(self):
248 class Check: pass
249
250 # This should mirror the structure in Modules/_ctypes/_ctypes_test.c
251 class X(Structure):
252 _fields_ = [
253 ('first', c_ulong),
254 ('second', c_ulong),
255 ('third', c_ulong),
256 ]
257
258 def callback(check, s):
259 check.first = s.first
260 check.second = s.second
261 check.third = s.third
262 # See issue #29565.
263 # The structure should be passed by value, so
264 # any changes to it should not be reflected in
265 # the value passed
266 s.first = s.second = s.third = 0x0badf00d
267
268 check = Check()
269 s = X()
270 s.first = 0xdeadbeef
271 s.second = 0xcafebabe
272 s.third = 0x0bad1dea
273
274 CALLBACK = CFUNCTYPE(None, X)
275 dll = CDLL(_ctypes_test.__file__)
276 func = dll._testfunc_cbk_large_struct
277 func.argtypes = (X, CALLBACK)
278 func.restype = None
279 # the function just calls the callback with the passed structure
280 func(s, CALLBACK(functools.partial(callback, check)))
281 self.assertEqual(check.first, s.first)
282 self.assertEqual(check.second, s.second)
283 self.assertEqual(check.third, s.third)
284 self.assertEqual(check.first, 0xdeadbeef)
285 self.assertEqual(check.second, 0xcafebabe)
286 self.assertEqual(check.third, 0x0bad1dea)
287 # See issue #29565.
288 # Ensure that the original struct is unchanged.
289 self.assertEqual(s.first, check.first)
290 self.assertEqual(s.second, check.second)
291 self.assertEqual(s.third, check.third)
292
293 def test_callback_too_many_args(self):
294 def func(*args):
295 return len(args)
296
297 # valid call with nargs <= CTYPES_MAX_ARGCOUNT
298 proto = CFUNCTYPE(c_int, *(c_int,) * CTYPES_MAX_ARGCOUNT)
299 cb = proto(func)
300 args1 = (1,) * CTYPES_MAX_ARGCOUNT
301 self.assertEqual(cb(*args1), CTYPES_MAX_ARGCOUNT)
302
303 # invalid call with nargs > CTYPES_MAX_ARGCOUNT
304 args2 = (1,) * (CTYPES_MAX_ARGCOUNT + 1)
305 with self.assertRaises(ArgumentError):
306 cb(*args2)
307
308 # error when creating the type with too many arguments
309 with self.assertRaises(ArgumentError):
310 CFUNCTYPE(c_int, *(c_int,) * (CTYPES_MAX_ARGCOUNT + 1))
311
312 def test_convert_result_error(self):
313 def func():
314 return ("tuple",)
315
316 proto = CFUNCTYPE(c_int)
317 ctypes_func = proto(func)
318 with support.catch_unraisable_exception() as cm:
319 # don't test the result since it is an uninitialized value
320 result = ctypes_func()
321
322 self.assertIsInstance(cm.unraisable.exc_value, TypeError)
323 self.assertEqual(cm.unraisable.err_msg,
324 "Exception ignored on converting result "
325 "of ctypes callback function")
326 self.assertIs(cm.unraisable.object, func)
327
328
329 if __name__ == '__main__':
330 unittest.main()