Debian Codegraph @

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

raw symbols SCIP
1 import sys
2 from ctypes import *
3 from ctypes.test import xfail
4 import unittest
5 import struct
6
7 def valid_ranges(*types):
8 # given a sequence of numeric types, collect their _type_
9 # attribute, which is a single format character compatible with
10 # the struct module, use the struct module to calculate the
11 # minimum and maximum value allowed for this format.
12 # Returns a list of (min, max) values.
13 result = []
14 for t in types:
15 fmt = t._type_
16 size = struct.calcsize(fmt)
17 a = struct.unpack(fmt, (b"\x00"*32)[:size])[0]
18 b = struct.unpack(fmt, (b"\xFF"*32)[:size])[0]
19 c = struct.unpack(fmt, (b"\x7F"+b"\x00"*32)[:size])[0]
20 d = struct.unpack(fmt, (b"\x80"+b"\xFF"*32)[:size])[0]
21 result.append((min(a, b, c, d), max(a, b, c, d)))
22 return result
23
24 ArgType = type(byref(c_int(0)))
25
26 unsigned_types = [c_ubyte, c_ushort, c_uint, c_ulong]
27 signed_types = [c_byte, c_short, c_int, c_long, c_longlong]
28
29 bool_types = []
30
31 float_types = [c_double, c_float]
32
33 try:
34 c_ulonglong
35 c_longlong
36 except NameError:
37 pass
38 else:
39 unsigned_types.append(c_ulonglong)
40 signed_types.append(c_longlong)
41
42 try:
43 c_bool
44 except NameError:
45 pass
46 else:
47 bool_types.append(c_bool)
48
49 unsigned_ranges = valid_ranges(*unsigned_types)
50 signed_ranges = valid_ranges(*signed_types)
51 bool_values = [True, False, 0, 1, -1, 5000, 'test', [], [1]]
52
53 ################################################################
54
55 class NumberTestCase(unittest.TestCase):
56
57 def test_default_init(self):
58 # default values are set to zero
59 for t in signed_types + unsigned_types + float_types:
60 self.assertEqual(t().value, 0)
61
62 def test_unsigned_values(self):
63 # the value given to the constructor is available
64 # as the 'value' attribute
65 for t, (l, h) in zip(unsigned_types, unsigned_ranges):
66 self.assertEqual(t(l).value, l)
67 self.assertEqual(t(h).value, h)
68
69 def test_signed_values(self):
70 # see above
71 for t, (l, h) in zip(signed_types, signed_ranges):
72 self.assertEqual(t(l).value, l)
73 self.assertEqual(t(h).value, h)
74
75 def test_bool_values(self):
76 from operator import truth
77 for t, v in zip(bool_types, bool_values):
78 self.assertEqual(t(v).value, truth(v))
79
80 def test_typeerror(self):
81 # Only numbers are allowed in the constructor,
82 # otherwise TypeError is raised
83 for t in signed_types + unsigned_types + float_types:
84 self.assertRaises(TypeError, t, "")
85 self.assertRaises(TypeError, t, None)
86
87 @xfail
88 def test_from_param(self):
89 # the from_param class method attribute always
90 # returns PyCArgObject instances
91 for t in signed_types + unsigned_types + float_types:
92 self.assertEqual(ArgType, type(t.from_param(0)))
93
94 @xfail
95 def test_byref(self):
96 # calling byref returns also a PyCArgObject instance
97 for t in signed_types + unsigned_types + float_types + bool_types:
98 parm = byref(t())
99 self.assertEqual(ArgType, type(parm))
100
101
102 def test_floats(self):
103 # c_float and c_double can be created from
104 # Python int and float
105 class FloatLike:
106 def __float__(self):
107 return 2.0
108 f = FloatLike()
109 for t in float_types:
110 self.assertEqual(t(2.0).value, 2.0)
111 self.assertEqual(t(2).value, 2.0)
112 self.assertEqual(t(2).value, 2.0)
113 self.assertEqual(t(f).value, 2.0)
114
115 def test_integers(self):
116 class FloatLike:
117 def __float__(self):
118 return 2.0
119 f = FloatLike()
120 class IntLike:
121 def __int__(self):
122 return 2
123 d = IntLike()
124 class IndexLike:
125 def __index__(self):
126 return 2
127 i = IndexLike()
128 # integers cannot be constructed from floats,
129 # but from integer-like objects
130 for t in signed_types + unsigned_types:
131 self.assertRaises(TypeError, t, 3.14)
132 self.assertRaises(TypeError, t, f)
133 if sys.implementation.name != 'pypy':
134 # IntLike should not be assigned to int since it is missing __index__
135 self.assertRaises(TypeError, t, d)
136 self.assertEqual(t(i).value, 2)
137
138 def test_sizes(self):
139 for t in signed_types + unsigned_types + float_types + bool_types:
140 try:
141 size = struct.calcsize(t._type_)
142 except struct.error:
143 continue
144 # sizeof of the type...
145 self.assertEqual(sizeof(t), size)
146 # and sizeof of an instance
147 self.assertEqual(sizeof(t()), size)
148
149 def test_alignments(self):
150 for t in signed_types + unsigned_types + float_types:
151 code = t._type_ # the typecode
152 align = struct.calcsize("c%c" % code) - struct.calcsize(code)
153
154 # alignment of the type...
155 self.assertEqual((code, alignment(t)),
156 (code, align))
157 # and alignment of an instance
158 self.assertEqual((code, alignment(t())),
159 (code, align))
160
161 def test_int_from_address(self):
162 from array import array
163 for t in signed_types + unsigned_types:
164 # the array module doesn't support all format codes
165 # (no 'q' or 'Q')
166 try:
167 array(t._type_)
168 except ValueError:
169 continue
170 a = array(t._type_, [100])
171
172 # v now is an integer at an 'external' memory location
173 v = t.from_address(a.buffer_info()[0])
174 self.assertEqual(v.value, a[0])
175 self.assertEqual(type(v), t)
176
177 # changing the value at the memory location changes v's value also
178 a[0] = 42
179 self.assertEqual(v.value, a[0])
180
181
182 def test_float_from_address(self):
183 from array import array
184 for t in float_types:
185 a = array(t._type_, [3.14])
186 v = t.from_address(a.buffer_info()[0])
187 self.assertEqual(v.value, a[0])
188 self.assertIs(type(v), t)
189 a[0] = 2.3456e17
190 self.assertEqual(v.value, a[0])
191 self.assertIs(type(v), t)
192
193 def test_char_from_address(self):
194 from ctypes import c_char
195 from array import array
196
197 a = array('b', [0])
198 a[0] = ord('x')
199 v = c_char.from_address(a.buffer_info()[0])
200 self.assertEqual(v.value, b'x')
201 self.assertIs(type(v), c_char)
202
203 a[0] = ord('?')
204 self.assertEqual(v.value, b'?')
205
206 def test_init(self):
207 # c_int() can be initialized from Python's int, and c_int.
208 # Not from c_long or so, which seems strange, abc should
209 # probably be changed:
210 self.assertRaises(TypeError, c_int, c_long(42))
211
212 def test_float_overflow(self):
213 import sys
214 big_int = int(sys.float_info.max) * 2
215 for t in float_types + [c_longdouble]:
216 self.assertRaises(OverflowError, t, big_int)
217 if (hasattr(t, "__ctype_be__")):
218 self.assertRaises(OverflowError, t.__ctype_be__, big_int)
219 if (hasattr(t, "__ctype_le__")):
220 self.assertRaises(OverflowError, t.__ctype_le__, big_int)
221
222
223 if __name__ == '__main__':
224 unittest.main()