import unittest from ctypes import * import re, sys if sys.byteorder == "little": THIS_ENDIAN = "<" OTHER_ENDIAN = ">" else: THIS_ENDIAN = ">" OTHER_ENDIAN = "<" def normalize(format): # Remove current endian specifier and white space from a format # string if format is None: return "" format = format.replace(OTHER_ENDIAN, THIS_ENDIAN) return re.sub(r"\s", "", format) class Test(unittest.TestCase): def test_native_types(self): for tp, fmt, shape, itemtp in native_types: ob = tp() v = memoryview(ob) try: self.assertEqual(normalize(v.format), normalize(fmt)) if shape is not None: self.assertEqual(len(v), shape[0]) else: self.assertEqual(len(v) * sizeof(itemtp), sizeof(ob)) self.assertEqual(v.itemsize, sizeof(itemtp)) self.assertEqual(v.shape, shape) # ctypes object always have a non-strided memory block self.assertEqual(v.strides, None) # they are always read/write self.assertFalse(v.readonly) if v.shape: n = 1 for dim in v.shape: n = n * dim self.assertEqual(n * v.itemsize, len(v.tobytes())) except: # so that we can see the failing type print(tp) raise def test_endian_types(self): for tp, fmt, shape, itemtp in endian_types: ob = tp() v = memoryview(ob) try: self.assertEqual(v.format, fmt) if shape is not None: self.assertEqual(len(v), shape[0]) else: self.assertEqual(len(v) * sizeof(itemtp), sizeof(ob)) self.assertEqual(v.itemsize, sizeof(itemtp)) self.assertEqual(v.shape, shape) # ctypes object always have a non-strided memory block self.assertEqual(v.strides, None) # they are always read/write self.assertFalse(v.readonly) if v.shape: n = 1 for dim in v.shape: n = n * dim self.assertEqual(n, len(v)) except: # so that we can see the failing type print(tp) raise # define some structure classes class Point(Structure): _fields_ = [("x", c_long), ("y", c_long)] class PackedPoint(Structure): _pack_ = 2 _fields_ = [("x", c_long), ("y", c_long)] class Point2(Structure): pass Point2._fields_ = [("x", c_long), ("y", c_long)] class EmptyStruct(Structure): _fields_ = [] class aUnion(Union): _fields_ = [("a", c_int)] class Incomplete(Structure): pass class Complete(Structure): pass PComplete = POINTER(Complete) Complete._fields_ = [("a", c_long)] ################################################################ # # This table contains format strings as they look on little endian # machines. The test replaces '<' with '>' on big endian machines. # native_types = [ # type format shape calc itemsize ## simple types (c_char, "l:x:>l:y:}", None, BEPoint), (LEPoint, "T{l:x:>l:y:}", None, POINTER(BEPoint)), (POINTER(LEPoint), "&T{