def test_scrap_put_text(self): scrap.put(pygame.SCRAP_TEXT, as_bytes("Hello world")) self.assertEqual(scrap.get(pygame.SCRAP_TEXT), as_bytes("Hello world")) scrap.put(pygame.SCRAP_TEXT, as_bytes("Another String")) self.assertEqual(scrap.get(pygame.SCRAP_TEXT), as_bytes("Another String"))
def test_scrap_put_text (self): scrap.put (pygame.SCRAP_TEXT, as_bytes("Hello world")) self.assertEquals (scrap.get (pygame.SCRAP_TEXT), as_bytes("Hello world")) scrap.put (pygame.SCRAP_TEXT, as_bytes("Another String")) self.assertEquals (scrap.get (pygame.SCRAP_TEXT), as_bytes("Another String"))
def test_put__text(self): """Ensures put can place text into the clipboard.""" scrap.put(pygame.SCRAP_TEXT, as_bytes("Hello world")) self.assertEqual(scrap.get(pygame.SCRAP_TEXT), as_bytes("Hello world")) scrap.put(pygame.SCRAP_TEXT, as_bytes("Another String")) self.assertEqual(scrap.get(pygame.SCRAP_TEXT), as_bytes("Another String"))
def test_render(self): """ """ f = pygame_font.Font(None, 20) s = f.render("foo", True, [0, 0, 0], [255, 255, 255]) s = f.render("xxx", True, [0, 0, 0], [255, 255, 255]) s = f.render("", True, [0, 0, 0], [255, 255, 255]) s = f.render("foo", False, [0, 0, 0], [255, 255, 255]) s = f.render("xxx", False, [0, 0, 0], [255, 255, 255]) s = f.render("xxx", False, [0, 0, 0]) s = f.render(" ", False, [0, 0, 0]) s = f.render(" ", False, [0, 0, 0], [255, 255, 255]) # null text should be 1 pixel wide. s = f.render("", False, [0, 0, 0], [255, 255, 255]) self.assertEqual(s.get_size()[0], 1) # None text should be 1 pixel wide. s = f.render(None, False, [0, 0, 0], [255, 255, 255]) self.assertEqual(s.get_size()[0], 1) # Non-text should raise a TypeError. self.assertRaises(TypeError, f.render, [], False, [0, 0, 0], [255, 255, 255]) self.assertRaises(TypeError, f.render, 1, False, [0, 0, 0], [255, 255, 255]) # is background transparent for antialiasing? s = f.render(".", True, [255, 255, 255]) self.failUnlessEqual(s.get_at((0, 0))[3], 0) # is Unicode and bytes encoding correct? # Cannot really test if the correct characters are rendered, but # at least can assert the encodings differ. su = f.render(as_unicode("."), False, [0, 0, 0], [255, 255, 255]) sb = f.render(as_bytes("."), False, [0, 0, 0], [255, 255, 255]) self.assert_(equal_images(su, sb)) u = as_unicode(r"\u212A") b = u.encode("UTF-16")[ 2:] # Keep byte order consistent. [2:] skips BOM sb = f.render(b, False, [0, 0, 0], [255, 255, 255]) try: su = f.render(u, False, [0, 0, 0], [255, 255, 255]) except pygame.error: pass else: self.assert_(not equal_images(su, sb)) # If the font module is SDL_ttf based, then it can only supports UCS-2; # it will raise an exception for an out-of-range UCS-4 code point. if UCS_4 and not hasattr(f, 'ucs4'): ucs_2 = as_unicode(r"\uFFEE") s = f.render(ucs_2, False, [0, 0, 0], [255, 255, 255]) ucs_4 = as_unicode(r"\U00010000") self.assertRaises(UnicodeError, f.render, ucs_4, False, [0, 0, 0], [255, 255, 255]) b = as_bytes("ab\x00cd") self.assertRaises(ValueError, f.render, b, 0, [0, 0, 0]) u = as_unicode("ab\x00cd") self.assertRaises(ValueError, f.render, b, 0, [0, 0, 0])
def test_render(self): """ """ f = pygame_font.Font(None, 20) s = f.render("foo", True, [0, 0, 0], [255, 255, 255]) s = f.render("xxx", True, [0, 0, 0], [255, 255, 255]) s = f.render("", True, [0, 0, 0], [255, 255, 255]) s = f.render("foo", False, [0, 0, 0], [255, 255, 255]) s = f.render("xxx", False, [0, 0, 0], [255, 255, 255]) s = f.render("xxx", False, [0, 0, 0]) s = f.render(" ", False, [0, 0, 0]) s = f.render(" ", False, [0, 0, 0], [255, 255, 255]) # null text should be 1 pixel wide. s = f.render("", False, [0, 0, 0], [255, 255, 255]) self.assertEqual(s.get_size()[0], 1) # None text should be 1 pixel wide. s = f.render(None, False, [0, 0, 0], [255, 255, 255]) self.assertEqual(s.get_size()[0], 1) # Non-text should raise a TypeError. self.assertRaises(TypeError, f.render, [], False, [0, 0, 0], [255, 255, 255]) self.assertRaises(TypeError, f.render, 1, False, [0, 0, 0], [255, 255, 255]) # is background transparent for antialiasing? s = f.render(".", True, [255, 255, 255]) self.failUnlessEqual(s.get_at((0, 0))[3], 0) # is Unicode and bytes encoding correct? # Cannot really test if the correct characters are rendered, but # at least can assert the encodings differ. su = f.render(as_unicode("."), False, [0, 0, 0], [255, 255, 255]) sb = f.render(as_bytes("."), False, [0, 0, 0], [255, 255, 255]) self.assert_(equal_images(su, sb)) u = as_unicode(r"\u212A") b = u.encode("UTF-16")[2:] # Keep byte order consistent. [2:] skips BOM sb = f.render(b, False, [0, 0, 0], [255, 255, 255]) try: su = f.render(u, False, [0, 0, 0], [255, 255, 255]) except pygame.error: pass else: self.assert_(not equal_images(su, sb)) # If the font module is SDL_ttf based, then it can only supports UCS-2; # it will raise an exception for an out-of-range UCS-4 code point. if UCS_4 and not hasattr(f, 'ucs4'): ucs_2 = as_unicode(r"\uFFEE") s = f.render(ucs_2, False, [0, 0, 0], [255, 255, 255]) ucs_4 = as_unicode(r"\U00010000") self.assertRaises(UnicodeError, f.render, ucs_4, False, [0, 0, 0], [255, 255, 255]) b = as_bytes("ab\x00cd") self.assertRaises(ValueError, f.render, b, 0, [0, 0, 0]) u = as_unicode("ab\x00cd") self.assertRaises(ValueError, f.render, b, 0, [0, 0, 0])
def test_put(self): """Ensures put can place data into the clipboard when using a user defined type identifier. """ DATA_TYPE = "arbitrary buffer" scrap.put(DATA_TYPE, as_bytes("buf")) r = scrap.get(DATA_TYPE) self.assertEqual(r, as_bytes("buf"))
def test_as_bytes(self): ords = [0, 1, 0x7F, 0x80, 0xC3, 0x20, 0xC3, 0xB6, 0xFF] s = ''.join([chr(i) for i in ords]) self.failUnlessEqual(len(s), len(ords)) b = compat.as_bytes(s) self.failUnless(isinstance(b, compat.bytes_)) self.failUnlessEqual([compat.ord_(i) for i in b], ords)
def test_get_raw_more(self): """ test the array interface a bit better. """ import platform IS_PYPY = 'PyPy' == platform.python_implementation() if IS_PYPY: return from ctypes import pythonapi, c_void_p, py_object try: Bytes_FromString = pythonapi.PyBytes_FromString except: Bytes_FromString = pythonapi.PyString_FromString Bytes_FromString.restype = c_void_p Bytes_FromString.argtypes = [py_object] mixer.init() try: samples = as_bytes('abcdefgh') # keep byte size a multiple of 4 snd = mixer.Sound(buffer=samples) raw = snd.get_raw() self.assertTrue(isinstance(raw, bytes_)) self.assertNotEqual(snd._samples_address, Bytes_FromString(samples)) self.assertEqual(raw, samples) finally: mixer.quit()
def test_get_raw(self): mixer.init() samples = as_bytes('abcdefgh') # keep byte size a multiple of 4 snd = mixer.Sound(buffer=samples) raw = snd.get_raw() self.assertTrue(isinstance(raw, bytes_)) self.assertEqual(raw, samples)
def test_as_bytes(self): ords = [0, 1, 0x7F, 0x80, 0xC3, 0x20, 0xC3, 0xB6, 0xFF] s = "".join([chr(i) for i in ords]) self.assertEqual(len(s), len(ords)) b = compat.as_bytes(s) self.assertIsInstance(b, compat.bytes_) self.assertEqual([compat.ord_(i) for i in b], ords)
def test_string_with_null_bytes(self): b = as_bytes("a\x00b\x00c") encoded_string = encode_string(b, etype=SyntaxError) encoded_decode_string = encode_string(b.decode(), "ascii", "strict") self.assertIs(encoded_string, b) self.assertEqual(encoded_decode_string, b)
def test_refcount(self): bpath = as_bytes(" This is a string that is not cached.")[1:] upath = bpath.decode('ascii') before = getrefcount(bpath) bpath = encode_string(bpath) self.assertEqual(getrefcount(bpath), before) bpath = encode_string(upath) self.assertEqual(getrefcount(bpath), before)
def test_render(self): f = pygame_font.Font(None, 20) s = f.render("foo", True, [0, 0, 0], [255, 255, 255]) s = f.render("xxx", True, [0, 0, 0], [255, 255, 255]) s = f.render("", True, [0, 0, 0], [255, 255, 255]) s = f.render("foo", False, [0, 0, 0], [255, 255, 255]) s = f.render("xxx", False, [0, 0, 0], [255, 255, 255]) s = f.render("xxx", False, [0, 0, 0]) s = f.render(" ", False, [0, 0, 0]) s = f.render(" ", False, [0, 0, 0], [255, 255, 255]) # null text should be 0 pixel wide. s = f.render("", False, [0, 0, 0], [255, 255, 255]) self.assertEqual(s.get_size()[0], 0) # None text should be 0 pixel wide. s = f.render(None, False, [0, 0, 0], [255, 255, 255]) self.assertEqual(s.get_size()[0], 0) # Non-text should raise a TypeError. self.assertRaises(TypeError, f.render, [], False, [0, 0, 0], [255, 255, 255]) self.assertRaises(TypeError, f.render, 1, False, [0, 0, 0], [255, 255, 255]) # is background transparent for antialiasing? s = f.render(".", True, [255, 255, 255]) self.assertEqual(s.get_at((0, 0))[3], 0) # is Unicode and bytes encoding correct? # Cannot really test if the correct characters are rendered, but # at least can assert the encodings differ. su = f.render(as_unicode("."), False, [0, 0, 0], [255, 255, 255]) sb = f.render(as_bytes("."), False, [0, 0, 0], [255, 255, 255]) self.assertTrue(equal_images(su, sb)) u = as_unicode(r"\u212A") b = u.encode("UTF-16")[ 2:] # Keep byte order consistent. [2:] skips BOM sb = f.render(b, False, [0, 0, 0], [255, 255, 255]) try: # FIXME why do we do this try/except ? su = f.render(u, False, [0, 0, 0], [255, 255, 255]) except pygame.error: pass else: self.assertFalse(equal_images(su, sb)) b = as_bytes("ab\x00cd") self.assertRaises(ValueError, f.render, b, 0, [0, 0, 0]) u = as_unicode("ab\x00cd") self.assertRaises(ValueError, f.render, b, 0, [0, 0, 0])
def test_get_raw(self): """Ensure get_raw returns the correct bytestring.""" samples = as_bytes('abcdefgh') # keep byte size a multiple of 4 snd = mixer.Sound(buffer=samples) raw = snd.get_raw() self.assertIsInstance(raw, bytes_) self.assertEqual(raw, samples)
def test_init__reinit(self): """Ensures reinitializing the scrap module doesn't clear its data.""" data_type = pygame.SCRAP_TEXT expected_data = as_bytes("test_init__reinit") scrap.put(data_type, expected_data) scrap.init() self.assertEqual(scrap.get(data_type), expected_data)
def test_get_raw(self): mixer.init() try: samples = as_bytes('abcdefgh') # keep byte size a multiple of 4 snd = mixer.Sound(buffer=samples) raw = snd.get_raw() self.assertTrue(isinstance(raw, bytes_)) self.assertEqual(raw, samples) finally: mixer.quit()
def test_metrics(self): # Ensure bytes decoding works correctly. Can only compare results # with unicode for now. f = pygame_font.Font(None, 20) um = f.metrics(as_unicode(".")) bm = f.metrics(as_bytes(".")) self.assertEqual(len(um), 1) self.assertEqual(len(bm), 1) self.assertIsNotNone(um[0]) self.assertEqual(um, bm) u = u"\u212A" b = u.encode("UTF-16")[ 2:] # Keep byte order consistent. [2:] skips BOM bm = f.metrics(b) self.assertEqual(len(bm), 2) try: # FIXME why do we do this try/except ? um = f.metrics(u) except pygame.error: pass else: self.assertEqual(len(um), 1) self.assertNotEqual(bm[0], um[0]) self.assertNotEqual(bm[1], um[0]) if UCS_4: u = u"\U00013000" bm = f.metrics(u) self.assertEqual(len(bm), 1) self.assertIsNone(bm[0]) return # unfinished # The documentation is useless here. How large a list? # How do list positions relate to character codes? # What about unicode characters? # __doc__ (as of 2008-08-02) for pygame_font.Font.metrics: # Font.metrics(text): return list # Gets the metrics for each character in the pased string. # # The list contains tuples for each character, which contain the # minimum X offset, the maximum X offset, the minimum Y offset, the # maximum Y offset and the advance offset (bearing plus width) of the # character. [(minx, maxx, miny, maxy, advance), (minx, maxx, miny, # maxy, advance), ...] self.fail()
def test_array_interface(self): mixer.init(22050, -16, 1, allowedchanges=0) snd = mixer.Sound(buffer=as_bytes('\x00\x7f') * 20) d = snd.__array_interface__ self.assertTrue(isinstance(d, dict)) if pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN: typestr = '<i2' else: typestr = '>i2' self.assertEqual(d['typestr'], typestr) self.assertEqual(d['shape'], (20, )) self.assertEqual(d['strides'], (2, )) self.assertEqual(d['data'], (snd._samples_address, False))
def test_array_interface(self): mixer.init(22050, -16, 1, allowedchanges=0) snd = mixer.Sound(buffer=as_bytes("\x00\x7f") * 20) d = snd.__array_interface__ self.assertTrue(isinstance(d, dict)) if pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN: typestr = "<i2" else: typestr = ">i2" self.assertEqual(d["typestr"], typestr) self.assertEqual(d["shape"], (20, )) self.assertEqual(d["strides"], (2, )) self.assertEqual(d["data"], (snd._samples_address, False))
def test_get_raw(self): """Ensure get_raw returns the correct bytestring.""" try: samples = as_bytes("abcdefgh") # keep byte size a multiple of 4 snd = mixer.Sound(buffer=samples) raw = snd.get_raw() self.assertIsInstance(raw, bytes_) self.assertEqual(raw, samples) finally: pygame.mixer.quit() with self.assertRaisesRegex(pygame.error, "mixer not initialized"): snd.get_raw()
def test_array_interface(self): mixer.init(22050, -16, 1) try: snd = mixer.Sound(as_bytes('\x00\x7f') * 20) d = snd.__array_interface__ self.assertTrue(isinstance(d, dict)) if pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN: typestr = '<i2' else: typestr = '>i2' self.assertEqual(d['typestr'], typestr) self.assertEqual(d['shape'], (20,)) self.assertEqual(d['strides'], (2,)) self.assertEqual(d['data'], (snd._samples_address, False)) finally: mixer.quit()
def test_samples_address(self): """Test the _samples_address getter.""" from ctypes import pythonapi, c_void_p, py_object try: Bytes_FromString = pythonapi.PyBytes_FromString # python 3 except: Bytes_FromString = pythonapi.PyString_FromString # python 2 Bytes_FromString.restype = c_void_p Bytes_FromString.argtypes = [py_object] samples = as_bytes('abcdefgh') # keep byte size a multiple of 4 sample_bytes = Bytes_FromString(samples) snd = mixer.Sound(buffer=samples) self.assertNotEqual(snd._samples_address, sample_bytes)
def test_samples(self): null_byte = as_bytes("\x00") def check_sample(size, channels, test_data): try: pygame.mixer.init(22050, size, channels, allowedchanges=0) except pygame.error: # Not all sizes are supported on all systems. return try: __, sz, __ = pygame.mixer.get_init() if sz == size: zeroed = null_byte * ( (abs(size) // 8) * len(test_data) * channels) snd = pygame.mixer.Sound(buffer=zeroed) samples = pygame.sndarray.samples(snd) self._assert_compatible(samples, size) ##print ('X %s' % (samples.shape,)) ##print ('Y %s' % (test_data,)) samples[...] = test_data arr = pygame.sndarray.array(snd) self.assertTrue( alltrue(samples == arr), "size: %i\n%s\n%s" % (size, arr, test_data), ) finally: pygame.mixer.quit() check_sample(8, 1, [0, 0x0F, 0xF0, 0xFF]) check_sample(8, 2, [[0, 0x80], [0x2D, 0x41], [0x64, 0xA1], [0xFF, 0x40]]) check_sample(16, 1, [0, 0x00FF, 0xFF00, 0xFFFF]) check_sample( 16, 2, [[0, 0xFFFF], [0xFFFF, 0], [0x00FF, 0xFF00], [0x0F0F, 0xF0F0]]) check_sample(-8, 1, [0, -0x80, 0x7F, 0x64]) check_sample(-8, 2, [[0, -0x80], [-0x64, 0x64], [0x25, -0x50], [0xFF, 0]]) check_sample(-16, 1, [0, 0x7FFF, -0x7FFF, -1]) check_sample(-16, 2, [[0, -0x7FFF], [-0x7FFF, 0], [0x7FFF, 0], [0, 0x7FFF]]) if SDL2: check_sample(32, 2, [[0.0, -1.0], [-1.0, 0], [1.0, 0], [0, 1.0]])
def test_metrics(self): # Ensure bytes decoding works correctly. Can only compare results # with unicode for now. f = pygame_font.Font(None, 20); um = f.metrics(as_unicode(".")) bm = f.metrics(as_bytes(".")) self.assert_(len(um) == 1) self.assert_(len(bm) == 1) self.assert_(um[0] is not None) self.assert_(um == bm) u = as_unicode(r"\u212A") b = u.encode("UTF-16")[2:] # Keep byte order consistent. [2:] skips BOM bm = f.metrics(b) self.assert_(len(bm) == 2) try: um = f.metrics(u) except pygame.error: pass else: self.assert_(len(um) == 1) self.assert_(bm[0] != um[0]) self.assert_(bm[1] != um[0]) if UCS_4: u = as_unicode(r"\U00013000") bm = f.metrics(u) self.assert_(len(bm) == 1 and bm[0] is None) return # unfinished # The documentation is useless here. How large a list? # How do list positions relate to character codes? # What about unicode characters? # __doc__ (as of 2008-08-02) for pygame_font.Font.metrics: # Font.metrics(text): return list # Gets the metrics for each character in the pased string. # # The list contains tuples for each character, which contain the # minimum X offset, the maximum X offset, the minimum Y offset, the # maximum Y offset and the advance offset (bearing plus width) of the # character. [(minx, maxx, miny, maxy, advance), (minx, maxx, miny, # maxy, advance), ...] self.fail()
def test_get_raw_more(self): """ test the array interface a bit better. """ from ctypes import pythonapi, c_void_p, py_object try: Bytes_FromString = pythonapi.PyBytes_FromString except: Bytes_FromString = pythonapi.PyString_FromString Bytes_FromString.restype = c_void_p Bytes_FromString.argtypes = [py_object] mixer.init() samples = as_bytes('abcdefgh') # keep byte size a multiple of 4 snd = mixer.Sound(buffer=samples) raw = snd.get_raw() self.assertTrue(isinstance(raw, bytes_)) self.assertNotEqual(snd._samples_address, Bytes_FromString(samples)) self.assertEqual(raw, samples)
def test_samples(self): null_byte = as_bytes('\x00') def check_sample(size, channels, test_data): try: pygame.mixer.init(22050, size, channels) except pygame.error: # Not all sizes are supported on all systems. return try: __, sz, __ = pygame.mixer.get_init() if sz == size: zeroed = null_byte * ( (abs(size) // 8) * len(test_data) * channels) snd = pygame.mixer.Sound(buffer=zeroed) samples = pygame.sndarray.samples(snd) self._assert_compatible(samples, size) ##print ('X %s' % (samples.shape,)) ##print ('Y %s' % (test_data,)) samples[...] = test_data arr = pygame.sndarray.array(snd) self.failUnless( alltrue(samples == arr), "size: %i\n%s\n%s" % (size, arr, test_data)) finally: pygame.mixer.quit() check_sample(8, 1, [0, 0x0f, 0xf0, 0xff]) check_sample(8, 2, [[0, 0x80], [0x2D, 0x41], [0x64, 0xA1], [0xff, 0x40]]) check_sample(16, 1, [0, 0x00ff, 0xff00, 0xffff]) check_sample( 16, 2, [[0, 0xffff], [0xffff, 0], [0x00ff, 0xff00], [0x0f0f, 0xf0f0]]) check_sample(-8, 1, [0, -0x80, 0x7f, 0x64]) check_sample(-8, 2, [[0, -0x80], [-0x64, 0x64], [0x25, -0x50], [0xff, 0]]) check_sample(-16, 1, [0, 0x7fff, -0x7fff, -1]) check_sample(-16, 2, [[0, -0x7fff], [-0x7fff, 0], [0x7fff, 0], [0, 0x7fff]]) if pygame.get_sdl_version()[0] >= 2: check_sample(32, 2, [[0.0, -1.0], [-1.0, 0], [1.0, 0], [0, 1.0]])
def test_get_raw(self): from ctypes import pythonapi, c_void_p, py_object try: Bytes_FromString = pythonapi.PyBytes_FromString except: Bytes_FromString = pythonapi.PyString_FromString Bytes_FromString.restype = c_void_p Bytes_FromString.argtypes = [py_object] mixer.init() try: samples = as_bytes('abcdefgh') # keep byte size a multiple of 4 snd = mixer.Sound(buffer=samples) raw = snd.get_raw() self.assertTrue(isinstance(raw, bytes_)) self.assertNotEqual(snd._samples_address, Bytes_FromString(samples)) self.assertEqual(raw, samples) finally: mixer.quit()
def test_samples(self): if not arraytype: self.fail("no array package installed") null_byte = as_bytes('\x00') def check_sample(size, channels, test_data): try: pygame.mixer.init(22050, size, channels) except pygame.error: # Not all sizes are supported on all systems. return try: __, sz, __ = pygame.mixer.get_init() if sz == size: zeroed = null_byte * ((abs(size) // 8) * len(test_data) * channels) snd = pygame.mixer.Sound(buffer=zeroed) samples = pygame.sndarray.samples(snd) self._assert_compatible(samples, size) ##print ('X %s' % (samples.shape,)) ##print ('Y %s' % (test_data,)) samples[...] = test_data arr = pygame.sndarray.array(snd) self.failUnless(alltrue(samples == arr), "size: %i\n%s\n%s" % (size, arr, test_data)) finally: pygame.mixer.quit() check_sample(8, 1, [0, 0x0f, 0xf0, 0xff]) check_sample(8, 2, [[0, 0x80], [0x2D, 0x41], [0x64, 0xA1], [0xff, 0x40]]) check_sample(16, 1, [0, 0x00ff, 0xff00, 0xffff]) check_sample(16, 2, [[0, 0xffff], [0xffff, 0], [0x00ff, 0xff00], [0x0f0f, 0xf0f0]]) check_sample(-8, 1, [0, -0x80, 0x7f, 0x64]) check_sample(-8, 2, [[0, -0x80], [-0x64, 0x64], [0x25, -0x50], [0xff, 0]]) check_sample(-16, 1, [0, 0x7fff, -0x7fff, -1]) check_sample(-16, 2, [[0, -0x7fff], [-0x7fff, 0], [0x7fff, 0], [0, 0x7fff]])
def test_samples_address(self): """Test the _samples_address getter.""" try: from ctypes import pythonapi, c_void_p, py_object try: Bytes_FromString = pythonapi.PyBytes_FromString # python 3 except: Bytes_FromString = pythonapi.PyString_FromString # python 2 Bytes_FromString.restype = c_void_p Bytes_FromString.argtypes = [py_object] samples = as_bytes("abcdefgh") # keep byte size a multiple of 4 sample_bytes = Bytes_FromString(samples) snd = mixer.Sound(buffer=samples) self.assertNotEqual(snd._samples_address, sample_bytes) finally: pygame.mixer.quit() with self.assertRaisesRegex(pygame.error, "mixer not initialized"): snd._samples_address
class BufferProxyLegacyTest(unittest.TestCase): content = as_bytes('\x01\x00\x00\x02') * 12 buffer = ctypes.create_string_buffer(content) data = (ctypes.addressof(buffer), True) 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) 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') 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()
def test_get_BytesIO(self): BytesIO = compat.get_BytesIO() b1 = compat.as_bytes("\x00\xffabc") b2 = BytesIO(b1).read() self.failUnless(isinstance(b2, compat.bytes_)) self.failUnlessEqual(b2, b1)
def test_put (self): scrap.put ("arbitrary buffer", as_bytes("buf")) r = scrap.get ("arbitrary buffer") self.assertEquals (r, as_bytes("buf"))
def test_path_with_null_bytes(self): b = as_bytes("a\x00b\x00c") self.assert_(encode_file_path(b) is None)
def test_etype(self): b = as_bytes("a\x00b\x00c") self.assertRaises(TypeError, encode_file_path, b, TypeError)
def test_smp(self): utf_8 = as_bytes("a\xF0\x93\x82\xA7b") u = as_unicode(r"a\U000130A7b") b = encode_string(u, 'utf-8', 'strict', AssertionError) self.assertEqual(b, utf_8)
def test_string_with_null_bytes(self): b = as_bytes("a\x00b\x00c") self.assert_(encode_string(b, etype=SyntaxError) is b) u = b.decode() self.assert_(encode_string(u, 'ascii', 'strict') == b)
def test_obj_bytes(self): b = as_bytes("encyclop\xE6dia") self.assert_(encode_string(b, 'ascii', 'strict') is b)
class Font(_Font): """Font(filename, size) -> Font Font(object, size) -> Font create a new Font object from a file (freetype alternative) This Font type differs from font.Font in that it can render glyphs for Unicode code points in the supplementary planes (> 0xFFFF). """ __encode_file_path = staticmethod(encode_file_path) __get_default_resolution = staticmethod(get_default_resolution) __default_font = encode_file_path(get_default_font()) __unull = as_unicode(r"\x00") __bnull = as_bytes("\x00") def __init__(self, file, size=-1): if size <= 1: size = 1 if isinstance(file, unicode_): try: bfile = self.__encode_file_path(file, ValueError) except ValueError: bfile = '' else: bfile = file if isinstance(bfile, bytes_) and bfile == self.__default_font: file = None if file is None: resolution = int(self.__get_default_resolution() * 0.6875) if resolution == 0: resolution = 1 else: resolution = 0 super(Font, self).__init__(file, size=size, resolution=resolution) self.strength = 1.0 / 12.0 self.kerning = False self.origin = True self.pad = True self.ucs4 = True self.underline_adjustment = 1.0 def render(self, text, antialias, color, background=None): """render(text, antialias, color, background=None) -> Surface draw text on a new Surface""" if text is None: text = "" if (isinstance(text, unicode_) and self.__unull in text): raise ValueError("A null character was found in the text") if (isinstance(text, bytes_) and self.__bnull in text): raise ValueError("A null character was found in the text") save_antialiased = self.antialiased self.antialiased = bool(antialias) try: s, r = super(Font, self).render(text, color, background) return s finally: self.antialiased = save_antialiased def set_bold(self, value): """set_bold(bool) -> None enable fake rendering of bold text""" self.wide = bool(value) def get_bold(self): """get_bold() -> bool check if text will be rendered bold""" return self.wide bold = property(get_bold, set_bold) def set_italic(self, value): """set_italic(bool) -> None enable fake rendering of italic text""" self.oblique = bool(value) def get_italic(self): """get_italic() -> bool check if the text will be rendered italic""" return self.oblique italic = property(get_italic, set_italic) def set_underline(self, value): """set_underline(bool) -> None control if text is rendered with an underline""" self.underline = bool(value) def get_underline(self): """set_bold(bool) -> None enable fake rendering of bold text""" return self.underline def metrics(self, text): """metrics(text) -> list Gets the metrics for each character in the passed string.""" return self.get_metrics(text) def get_ascent(self): """get_ascent() -> int get the ascent of the font""" return self.get_sized_ascender() def get_descent(self): """get_descent() -> int get the descent of the font""" return self.get_sized_descender() def get_height(self): """get_height() -> int get the height of the font""" return self.get_sized_ascender() - self.get_sized_descender() + 1 def get_linesize(self): """get_linesize() -> int get the line space of the font text""" return self.get_sized_height() def size(self, text): """size(text) -> (width, height) determine the amount of space needed to render text""" return self.get_rect(text).size
print ("Type %s : None" % (t,)) else: print ("Type %s : '%s'" % (t, r.decode('ascii', 'ignore'))) if "image" in t: namehint = t.split("/")[1] if namehint in ['bmp', 'png', 'jpg']: f = BytesIO(r) loaded_surf = pygame.image.load(f, "." + namehint) screen.blit(loaded_surf, (0,0)) elif e.type == KEYDOWN and e.key == K_p: # Place some text into the selection. print ("Placing clipboard text.") scrap.put (SCRAP_TEXT, as_bytes("Hello. This is a message from scrap.")) elif e.type == KEYDOWN and e.key == K_a: # Get all available types. print ("Getting the available types from the clipboard.") types = scrap.get_types () print (types) if len (types) > 0: print ("Contains %s: %s" % (types[0], scrap.contains (types[0]))) print ("Contains _INVALID_: ", scrap.contains ("_INVALID_")) elif e.type == KEYDOWN and e.key == K_i: print ("Putting image into the clipboard.") scrap.set_mode (SCRAP_CLIPBOARD) fp = open (os.path.join(main_dir, 'data', 'liquid.bmp'), 'rb')
def test_sound_args(self): def get_bytes(snd): return snd.get_buffer().raw mixer.init() try: sample = as_bytes('\x00\xff') * 24 wave_path = example_path(os.path.join('data', 'house_lo.wav')) uwave_path = unicode_(wave_path) bwave_path = uwave_path.encode(sys.getfilesystemencoding()) snd = mixer.Sound(file=wave_path) self.assert_(snd.get_length() > 0.5) snd_bytes = get_bytes(snd) self.assert_(len(snd_bytes) > 1000) self.assert_(get_bytes(mixer.Sound(wave_path)) == snd_bytes) self.assert_(get_bytes(mixer.Sound(file=uwave_path)) == snd_bytes) self.assert_(get_bytes(mixer.Sound(uwave_path)) == snd_bytes) arg_emsg = 'Sound takes either 1 positional or 1 keyword argument' try: mixer.Sound() except TypeError: self.assertEqual(str(geterror()), arg_emsg) else: self.fail("no exception") try: mixer.Sound(wave_path, buffer=sample) except TypeError: self.assertEqual(str(geterror()), arg_emsg) else: self.fail("no exception") try: mixer.Sound(sample, file=wave_path) except TypeError: self.assertEqual(str(geterror()), arg_emsg) else: self.fail("no exception") try: mixer.Sound(buffer=sample, file=wave_path) except TypeError: self.assertEqual(str(geterror()), arg_emsg) else: self.fail("no exception") try: mixer.Sound(foobar=sample) except TypeError: emsg = "Unrecognized keyword argument 'foobar'" self.assertEqual(str(geterror()), emsg) else: self.fail("no exception") snd = mixer.Sound(wave_path, **{}) self.assertEqual(get_bytes(snd), snd_bytes) snd = mixer.Sound(*[], **{'file': wave_path}) try: snd = mixer.Sound([]) except TypeError: emsg = 'Unrecognized argument (type list)' self.assertEqual(str(geterror()), emsg) else: self.fail("no exception") try: snd = mixer.Sound(buffer=[]) except TypeError: emsg = 'Expected object with buffer interface: got a list' self.assertEqual(str(geterror()), emsg) else: self.fail("no exception") ufake_path = unicode_('12345678') self.assertRaises(pygame.error, mixer.Sound, ufake_path) try: mixer.Sound(buffer=unicode_('something')) except TypeError: emsg = 'Unicode object not allowed as buffer object' self.assertEqual(str(geterror()), emsg) else: self.fail("no exception") self.assertEqual(get_bytes(mixer.Sound(buffer=sample)), sample) self.assertEqual(get_bytes(mixer.Sound(sample)), sample) self.assertEqual(get_bytes(mixer.Sound(file=bwave_path)), snd_bytes) self.assertEqual(get_bytes(mixer.Sound(bwave_path)), snd_bytes) snd = mixer.Sound(wave_path) try: mixer.Sound(wave_path, array=snd) except TypeError: self.assertEqual(str(geterror()), arg_emsg) else: self.fail("no exception") try: mixer.Sound(buffer=sample, array=snd) except TypeError: self.assertEqual(str(geterror()), arg_emsg) else: self.fail("no exception") snd2 = mixer.Sound(array=snd) self.assertEqual(snd.get_buffer().raw, snd2.get_buffer().raw) finally: mixer.quit()
def test_put(self): scrap.put("arbitrary buffer", as_bytes("buf")) r = scrap.get("arbitrary buffer") self.assertEquals(r, as_bytes("buf"))
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)