ยปCore Development>Code coverage>Lib/ctypes/test/test_structures.py

Python code coverage for Lib/ctypes/test/test_structures.py

#countcontent
1n/aimport unittest
2n/afrom ctypes import *
3n/afrom ctypes.test import need_symbol
4n/afrom struct import calcsize
5n/aimport _testcapi
6n/a
7n/aclass SubclassesTest(unittest.TestCase):
8n/a def test_subclass(self):
9n/a class X(Structure):
10n/a _fields_ = [("a", c_int)]
11n/a
12n/a class Y(X):
13n/a _fields_ = [("b", c_int)]
14n/a
15n/a class Z(X):
16n/a pass
17n/a
18n/a self.assertEqual(sizeof(X), sizeof(c_int))
19n/a self.assertEqual(sizeof(Y), sizeof(c_int)*2)
20n/a self.assertEqual(sizeof(Z), sizeof(c_int))
21n/a self.assertEqual(X._fields_, [("a", c_int)])
22n/a self.assertEqual(Y._fields_, [("b", c_int)])
23n/a self.assertEqual(Z._fields_, [("a", c_int)])
24n/a
25n/a def test_subclass_delayed(self):
26n/a class X(Structure):
27n/a pass
28n/a self.assertEqual(sizeof(X), 0)
29n/a X._fields_ = [("a", c_int)]
30n/a
31n/a class Y(X):
32n/a pass
33n/a self.assertEqual(sizeof(Y), sizeof(X))
34n/a Y._fields_ = [("b", c_int)]
35n/a
36n/a class Z(X):
37n/a pass
38n/a
39n/a self.assertEqual(sizeof(X), sizeof(c_int))
40n/a self.assertEqual(sizeof(Y), sizeof(c_int)*2)
41n/a self.assertEqual(sizeof(Z), sizeof(c_int))
42n/a self.assertEqual(X._fields_, [("a", c_int)])
43n/a self.assertEqual(Y._fields_, [("b", c_int)])
44n/a self.assertEqual(Z._fields_, [("a", c_int)])
45n/a
46n/aclass StructureTestCase(unittest.TestCase):
47n/a formats = {"c": c_char,
48n/a "b": c_byte,
49n/a "B": c_ubyte,
50n/a "h": c_short,
51n/a "H": c_ushort,
52n/a "i": c_int,
53n/a "I": c_uint,
54n/a "l": c_long,
55n/a "L": c_ulong,
56n/a "q": c_longlong,
57n/a "Q": c_ulonglong,
58n/a "f": c_float,
59n/a "d": c_double,
60n/a }
61n/a
62n/a def test_simple_structs(self):
63n/a for code, tp in self.formats.items():
64n/a class X(Structure):
65n/a _fields_ = [("x", c_char),
66n/a ("y", tp)]
67n/a self.assertEqual((sizeof(X), code),
68n/a (calcsize("c%c0%c" % (code, code)), code))
69n/a
70n/a def test_unions(self):
71n/a for code, tp in self.formats.items():
72n/a class X(Union):
73n/a _fields_ = [("x", c_char),
74n/a ("y", tp)]
75n/a self.assertEqual((sizeof(X), code),
76n/a (calcsize("%c" % (code)), code))
77n/a
78n/a def test_struct_alignment(self):
79n/a class X(Structure):
80n/a _fields_ = [("x", c_char * 3)]
81n/a self.assertEqual(alignment(X), calcsize("s"))
82n/a self.assertEqual(sizeof(X), calcsize("3s"))
83n/a
84n/a class Y(Structure):
85n/a _fields_ = [("x", c_char * 3),
86n/a ("y", c_int)]
87n/a self.assertEqual(alignment(Y), alignment(c_int))
88n/a self.assertEqual(sizeof(Y), calcsize("3si"))
89n/a
90n/a class SI(Structure):
91n/a _fields_ = [("a", X),
92n/a ("b", Y)]
93n/a self.assertEqual(alignment(SI), max(alignment(Y), alignment(X)))
94n/a self.assertEqual(sizeof(SI), calcsize("3s0i 3si 0i"))
95n/a
96n/a class IS(Structure):
97n/a _fields_ = [("b", Y),
98n/a ("a", X)]
99n/a
100n/a self.assertEqual(alignment(SI), max(alignment(X), alignment(Y)))
101n/a self.assertEqual(sizeof(IS), calcsize("3si 3s 0i"))
102n/a
103n/a class XX(Structure):
104n/a _fields_ = [("a", X),
105n/a ("b", X)]
106n/a self.assertEqual(alignment(XX), alignment(X))
107n/a self.assertEqual(sizeof(XX), calcsize("3s 3s 0s"))
108n/a
109n/a def test_empty(self):
110n/a # I had problems with these
111n/a #
112n/a # Although these are pathological cases: Empty Structures!
113n/a class X(Structure):
114n/a _fields_ = []
115n/a
116n/a class Y(Union):
117n/a _fields_ = []
118n/a
119n/a # Is this really the correct alignment, or should it be 0?
120n/a self.assertTrue(alignment(X) == alignment(Y) == 1)
121n/a self.assertTrue(sizeof(X) == sizeof(Y) == 0)
122n/a
123n/a class XX(Structure):
124n/a _fields_ = [("a", X),
125n/a ("b", X)]
126n/a
127n/a self.assertEqual(alignment(XX), 1)
128n/a self.assertEqual(sizeof(XX), 0)
129n/a
130n/a def test_fields(self):
131n/a # test the offset and size attributes of Structure/Unoin fields.
132n/a class X(Structure):
133n/a _fields_ = [("x", c_int),
134n/a ("y", c_char)]
135n/a
136n/a self.assertEqual(X.x.offset, 0)
137n/a self.assertEqual(X.x.size, sizeof(c_int))
138n/a
139n/a self.assertEqual(X.y.offset, sizeof(c_int))
140n/a self.assertEqual(X.y.size, sizeof(c_char))
141n/a
142n/a # readonly
143n/a self.assertRaises((TypeError, AttributeError), setattr, X.x, "offset", 92)
144n/a self.assertRaises((TypeError, AttributeError), setattr, X.x, "size", 92)
145n/a
146n/a class X(Union):
147n/a _fields_ = [("x", c_int),
148n/a ("y", c_char)]
149n/a
150n/a self.assertEqual(X.x.offset, 0)
151n/a self.assertEqual(X.x.size, sizeof(c_int))
152n/a
153n/a self.assertEqual(X.y.offset, 0)
154n/a self.assertEqual(X.y.size, sizeof(c_char))
155n/a
156n/a # readonly
157n/a self.assertRaises((TypeError, AttributeError), setattr, X.x, "offset", 92)
158n/a self.assertRaises((TypeError, AttributeError), setattr, X.x, "size", 92)
159n/a
160n/a # XXX Should we check nested data types also?
161n/a # offset is always relative to the class...
162n/a
163n/a def test_packed(self):
164n/a class X(Structure):
165n/a _fields_ = [("a", c_byte),
166n/a ("b", c_longlong)]
167n/a _pack_ = 1
168n/a
169n/a self.assertEqual(sizeof(X), 9)
170n/a self.assertEqual(X.b.offset, 1)
171n/a
172n/a class X(Structure):
173n/a _fields_ = [("a", c_byte),
174n/a ("b", c_longlong)]
175n/a _pack_ = 2
176n/a self.assertEqual(sizeof(X), 10)
177n/a self.assertEqual(X.b.offset, 2)
178n/a
179n/a import struct
180n/a longlong_size = struct.calcsize("q")
181n/a longlong_align = struct.calcsize("bq") - longlong_size
182n/a
183n/a class X(Structure):
184n/a _fields_ = [("a", c_byte),
185n/a ("b", c_longlong)]
186n/a _pack_ = 4
187n/a self.assertEqual(sizeof(X), min(4, longlong_align) + longlong_size)
188n/a self.assertEqual(X.b.offset, min(4, longlong_align))
189n/a
190n/a class X(Structure):
191n/a _fields_ = [("a", c_byte),
192n/a ("b", c_longlong)]
193n/a _pack_ = 8
194n/a
195n/a self.assertEqual(sizeof(X), min(8, longlong_align) + longlong_size)
196n/a self.assertEqual(X.b.offset, min(8, longlong_align))
197n/a
198n/a
199n/a d = {"_fields_": [("a", "b"),
200n/a ("b", "q")],
201n/a "_pack_": -1}
202n/a self.assertRaises(ValueError, type(Structure), "X", (Structure,), d)
203n/a
204n/a # Issue 15989
205n/a d = {"_fields_": [("a", c_byte)],
206n/a "_pack_": _testcapi.INT_MAX + 1}
207n/a self.assertRaises(ValueError, type(Structure), "X", (Structure,), d)
208n/a d = {"_fields_": [("a", c_byte)],
209n/a "_pack_": _testcapi.UINT_MAX + 2}
210n/a self.assertRaises(ValueError, type(Structure), "X", (Structure,), d)
211n/a
212n/a def test_initializers(self):
213n/a class Person(Structure):
214n/a _fields_ = [("name", c_char*6),
215n/a ("age", c_int)]
216n/a
217n/a self.assertRaises(TypeError, Person, 42)
218n/a self.assertRaises(ValueError, Person, b"asldkjaslkdjaslkdj")
219n/a self.assertRaises(TypeError, Person, "Name", "HI")
220n/a
221n/a # short enough
222n/a self.assertEqual(Person(b"12345", 5).name, b"12345")
223n/a # exact fit
224n/a self.assertEqual(Person(b"123456", 5).name, b"123456")
225n/a # too long
226n/a self.assertRaises(ValueError, Person, b"1234567", 5)
227n/a
228n/a def test_conflicting_initializers(self):
229n/a class POINT(Structure):
230n/a _fields_ = [("phi", c_float), ("rho", c_float)]
231n/a # conflicting positional and keyword args
232n/a self.assertRaisesRegex(TypeError, "phi", POINT, 2, 3, phi=4)
233n/a self.assertRaisesRegex(TypeError, "rho", POINT, 2, 3, rho=4)
234n/a
235n/a # too many initializers
236n/a self.assertRaises(TypeError, POINT, 2, 3, 4)
237n/a
238n/a def test_keyword_initializers(self):
239n/a class POINT(Structure):
240n/a _fields_ = [("x", c_int), ("y", c_int)]
241n/a pt = POINT(1, 2)
242n/a self.assertEqual((pt.x, pt.y), (1, 2))
243n/a
244n/a pt = POINT(y=2, x=1)
245n/a self.assertEqual((pt.x, pt.y), (1, 2))
246n/a
247n/a def test_invalid_field_types(self):
248n/a class POINT(Structure):
249n/a pass
250n/a self.assertRaises(TypeError, setattr, POINT, "_fields_", [("x", 1), ("y", 2)])
251n/a
252n/a def test_invalid_name(self):
253n/a # field name must be string
254n/a def declare_with_name(name):
255n/a class S(Structure):
256n/a _fields_ = [(name, c_int)]
257n/a
258n/a self.assertRaises(TypeError, declare_with_name, b"x")
259n/a
260n/a def test_intarray_fields(self):
261n/a class SomeInts(Structure):
262n/a _fields_ = [("a", c_int * 4)]
263n/a
264n/a # can use tuple to initialize array (but not list!)
265n/a self.assertEqual(SomeInts((1, 2)).a[:], [1, 2, 0, 0])
266n/a self.assertEqual(SomeInts((1, 2)).a[::], [1, 2, 0, 0])
267n/a self.assertEqual(SomeInts((1, 2)).a[::-1], [0, 0, 2, 1])
268n/a self.assertEqual(SomeInts((1, 2)).a[::2], [1, 0])
269n/a self.assertEqual(SomeInts((1, 2)).a[1:5:6], [2])
270n/a self.assertEqual(SomeInts((1, 2)).a[6:4:-1], [])
271n/a self.assertEqual(SomeInts((1, 2, 3, 4)).a[:], [1, 2, 3, 4])
272n/a self.assertEqual(SomeInts((1, 2, 3, 4)).a[::], [1, 2, 3, 4])
273n/a # too long
274n/a # XXX Should raise ValueError?, not RuntimeError
275n/a self.assertRaises(RuntimeError, SomeInts, (1, 2, 3, 4, 5))
276n/a
277n/a def test_nested_initializers(self):
278n/a # test initializing nested structures
279n/a class Phone(Structure):
280n/a _fields_ = [("areacode", c_char*6),
281n/a ("number", c_char*12)]
282n/a
283n/a class Person(Structure):
284n/a _fields_ = [("name", c_char * 12),
285n/a ("phone", Phone),
286n/a ("age", c_int)]
287n/a
288n/a p = Person(b"Someone", (b"1234", b"5678"), 5)
289n/a
290n/a self.assertEqual(p.name, b"Someone")
291n/a self.assertEqual(p.phone.areacode, b"1234")
292n/a self.assertEqual(p.phone.number, b"5678")
293n/a self.assertEqual(p.age, 5)
294n/a
295n/a @need_symbol('c_wchar')
296n/a def test_structures_with_wchar(self):
297n/a class PersonW(Structure):
298n/a _fields_ = [("name", c_wchar * 12),
299n/a ("age", c_int)]
300n/a
301n/a p = PersonW("Someone \xe9")
302n/a self.assertEqual(p.name, "Someone \xe9")
303n/a
304n/a self.assertEqual(PersonW("1234567890").name, "1234567890")
305n/a self.assertEqual(PersonW("12345678901").name, "12345678901")
306n/a # exact fit
307n/a self.assertEqual(PersonW("123456789012").name, "123456789012")
308n/a #too long
309n/a self.assertRaises(ValueError, PersonW, "1234567890123")
310n/a
311n/a def test_init_errors(self):
312n/a class Phone(Structure):
313n/a _fields_ = [("areacode", c_char*6),
314n/a ("number", c_char*12)]
315n/a
316n/a class Person(Structure):
317n/a _fields_ = [("name", c_char * 12),
318n/a ("phone", Phone),
319n/a ("age", c_int)]
320n/a
321n/a cls, msg = self.get_except(Person, b"Someone", (1, 2))
322n/a self.assertEqual(cls, RuntimeError)
323n/a self.assertEqual(msg,
324n/a "(Phone) <class 'TypeError'>: "
325n/a "expected bytes, int found")
326n/a
327n/a cls, msg = self.get_except(Person, b"Someone", (b"a", b"b", b"c"))
328n/a self.assertEqual(cls, RuntimeError)
329n/a self.assertEqual(msg,
330n/a "(Phone) <class 'TypeError'>: too many initializers")
331n/a
332n/a def test_huge_field_name(self):
333n/a # issue12881: segfault with large structure field names
334n/a def create_class(length):
335n/a class S(Structure):
336n/a _fields_ = [('x' * length, c_int)]
337n/a
338n/a for length in [10 ** i for i in range(0, 8)]:
339n/a try:
340n/a create_class(length)
341n/a except MemoryError:
342n/a # MemoryErrors are OK, we just don't want to segfault
343n/a pass
344n/a
345n/a def get_except(self, func, *args):
346n/a try:
347n/a func(*args)
348n/a except Exception as detail:
349n/a return detail.__class__, str(detail)
350n/a
351n/a @unittest.skip('test disabled')
352n/a def test_subclass_creation(self):
353n/a meta = type(Structure)
354n/a # same as 'class X(Structure): pass'
355n/a # fails, since we need either a _fields_ or a _abstract_ attribute
356n/a cls, msg = self.get_except(meta, "X", (Structure,), {})
357n/a self.assertEqual((cls, msg),
358n/a (AttributeError, "class must define a '_fields_' attribute"))
359n/a
360n/a def test_abstract_class(self):
361n/a class X(Structure):
362n/a _abstract_ = "something"
363n/a # try 'X()'
364n/a cls, msg = self.get_except(eval, "X()", locals())
365n/a self.assertEqual((cls, msg), (TypeError, "abstract class"))
366n/a
367n/a def test_methods(self):
368n/a## class X(Structure):
369n/a## _fields_ = []
370n/a
371n/a self.assertIn("in_dll", dir(type(Structure)))
372n/a self.assertIn("from_address", dir(type(Structure)))
373n/a self.assertIn("in_dll", dir(type(Structure)))
374n/a
375n/a def test_positional_args(self):
376n/a # see also http://bugs.python.org/issue5042
377n/a class W(Structure):
378n/a _fields_ = [("a", c_int), ("b", c_int)]
379n/a class X(W):
380n/a _fields_ = [("c", c_int)]
381n/a class Y(X):
382n/a pass
383n/a class Z(Y):
384n/a _fields_ = [("d", c_int), ("e", c_int), ("f", c_int)]
385n/a
386n/a z = Z(1, 2, 3, 4, 5, 6)
387n/a self.assertEqual((z.a, z.b, z.c, z.d, z.e, z.f),
388n/a (1, 2, 3, 4, 5, 6))
389n/a z = Z(1)
390n/a self.assertEqual((z.a, z.b, z.c, z.d, z.e, z.f),
391n/a (1, 0, 0, 0, 0, 0))
392n/a self.assertRaises(TypeError, lambda: Z(1, 2, 3, 4, 5, 6, 7))
393n/a
394n/aclass PointerMemberTestCase(unittest.TestCase):
395n/a
396n/a def test(self):
397n/a # a Structure with a POINTER field
398n/a class S(Structure):
399n/a _fields_ = [("array", POINTER(c_int))]
400n/a
401n/a s = S()
402n/a # We can assign arrays of the correct type
403n/a s.array = (c_int * 3)(1, 2, 3)
404n/a items = [s.array[i] for i in range(3)]
405n/a self.assertEqual(items, [1, 2, 3])
406n/a
407n/a # The following are bugs, but are included here because the unittests
408n/a # also describe the current behaviour.
409n/a #
410n/a # This fails with SystemError: bad arg to internal function
411n/a # or with IndexError (with a patch I have)
412n/a
413n/a s.array[0] = 42
414n/a
415n/a items = [s.array[i] for i in range(3)]
416n/a self.assertEqual(items, [42, 2, 3])
417n/a
418n/a s.array[0] = 1
419n/a
420n/a## s.array[1] = 42
421n/a
422n/a items = [s.array[i] for i in range(3)]
423n/a self.assertEqual(items, [1, 2, 3])
424n/a
425n/a def test_none_to_pointer_fields(self):
426n/a class S(Structure):
427n/a _fields_ = [("x", c_int),
428n/a ("p", POINTER(c_int))]
429n/a
430n/a s = S()
431n/a s.x = 12345678
432n/a s.p = None
433n/a self.assertEqual(s.x, 12345678)
434n/a
435n/aclass TestRecursiveStructure(unittest.TestCase):
436n/a def test_contains_itself(self):
437n/a class Recursive(Structure):
438n/a pass
439n/a
440n/a try:
441n/a Recursive._fields_ = [("next", Recursive)]
442n/a except AttributeError as details:
443n/a self.assertIn("Structure or union cannot contain itself",
444n/a str(details))
445n/a else:
446n/a self.fail("Structure or union cannot contain itself")
447n/a
448n/a
449n/a def test_vice_versa(self):
450n/a class First(Structure):
451n/a pass
452n/a class Second(Structure):
453n/a pass
454n/a
455n/a First._fields_ = [("second", Second)]
456n/a
457n/a try:
458n/a Second._fields_ = [("first", First)]
459n/a except AttributeError as details:
460n/a self.assertIn("_fields_ is final", str(details))
461n/a else:
462n/a self.fail("AttributeError not raised")
463n/a
464n/aif __name__ == '__main__':
465n/a unittest.main()