Пример #1
0
 def test_attribute(self):
     v = BufferProxy(self.view_keywords)
     self.assertRaises(AttributeError, getattr, v, 'undefined')
     v.undefined = 12
     self.assertEqual(v.undefined, 12)
     del v.undefined
     self.assertRaises(AttributeError, getattr, v, 'undefined')
Пример #2
0
    def test_raw(self):

        # __doc__ (as of 2008-08-02) for pygame.bufferproxy.BufferProxy.raw:

        # The raw buffer data as string. The string may contain NUL bytes.

        bf = BufferProxy({
            'shape': (len(self.content), ),
            'typestr': '|u1',
            'data': self.data
        })
        self.assertEqual(bf.raw, self.content)
        bf = BufferProxy({
            'shape': (3, 4),
            'typestr': '|u4',
            'data': self.data,
            'strides': (4, 12)
        })
        self.assertEqual(bf.raw, self.content)
        bf = BufferProxy({
            'shape': (3, 4),
            'typestr': '|u1',
            'data': self.data,
            'strides': (16, 4)
        })
        self.assertRaises(ValueError, getattr, bf, 'raw')
Пример #3
0
    def test_raw(self):

        # __doc__ (as of 2008-08-02) for pygame.bufferproxy.BufferProxy.raw:

        # The raw buffer data as string. The string may contain NUL bytes.

        bf = BufferProxy({
            "shape": (len(self.content), ),
            "typestr": "|u1",
            "data": self.data
        })
        self.assertEqual(bf.raw, self.content)
        bf = BufferProxy({
            "shape": (3, 4),
            "typestr": "|u4",
            "data": self.data,
            "strides": (4, 12)
        })
        self.assertEqual(bf.raw, self.content)
        bf = BufferProxy({
            "shape": (3, 4),
            "typestr": "|u1",
            "data": self.data,
            "strides": (16, 4)
        })
        self.assertRaises(ValueError, getattr, bf, "raw")
Пример #4
0
    def test_after(self):
        def callback(parent):
            success.append(parent is p)

        kwds = dict(self.view_keywords)
        p = []
        kwds['parent'] = p

        # For array interface
        success = []
        kwds['after'] = callback
        v = BufferProxy(kwds)
        self.assertEqual(len(success), 0)
        d = v.__array_interface__
        self.assertEqual(len(success), 0)
        d = v.__array_interface__
        self.assertEqual(len(success), 0)
        d = v = None
        gc.collect()
        self.assertEqual(len(success), 1)
        self.assertTrue(success[0])

        # For array struct
        success = []
        kwds['after'] = callback
        v = BufferProxy(kwds)
        self.assertEqual(len(success), 0)
        c = v.__array_struct__
        self.assertEqual(len(success), 0)
        c = v.__array_struct__
        self.assertEqual(len(success), 0)
        c = v = None
        gc.collect()
        self.assertEqual(len(success), 1)
        self.assertTrue(success[0])
Пример #5
0
 def test_attribute(self):
     v = BufferProxy(self.view_keywords)
     self.assertRaises(AttributeError, getattr, v, 'undefined')
     v.undefined = 12;
     self.assertEqual(v.undefined, 12)
     del v.undefined
     self.assertRaises(AttributeError, getattr, v, 'undefined')
Пример #6
0
    def test_write(self):

        # __doc__ (as of 2008-08-02) for pygame.bufferproxy.BufferProxy.write:

        # B.write (bufferproxy, buffer, offset) -> None
        #
        # Writes raw data to the bufferproxy.
        #
        # Writes the raw data from buffer to the BufferProxy object, starting
        # at the specified offset within the BufferProxy.
        # If the length of the passed buffer exceeds the length of the
        # BufferProxy (reduced by the offset), an IndexError will be raised.
        from ctypes import c_byte, sizeof, addressof, string_at, memset

        nullbyte = '\x00'.encode('latin_1')
        Buf = c_byte * 10
        data_buf = Buf(*range(1, 3 * sizeof(Buf) + 1, 3))
        data = string_at(data_buf, sizeof(data_buf))
        buf = Buf()
        bp = BufferProxy({
            'typestr': '|u1',
            'shape': (sizeof(buf), ),
            'data': (addressof(buf), False)
        })
        try:
            self.assertEqual(bp.raw, nullbyte * sizeof(Buf))
            bp.write(data)
            self.assertEqual(bp.raw, data)
            memset(buf, 0, sizeof(buf))
            bp.write(data[:3], 2)
            raw = bp.raw
            self.assertEqual(raw[:2], nullbyte * 2)
            self.assertEqual(raw[2:5], data[:3])
            self.assertEqual(raw[5:], nullbyte * (sizeof(Buf) - 5))
            bp.write(data[:3], bp.length - 3)
            raw = bp.raw
            self.assertEqual(raw[-3:], data[:3])
            self.assertRaises(IndexError, bp.write, data, 1)
            self.assertRaises(IndexError, bp.write, data[:5], -1)
            self.assertRaises(IndexError, bp.write, data[:5], bp.length)
            self.assertRaises(TypeError, bp.write, 12)
            bp = BufferProxy({
                'typestr': '|u1',
                'shape': (sizeof(buf), ),
                'data': (addressof(buf), True)
            })
            self.assertRaises(pygame.BufferError, bp.write,
                              '123'.encode('latin_1'))
        finally:
            # Make sure bp is garbage collected before buf
            bp = None
            gc.collect()
