1 | n/a | from ctypes import * |
---|
2 | n/a | import unittest |
---|
3 | n/a | |
---|
4 | n/a | class VarSizeTest(unittest.TestCase): |
---|
5 | n/a | def test_resize(self): |
---|
6 | n/a | class X(Structure): |
---|
7 | n/a | _fields_ = [("item", c_int), |
---|
8 | n/a | ("array", c_int * 1)] |
---|
9 | n/a | |
---|
10 | n/a | self.assertEqual(sizeof(X), sizeof(c_int) * 2) |
---|
11 | n/a | x = X() |
---|
12 | n/a | x.item = 42 |
---|
13 | n/a | x.array[0] = 100 |
---|
14 | n/a | self.assertEqual(sizeof(x), sizeof(c_int) * 2) |
---|
15 | n/a | |
---|
16 | n/a | # make room for one additional item |
---|
17 | n/a | new_size = sizeof(X) + sizeof(c_int) * 1 |
---|
18 | n/a | resize(x, new_size) |
---|
19 | n/a | self.assertEqual(sizeof(x), new_size) |
---|
20 | n/a | self.assertEqual((x.item, x.array[0]), (42, 100)) |
---|
21 | n/a | |
---|
22 | n/a | # make room for 10 additional items |
---|
23 | n/a | new_size = sizeof(X) + sizeof(c_int) * 9 |
---|
24 | n/a | resize(x, new_size) |
---|
25 | n/a | self.assertEqual(sizeof(x), new_size) |
---|
26 | n/a | self.assertEqual((x.item, x.array[0]), (42, 100)) |
---|
27 | n/a | |
---|
28 | n/a | # make room for one additional item |
---|
29 | n/a | new_size = sizeof(X) + sizeof(c_int) * 1 |
---|
30 | n/a | resize(x, new_size) |
---|
31 | n/a | self.assertEqual(sizeof(x), new_size) |
---|
32 | n/a | self.assertEqual((x.item, x.array[0]), (42, 100)) |
---|
33 | n/a | |
---|
34 | n/a | def test_array_invalid_length(self): |
---|
35 | n/a | # cannot create arrays with non-positive size |
---|
36 | n/a | self.assertRaises(ValueError, lambda: c_int * -1) |
---|
37 | n/a | self.assertRaises(ValueError, lambda: c_int * -3) |
---|
38 | n/a | |
---|
39 | n/a | def test_zerosized_array(self): |
---|
40 | n/a | array = (c_int * 0)() |
---|
41 | n/a | # accessing elements of zero-sized arrays raise IndexError |
---|
42 | n/a | self.assertRaises(IndexError, array.__setitem__, 0, None) |
---|
43 | n/a | self.assertRaises(IndexError, array.__getitem__, 0) |
---|
44 | n/a | self.assertRaises(IndexError, array.__setitem__, 1, None) |
---|
45 | n/a | self.assertRaises(IndexError, array.__getitem__, 1) |
---|
46 | n/a | self.assertRaises(IndexError, array.__setitem__, -1, None) |
---|
47 | n/a | self.assertRaises(IndexError, array.__getitem__, -1) |
---|
48 | n/a | |
---|
49 | n/a | if __name__ == "__main__": |
---|
50 | n/a | unittest.main() |
---|