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