Пример #7
0
    def test_length(self):

        # __doc__ (as of 2008-08-02) for pygame.bufferproxy.BufferProxy.length:

        # The size of the buffer data in bytes.
        bf = BufferProxy(
            {"shape": (3, 4), "typestr": "|u4", "data": self.data, "strides": (12, 4)}
        )
        self.assertEqual(bf.length, len(self.content))
        bf = BufferProxy(
            {"shape": (3, 3), "typestr": "|u4", "data": self.data, "strides": (12, 4)}
        )
        self.assertEqual(bf.length, 3 * 3 * 4)
Пример #8
0
    def test_length(self):

        # __doc__ (as of 2008-08-02) for pygame.bufferproxy.BufferProxy.length:

          # The size of the buffer data in bytes.
        bf = BufferProxy({'shape': (3, 4),
                          'typestr': '|u4',
                          'data': self.data,
                          'strides': (12, 4)})
        self.assertEqual(bf.length, len(self.content))
        bf = BufferProxy({'shape': (3, 3),
                          'typestr': '|u4',
                          'data': self.data,
                          'strides': (12, 4)})
        self.assertEqual(bf.length, 3*3*4)
Пример #9
0
 def test_weakref(self):
     v = BufferProxy(self.view_keywords)
     weak_v = weakref.ref(v)
     self.assert_(weak_v() is v)
     v = None
     gc.collect()
     self.assert_(weak_v() is None)
Пример #10
0
    def test_parent_property(self):
        kwds = dict(self.view_keywords)
        p = []
        kwds['parent'] = p
        v = BufferProxy(kwds)

        self.assertIs(v.parent, p)
Пример #11
0
    def test_bad_format(self):
        from pygame.bufferproxy import BufferProxy
        from pygame.newbuffer import BufferMixin
        from ctypes import create_string_buffer, addressof

        buftools = self.buftools
        Exporter = buftools.Exporter
        Importer = buftools.Importer
        PyBUF_FORMAT = buftools.PyBUF_FORMAT

        for format in [
                "",
                "=",
                "1",
                " ",
                "2h",
                "=2h",
                "0x",
                "11x",
                "=!",
                "h ",
                " h",
                "hh",
                "?",
        ]:
            exp = Exporter((1, ), format, itemsize=2)
            b = BufferProxy(exp)
            self.assertRaises(ValueError, Importer, b, PyBUF_FORMAT)
Пример #12
0
    def NEWBUF_test_newbuf(self):
        from pygame.bufferproxy import BufferProxy

        Exporter = self.buftools.Exporter
        _shape = [2, 3, 5, 7, 11]  # Some prime numbers
        for ndim in range(1, len(_shape)):
            o = Exporter(_shape[0:ndim], '=h')
            v = BufferProxy(o)
            self.NEWBUF_assertSame(v, o)
        ndim = 2
        shape = _shape[0:ndim]
        for format in ['b', 'B', '=h', '=H', '=i', '=I', '=q', '=Q', 'f', 'd',
                       '1h', '=1h', 'x', '1x', '2x', '3x', '4x', '5x', '6x',
                       '7x', '8x', '9x']:
            o = Exporter(shape, format)
            v = BufferProxy(o)
            self.NEWBUF_assertSame(v, o)
Пример #13
0
    def test_before(self):
        def callback(parent):
            success.append(parent is p)

        class MyException(Exception):
            pass

        def raise_exception(parent):
            raise MyException("Just a test.")

        kwds = dict(self.view_keywords)
        p = []
        kwds['parent'] = p

        # For array interface
        success = []
        kwds['before'] = callback
        v = BufferProxy(kwds)
        self.assertEqual(len(success), 0)
        d = v.__array_interface__
        self.assertEqual(len(success), 1)
        self.assertTrue(success[0])
        d = v.__array_interface__
        self.assertEqual(len(success), 1)
        d = v = None
        gc.collect()
        self.assertEqual(len(success), 1)

        # For array struct
        success = []
        kwds['before'] = callback
        v = BufferProxy(kwds)
        self.assertEqual(len(success), 0)
        c = v.__array_struct__
        self.assertEqual(len(success), 1)
        self.assertTrue(success[0])
        c = v.__array_struct__
        self.assertEqual(len(success), 1)
        c = v = None
        gc.collect()
        self.assertEqual(len(success), 1)

        # Callback raises an exception
        kwds['before'] = raise_exception
        v = BufferProxy(kwds)
        self.assertRaises(MyException, lambda: v.__array_struct__)
Пример #14
0
 def test___array_interface___property(self):
     kwds = self.view_keywords
     v = BufferProxy(kwds)
     d = v.__array_interface__
     self.assertEqual(len(d), 5)
     self.assertEqual(d["version"], 3)
     self.assertEqual(d["shape"], kwds["shape"])
     self.assertEqual(d["typestr"], kwds["typestr"])
     self.assertEqual(d["data"], kwds["data"])
     self.assertEqual(d["strides"], kwds["strides"])
