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,
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 integer expected")
92
93 def test_c_wchar(self):
94 with self.assertRaises(TypeError) as cm:
95 c_wchar.from_param("abc")
96 self.assertEqual(str(cm.exception),
97 "one character unicode string expected")
98
99
100 with self.assertRaises(TypeError) as cm:
101 c_wchar.from_param(123)
102 self.assertEqual(str(cm.exception),
103 "unicode string expected instead of int instance")
104
105 def test_int_pointers(self):
106 LPINT = POINTER(c_int)
107
108 x = LPINT.from_param(pointer(c_int(42)))
109 self.assertEqual(x.contents.value, 42)
110 self.assertEqual(LPINT(c_int(42)).contents.value, 42)
111
112 self.assertEqual(LPINT.from_param(None), None)
113
114 if c_int != c_long:
115 self.assertRaises(TypeError, LPINT.from_param, pointer(c_long(42)))
116 self.assertRaises(TypeError, LPINT.from_param, pointer(c_uint(42)))
117 self.assertRaises(TypeError, LPINT.from_param, pointer(c_short(42)))
118
119 def test_byref_pointer(self):
120 # The from_param class method of POINTER(typ) classes accepts what is
121 # returned by byref(obj), it type(obj) == typ
122 LPINT = POINTER(c_int)
123
124 LPINT.from_param(byref(c_int(42)))
125
126 self.assertRaises(TypeError, LPINT.from_param, byref(c_short(22)))
127 if c_int != c_long:
128 self.assertRaises(TypeError, LPINT.from_param, byref(c_long(22)))
129 self.assertRaises(TypeError, LPINT.from_param, byref(c_uint(22)))
130
131 def test_byref_pointerpointer(self):
132 # See above
133
134 LPLPINT = POINTER(POINTER(c_int))
135 LPLPINT.from_param(byref(pointer(c_int(42))))
136
137 self.assertRaises(TypeError, LPLPINT.from_param, byref(pointer(c_short(22))))
138 if c_int != c_long:
139 self.assertRaises(TypeError, LPLPINT.from_param, byref(pointer(c_long(22))))
140 self.assertRaises(TypeError, LPLPINT.from_param, byref(pointer(c_uint(22))))
141
142 def test_array_pointers(self):
143 INTARRAY = c_int * 3
144 ia = INTARRAY()
145 self.assertEqual(len(ia), 3)
146 self.assertEqual([ia[i] for i in range(3)], [0, 0, 0])
147
148 # Pointers are only compatible with arrays containing items of
149 # the same type!
150 LPINT = POINTER(c_int)
151 LPINT.from_param((c_int*3)())
152 self.assertRaises(TypeError, LPINT.from_param, c_short*3)
153 self.assertRaises(TypeError, LPINT.from_param, c_long*3)
154 self.assertRaises(TypeError, LPINT.from_param, c_uint*3)
155
156 def test_noctypes_argtype(self):
157 func = CDLL(_ctypes_test.__file__)._testfunc_p_p
158 func.restype = c_void_p
159 # TypeError: has no from_param method
160 self.assertRaises(TypeError, setattr, func, "argtypes", (object,))
161
162 class Adapter:
163 def from_param(cls, obj):
164 return None
165
166 func.argtypes = (Adapter(),)
167 self.assertEqual(func(None), None)
168 self.assertEqual(func(object()), None)
169
170 class Adapter:
171 def from_param(cls, obj):
172 return obj
173
174 func.argtypes = (Adapter(),)
175 # don't know how to convert parameter 1
176 self.assertRaises(ArgumentError, func, object())
177 self.assertEqual(func(c_void_p(42)), 42)
178
179 class Adapter:
180 def from_param(cls, obj):
181 raise ValueError(obj)
182
183 func.argtypes = (Adapter(),)
184 # ArgumentError: argument 1: ValueError: 99
185 self.assertRaises(ArgumentError, func, 99)
186
187 def test_abstract(self):
188 self.assertRaises(TypeError, Array.from_param, 42)
189 self.assertRaises(TypeError, Structure.from_param, 42)
190 self.assertRaises(TypeError, Union.from_param, 42)
191 self.assertRaises(TypeError, _CFuncPtr.from_param, 42)
192 self.assertRaises(TypeError, _Pointer.from_param, 42)
193 self.assertRaises(TypeError, _SimpleCData.from_param, 42)
194
195 @test.support.cpython_only
196 def test_issue31311(self):
197 # __setstate__ should neither raise a SystemError nor crash in case
198 # of a bad __dict__.
199
200 class BadStruct(Structure):
201 @property
202 def __dict__(self):
203 pass
204 with self.assertRaises(TypeError):
205 BadStruct().__setstate__({}, b'foo')
206
207 class WorseStruct(Structure):
208 @property
209 def __dict__(self):
210 1/0
211 with self.assertRaises(ZeroDivisionError):
212 WorseStruct().__setstate__({}, b'foo')
213
214 def test_parameter_repr(self):
215 self.assertRegex(repr(c_bool.from_param(True)), r"^<cparam '\?' at 0x[A-Fa-f0-9]+>$")
216 self.assertEqual(repr(c_char.from_param(97)), "<cparam 'c' ('a')>")
217 self.assertRegex(repr(c_wchar.from_param('a')), r"^<cparam 'u' at 0x[A-Fa-f0-9]+>$")
218 self.assertEqual(repr(c_byte.from_param(98)), "<cparam 'b' (98)>")
219 self.assertEqual(repr(c_ubyte.from_param(98)), "<cparam 'B' (98)>")
220 self.assertEqual(repr(c_short.from_param(511)), "<cparam 'h' (511)>")
221 self.assertEqual(repr(c_ushort.from_param(511)), "<cparam 'H' (511)>")
222 self.assertRegex(repr(c_int.from_param(20000)), r"^<cparam '[li]' \(20000\)>$")
223 self.assertRegex(repr(c_uint.from_param(20000)), r"^<cparam '[LI]' \(20000\)>$")
224 self.assertRegex(repr(c_long.from_param(20000)), r"^<cparam '[li]' \(20000\)>$")
225 self.assertRegex(repr(c_ulong.from_param(20000)), r"^<cparam '[LI]' \(20000\)>$")
226 self.assertRegex(repr(c_longlong.from_param(20000)), r"^<cparam '[liq]' \(20000\)>$")
227 self.assertRegex(repr(c_ulonglong.from_param(20000)), r"^<cparam '[LIQ]' \(20000\)>$")
228 self.assertEqual(repr(c_float.from_param(1.5)), "<cparam 'f' (1.5)>")
229 self.assertEqual(repr(c_double.from_param(1.5)), "<cparam 'd' (1.5)>")
230 if sys.float_repr_style == 'short':
231 self.assertEqual(repr(c_double.from_param(1e300)), "<cparam 'd' (1e+300)>")
232 self.assertRegex(repr(c_longdouble.from_param(1.5)), r"^<cparam ('d' \(1.5\)|'g' at 0x[A-Fa-f0-9]+)>$")
233 self.assertRegex(repr(c_char_p.from_param(b'hihi')), r"^<cparam 'z' \(0x[A-Fa-f0-9]+\)>$")
234 self.assertRegex(repr(c_wchar_p.from_param('hihi')), r"^<cparam 'Z' \(0x[A-Fa-f0-9]+\)>$")
235 self.assertRegex(repr(c_void_p.from_param(0x12)), r"^<cparam 'P' \(0x0*12\)>$")
236
237 @test.support.cpython_only
238 def test_from_param_result_refcount(self):
239 # Issue #99952
240 class X(Structure):
241 """This struct size is <= sizeof(void*)."""
242 _fields_ = [("a", c_void_p)]
243
244 def __del__(self):
245 trace.append(4)
246
247 @classmethod
248 def from_param(cls, value):
249 trace.append(2)
250 return cls()
251
252 PyList_Append = PyDLL(_ctypes_test.__file__)._testfunc_pylist_append
253 PyList_Append.restype = c_int
254 PyList_Append.argtypes = [py_object, py_object, X]
255
256 trace = []
257 trace.append(1)
258 PyList_Append(trace, 3, "dummy")
259 trace.append(5)
260
261 self.assertEqual(trace, [1, 2, 3, 4, 5])
262
263 class Y(Structure):
264 """This struct size is > sizeof(void*)."""
265 _fields_ = [("a", c_void_p), ("b", c_void_p)]
266
267 def __del__(self):
268 trace.append(4)
269
270 @classmethod
271 def from_param(cls, value):
272 trace.append(2)
273 return cls()
274
275 PyList_Append = PyDLL(_ctypes_test.__file__)._testfunc_pylist_append
276 PyList_Append.restype = c_int
277 PyList_Append.argtypes = [py_object, py_object, Y]
278
279 trace = []
280 trace.append(1)
281 PyList_Append(trace, 3, "dummy")
282 trace.append(5)
283
284 self.assertEqual(trace, [1, 2, 3, 4, 5])
285
286
287 if __name__ == '__main__':
288 unittest.main()