Debian Codegraph @

Lib/test/test_ctypes/test_parameters.py

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