Пример #15
0
 def test___array_interface___property(self):
     kwds = self.view_keywords
     v = BufferProxy(kwds)
     d = v.__array_interface__
     self.assertEqual(len(d), 5)
     self.assertEqual(d['version'], 3)
     self.assertEqual(d['shape'], kwds['shape'])
     self.assertEqual(d['typestr'], kwds['typestr'])
     self.assertEqual(d['data'], kwds['data'])
     self.assertEqual(d['strides'], kwds['strides'])
Пример #16
0
    def test_GetView_array_struct(self):
        from pygame.bufferproxy import BufferProxy

        class Exporter(self.ExporterBase):
            def __init__(self, shape, typechar, itemsize):
                super(Exporter, self).__init__(shape, typechar, itemsize)
                self.view = BufferProxy(self.__dict__)

            def get__array_struct__(self):
                return self.view.__array_struct__

            __array_struct__ = property(get__array_struct__)
            # Should not cause PgObject_GetBuffer to fail
            __array_interface__ = property(lambda self: None)

        _shape = [2, 3, 5, 7, 11]  # Some prime numbers
        for ndim in range(1, len(_shape)):
            o = Exporter(_shape[0:ndim], 'i', 2)
            v = BufferProxy(o)
            self.assertSame(v, o)
        ndim = 2
        shape = _shape[0:ndim]
        for typechar in ('i', 'u'):
            for itemsize in (1, 2, 4, 8):
                o = Exporter(shape, typechar, itemsize)
                v = BufferProxy(o)
                self.assertSame(v, o)
        for itemsize in (4, 8):
            o = Exporter(shape, 'f', itemsize)
            v = BufferProxy(o)
            self.assertSame(v, o)

        # Check returned cobject/capsule reference count
        try:
            from sys import getrefcount
        except ImportError:
            # PyPy: no reference counting
            pass
        else:
            o = Exporter(shape, typechar, itemsize)
            self.assertEqual(getrefcount(o.__array_struct__), 1)
Пример #17
0
    def test_newbuf(self):
        from pygame.bufferproxy import BufferProxy

        Exporter = self.buftools.Exporter
        _shape = [2, 3, 5, 7, 11]  # Some prime numbers
        for ndim in range(1, len(_shape)):
            o = Exporter(_shape[0:ndim], "=h")
            v = BufferProxy(o)
            self.NEWBUF_assertSame(v, o)
        ndim = 2
        shape = _shape[0:ndim]
        for format in [
                "b",
                "B",
                "=h",
                "=H",
                "=i",
                "=I",
                "=q",
                "=Q",
                "f",
                "d",
                "1h",
                "=1h",
                "x",
                "1x",
                "2x",
                "3x",
                "4x",
                "5x",
                "6x",
                "7x",
                "8x",
                "9x",
        ]:
            o = Exporter(shape, format)
            v = BufferProxy(o)
            self.NEWBUF_assertSame(v, o)
Пример #18
0
    def test_write(self):

        # __doc__ (as of 2008-08-02) for pygame.bufferproxy.BufferProxy.write:

          # B.write (bufferproxy, buffer, offset) -> None
          #
          # Writes raw data to the bufferproxy.
          #
          # Writes the raw data from buffer to the BufferProxy object, starting
          # at the specified offset within the BufferProxy.
          # If the length of the passed buffer exceeds the length of the
          # BufferProxy (reduced by the offset), an IndexError will be raised.
        from ctypes import c_byte, sizeof, addressof, string_at, memset

        nullbyte = '\x00'.encode('latin_1')
        Buf = c_byte * 10
        data_buf = Buf(*range(1, 3 * sizeof(Buf) + 1, 3))
        data = string_at(data_buf, sizeof(data_buf))
        buf = Buf()
        bp = BufferProxy({'typestr': '|u1',
                          'shape': (sizeof(buf),),
                          'data': (addressof(buf), False)})
        try:
            self.assertEqual(bp.raw, nullbyte * sizeof(Buf))
            bp.write(data)
            self.assertEqual(bp.raw, data)
            memset(buf, 0, sizeof(buf))
            bp.write(data[:3], 2)
            raw = bp.raw
            self.assertEqual(raw[:2], nullbyte * 2)
            self.assertEqual(raw[2:5], data[:3])
            self.assertEqual(raw[5:], nullbyte * (sizeof(Buf) - 5))
            bp.write(data[:3], bp.length - 3)
            raw = bp.raw
            self.assertEqual(raw[-3:], data[:3])
            self.assertRaises(IndexError, bp.write, data, 1)
            self.assertRaises(IndexError, bp.write, data[:5], -1)
            self.assertRaises(IndexError, bp.write, data[:5], bp.length)
            self.assertRaises(TypeError, bp.write, 12)
            bp = BufferProxy({'typestr': '|u1',
                              'shape': (sizeof(buf),),
                              'data': (addressof(buf), True)})
            self.assertRaises(BufferError, bp.write, '123'.encode('latin_1'))
        finally:
            # Make sure bp is garbage collected before buf
            bp = None
            gc.collect()
