convert usage of fail* to assert*
[python.git] / Lib / ctypes / test / test_cast.py
blob906fffc90611cdd58a3fc1b25539e87ddbcdbda9
1 from ctypes import *
2 import unittest
3 import sys
5 class Test(unittest.TestCase):
7 def test_array2pointer(self):
8 array = (c_int * 3)(42, 17, 2)
10 # casting an array to a pointer works.
11 ptr = cast(array, POINTER(c_int))
12 self.assertEqual([ptr[i] for i in range(3)], [42, 17, 2])
14 if 2*sizeof(c_short) == sizeof(c_int):
15 ptr = cast(array, POINTER(c_short))
16 if sys.byteorder == "little":
17 self.assertEqual([ptr[i] for i in range(6)],
18 [42, 0, 17, 0, 2, 0])
19 else:
20 self.assertEqual([ptr[i] for i in range(6)],
21 [0, 42, 0, 17, 0, 2])
23 def test_address2pointer(self):
24 array = (c_int * 3)(42, 17, 2)
26 address = addressof(array)
27 ptr = cast(c_void_p(address), POINTER(c_int))
28 self.assertEqual([ptr[i] for i in range(3)], [42, 17, 2])
30 ptr = cast(address, POINTER(c_int))
31 self.assertEqual([ptr[i] for i in range(3)], [42, 17, 2])
33 def test_p2a_objects(self):
34 array = (c_char_p * 5)()
35 self.assertEqual(array._objects, None)
36 array[0] = "foo bar"
37 self.assertEqual(array._objects, {'0': "foo bar"})
39 p = cast(array, POINTER(c_char_p))
40 # array and p share a common _objects attribute
41 self.assertTrue(p._objects is array._objects)
42 self.assertEqual(array._objects, {'0': "foo bar", id(array): array})
43 p[0] = "spam spam"
44 self.assertEqual(p._objects, {'0': "spam spam", id(array): array})
45 self.assertTrue(array._objects is p._objects)
46 p[1] = "foo bar"
47 self.assertEqual(p._objects, {'1': 'foo bar', '0': "spam spam", id(array): array})
48 self.assertTrue(array._objects is p._objects)
50 def test_other(self):
51 p = cast((c_int * 4)(1, 2, 3, 4), POINTER(c_int))
52 self.assertEqual(p[:4], [1,2, 3, 4])
53 self.assertEqual(p[:4:], [1, 2, 3, 4])
54 self.assertEqual(p[3:-1:-1], [4, 3, 2, 1])
55 self.assertEqual(p[:4:3], [1, 4])
56 c_int()
57 self.assertEqual(p[:4], [1, 2, 3, 4])
58 self.assertEqual(p[:4:], [1, 2, 3, 4])
59 self.assertEqual(p[3:-1:-1], [4, 3, 2, 1])
60 self.assertEqual(p[:4:3], [1, 4])
61 p[2] = 96
62 self.assertEqual(p[:4], [1, 2, 96, 4])
63 self.assertEqual(p[:4:], [1, 2, 96, 4])
64 self.assertEqual(p[3:-1:-1], [4, 96, 2, 1])
65 self.assertEqual(p[:4:3], [1, 4])
66 c_int()
67 self.assertEqual(p[:4], [1, 2, 96, 4])
68 self.assertEqual(p[:4:], [1, 2, 96, 4])
69 self.assertEqual(p[3:-1:-1], [4, 96, 2, 1])
70 self.assertEqual(p[:4:3], [1, 4])
72 def test_char_p(self):
73 # This didn't work: bad argument to internal function
74 s = c_char_p("hiho")
75 self.assertEqual(cast(cast(s, c_void_p), c_char_p).value,
76 "hiho")
78 try:
79 c_wchar_p
80 except NameError:
81 pass
82 else:
83 def test_wchar_p(self):
84 s = c_wchar_p("hiho")
85 self.assertEqual(cast(cast(s, c_void_p), c_wchar_p).value,
86 "hiho")
88 if __name__ == "__main__":
89 unittest.main()