Debian Codegraph @

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

raw symbols SCIP
1 import unittest
2 from ctypes.test import need_symbol, xfail
3 import test.support
4
5 class SimpleTypesTestCase(unittest.TestCase):
6
7 def setUp(self):
8 import ctypes
9 try:
10 from _ctypes import set_conversion_mode
11 except ImportError:
12 pass
13 else:
14 self.prev_conv_mode = set_conversion_mode("ascii", "strict")
15
16 def tearDown(self):
17 try:
18 from _ctypes import set_conversion_mode
19 except ImportError:
20 pass
21 else:
22 set_conversion_mode(*self.prev_conv_mode)
23
24 def test_subclasses(self):
25 from ctypes import c_void_p, c_char_p
26 # ctypes 0.9.5 and before did overwrite from_param in SimpleType_new
27 class CVOIDP(c_void_p):
28 def from_param(cls, value):
29 return value * 2
30 from_param = classmethod(from_param)
31
32 class CCHARP(c_char_p):
33 def from_param(cls, value):
34 return value * 4
35 from_param = classmethod(from_param)
36
37 self.assertEqual(CVOIDP.from_param("abc"), "abcabc")
38 self.assertEqual(CCHARP.from_param("abc"), "abcabcabcabc")
39
40 @need_symbol('c_wchar_p')
41 def test_subclasses_c_wchar_p(self):
42 from ctypes import c_wchar_p
43
44 class CWCHARP(c_wchar_p):
45 def from_param(cls, value):
46 return value * 3
47 from_param = classmethod(from_param)
48
49 self.assertEqual(CWCHARP.from_param("abc"), "abcabcabc")
50
51 # XXX Replace by c_char_p tests
52 @xfail
53 def test_cstrings(self):
54 from ctypes import c_char_p
55
56 # c_char_p.from_param on a Python String packs the string
57 # into a cparam object
58 s = b"123"
59 self.assertIs(c_char_p.from_param(s)._obj, s)
60
61 # new in 0.9.1: convert (encode) unicode to ascii
62 self.assertEqual(c_char_p.from_param(b"123")._obj, b"123")
63 self.assertRaises(TypeError, c_char_p.from_param, "123\377")
64 self.assertRaises(TypeError, c_char_p.from_param, 42)
65
66 # calling c_char_p.from_param with a c_char_p instance
67 # returns the argument itself:
68 a = c_char_p(b"123")
69 self.assertIs(c_char_p.from_param(a), a)
70
71 @need_symbol('c_wchar_p')
72 def test_cw_strings(self):
73 from ctypes import c_wchar_p
74
75 c_wchar_p.from_param("123")
76
77 self.assertRaises(TypeError, c_wchar_p.from_param, 42)
78 self.assertRaises(TypeError, c_wchar_p.from_param, b"123\377")
79
80 pa = c_wchar_p.from_param(c_wchar_p("123"))
81 self.assertEqual(type(pa), c_wchar_p)
82
83 @xfail
84 def test_int_pointers(self):
85 from ctypes import c_short, c_uint, c_int, c_long, POINTER, pointer
86 LPINT = POINTER(c_int)
87
88 ## p = pointer(c_int(42))
89 ## x = LPINT.from_param(p)
90 x = LPINT.from_param(pointer(c_int(42)))
91 self.assertEqual(x.contents.value, 42)
92 self.assertEqual(LPINT(c_int(42)).contents.value, 42)
93
94 self.assertEqual(LPINT.from_param(None), None)
95
96 if c_int != c_long:
97 self.assertRaises(TypeError, LPINT.from_param, pointer(c_long(42)))
98 self.assertRaises(TypeError, LPINT.from_param, pointer(c_uint(42)))
99 self.assertRaises(TypeError, LPINT.from_param, pointer(c_short(42)))
100
101 def test_byref_pointer(self):
102 # The from_param class method of POINTER(typ) classes accepts what is
103 # returned by byref(obj), it type(obj) == typ
104 from ctypes import c_short, c_uint, c_int, c_long, POINTER, byref
105 LPINT = POINTER(c_int)
106
107 LPINT.from_param(byref(c_int(42)))
108
109 self.assertRaises(TypeError, LPINT.from_param, byref(c_short(22)))
110 if c_int != c_long:
111 self.assertRaises(TypeError, LPINT.from_param, byref(c_long(22)))
112 self.assertRaises(TypeError, LPINT.from_param, byref(c_uint(22)))
113
114 def test_byref_pointerpointer(self):
115 # See above
116 from ctypes import c_short, c_uint, c_int, c_long, pointer, POINTER, byref
117
118 LPLPINT = POINTER(POINTER(c_int))
119 LPLPINT.from_param(byref(pointer(c_int(42))))
120
121 self.assertRaises(TypeError, LPLPINT.from_param, byref(pointer(c_short(22))))
122 if c_int != c_long:
123 self.assertRaises(TypeError, LPLPINT.from_param, byref(pointer(c_long(22))))
124 self.assertRaises(TypeError, LPLPINT.from_param, byref(pointer(c_uint(22))))
125
126 def test_array_pointers(self):
127 from ctypes import c_short, c_uint, c_int, c_long, POINTER
128 INTARRAY = c_int * 3
129 ia = INTARRAY()
130 self.assertEqual(len(ia), 3)
131 self.assertEqual([ia[i] for i in range(3)], [0, 0, 0])
132
133 # Pointers are only compatible with arrays containing items of
134 # the same type!
135 LPINT = POINTER(c_int)
136 LPINT.from_param((c_int*3)())
137 self.assertRaises(TypeError, LPINT.from_param, c_short*3)
138 self.assertRaises(TypeError, LPINT.from_param, c_long*3)
139 self.assertRaises(TypeError, LPINT.from_param, c_uint*3)
140
141 def test_noctypes_argtype(self):
142 import _ctypes_test
143 from ctypes import CDLL, c_void_p, ArgumentError
144
145 func = CDLL(_ctypes_test.__file__)._testfunc_p_p
146 func.restype = c_void_p
147 # TypeError: has no from_param method
148 self.assertRaises(TypeError, setattr, func, "argtypes", (object,))
149
150 class Adapter:
151 def from_param(cls, obj):
152 return None
153
154 func.argtypes = (Adapter(),)
155 self.assertEqual(func(None), None)
156 self.assertEqual(func(object()), None)
157
158 class Adapter:
159 def from_param(cls, obj):
160 return obj
161
162 func.argtypes = (Adapter(),)
163 # don't know how to convert parameter 1
164 self.assertRaises(ArgumentError, func, object())
165 self.assertEqual(func(c_void_p(42)), 42)
166
167 class Adapter:
168 def from_param(cls, obj):
169 raise ValueError(obj)
170
171 func.argtypes = (Adapter(),)
172 # ArgumentError: argument 1: ValueError: 99
173 self.assertRaises(ArgumentError, func, 99)
174
175 def test_abstract(self):
176 from ctypes import (Array, Structure, Union, _Pointer,
177 _SimpleCData, _CFuncPtr)
178
179 self.assertRaises(TypeError, Array.from_param, 42)
180 self.assertRaises(TypeError, Structure.from_param, 42)
181 self.assertRaises(TypeError, Union.from_param, 42)
182 self.assertRaises(TypeError, _CFuncPtr.from_param, 42)
183 self.assertRaises(TypeError, _Pointer.from_param, 42)
184 self.assertRaises(TypeError, _SimpleCData.from_param, 42)
185
186 @test.support.cpython_only
187 def test_issue31311(self):
188 # __setstate__ should neither raise a SystemError nor crash in case
189 # of a bad __dict__.
190 from ctypes import Structure
191
192 class BadStruct(Structure):
193 @property
194 def __dict__(self):
195 pass
196 with self.assertRaises(TypeError):
197 BadStruct().__setstate__({}, b'foo')
198
199 class WorseStruct(Structure):
200 @property
201 def __dict__(self):
202 1/0
203 with self.assertRaises(ZeroDivisionError):
204 WorseStruct().__setstate__({}, b'foo')
205
206 @test.support.cpython_only
207 def test_parameter_repr(self):
208 from ctypes import (
209 c_bool,
210 c_char,
211 c_wchar,
212 c_byte,
213 c_ubyte,
214 c_short,
215 c_ushort,
216 c_int,
217 c_uint,
218 c_long,
219 c_ulong,
220 c_longlong,
221 c_ulonglong,
222 c_float,
223 c_double,
224 c_longdouble,
225 c_char_p,
226 c_wchar_p,
227 c_void_p,
228 )
229 self.assertRegex(repr(c_bool.from_param(True)), r"^<cparam '\?' at 0x[A-Fa-f0-9]+>$")
230 self.assertEqual(repr(c_char.from_param(97)), "<cparam 'c' ('a')>")
231 self.assertRegex(repr(c_wchar.from_param('a')), r"^<cparam 'u' at 0x[A-Fa-f0-9]+>$")
232 self.assertEqual(repr(c_byte.from_param(98)), "<cparam 'b' (98)>")
233 self.assertEqual(repr(c_ubyte.from_param(98)), "<cparam 'B' (98)>")
234 self.assertEqual(repr(c_short.from_param(511)), "<cparam 'h' (511)>")
235 self.assertEqual(repr(c_ushort.from_param(511)), "<cparam 'H' (511)>")
236 self.assertRegex(repr(c_int.from_param(20000)), r"^<cparam '[li]' \(20000\)>$")
237 self.assertRegex(repr(c_uint.from_param(20000)), r"^<cparam '[LI]' \(20000\)>$")
238 self.assertRegex(repr(c_long.from_param(20000)), r"^<cparam '[li]' \(20000\)>$")
239 self.assertRegex(repr(c_ulong.from_param(20000)), r"^<cparam '[LI]' \(20000\)>$")
240 self.assertRegex(repr(c_longlong.from_param(20000)), r"^<cparam '[liq]' \(20000\)>$")
241 self.assertRegex(repr(c_ulonglong.from_param(20000)), r"^<cparam '[LIQ]' \(20000\)>$")
242 self.assertEqual(repr(c_float.from_param(1.5)), "<cparam 'f' (1.5)>")
243 self.assertEqual(repr(c_double.from_param(1.5)), "<cparam 'd' (1.5)>")
244 self.assertEqual(repr(c_double.from_param(1e300)), "<cparam 'd' (1e+300)>")
245 self.assertRegex(repr(c_longdouble.from_param(1.5)), r"^<cparam ('d' \(1.5\)|'g' at 0x[A-Fa-f0-9]+)>$")
246 self.assertRegex(repr(c_char_p.from_param(b'hihi')), r"^<cparam 'z' \(0x[A-Fa-f0-9]+\)>$")
247 self.assertRegex(repr(c_wchar_p.from_param('hihi')), r"^<cparam 'Z' \(0x[A-Fa-f0-9]+\)>$")
248 self.assertRegex(repr(c_void_p.from_param(0x12)), r"^<cparam 'P' \(0x0*12\)>$")
249
250 @test.support.cpython_only
251 def test_from_param_result_refcount(self):
252 # Issue #99952
253 import _ctypes_test
254 from ctypes import PyDLL, c_int, c_void_p, py_object, Structure
255
256 class X(Structure):
257 """This struct size is <= sizeof(void*)."""
258 _fields_ = [("a", c_void_p)]
259
260 def __del__(self):
261 trace.append(4)
262
263 @classmethod
264 def from_param(cls, value):
265 trace.append(2)
266 return cls()
267
268 PyList_Append = PyDLL(_ctypes_test.__file__)._testfunc_pylist_append
269 PyList_Append.restype = c_int
270 PyList_Append.argtypes = [py_object, py_object, X]
271
272 trace = []
273 trace.append(1)
274 PyList_Append(trace, 3, "dummy")
275 trace.append(5)
276
277 self.assertEqual(trace, [1, 2, 3, 4, 5])
278
279 class Y(Structure):
280 """This struct size is > sizeof(void*)."""
281 _fields_ = [("a", c_void_p), ("b", c_void_p)]
282
283 def __del__(self):
284 trace.append(4)
285
286 @classmethod
287 def from_param(cls, value):
288 trace.append(2)
289 return cls()
290
291 PyList_Append = PyDLL(_ctypes_test.__file__)._testfunc_pylist_append
292 PyList_Append.restype = c_int
293 PyList_Append.argtypes = [py_object, py_object, Y]
294
295 trace = []
296 trace.append(1)
297 PyList_Append(trace, 3, "dummy")
298 trace.append(5)
299
300 self.assertEqual(trace, [1, 2, 3, 4, 5])
301
302 ################################################################
303
304 if __name__ == '__main__':
305 unittest.main()