Пример #19
0
    def NEWBUF_test_bad_format(self):
        from pygame.bufferproxy import BufferProxy
        from pygame.newbuffer import BufferMixin
        from ctypes import create_string_buffer, addressof

        buftools = self.buftools
        Exporter = buftools.Exporter
        Importer = buftools.Importer
        PyBUF_FORMAT = buftools.PyBUF_FORMAT

        for format in ['', '=', '1', ' ', '2h', '=2h',
                       '0x', '11x', '=!', 'h ', ' h', 'hh', '?']:
            exp = Exporter((1,), format, itemsize=2)
            b = BufferProxy(exp)
            self.assertRaises(ValueError, Importer, b, PyBUF_FORMAT)
Пример #20
0
    def test_bad_format(self):
        from pygame.bufferproxy import BufferProxy

        buftools = self.buftools
        Exporter = buftools.Exporter
        Importer = buftools.Importer
        PyBUF_FORMAT = buftools.PyBUF_FORMAT

        for format in [
                '', '=', '1', ' ', '2h', '=2h', '0x', '11x', '=!', 'h ', ' h',
                'hh', '?'
        ]:
            exp = Exporter((1, ), format, itemsize=2)
            b = BufferProxy(exp)
            self.assertRaises(ValueError, Importer, b, PyBUF_FORMAT)
Пример #21
0
 def __repr__(self):
     return "*%s*" % (BufferProxy.__repr__(self), )
Пример #22
0
 def test_repr(self):
     v = BufferProxy(self.view_keywords)
     cname = BufferProxy.__name__
     oname, ovalue = re.findall(r"<([^)]+)\(([^)]+)\)>", repr(v))[0]
     self.assertEqual(oname, cname)
     self.assertEqual(v.length, int(ovalue))
Пример #23
0
    def test_gc(self):
        """refcount agnostic check that contained objects are freed"""
        def before_callback(parent):
            return r[0]

        def after_callback(parent):
            return r[1]

        class Obj(object):
            pass

        p = Obj()
        a = Obj()
        r = [Obj(), Obj()]
        weak_p = weakref.ref(p)
        weak_a = weakref.ref(a)
        weak_r0 = weakref.ref(r[0])
        weak_r1 = weakref.ref(r[1])
        weak_before = weakref.ref(before_callback)
        weak_after = weakref.ref(after_callback)
        kwds = dict(self.view_keywords)
        kwds['parent'] = p
        kwds['before'] = before_callback
        kwds['after'] = after_callback
        v = BufferProxy(kwds)
        v.some_attribute = a
        weak_v = weakref.ref(v)
        kwds = p = a = before_callback = after_callback = None
        gc.collect()
        self.assertTrue(weak_p() is not None)
        self.assertTrue(weak_a() is not None)
        self.assertTrue(weak_before() is not None)
        self.assertTrue(weak_after() is not None)
        v = None
        [gc.collect() for x in range(4)]
        self.assertTrue(weak_v() is None)
        self.assertTrue(weak_p() is None)
        self.assertTrue(weak_a() is None)
        self.assertTrue(weak_before() is None)
        self.assertTrue(weak_after() is None)
        self.assertTrue(weak_r0() is not None)
        self.assertTrue(weak_r1() is not None)
        r = None
        gc.collect()
        self.assertTrue(weak_r0() is None)
        self.assertTrue(weak_r1() is None)

        # Cycle removal
        kwds = dict(self.view_keywords)
        kwds['parent'] = []
        v = BufferProxy(kwds)
        v.some_attribute = v
        tracked = True
        for o in gc.get_objects():
            if o is v:
                break
        else:
            tracked = False
        self.assertTrue(tracked)
        kwds['parent'].append(v)
        kwds = None
        gc.collect()
        n1 = len(gc.garbage)
        v = None
        gc.collect()
        n2 = len(gc.garbage)
        self.assertEqual(n2, n1)
Пример #24
0
    def test_PgObject_GetBuffer_exception(self):
        # For consistency with surfarray
        from pygame.bufferproxy import BufferProxy

        bp = BufferProxy(1)
        self.assertRaises(ValueError, getattr, bp, 'length')
Пример #25
0
    def OLDBUF_test_oldbuf_arg(self):
        from pygame.bufferproxy import get_segcount, get_read_buffer, get_write_buffer

        content = as_bytes("\x01\x00\x00\x02") * 12
        memory = ctypes.create_string_buffer(content)
        memaddr = ctypes.addressof(memory)

        def raise_exception(o):
            raise ValueError("An exception")

        bf = BufferProxy(
            {
                "shape": (len(content),),
                "typestr": "|u1",
                "data": (memaddr, False),
                "strides": (1,),
            }
        )
        seglen, segaddr = get_read_buffer(bf, 0)
        self.assertEqual(segaddr, 0)
        self.assertEqual(seglen, 0)
        seglen, segaddr = get_write_buffer(bf, 0)
        self.assertEqual(segaddr, 0)
        self.assertEqual(seglen, 0)
        segcount, buflen = get_segcount(bf)
        self.assertEqual(segcount, 1)
        self.assertEqual(buflen, len(content))
        seglen, segaddr = get_read_buffer(bf, 0)
        self.assertEqual(segaddr, memaddr)
        self.assertEqual(seglen, len(content))
        seglen, segaddr = get_write_buffer(bf, 0)
        self.assertEqual(segaddr, memaddr)
        self.assertEqual(seglen, len(content))

        bf = BufferProxy(
            {
                "shape": (len(content),),
                "typestr": "|u1",
                "data": (memaddr, True),
                "strides": (1,),
            }
        )
        segcount, buflen = get_segcount(bf)
        self.assertEqual(segcount, 1)
        self.assertEqual(buflen, len(content))
        seglen, segaddr = get_read_buffer(bf, 0)
        self.assertEqual(segaddr, memaddr)
        self.assertEqual(seglen, len(content))
        self.assertRaises(ValueError, get_write_buffer, bf, 0)

        bf = BufferProxy(
            {
                "shape": (len(content),),
                "typestr": "|u1",
                "data": (memaddr, True),
                "strides": (1,),
                "before": raise_exception,
            }
        )
        segcount, buflen = get_segcount(bf)
        self.assertEqual(segcount, 0)
        self.assertEqual(buflen, 0)

        bf = BufferProxy(
            {
                "shape": (3, 4),
                "typestr": "|u4",
                "data": (memaddr, True),
                "strides": (12, 4),
            }
        )
        segcount, buflen = get_segcount(bf)
        self.assertEqual(segcount, 3 * 4)
        self.assertEqual(buflen, 3 * 4 * 4)
        for i in range(0, 4):
            seglen, segaddr = get_read_buffer(bf, i)
            self.assertEqual(segaddr, memaddr + i * 4)
            self.assertEqual(seglen, 4)
Пример #26
0
    def test_gc(self):
        """refcount agnostic check that contained objects are freed"""
        def before_callback(parent):
            return r[0]
        def after_callback(parent):
            return r[1]
        class Obj(object):
            pass
        p = Obj()
        a = Obj()
        r = [Obj(), Obj()]
        weak_p = weakref.ref(p)
        weak_a = weakref.ref(a)
        weak_r0 = weakref.ref(r[0])
        weak_r1 = weakref.ref(r[1])
        weak_before = weakref.ref(before_callback)
        weak_after = weakref.ref(after_callback)
        kwds = dict(self.view_keywords)
        kwds['parent'] = p
        kwds['before'] = before_callback
        kwds['after'] = after_callback
        v = BufferProxy(kwds)
        v.some_attribute = a
        weak_v = weakref.ref(v)
        kwds = p = a = before_callback = after_callback = None
        gc.collect()
        self.assertTrue(weak_p() is not None)
        self.assertTrue(weak_a() is not None)
        self.assertTrue(weak_before() is not None)
        self.assertTrue(weak_after() is not None)
        v = None
        gc.collect()
        self.assertTrue(weak_v() is None)
        self.assertTrue(weak_p() is None)
        self.assertTrue(weak_a() is None)
        self.assertTrue(weak_before() is None)
        self.assertTrue(weak_after() is None)
        self.assertTrue(weak_r0() is not None)
        self.assertTrue(weak_r1() is not None)
        r = None
        gc.collect()
        self.assertTrue(weak_r0() is None)
        self.assertTrue(weak_r1() is None)

        # Cycle removal
        kwds = dict(self.view_keywords)
        kwds['parent'] = []
        v = BufferProxy(kwds)
        v.some_attribute = v
        tracked = True
        for o in gc.get_objects():
            if o is v:
                break
        else:
            tracked = False
        self.assertTrue(tracked)
        kwds['parent'].append(v)
        kwds = None
        gc.collect()
        n1 = len(gc.garbage)
        v = None
        gc.collect()
        n2 = len(gc.garbage)
        self.assertEqual(n2, n1)
Пример #27
0
    def test_PgObject_GetBuffer_array_interface(self):
        from pygame.bufferproxy import BufferProxy

        class Exporter(self.ExporterBase):
            def get__array_interface__(self):
                return {
                    'version': 3,
                    'typestr': self.typestr,
                    'shape': self.shape,
                    'strides': self.strides,
                    'data': self.data
                }

            __array_interface__ = property(get__array_interface__)
            # Should be ignored by PgObject_GetBuffer
            __array_struct__ = property(lambda self: None)

        _shape = [2, 3, 5, 7, 11]  # Some prime numbers
        for ndim in range(1, len(_shape)):
            o = Exporter(_shape[0:ndim], 'i', 2)
            v = BufferProxy(o)
            self.assertSame(v, o)
        ndim = 2
        shape = _shape[0:ndim]
        for typechar in ('i', 'u'):
            for itemsize in (1, 2, 4, 8):
                o = Exporter(shape, typechar, itemsize)
                v = BufferProxy(o)
                self.assertSame(v, o)
        for itemsize in (4, 8):
            o = Exporter(shape, 'f', itemsize)
            v = BufferProxy(o)
            self.assertSame(v, o)

        # Is the dict received from an exporting object properly released?
        # The dict should be freed before PgObject_GetBuffer returns.
        # When the BufferProxy v's length property is referenced, v calls
        # PgObject_GetBuffer, which in turn references Exporter2 o's
        # __array_interface__ property. The Exporter2 instance o returns a
        # dict subclass for which it keeps both a regular reference and a
        # weak reference. The regular reference should be the only
        # remaining reference when PgObject_GetBuffer returns. This is
        # verified by first checking the weak reference both before and
        # after the regular reference held by o is removed.

        import weakref, gc

        class NoDictError(RuntimeError):
            pass

        class WRDict(dict):
            """Weak referenceable dict"""
            pass

        class Exporter2(Exporter):
            def get__array_interface__2(self):
                self.d = WRDict(Exporter.get__array_interface__(self))
                self.dict_ref = weakref.ref(self.d)
                return self.d

            __array_interface__ = property(get__array_interface__2)

            def free_dict(self):
                self.d = None

            def is_dict_alive(self):
                try:
                    return self.dict_ref() is not None
                except AttributeError:
                    raise NoDictError("__array_interface__ is unread")

        o = Exporter2((2, 4), 'u', 4)
        v = BufferProxy(o)
        self.assertRaises(NoDictError, o.is_dict_alive)
        length = v.length
        self.assertTrue(o.is_dict_alive())
        o.free_dict()
        gc.collect()
        self.assertFalse(o.is_dict_alive())
Пример #28
0
    def NEWBUF_test_newbuf(self):
        from ctypes import string_at

        from pygame.tests.test_utils import buftools
        Exporter = buftools.Exporter
        Importer = buftools.Importer
        exp = Exporter((10, ), 'B', readonly=True)
        b = BufferProxy(exp)
        self.assertEqual(b.length, exp.len)
        self.assertEqual(b.raw, string_at(exp.buf, exp.len))
        d = b.__array_interface__
        try:
            self.assertEqual(d['typestr'], '|u1')
            self.assertEqual(d['shape'], exp.shape)
            self.assertEqual(d['strides'], exp.strides)
            self.assertEqual(d['data'], (exp.buf, True))
        finally:
            d = None
        exp = Exporter((3, ), '=h')
        b = BufferProxy(exp)
        self.assertEqual(b.length, exp.len)
        self.assertEqual(b.raw, string_at(exp.buf, exp.len))
        d = b.__array_interface__
        try:
            lil_endian = pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN
            f = '{}i{}'.format('<' if lil_endian else '>', exp.itemsize)
            self.assertEqual(d['typestr'], f)
            self.assertEqual(d['shape'], exp.shape)
            self.assertEqual(d['strides'], exp.strides)
            self.assertEqual(d['data'], (exp.buf, False))
        finally:
            d = None

        exp = Exporter((10, 2), '=i')
        b = BufferProxy(exp)
        imp = Importer(b, buftools.PyBUF_RECORDS)
        self.assertTrue(imp.obj is b)
        self.assertEqual(imp.buf, exp.buf)
        self.assertEqual(imp.ndim, exp.ndim)
        self.assertEqual(imp.format, exp.format)
        self.assertEqual(imp.readonly, exp.readonly)
        self.assertEqual(imp.itemsize, exp.itemsize)
        self.assertEqual(imp.len, exp.len)
        self.assertEqual(imp.shape, exp.shape)
        self.assertEqual(imp.strides, exp.strides)
        self.assertTrue(imp.suboffsets is None)

        d = {
            'typestr': '|u1',
            'shape': (10, ),
            'strides': (1, ),
            'data': (9, True)
        }  # 9? Will not reading the data anyway.
        b = BufferProxy(d)
        imp = Importer(b, buftools.PyBUF_SIMPLE)
        self.assertTrue(imp.obj is b)
        self.assertEqual(imp.buf, 9)
        self.assertEqual(imp.len, 10)
        self.assertEqual(imp.format, None)
        self.assertEqual(imp.itemsize, 1)
        self.assertEqual(imp.ndim, 0)
        self.assertTrue(imp.readonly)
        self.assertTrue(imp.shape is None)
        self.assertTrue(imp.strides is None)
        self.assertTrue(imp.suboffsets is None)
Пример #29
0
    def OLDBUF_test_oldbuf_arg(self):
        from pygame.bufferproxy import (get_segcount, get_read_buffer,
                                        get_write_buffer)

        content = as_bytes('\x01\x00\x00\x02') * 12
        memory = ctypes.create_string_buffer(content)
        memaddr = ctypes.addressof(memory)

        def raise_exception(o):
            raise ValueError("An exception")

        bf = BufferProxy({
            'shape': (len(content), ),
            'typestr': '|u1',
            'data': (memaddr, False),
            'strides': (1, )
        })
        seglen, segaddr = get_read_buffer(bf, 0)
        self.assertEqual(segaddr, 0)
        self.assertEqual(seglen, 0)
        seglen, segaddr = get_write_buffer(bf, 0)
        self.assertEqual(segaddr, 0)
        self.assertEqual(seglen, 0)
        segcount, buflen = get_segcount(bf)
        self.assertEqual(segcount, 1)
        self.assertEqual(buflen, len(content))
        seglen, segaddr = get_read_buffer(bf, 0)
        self.assertEqual(segaddr, memaddr)
        self.assertEqual(seglen, len(content))
        seglen, segaddr = get_write_buffer(bf, 0)
        self.assertEqual(segaddr, memaddr)
        self.assertEqual(seglen, len(content))

        bf = BufferProxy({
            'shape': (len(content), ),
            'typestr': '|u1',
            'data': (memaddr, True),
            'strides': (1, )
        })
        segcount, buflen = get_segcount(bf)
        self.assertEqual(segcount, 1)
        self.assertEqual(buflen, len(content))
        seglen, segaddr = get_read_buffer(bf, 0)
        self.assertEqual(segaddr, memaddr)
        self.assertEqual(seglen, len(content))
        self.assertRaises(ValueError, get_write_buffer, bf, 0)

        bf = BufferProxy({
            'shape': (len(content), ),
            'typestr': '|u1',
            'data': (memaddr, True),
            'strides': (1, ),
            'before': raise_exception
        })
        segcount, buflen = get_segcount(bf)
        self.assertEqual(segcount, 0)
        self.assertEqual(buflen, 0)

        bf = BufferProxy({
            'shape': (3, 4),
            'typestr': '|u4',
            'data': (memaddr, True),
            'strides': (12, 4)
        })
        segcount, buflen = get_segcount(bf)
        self.assertEqual(segcount, 3 * 4)
        self.assertEqual(buflen, 3 * 4 * 4)
        for i in range(0, 4):
            seglen, segaddr = get_read_buffer(bf, i)
            self.assertEqual(segaddr, memaddr + i * 4)
            self.assertEqual(seglen, 4)
Пример #30
0
 def __init__(self, shape, typechar, itemsize):
     super(Exporter, self).__init__(shape, typechar, itemsize)
     self.view = BufferProxy(self.__dict__)
Пример #31
0
 def __repr__(self):
     return "*%s*" % (BufferProxy.__repr__(self),)
Пример #32
0
    def NEWBUF_test_PgDict_AsBuffer_PyBUF_flags(self):
        from pygame.bufferproxy import BufferProxy

        is_lil_endian = pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN
        fsys, frev = ('<', '>') if is_lil_endian else ('>', '<')
        buftools = self.buftools
        Importer = buftools.Importer
        a = BufferProxy({
            'typestr': '|u4',
            'shape': (10, 2),
            'data': (9, False)
        })  # 9? No data accesses.
        b = Importer(a, buftools.PyBUF_SIMPLE)
        self.assertEqual(b.ndim, 0)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, a.length)
        self.assertEqual(b.itemsize, 4)
        self.assertTrue(b.shape is None)
        self.assertTrue(b.strides is None)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, 9)
        b = Importer(a, buftools.PyBUF_WRITABLE)
        self.assertEqual(b.ndim, 0)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, a.length)
        self.assertEqual(b.itemsize, 4)
        self.assertTrue(b.shape is None)
        self.assertTrue(b.strides is None)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, 9)
        b = Importer(a, buftools.PyBUF_ND)
        self.assertEqual(b.ndim, 2)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, a.length)
        self.assertEqual(b.itemsize, 4)
        self.assertEqual(b.shape, (10, 2))
        self.assertTrue(b.strides is None)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, 9)
        a = BufferProxy({
            'typestr': fsys + 'i2',
            'shape': (5, 10),
            'strides': (24, 2),
            'data': (42, False)
        })  # 42? No data accesses.
        b = Importer(a, buftools.PyBUF_STRIDES)
        self.assertEqual(b.ndim, 2)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, 100)
        self.assertEqual(b.itemsize, 2)
        self.assertEqual(b.shape, (5, 10))
        self.assertEqual(b.strides, (24, 2))
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, 42)
        b = Importer(a, buftools.PyBUF_FULL_RO)
        self.assertEqual(b.ndim, 2)
        self.assertEqual(b.format, '=h')
        self.assertEqual(b.len, 100)
        self.assertEqual(b.itemsize, 2)
        self.assertEqual(b.shape, (5, 10))
        self.assertEqual(b.strides, (24, 2))
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, 42)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_SIMPLE)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_ND)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_C_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_F_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_ANY_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_CONTIG)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_SIMPLE)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_ND)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_C_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_F_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_ANY_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_CONTIG)
        a = BufferProxy({
            'typestr': frev + 'i2',
            'shape': (3, 5, 10),
            'strides': (120, 24, 2),
            'data': (1000000, True)
        })  # 1000000? No data accesses.
        b = Importer(a, buftools.PyBUF_FULL_RO)
        self.assertEqual(b.ndim, 3)
        self.assertEqual(b.format, frev + 'h')
        self.assertEqual(b.len, 300)
        self.assertEqual(b.itemsize, 2)
        self.assertEqual(b.shape, (3, 5, 10))
        self.assertEqual(b.strides, (120, 24, 2))
        self.assertTrue(b.suboffsets is None)
        self.assertTrue(b.readonly)
        self.assertEqual(b.buf, 1000000)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_FULL)
Пример #33
0
    def NEWBUF_test_PgObject_AsBuffer_PyBUF_flags(self):
        from pygame.bufferproxy import BufferProxy
        import ctypes

        is_lil_endian = pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN
        fsys, frev = ('<', '>') if is_lil_endian else ('>', '<')
        buftools = self.buftools
        Importer = buftools.Importer
        e = arrinter.Exporter((10, 2),
                              typekind='f',
                              itemsize=ctypes.sizeof(ctypes.c_double))
        a = BufferProxy(e)
        b = Importer(a, buftools.PyBUF_SIMPLE)
        self.assertEqual(b.ndim, 0)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, e.len)
        self.assertEqual(b.itemsize, e.itemsize)
        self.assertTrue(b.shape is None)
        self.assertTrue(b.strides is None)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, e.data)
        b = Importer(a, buftools.PyBUF_WRITABLE)
        self.assertEqual(b.ndim, 0)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, e.len)
        self.assertEqual(b.itemsize, e.itemsize)
        self.assertTrue(b.shape is None)
        self.assertTrue(b.strides is None)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, e.data)
        b = Importer(a, buftools.PyBUF_ND)
        self.assertEqual(b.ndim, e.nd)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, a.length)
        self.assertEqual(b.itemsize, e.itemsize)
        self.assertEqual(b.shape, e.shape)
        self.assertTrue(b.strides is None)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, e.data)
        e = arrinter.Exporter((5, 10),
                              typekind='i',
                              itemsize=2,
                              strides=(24, 2))
        a = BufferProxy(e)
        b = Importer(a, buftools.PyBUF_STRIDES)
        self.assertEqual(b.ndim, e.nd)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, e.len)
        self.assertEqual(b.itemsize, e.itemsize)
        self.assertEqual(b.shape, e.shape)
        self.assertEqual(b.strides, e.strides)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, e.data)
        b = Importer(a, buftools.PyBUF_FULL_RO)
        self.assertEqual(b.ndim, e.nd)
        self.assertEqual(b.format, '=h')
        self.assertEqual(b.len, e.len)
        self.assertEqual(b.itemsize, e.itemsize)
        self.assertEqual(b.shape, e.shape)
        self.assertEqual(b.strides, e.strides)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, e.data)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_SIMPLE)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_WRITABLE)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_WRITABLE)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_ND)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_C_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_F_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_ANY_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_CONTIG)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_SIMPLE)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_ND)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_C_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_F_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a,
                          buftools.PyBUF_ANY_CONTIGUOUS)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_CONTIG)
        e = arrinter.Exporter((3, 5, 10),
                              typekind='i',
                              itemsize=2,
                              strides=(120, 24, 2),
                              flags=arrinter.PAI_ALIGNED)
        a = BufferProxy(e)
        b = Importer(a, buftools.PyBUF_FULL_RO)
        self.assertEqual(b.ndim, e.nd)
        self.assertEqual(b.format, frev + 'h')
        self.assertEqual(b.len, e.len)
        self.assertEqual(b.itemsize, e.itemsize)
        self.assertEqual(b.shape, e.shape)
        self.assertEqual(b.strides, e.strides)
        self.assertTrue(b.suboffsets is None)
        self.assertTrue(b.readonly)
        self.assertEqual(b.buf, e.data)
        self.assertRaises(BufferError, Importer, a, buftools.PyBUF_FULL)
Пример #34
0
    def NEWBUF_test_newbuf(self):
        from ctypes import string_at

        from pygame.tests.test_utils import buftools

        Exporter = buftools.Exporter
        Importer = buftools.Importer
        exp = Exporter((10,), "B", readonly=True)
        b = BufferProxy(exp)
        self.assertEqual(b.length, exp.len)
        self.assertEqual(b.raw, string_at(exp.buf, exp.len))
        d = b.__array_interface__
        try:
            self.assertEqual(d["typestr"], "|u1")
            self.assertEqual(d["shape"], exp.shape)
            self.assertEqual(d["strides"], exp.strides)
            self.assertEqual(d["data"], (exp.buf, True))
        finally:
            d = None
        exp = Exporter((3,), "=h")
        b = BufferProxy(exp)
        self.assertEqual(b.length, exp.len)
        self.assertEqual(b.raw, string_at(exp.buf, exp.len))
        d = b.__array_interface__
        try:
            lil_endian = pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN
            f = "{}i{}".format("<" if lil_endian else ">", exp.itemsize)
            self.assertEqual(d["typestr"], f)
            self.assertEqual(d["shape"], exp.shape)
            self.assertEqual(d["strides"], exp.strides)
            self.assertEqual(d["data"], (exp.buf, False))
        finally:
            d = None

        exp = Exporter((10, 2), "=i")
        b = BufferProxy(exp)
        imp = Importer(b, buftools.PyBUF_RECORDS)
        self.assertTrue(imp.obj is b)
        self.assertEqual(imp.buf, exp.buf)
        self.assertEqual(imp.ndim, exp.ndim)
        self.assertEqual(imp.format, exp.format)
        self.assertEqual(imp.readonly, exp.readonly)
        self.assertEqual(imp.itemsize, exp.itemsize)
        self.assertEqual(imp.len, exp.len)
        self.assertEqual(imp.shape, exp.shape)
        self.assertEqual(imp.strides, exp.strides)
        self.assertTrue(imp.suboffsets is None)

        d = {
            "typestr": "|u1",
            "shape": (10,),
            "strides": (1,),
            "data": (9, True),
        }  # 9? Will not reading the data anyway.
        b = BufferProxy(d)
        imp = Importer(b, buftools.PyBUF_SIMPLE)
        self.assertTrue(imp.obj is b)
        self.assertEqual(imp.buf, 9)
        self.assertEqual(imp.len, 10)
        self.assertEqual(imp.format, None)
        self.assertEqual(imp.itemsize, 1)
        self.assertEqual(imp.ndim, 0)
        self.assertTrue(imp.readonly)
        self.assertTrue(imp.shape is None)
        self.assertTrue(imp.strides is None)
        self.assertTrue(imp.suboffsets is None)