This commit is contained in:
Nielson Tschá
2021-03-16 13:35:01 +01:00
commit a0f3d0edd7
898 changed files with 196589 additions and 0 deletions
@@ -0,0 +1,40 @@
"""Pygame unit test suite package
Exports function run()
A quick way to run the test suite package from the command line
is by importing the go submodule:
python -m "import pygame.tests" [<test options>]
Command line option --help displays a usage message. Available options
correspond to the pygame.tests.run arguments.
The xxxx_test submodules of the tests package are unit test suites for
individual parts of Pygame. Each can also be run as a main program. This is
useful if the test, such as cdrom_test, is interactive.
For Pygame development the test suite can be run from a Pygame distribution
root directory using run_tests.py. Alternately, test/__main__.py can be run
directly.
"""
if __name__ == "pygame.tests":
from pygame.tests.test_utils.run_tests import run
elif __name__ == "__main__":
import os
import sys
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
if is_pygame_pkg:
import pygame.tests.__main__
else:
import test.__main__
else:
from test.test_utils.run_tests import run
@@ -0,0 +1,144 @@
"""Load and run the Pygame test suite
python -c "import pygame.tests.go" [<test options>]
or
python test/go.py [<test options>]
Command line option --help displays a command line usage message.
run_tests.py in the main distribution directory is an alternative to test.go
"""
import sys
if __name__ == "__main__":
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
if is_pygame_pkg:
from pygame.tests.test_utils.run_tests import run_and_exit
from pygame.tests.test_utils.test_runner import opt_parser
else:
from test.test_utils.run_tests import run_and_exit
from test.test_utils.test_runner import opt_parser
if is_pygame_pkg:
test_pkg_name = "pygame.tests"
else:
test_pkg_name = "test"
program_name = sys.argv[0]
if program_name == "-c":
program_name = 'python -c "import %s.go"' % test_pkg_name
###########################################################################
# Set additional command line options
#
# Defined in test_runner.py as it shares options, added to here
opt_parser.set_usage(
"""
Runs all or some of the %(pkg)s.xxxx_test tests.
$ %(exec)s sprite threads -sd
Runs the sprite and threads module tests isolated in subprocesses, dumping
all failing tests info in the form of a dict.
"""
% {"pkg": test_pkg_name, "exec": program_name}
)
opt_parser.add_option(
"-d", "--dump", action="store_true", help="dump results as dict ready to eval"
)
opt_parser.add_option("-F", "--file", help="dump results to a file")
opt_parser.add_option(
"-m",
"--multi_thread",
metavar="THREADS",
type="int",
help="run subprocessed tests in x THREADS",
)
opt_parser.add_option(
"-t",
"--time_out",
metavar="SECONDS",
type="int",
help="kill stalled subprocessed tests after SECONDS",
)
opt_parser.add_option(
"-f", "--fake", metavar="DIR", help="run fake tests in run_tests__tests/$DIR"
)
opt_parser.add_option(
"-p",
"--python",
metavar="PYTHON",
help="path to python excutable to run subproccesed tests\n"
"default (sys.executable): %s" % sys.executable,
)
opt_parser.add_option(
"-I",
"--interactive",
action="store_true",
help="include tests requiring user input",
)
opt_parser.add_option("-S", "--seed", type="int", help="Randomisation seed")
###########################################################################
# Set run() keyword arguements according to command line arguemnts.
# args will be the test module list, passed as positional argumemts.
options, args = opt_parser.parse_args()
kwds = {}
if options.incomplete:
kwds["incomplete"] = True
if options.usesubprocess:
kwds["usesubprocess"] = True
else:
kwds["usesubprocess"] = False
if options.dump:
kwds["dump"] = True
if options.file:
kwds["file"] = options.file
if options.exclude:
kwds["exclude"] = options.exclude
if options.unbuffered:
kwds["unbuffered"] = True
if options.randomize:
kwds["randomize"] = True
if options.seed is not None:
kwds["seed"] = options.seed
if options.multi_thread is not None:
kwds["multi_thread"] = options.multi_thread
if options.time_out is not None:
kwds["time_out"] = options.time_out
if options.fake:
kwds["fake"] = options.fake
if options.python:
kwds["python"] = options.python
if options.interactive:
kwds["interactive"] = True
kwds["verbosity"] = options.verbosity if options.verbosity is not None else 1
###########################################################################
# Run the test suite.
run_and_exit(*args, **kwds)
@@ -0,0 +1,664 @@
# -*- coding: utf8 -*-
import sys
import unittest
import platform
IS_PYPY = "PyPy" == platform.python_implementation()
try:
from pygame.tests.test_utils import arrinter
except NameError:
pass
import pygame
init_called = quit_called = 0
def __PYGAMEinit__(): # called automatically by pygame.init()
global init_called
init_called = init_called + 1
pygame.register_quit(pygame_quit)
# Returning False indicates that the initialization has failed. It is
# purposely done here to test that failing modules are reported.
return False
def pygame_quit():
global quit_called
quit_called = quit_called + 1
quit_hook_ran = 0
def quit_hook():
global quit_hook_ran
quit_hook_ran = 1
class BaseModuleTest(unittest.TestCase):
def tearDown(self):
# Clean up after each test method.
pygame.quit()
def testAutoInit(self):
pygame.init()
pygame.quit()
self.assertEqual(init_called, 1)
self.assertEqual(quit_called, 1)
def test_get_sdl_byteorder(self):
"""Ensure the SDL byte order is valid"""
byte_order = pygame.get_sdl_byteorder()
expected_options = (pygame.LIL_ENDIAN, pygame.BIG_ENDIAN)
self.assertIn(byte_order, expected_options)
def test_get_sdl_version(self):
"""Ensure the SDL version is valid"""
self.assertEqual(len(pygame.get_sdl_version()), 3)
class ExporterBase(object):
def __init__(self, shape, typechar, itemsize):
import ctypes
ndim = len(shape)
self.ndim = ndim
self.shape = tuple(shape)
array_len = 1
for d in shape:
array_len *= d
self.size = itemsize * array_len
self.parent = ctypes.create_string_buffer(self.size)
self.itemsize = itemsize
strides = [itemsize] * ndim
for i in range(ndim - 1, 0, -1):
strides[i - 1] = strides[i] * shape[i]
self.strides = tuple(strides)
self.data = ctypes.addressof(self.parent), False
if self.itemsize == 1:
byteorder = "|"
elif sys.byteorder == "big":
byteorder = ">"
else:
byteorder = "<"
self.typestr = byteorder + typechar + str(self.itemsize)
def assertSame(self, proxy, obj):
self.assertEqual(proxy.length, obj.size)
iface = proxy.__array_interface__
self.assertEqual(iface["typestr"], obj.typestr)
self.assertEqual(iface["shape"], obj.shape)
self.assertEqual(iface["strides"], obj.strides)
self.assertEqual(iface["data"], obj.data)
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())
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)
if pygame.HAVE_NEWBUF:
from pygame.tests.test_utils import buftools
def NEWBUF_assertSame(self, proxy, exp):
buftools = self.buftools
Importer = buftools.Importer
self.assertEqual(proxy.length, exp.len)
imp = Importer(proxy, buftools.PyBUF_RECORDS_RO)
self.assertEqual(imp.readonly, exp.readonly)
self.assertEqual(imp.format, exp.format)
self.assertEqual(imp.itemsize, exp.itemsize)
self.assertEqual(imp.ndim, exp.ndim)
self.assertEqual(imp.shape, exp.shape)
self.assertEqual(imp.strides, exp.strides)
self.assertTrue(imp.suboffsets is None)
@unittest.skipIf(not pygame.HAVE_NEWBUF, "newbuf not implemented")
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)
@unittest.skipIf(not pygame.HAVE_NEWBUF, "newbuf not implemented")
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)
@unittest.skipIf(not pygame.HAVE_NEWBUF, "newbuf not implemented")
def 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)
@unittest.skipIf(IS_PYPY or (not pygame.HAVE_NEWBUF), "newbuf with ctypes")
def 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)
def test_PgObject_GetBuffer_exception(self):
# For consistency with surfarray
from pygame.bufferproxy import BufferProxy
bp = BufferProxy(1)
self.assertRaises(ValueError, getattr, bp, "length")
def not_init_assertions(self):
self.assertFalse(pygame.get_init(), "pygame shouldn't be initialized")
self.assertFalse(pygame.display.get_init(), "display shouldn't be initialized")
if "pygame.mixer" in sys.modules:
self.assertFalse(pygame.mixer.get_init(), "mixer shouldn't be initialized")
if "pygame.font" in sys.modules:
self.assertFalse(pygame.font.get_init(), "init shouldn't be initialized")
## !!! TODO : Remove when scrap works for OS X
import platform
if platform.system().startswith("Darwin"):
return
try:
self.assertRaises(pygame.error, pygame.scrap.get)
except NotImplementedError:
# Scrap is optional.
pass
# pygame.cdrom
# pygame.joystick
def init_assertions(self):
self.assertTrue(pygame.get_init())
self.assertTrue(pygame.display.get_init())
if "pygame.mixer" in sys.modules:
self.assertTrue(pygame.mixer.get_init())
if "pygame.font" in sys.modules:
self.assertTrue(pygame.font.get_init())
def test_quit__and_init(self):
# __doc__ (as of 2008-06-25) for pygame.base.quit:
# pygame.quit(): return None
# uninitialize all pygame modules
# Make sure everything is not init
self.not_init_assertions()
# Initiate it
pygame.init()
# Check
self.init_assertions()
# Quit
pygame.quit()
# All modules have quit
self.not_init_assertions()
def test_register_quit(self):
"""Ensure that a registered function is called on quit()"""
self.assertFalse(quit_hook_ran)
pygame.init()
pygame.register_quit(quit_hook)
pygame.quit()
self.assertTrue(quit_hook_ran)
def test_get_error(self):
# __doc__ (as of 2008-08-02) for pygame.base.get_error:
# pygame.get_error(): return errorstr
# get the current error message
#
# SDL maintains an internal error message. This message will usually
# be given to you when pygame.error is raised. You will rarely need to
# call this function.
#
# The first error could be all sorts of nonsense or empty.
e = pygame.get_error()
pygame.set_error("hi")
self.assertEqual(pygame.get_error(), "hi")
pygame.set_error("")
self.assertEqual(pygame.get_error(), "")
def test_set_error(self):
# The first error could be all sorts of nonsense or empty.
e = pygame.get_error()
pygame.set_error("hi")
self.assertEqual(pygame.get_error(), "hi")
pygame.set_error("")
self.assertEqual(pygame.get_error(), "")
def test_unicode_error(self):
if sys.version_info.major > 2:
pygame.set_error(u"你好")
self.assertEqual(u"你好", pygame.get_error())
else:
# no unicode objects for now
pygame.set_error(u"你好")
encstr = u"你好".encode("utf8")
self.assertEqual(encstr, pygame.get_error())
def test_init(self):
"""Ensures init() works properly."""
# Make sure nothing initialized.
self.not_init_assertions()
# The exact number of modules can change, but it should never be < 0.
expected_min_passes = 0
# The __PYGAMEinit__ function in this module returns False, so this
# should give a fail count of 1. All other modules should pass.
expected_fails = 1
passes, fails = pygame.init()
self.init_assertions()
self.assertGreaterEqual(passes, expected_min_passes)
self.assertEqual(fails, expected_fails)
def test_get_init(self):
# Test if get_init() gets the init state.
self.assertFalse(pygame.get_init())
def test_get_init__after_init(self):
# Test if get_init() gets the init state after pygame.init() called.
pygame.init()
self.assertTrue(pygame.get_init())
def test_get_init__after_quit(self):
# Test if get_init() gets the init state after pygame.quit() called.
pygame.init()
pygame.quit()
self.assertFalse(pygame.get_init())
def todo_test_segfault(self):
# __doc__ (as of 2008-08-02) for pygame.base.segfault:
# crash
self.fail()
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,157 @@
import unittest
import pygame
from pygame.locals import *
class BlitTest(unittest.TestCase):
def test_SRCALPHA(self):
""" SRCALPHA tests.
"""
# blend(s, 0, d) = d
s = pygame.Surface((1, 1), SRCALPHA, 32)
s.fill((255, 255, 255, 0))
d = pygame.Surface((1, 1), SRCALPHA, 32)
d.fill((0, 0, 255, 255))
s.blit(d, (0, 0))
self.assertEqual(s.get_at((0, 0)), d.get_at((0, 0)))
# blend(s, 255, d) = s
s = pygame.Surface((1, 1), SRCALPHA, 32)
s.fill((123, 0, 0, 255))
s1 = pygame.Surface((1, 1), SRCALPHA, 32)
s1.fill((123, 0, 0, 255))
d = pygame.Surface((1, 1), SRCALPHA, 32)
d.fill((10, 0, 0, 0))
s.blit(d, (0, 0))
self.assertEqual(s.get_at((0, 0)), s1.get_at((0, 0)))
# TODO: these should be true too.
# blend(0, sA, 0) = 0
# blend(255, sA, 255) = 255
# blend(s, sA, d) <= 255
def test_BLEND(self):
""" BLEND_ tests.
"""
# test that it doesn't overflow, and that it is saturated.
s = pygame.Surface((1, 1), SRCALPHA, 32)
s.fill((255, 255, 255, 0))
d = pygame.Surface((1, 1), SRCALPHA, 32)
d.fill((0, 0, 255, 255))
s.blit(d, (0, 0), None, BLEND_ADD)
# print "d %s" % (d.get_at((0,0)),)
# print s.get_at((0,0))
# self.assertEqual(s.get_at((0,0))[2], 255 )
# self.assertEqual(s.get_at((0,0))[3], 0 )
s.blit(d, (0, 0), None, BLEND_RGBA_ADD)
# print s.get_at((0,0))
self.assertEqual(s.get_at((0, 0))[3], 255)
# test adding works.
s.fill((20, 255, 255, 0))
d.fill((10, 0, 255, 255))
s.blit(d, (0, 0), None, BLEND_ADD)
self.assertEqual(s.get_at((0, 0))[2], 255)
# test subbing works.
s.fill((20, 255, 255, 0))
d.fill((10, 0, 255, 255))
s.blit(d, (0, 0), None, BLEND_SUB)
self.assertEqual(s.get_at((0, 0))[0], 10)
# no overflow in sub blend.
s.fill((20, 255, 255, 0))
d.fill((30, 0, 255, 255))
s.blit(d, (0, 0), None, BLEND_SUB)
self.assertEqual(s.get_at((0, 0))[0], 0)
def make_blit_list(self, num_surfs):
blit_list = []
for i in range(num_surfs):
dest = (i * 10, 0)
surf = pygame.Surface((10, 10), SRCALPHA, 32)
color = (i * 1, i * 1, i * 1)
surf.fill(color)
blit_list.append((surf, dest))
return blit_list
def test_blits(self):
NUM_SURFS = 255
PRINT_TIMING = 0
dst = pygame.Surface((NUM_SURFS * 10, 10), SRCALPHA, 32)
dst.fill((230, 230, 230))
blit_list = self.make_blit_list(NUM_SURFS)
def blits(blit_list):
for surface, dest in blit_list:
dst.blit(surface, dest)
from time import time
t0 = time()
results = blits(blit_list)
t1 = time()
if PRINT_TIMING:
print("python blits: %s" % (t1 - t0))
dst.fill((230, 230, 230))
t0 = time()
results = dst.blits(blit_list)
t1 = time()
if PRINT_TIMING:
print("Surface.blits :%s" % (t1 - t0))
# check if we blit all the different colors in the correct spots.
for i in range(NUM_SURFS):
color = (i * 1, i * 1, i * 1)
self.assertEqual(dst.get_at((i * 10, 0)), color)
self.assertEqual(dst.get_at(((i * 10) + 5, 5)), color)
self.assertEqual(len(results), NUM_SURFS)
t0 = time()
results = dst.blits(blit_list, doreturn=0)
t1 = time()
if PRINT_TIMING:
print("Surface.blits doreturn=0: %s" % (t1 - t0))
self.assertEqual(results, None)
t0 = time()
results = dst.blits(((surf, dest) for surf, dest in blit_list))
t1 = time()
if PRINT_TIMING:
print("Surface.blits generator: %s" % (t1 - t0))
def test_blits_not_sequence(self):
dst = pygame.Surface((100, 10), SRCALPHA, 32)
self.assertRaises(ValueError, dst.blits, None)
def test_blits_wrong_length(self):
dst = pygame.Surface((100, 10), SRCALPHA, 32)
self.assertRaises(
ValueError, dst.blits, [pygame.Surface((10, 10), SRCALPHA, 32)]
)
def test_blits_bad_surf_args(self):
dst = pygame.Surface((100, 10), SRCALPHA, 32)
self.assertRaises(TypeError, dst.blits, [(None, None)])
def test_blits_bad_dest(self):
dst = pygame.Surface((100, 10), SRCALPHA, 32)
self.assertRaises(
TypeError, dst.blits, [(pygame.Surface((10, 10), SRCALPHA, 32), None)]
)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,509 @@
import sys
import re
import weakref
import gc
import ctypes
import unittest
import pygame
from pygame.bufferproxy import BufferProxy
from pygame.compat import as_bytes
try:
BufferError
except NameError:
from pygame import BufferError
class BufferProxyTest(unittest.TestCase):
view_keywords = {
"shape": (5, 4, 3),
"typestr": "|u1",
"data": (0, True),
"strides": (4, 20, 1),
}
def test_module_name(self):
self.assertEqual(pygame.bufferproxy.__name__, "pygame.bufferproxy")
def test_class_name(self):
self.assertEqual(BufferProxy.__name__, "BufferProxy")
def test___array_struct___property(self):
kwds = self.view_keywords
v = BufferProxy(kwds)
d = pygame.get_array_interface(v)
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"])
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"])
def test_parent_property(self):
kwds = dict(self.view_keywords)
p = []
kwds["parent"] = p
v = BufferProxy(kwds)
self.assertIs(v.parent, p)
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__)
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])
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")
def test_weakref(self):
v = BufferProxy(self.view_keywords)
weak_v = weakref.ref(v)
self.assertIs(weak_v(), v)
v = None
gc.collect()
self.assertIsNone(weak_v())
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)
def test_c_api(self):
api = pygame.bufferproxy._PYGAME_C_API
api_type = type(pygame.base._PYGAME_C_API)
self.assertIsInstance(api, api_type)
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))
def test_subclassing(self):
class MyBufferProxy(BufferProxy):
def __repr__(self):
return "*%s*" % (BufferProxy.__repr__(self),)
kwds = dict(self.view_keywords)
kwds["parent"] = 0
v = MyBufferProxy(kwds)
self.assertEqual(v.parent, 0)
r = repr(v)
self.assertEqual(r[:2], "*<")
self.assertEqual(r[-2:], ">*")
@unittest.skipIf(not pygame.HAVE_NEWBUF, "newbuf not implemented")
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)
try:
pygame.bufferproxy.get_segcount
except AttributeError:
pass
else:
def test_oldbuf_arg(self):
self.OLDBUF_test_oldbuf_arg()
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)
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()
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,9 @@
import unittest
import math
import pygame
from pygame.compat import long_
class CameraModuleTest(unittest.TestCase):
pass
@@ -0,0 +1 @@
__tags__ = ["interactive", "SDL2_ignore"]
@@ -0,0 +1,321 @@
import unittest
from pygame.tests.test_utils import question, prompt
import pygame
pygame.cdrom.init()
# The number of CD drives available for testing.
CD_DRIVE_COUNT = pygame.cdrom.get_count()
pygame.cdrom.quit()
class CDROMModuleTest(unittest.TestCase):
def setUp(self):
pygame.cdrom.init()
def tearDown(self):
pygame.cdrom.quit()
def todo_test_CD(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD:
# pygame.cdrom.CD(id): return CD
# class to manage a cdrom drive
#
# You can create a CD object for each cdrom on the system. Use
# pygame.cdrom.get_count() to determine how many drives actually
# exist. The id argument is an integer of the drive, starting at zero.
#
# The CD object is not initialized, you can only call CD.get_id() and
# CD.get_name() on an uninitialized drive.
#
# It is safe to create multiple CD objects for the same drive, they
# will all cooperate normally.
#
self.fail()
def test_get_count(self):
"""Ensure the correct number of CD drives can be detected."""
count = pygame.cdrom.get_count()
response = question(
"Is the correct number of CD drives on this " "system [{}]?".format(count)
)
self.assertTrue(response)
def test_get_init(self):
"""Ensure the initialization state can be retrieved."""
self.assertTrue(pygame.cdrom.get_init())
def test_init(self):
"""Ensure module still initialized after multiple init() calls."""
pygame.cdrom.init()
pygame.cdrom.init()
self.assertTrue(pygame.cdrom.get_init())
def test_quit(self):
"""Ensure module not initialized after quit() called."""
pygame.cdrom.quit()
self.assertFalse(pygame.cdrom.get_init())
def test_quit__multiple(self):
"""Ensure module still not initialized after multiple quit() calls."""
pygame.cdrom.quit()
pygame.cdrom.quit()
self.assertFalse(pygame.cdrom.get_init())
@unittest.skipIf(0 == CD_DRIVE_COUNT, "No CD drives detected")
class CDTypeTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
pygame.cdrom.init()
cls._cd_id = 0 # Only testing drive 0 for now. Expand in the future.
cls._cd = pygame.cdrom.CD(cls._cd_id)
@classmethod
def tearDownClass(cls):
pygame.cdrom.quit()
def setUp(self):
self._cd.init()
def tearDown(self):
self._cd.quit()
def test_eject(self):
"""Ensure CD drive opens/ejects."""
self._cd.eject()
response = question("Did the CD eject?")
self.assertTrue(response)
prompt("Please close the CD drive")
def test_get_name(self):
"""Ensure correct name for CD drive."""
cd_name = self._cd.get_name()
response = question(
"Is the correct name for the CD drive [{}]?" "".format(cd_name)
)
self.assertTrue(response)
def todo_test_get_all(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.get_all:
# CD.get_all(): return [(audio, start, end, lenth), ...]
# get all track information
#
# Return a list with information for every track on the cdrom. The
# information consists of a tuple with four values. The audio value is
# True if the track contains audio data. The start, end, and length
# values are floating point numbers in seconds. Start and end
# represent absolute times on the entire disc.
#
self.fail()
def todo_test_get_busy(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.get_busy:
# CD.get_busy(): return bool
# true if the drive is playing audio
#
# Returns True if the drive busy playing back audio.
self.fail()
def todo_test_get_current(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.get_current:
# CD.get_current(): return track, seconds
# the current audio playback position
#
# Returns both the current track and time of that track. This method
# works when the drive is either playing or paused.
#
# Note, track 0 is the first track on the CD. Track numbers start at zero.
self.fail()
def test_get_empty(self):
"""Ensure correct name for CD drive."""
prompt("Please ensure the CD drive is closed")
is_empty = self._cd.get_empty()
response = question("Is the CD drive empty?")
self.assertEqual(is_empty, response)
def test_get_id(self):
"""Ensure the drive id/index is correct."""
cd_id = self._cd.get_id()
self.assertEqual(self._cd_id, cd_id)
def test_get_init(self):
"""Ensure the initialization state can be retrieved."""
self.assertTrue(self._cd.get_init())
def todo_test_get_numtracks(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.get_numtracks:
# CD.get_numtracks(): return count
# the number of tracks on the cdrom
#
# Return the number of tracks on the cdrom in the drive. This will
# return zero of the drive is empty or has no tracks.
#
self.fail()
def todo_test_get_paused(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.get_paused:
# CD.get_paused(): return bool
# true if the drive is paused
#
# Returns True if the drive is currently paused.
self.fail()
def todo_test_get_track_audio(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.get_track_audio:
# CD.get_track_audio(track): return bool
# true if the cdrom track has audio data
#
# Determine if a track on a cdrom contains audio data. You can also
# call CD.num_tracks() and CD.get_all() to determine more information
# about the cdrom.
#
# Note, track 0 is the first track on the CD. Track numbers start at zero.
self.fail()
def todo_test_get_track_length(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.get_track_length:
# CD.get_track_length(track): return seconds
# length of a cdrom track
#
# Return a floating point value in seconds of the length of the cdrom track.
# Note, track 0 is the first track on the CD. Track numbers start at zero.
self.fail()
def todo_test_get_track_start(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.get_track_start:
# CD.get_track_start(track): return seconds
# start time of a cdrom track
#
# Return the absolute time in seconds where at start of the cdrom track.
# Note, track 0 is the first track on the CD. Track numbers start at zero.
self.fail()
def test_init(self):
"""Ensure CD drive still initialized after multiple init() calls."""
self._cd.init()
self._cd.init()
self.assertTrue(self._cd.get_init())
def todo_test_pause(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.pause:
# CD.pause(): return None
# temporarily stop audio playback
#
# Temporarily stop audio playback on the CD. The playback can be
# resumed at the same point with the CD.resume() method. If the CD is
# not playing this method does nothing.
#
# Note, track 0 is the first track on the CD. Track numbers start at zero.
self.fail()
def todo_test_play(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.play:
# CD.init(): return None
# initialize a cdrom drive for use
#
# Playback audio from an audio cdrom in the drive. Besides the track
# number argument, you can also pass a starting and ending time for
# playback. The start and end time are in seconds, and can limit the
# section of an audio track played.
#
# If you pass a start time but no end, the audio will play to the end
# of the track. If you pass a start time and 'None' for the end time,
# the audio will play to the end of the entire disc.
#
# See the CD.get_numtracks() and CD.get_track_audio() to find tracks to playback.
# Note, track 0 is the first track on the CD. Track numbers start at zero.
self.fail()
def test_quit(self):
"""Ensure CD drive not initialized after quit() called."""
self._cd.quit()
self.assertFalse(self._cd.get_init())
def test_quit__multiple(self):
"""Ensure CD drive still not initialized after multiple quit() calls.
"""
self._cd.quit()
self._cd.quit()
self.assertFalse(self._cd.get_init())
def todo_test_resume(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.resume:
# CD.resume(): return None
# unpause audio playback
#
# Unpause a paused CD. If the CD is not paused or already playing,
# this method does nothing.
#
self.fail()
def todo_test_stop(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.stop:
# CD.stop(): return None
# stop audio playback
#
# Stops playback of audio from the cdrom. This will also lose the
# current playback position. This method does nothing if the drive
# isn't already playing audio.
#
self.fail()
################################################################################
if __name__ == "__main__":
unittest.main()
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,89 @@
import sys
import unittest
from pygame import compat
encode_file_path = sys.modules["pygame.rwobject"].encode_file_path
class CompatModuleTest(unittest.TestCase):
def test_as_unicode(self):
r = r"Bo\u00F6tes"
ords = [ord("B"), ord("o"), 0xF6, ord("t"), ord("e"), ord("s")]
self.assertEqual(len(r), 11)
u = compat.as_unicode(r)
self.assertIsInstance(u, compat.unicode_)
self.assertEqual([ord(c) for c in u], ords)
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_ord_(self):
self.assertIsInstance(compat.ord_(compat.bytes_(1)[0]), int)
def test_bytes_(self):
self.assertFalse(compat.bytes_ is compat.unicode_)
self.assertTrue(hasattr(compat.bytes_, "capitalize"))
self.assertFalse(hasattr(compat.bytes_, "isdecimal"))
def test_unicode_(self):
self.assertTrue(hasattr(compat.unicode_(), "isdecimal"))
def test_long_(self):
self.assertIsInstance(int("99999999999999999999"), compat.long_)
def test_geterror(self):
msg = "Success"
try:
raise TypeError(msg)
except TypeError:
e = compat.geterror()
self.assertIsInstance(e, TypeError)
self.assertEqual(str(e), msg)
def test_xrange_(self):
self.assertFalse(isinstance(compat.xrange_(2), list))
def test_unichr_(self):
ordval = 86
c = compat.unichr_(ordval)
self.assertIsInstance(c, compat.unicode_)
self.assertEqual(ord(c), ordval)
def test_get_BytesIO(self):
BytesIO = compat.get_BytesIO()
b1 = compat.as_bytes("\x00\xffabc")
b2 = BytesIO(b1).read()
self.assertIsInstance(b2, compat.bytes_)
self.assertEqual(b2, b1)
def test_get_StringIO(self):
StringIO = compat.get_StringIO()
b1 = "abcde"
b2 = StringIO(b1).read()
self.assertIsInstance(b2, str)
self.assertEqual(b2, b1)
def test_raw_input_(self):
StringIO = compat.get_StringIO()
msg = "success"
tmp = sys.stdin
sys.stdin = StringIO(msg + "\n")
try:
s = compat.raw_input_()
self.assertEqual(s, msg)
finally:
sys.stdin = tmp
def test_filesystem_encode(self):
upath = compat.as_unicode(r"ab\u212Acd")
self.assertEqual(compat.filesystem_encode(upath), encode_file_path(upath))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,458 @@
import unittest
import pygame.constants
SDL2 = pygame.get_sdl_version()[0] >= 2
# K_* and KSCAN_* common names.
K_AND_KSCAN_COMMON_NAMES = (
"UNKNOWN",
"BACKSPACE",
"TAB",
"CLEAR",
"RETURN",
"PAUSE",
"ESCAPE",
"SPACE",
"COMMA",
"MINUS",
"PERIOD",
"SLASH",
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"SEMICOLON",
"EQUALS",
"LEFTBRACKET",
"BACKSLASH",
"RIGHTBRACKET",
"DELETE",
"KP0",
"KP1",
"KP2",
"KP3",
"KP4",
"KP5",
"KP6",
"KP7",
"KP8",
"KP9",
"KP_PERIOD",
"KP_DIVIDE",
"KP_MULTIPLY",
"KP_MINUS",
"KP_PLUS",
"KP_ENTER",
"KP_EQUALS",
"UP",
"DOWN",
"RIGHT",
"LEFT",
"INSERT",
"HOME",
"END",
"PAGEUP",
"PAGEDOWN",
"F1",
"F2",
"F3",
"F4",
"F5",
"F6",
"F7",
"F8",
"F9",
"F10",
"F11",
"F12",
"F13",
"F14",
"F15",
"NUMLOCK",
"CAPSLOCK",
"SCROLLOCK",
"RSHIFT",
"LSHIFT",
"RCTRL",
"LCTRL",
"RALT",
"LALT",
"RMETA",
"LMETA",
"LSUPER",
"RSUPER",
"MODE",
"HELP",
"PRINT",
"SYSREQ",
"BREAK",
"MENU",
"POWER",
"EURO",
)
if SDL2:
K_AND_KSCAN_COMMON_NAMES += (
"KP_0",
"KP_1",
"KP_2",
"KP_3",
"KP_4",
"KP_5",
"KP_6",
"KP_7",
"KP_8",
"KP_9",
"NUMLOCKCLEAR",
"SCROLLLOCK",
"RGUI",
"LGUI",
"PRINTSCREEN",
"CURRENCYUNIT",
"CURRENCYSUBUNIT",
)
# Constants that have the same value.
K_AND_KSCAN_COMMON_OVERLAPS = ()
if SDL2:
K_AND_KSCAN_COMMON_OVERLAPS += (
("KP0", "KP_0"),
("KP1", "KP_1"),
("KP2", "KP_2"),
("KP3", "KP_3"),
("KP4", "KP_4"),
("KP5", "KP_5"),
("KP6", "KP_6"),
("KP7", "KP_7"),
("KP8", "KP_8"),
("KP9", "KP_9"),
("NUMLOCK", "NUMLOCKCLEAR"),
("SCROLLOCK", "SCROLLLOCK"),
("LSUPER", "LMETA", "LGUI"),
("RSUPER", "RMETA", "RGUI"),
("PRINT", "PRINTSCREEN"),
("BREAK", "PAUSE"),
("EURO", "CURRENCYUNIT"),
)
def create_overlap_set(constant_names):
"""Helper function to find overlapping constant values/names.
Returns a set of fronzensets:
set(frozenset(names of overlapping constants), ...)
"""
# Create an overlap dict.
overlap_dict = {}
for name in constant_names:
value = getattr(pygame.constants, name)
overlap_dict.setdefault(value, set()).add(name)
# Get all entries with more than 1 value.
overlaps = set()
for overlap_names in overlap_dict.values():
if len(overlap_names) > 1:
overlaps.add(frozenset(overlap_names))
return overlaps
class KConstantsTests(unittest.TestCase):
"""Test K_* (key) constants."""
# K_* specific names.
K_SPECIFIC_NAMES = (
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z",
"QUOTE",
"BACKQUOTE",
"EXCLAIM",
"QUOTEDBL",
"HASH",
"DOLLAR",
"AMPERSAND",
"LEFTPAREN",
"RIGHTPAREN",
"ASTERISK",
"PLUS",
"COLON",
"LESS",
"GREATER",
"QUESTION",
"AT",
"CARET",
"UNDERSCORE",
)
if SDL2:
K_SPECIFIC_NAMES += ("PERCENT",)
# Create a sequence of all the K_* constant names.
K_NAMES = tuple("K_" + n for n in K_AND_KSCAN_COMMON_NAMES + K_SPECIFIC_NAMES)
def test_k__existence(self):
"""Ensures K constants exist."""
for name in self.K_NAMES:
self.assertTrue(
hasattr(pygame.constants, name), "missing constant {}".format(name)
)
def test_k__type(self):
"""Ensures K constants are the correct type."""
for name in self.K_NAMES:
value = getattr(pygame.constants, name)
self.assertIs(type(value), int)
def test_k__value_overlap(self):
"""Ensures no unexpected K constant values overlap."""
EXPECTED_OVERLAPS = set(
[
frozenset(["K_" + n for n in item])
for item in K_AND_KSCAN_COMMON_OVERLAPS
]
)
overlaps = create_overlap_set(self.K_NAMES)
self.assertSetEqual(overlaps, EXPECTED_OVERLAPS)
@unittest.skipIf(not SDL2, "requires SDL2")
class KscanConstantsTests(unittest.TestCase):
"""Test KSCAN_* (scancode) constants."""
# KSCAN_* specific names.
KSCAN_SPECIFIC_NAMES = (
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
"APOSTROPHE",
"GRAVE",
"INTERNATIONAL1",
"INTERNATIONAL2",
"INTERNATIONAL3",
"INTERNATIONAL4",
"INTERNATIONAL5",
"INTERNATIONAL6",
"INTERNATIONAL7",
"INTERNATIONAL8",
"INTERNATIONAL9",
"LANG1",
"LANG2",
"LANG3",
"LANG4",
"LANG5",
"LANG6",
"LANG7",
"LANG8",
"LANG9",
"NONUSBACKSLASH",
"NONUSHASH",
)
# Create a sequence of all the KSCAN_* constant names.
KSCAN_NAMES = tuple(
"KSCAN_" + n for n in K_AND_KSCAN_COMMON_NAMES + KSCAN_SPECIFIC_NAMES
)
def test_kscan__existence(self):
"""Ensures KSCAN constants exist."""
for name in self.KSCAN_NAMES:
self.assertTrue(
hasattr(pygame.constants, name), "missing constant {}".format(name)
)
def test_kscan__type(self):
"""Ensures KSCAN constants are the correct type."""
for name in self.KSCAN_NAMES:
value = getattr(pygame.constants, name)
self.assertIs(type(value), int)
def test_kscan__value_overlap(self):
"""Ensures no unexpected KSCAN constant values overlap."""
EXPECTED_OVERLAPS = set(
[
frozenset(["KSCAN_" + n for n in item])
for item in K_AND_KSCAN_COMMON_OVERLAPS
]
)
overlaps = create_overlap_set(self.KSCAN_NAMES)
self.assertSetEqual(overlaps, EXPECTED_OVERLAPS)
class KmodConstantsTests(unittest.TestCase):
"""Test KMOD_* (key modifier) constants."""
# KMOD_* constant names.
KMOD_CONSTANTS = (
"KMOD_NONE",
"KMOD_LSHIFT",
"KMOD_RSHIFT",
"KMOD_SHIFT",
"KMOD_LCTRL",
"KMOD_RCTRL",
"KMOD_CTRL",
"KMOD_LALT",
"KMOD_RALT",
"KMOD_ALT",
"KMOD_LMETA",
"KMOD_RMETA",
"KMOD_META",
"KMOD_NUM",
"KMOD_CAPS",
"KMOD_MODE",
)
if SDL2:
KMOD_CONSTANTS += ("KMOD_LGUI", "KMOD_RGUI", "KMOD_GUI")
def test_kmod__existence(self):
"""Ensures KMOD constants exist."""
for name in self.KMOD_CONSTANTS:
self.assertTrue(
hasattr(pygame.constants, name), "missing constant {}".format(name)
)
def test_kmod__type(self):
"""Ensures KMOD constants are the correct type."""
for name in self.KMOD_CONSTANTS:
value = getattr(pygame.constants, name)
self.assertIs(type(value), int)
def test_kmod__value_overlap(self):
"""Ensures no unexpected KMOD constant values overlap."""
# KMODs that have the same values.
EXPECTED_OVERLAPS = set()
if SDL2:
EXPECTED_OVERLAPS.update(
[
frozenset(["KMOD_LGUI", "KMOD_LMETA"]),
frozenset(["KMOD_RGUI", "KMOD_RMETA"]),
frozenset(["KMOD_GUI", "KMOD_META"]),
]
)
overlaps = create_overlap_set(self.KMOD_CONSTANTS)
self.assertSetEqual(overlaps, EXPECTED_OVERLAPS)
def test_kmod__no_bitwise_overlap(self):
"""Ensures certain KMOD constants have no overlapping bits."""
NO_BITWISE_OVERLAP = (
"KMOD_NONE",
"KMOD_LSHIFT",
"KMOD_RSHIFT",
"KMOD_LCTRL",
"KMOD_RCTRL",
"KMOD_LALT",
"KMOD_RALT",
"KMOD_LMETA",
"KMOD_RMETA",
"KMOD_NUM",
"KMOD_CAPS",
"KMOD_MODE",
)
kmods = 0
for name in NO_BITWISE_OVERLAP:
value = getattr(pygame.constants, name)
self.assertFalse(kmods & value)
kmods |= value
def test_kmod__bitwise_overlap(self):
"""Ensures certain KMOD constants have overlapping bits."""
# KMODS that are comprised of other KMODs.
KMOD_COMPRISED_DICT = {
"KMOD_SHIFT": ("KMOD_LSHIFT", "KMOD_RSHIFT"),
"KMOD_CTRL": ("KMOD_LCTRL", "KMOD_RCTRL"),
"KMOD_ALT": ("KMOD_LALT", "KMOD_RALT"),
"KMOD_META": ("KMOD_LMETA", "KMOD_RMETA"),
}
if SDL2:
KMOD_COMPRISED_DICT.update({"KMOD_GUI": ("KMOD_LGUI", "KMOD_RGUI")})
for base_name, seq_names in KMOD_COMPRISED_DICT.items():
expected_value = 0 # Reset.
for name in seq_names:
expected_value |= getattr(pygame.constants, name)
value = getattr(pygame.constants, base_name)
self.assertEqual(value, expected_value)
################################################################################
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,64 @@
import unittest
from pygame.tests.test_utils import fixture_path
import pygame
class CursorsModuleTest(unittest.TestCase):
def todo_test_compile(self):
# __doc__ (as of 2008-06-25) for pygame.cursors.compile:
# pygame.cursors.compile(strings, black, white,xor) -> data, mask
# compile cursor strings into cursor data
#
# This takes a set of strings with equal length and computes
# the binary data for that cursor. The string widths must be
# divisible by 8.
#
# The black and white arguments are single letter strings that
# tells which characters will represent black pixels, and which
# characters represent white pixels. All other characters are
# considered clear.
#
# This returns a tuple containing the cursor data and cursor mask
# data. Both these arguments are used when setting a cursor with
# pygame.mouse.set_cursor().
self.fail()
def test_load_xbm(self):
# __doc__ (as of 2008-06-25) for pygame.cursors.load_xbm:
# pygame.cursors.load_xbm(cursorfile, maskfile) -> cursor_args
# reads a pair of XBM files into set_cursor arguments
#
# Arguments can either be filenames or filelike objects
# with the readlines method. Not largely tested, but
# should work with typical XBM files.
# Test that load_xbm will take filenames as arguments
cursorfile = fixture_path(r"xbm_cursors/white_sizing.xbm")
maskfile = fixture_path(r"xbm_cursors/white_sizing_mask.xbm")
cursor = pygame.cursors.load_xbm(cursorfile, maskfile)
# Test that load_xbm will take file objects as arguments
with open(cursorfile) as cursor_f, open(maskfile) as mask_f:
cursor = pygame.cursors.load_xbm(cursor_f, mask_f)
# Is it in a format that mouse.set_cursor won't blow up on?
pygame.display.init()
try:
pygame.mouse.set_cursor(*cursor)
except pygame.error as e:
if "not currently supported" in str(e):
unittest.skip("skipping test as set_cursor() is not supported")
finally:
pygame.display.quit()
################################################################################
if __name__ == "__main__":
unittest.main()
################################################################################
@@ -0,0 +1,433 @@
# -*- coding: utf-8 -*-
import unittest
import os
import pygame, pygame.transform
from pygame.compat import unicode_
from pygame import display
SDL2 = pygame.get_sdl_version()[0] >= 2
class DisplayModuleTest(unittest.TestCase):
default_caption = "pygame window"
def setUp(self):
display.init()
def tearDown(self):
display.quit()
def test_update(self):
""" see if pygame.display.update takes rects with negative values.
"|Tags:display|"
"""
screen = pygame.display.set_mode((100, 100))
screen.fill((55, 55, 55))
r1 = pygame.Rect(0, 0, 100, 100)
pygame.display.update(r1)
r2 = pygame.Rect(-10, 0, 100, 100)
pygame.display.update(r2)
r3 = pygame.Rect(-10, 0, -100, -100)
pygame.display.update(r3)
def test_Info(self):
inf = pygame.display.Info()
self.assertNotEqual(inf.current_h, -1)
self.assertNotEqual(inf.current_w, -1)
# probably have an older SDL than 1.2.10 if -1.
screen = pygame.display.set_mode((128, 128))
inf = pygame.display.Info()
self.assertEqual(inf.current_h, 128)
self.assertEqual(inf.current_w, 128)
def todo_test_flip(self):
# __doc__ (as of 2008-08-02) for pygame.display.flip:
# pygame.display.flip(): return None
# update the full display Surface to the screen
#
# This will update the contents of the entire display. If your display
# mode is using the flags pygame.HWSURFACE and pygame.DOUBLEBUF, this
# will wait for a vertical retrace and swap the surfaces. If you are
# using a different type of display mode, it will simply update the
# entire contents of the surface.
#
# When using an pygame.OPENGL display mode this will perform a gl buffer swap.
self.fail()
def todo_test_get_active(self):
# __doc__ (as of 2008-08-02) for pygame.display.get_active:
# pygame.display.get_active(): return bool
# true when the display is active on the display
#
# After pygame.display.set_mode() is called the display Surface will
# be visible on the screen. Most windowed displays can be hidden by
# the user. If the display Surface is hidden or iconified this will
# return False.
#
self.fail()
def test_get_caption(self):
screen = display.set_mode((100, 100))
self.assertEqual(display.get_caption()[0], self.default_caption)
def test_set_caption(self):
TEST_CAPTION = "test"
screen = display.set_mode((100, 100))
self.assertIsNone(display.set_caption(TEST_CAPTION))
self.assertEqual(display.get_caption()[0], TEST_CAPTION)
self.assertEqual(display.get_caption()[1], TEST_CAPTION)
def test_caption_unicode(self):
TEST_CAPTION = u"台"
display.set_caption(TEST_CAPTION)
import sys
if sys.version_info.major >= 3:
self.assertEqual(display.get_caption()[0], TEST_CAPTION)
else:
self.assertEqual(unicode_(display.get_caption()[0], "utf8"), TEST_CAPTION)
def todo_test_get_driver(self):
# __doc__ (as of 2008-08-02) for pygame.display.get_driver:
# pygame.display.get_driver(): return name
# get the name of the pygame display backend
#
# Pygame chooses one of many available display backends when it is
# initialized. This returns the internal name used for the display
# backend. This can be used to provide limited information about what
# display capabilities might be accelerated. See the SDL_VIDEODRIVER
# flags in pygame.display.set_mode() to see some of the common
# options.
#
self.fail()
def test_get_init(self):
"""Ensures the module's initialization state can be retrieved."""
# display.init() already called in setUp()
self.assertTrue(display.get_init())
# This decorator can be removed (or test changed) when issues #991 and #993
# are resolved.
@unittest.skipIf(SDL2, "SDL2 issues")
def test_get_surface(self):
"""Ensures get_surface gets the current display surface."""
lengths = (1, 5, 100)
for expected_size in ((w, h) for w in lengths for h in lengths):
for expected_depth in (8, 16, 24, 32):
expected_surface = display.set_mode(expected_size, 0, expected_depth)
surface = pygame.display.get_surface()
self.assertEqual(surface, expected_surface)
self.assertIsInstance(surface, pygame.Surface)
self.assertEqual(surface.get_size(), expected_size)
self.assertEqual(surface.get_bitsize(), expected_depth)
def test_get_surface__mode_not_set(self):
"""Ensures get_surface handles the display mode not being set."""
surface = pygame.display.get_surface()
self.assertIsNone(surface)
def todo_test_get_wm_info(self):
# __doc__ (as of 2008-08-02) for pygame.display.get_wm_info:
# pygame.display.get_wm_info(): return dict
# Get information about the current windowing system
#
# Creates a dictionary filled with string keys. The strings and values
# are arbitrarily created by the system. Some systems may have no
# information and an empty dictionary will be returned. Most platforms
# will return a "window" key with the value set to the system id for
# the current display.
#
# New with pygame 1.7.1
self.fail()
def todo_test_gl_get_attribute(self):
# __doc__ (as of 2008-08-02) for pygame.display.gl_get_attribute:
# pygame.display.gl_get_attribute(flag): return value
# get the value for an opengl flag for the current display
#
# After calling pygame.display.set_mode() with the pygame.OPENGL flag,
# it is a good idea to check the value of any requested OpenGL
# attributes. See pygame.display.gl_set_attribute() for a list of
# valid flags.
#
self.fail()
def todo_test_gl_set_attribute(self):
# __doc__ (as of 2008-08-02) for pygame.display.gl_set_attribute:
# pygame.display.gl_set_attribute(flag, value): return None
# request an opengl display attribute for the display mode
#
# When calling pygame.display.set_mode() with the pygame.OPENGL flag,
# Pygame automatically handles setting the OpenGL attributes like
# color and doublebuffering. OpenGL offers several other attributes
# you may want control over. Pass one of these attributes as the flag,
# and its appropriate value. This must be called before
# pygame.display.set_mode()
#
# The OPENGL flags are;
# GL_ALPHA_SIZE, GL_DEPTH_SIZE, GL_STENCIL_SIZE, GL_ACCUM_RED_SIZE,
# GL_ACCUM_GREEN_SIZE, GL_ACCUM_BLUE_SIZE, GL_ACCUM_ALPHA_SIZE,
# GL_MULTISAMPLEBUFFERS, GL_MULTISAMPLESAMPLES, GL_STEREO
self.fail()
def todo_test_iconify(self):
# __doc__ (as of 2008-08-02) for pygame.display.iconify:
# pygame.display.iconify(): return bool
# iconify the display surface
#
# Request the window for the display surface be iconified or hidden.
# Not all systems and displays support an iconified display. The
# function will return True if successfull.
#
# When the display is iconified pygame.display.get_active() will
# return False. The event queue should receive a ACTIVEEVENT event
# when the window has been iconified.
#
self.fail()
def test_init(self):
"""Ensures the module is initialized after init called."""
# display.init() already called in setUp(), so quit and re-init
display.quit()
display.init()
self.assertTrue(display.get_init())
def test_init__multiple(self):
"""Ensures the module is initialized after multiple init calls."""
display.init()
display.init()
self.assertTrue(display.get_init())
def test_list_modes(self):
modes = pygame.display.list_modes(depth=0, flags=pygame.FULLSCREEN, display=0)
# modes == -1 means any mode is supported.
if modes != -1:
self.assertEqual(len(modes[0]), 2)
self.assertEqual(type(modes[0][0]), int)
modes = pygame.display.list_modes()
if modes != -1:
self.assertEqual(len(modes[0]), 2)
self.assertEqual(type(modes[0][0]), int)
modes = pygame.display.list_modes(depth=0, flags=0, display=0)
if modes != -1:
self.assertEqual(len(modes[0]), 2)
self.assertEqual(type(modes[0][0]), int)
def test_mode_ok(self):
pygame.display.mode_ok((128, 128))
modes = pygame.display.list_modes()
if modes != -1:
size = modes[0]
self.assertNotEqual(pygame.display.mode_ok(size), 0)
pygame.display.mode_ok((128, 128), 0, 32)
pygame.display.mode_ok((128, 128), flags=0, depth=32, display=0)
def test_mode_ok_fullscreen(self):
modes = pygame.display.list_modes()
if modes != -1:
size = modes[0]
self.assertNotEqual(
pygame.display.mode_ok(size, flags=pygame.FULLSCREEN), 0
)
def test_mode_ok_scaled(self):
modes = pygame.display.list_modes()
if modes != -1:
size = modes[0]
self.assertNotEqual(pygame.display.mode_ok(size, flags=pygame.SCALED), 0)
def test_get_num_displays(self):
self.assertGreater(pygame.display.get_num_displays(), 0)
def test_quit(self):
"""Ensures the module is not initialized after quit called."""
display.quit()
self.assertFalse(display.get_init())
def test_quit__multiple(self):
"""Ensures the module is not initialized after multiple quit calls."""
display.quit()
display.quit()
self.assertFalse(display.get_init())
def todo_test_set_gamma(self):
# __doc__ (as of 2008-08-02) for pygame.display.set_gamma:
# pygame.display.set_gamma(red, green=None, blue=None): return bool
# change the hardware gamma ramps
#
# Set the red, green, and blue gamma values on the display hardware.
# If the green and blue arguments are not passed, they will both be
# the same as red. Not all systems and hardware support gamma ramps,
# if the function succeeds it will return True.
#
# A gamma value of 1.0 creates a linear color table. Lower values will
# darken the display and higher values will brighten.
#
self.fail()
def todo_test_set_gamma_ramp(self):
# __doc__ (as of 2008-08-02) for pygame.display.set_gamma_ramp:
# change the hardware gamma ramps with a custom lookup
# pygame.display.set_gamma_ramp(red, green, blue): return bool
# set_gamma_ramp(red, green, blue): return bool
#
# Set the red, green, and blue gamma ramps with an explicit lookup
# table. Each argument should be sequence of 256 integers. The
# integers should range between 0 and 0xffff. Not all systems and
# hardware support gamma ramps, if the function succeeds it will
# return True.
#
self.fail()
def todo_test_set_icon(self):
# __doc__ (as of 2008-08-02) for pygame.display.set_icon:
# pygame.display.set_icon(Surface): return None
# change the system image for the display window
#
# Sets the runtime icon the system will use to represent the display
# window. All windows default to a simple pygame logo for the window
# icon.
#
# You can pass any surface, but most systems want a smaller image
# around 32x32. The image can have colorkey transparency which will be
# passed to the system.
#
# Some systems do not allow the window icon to change after it has
# been shown. This function can be called before
# pygame.display.set_mode() to create the icon before the display mode
# is set.
#
self.fail()
def test_set_mode_kwargs(self):
pygame.display.set_mode(size=(1, 1), flags=0, depth=0, display=0)
def test_set_mode_scaled(self):
surf = pygame.display.set_mode(
size=(1, 1), flags=pygame.SCALED, depth=0, display=0
)
winsize = pygame.display.get_window_size()
self.assertEqual(
winsize[0] % surf.get_size()[0],
0,
"window width should be a multiple of the surface width",
)
self.assertEqual(
winsize[1] % surf.get_size()[1],
0,
"window height should be a multiple of the surface height",
)
self.assertEqual(
winsize[0] / surf.get_size()[0], winsize[1] / surf.get_size()[1]
)
def todo_test_set_palette(self):
# __doc__ (as of 2008-08-02) for pygame.display.set_palette:
# pygame.display.set_palette(palette=None): return None
# set the display color palette for indexed displays
#
# This will change the video display color palette for 8bit displays.
# This does not change the palette for the actual display Surface,
# only the palette that is used to display the Surface. If no palette
# argument is passed, the system default palette will be restored. The
# palette is a sequence of RGB triplets.
#
self.fail()
def todo_test_toggle_fullscreen(self):
# __doc__ (as of 2008-08-02) for pygame.display.toggle_fullscreen:
# pygame.display.toggle_fullscreen(): return bool
# switch between fullscreen and windowed displays
#
# Switches the display window between windowed and fullscreen modes.
# This function only works under the unix x11 video driver. For most
# situations it is better to call pygame.display.set_mode() with new
# display flags.
#
self.fail()
@unittest.skipIf(
os.environ.get("SDL_VIDEODRIVER") == "dummy",
'OpenGL requires a non-"dummy" SDL_VIDEODRIVER',
)
class DisplayOpenGLTest(unittest.TestCase):
def test_screen_size_opengl(self):
""" returns a surface with the same size requested.
|tags:display,slow,opengl|
"""
pygame.display.init()
screen = pygame.display.set_mode((640, 480), pygame.OPENGL)
self.assertEqual((640, 480), screen.get_size())
class X11CrashTest(unittest.TestCase):
def test_x11_set_mode_crash_gh1654(self):
# Test for https://github.com/pygame/pygame/issues/1654
# If unfixed, this will trip a segmentation fault
pygame.display.init()
pygame.display.quit()
screen = pygame.display.set_mode((640, 480), 0)
self.assertEqual((640, 480), screen.get_size())
if __name__ == "__main__":
unittest.main()
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,679 @@
import os
import sys
import unittest
import pygame
from pygame.compat import as_unicode
PY3 = sys.version_info >= (3, 0, 0)
################################################################################
EVENT_TYPES = (
# pygame.NOEVENT,
# pygame.ACTIVEEVENT,
pygame.KEYDOWN,
pygame.KEYUP,
pygame.MOUSEMOTION,
pygame.MOUSEBUTTONDOWN,
pygame.MOUSEBUTTONUP,
pygame.JOYAXISMOTION,
pygame.JOYBALLMOTION,
pygame.JOYHATMOTION,
pygame.JOYBUTTONDOWN,
pygame.JOYBUTTONUP,
pygame.VIDEORESIZE,
pygame.VIDEOEXPOSE,
pygame.QUIT,
pygame.SYSWMEVENT,
pygame.USEREVENT,
# pygame.NUMEVENTS,
)
NAMES_AND_EVENTS = (
("NoEvent", pygame.NOEVENT),
("ActiveEvent", pygame.ACTIVEEVENT),
("KeyDown", pygame.KEYDOWN),
("KeyUp", pygame.KEYUP),
("MouseMotion", pygame.MOUSEMOTION),
("MouseButtonDown", pygame.MOUSEBUTTONDOWN),
("MouseButtonUp", pygame.MOUSEBUTTONUP),
("JoyAxisMotion", pygame.JOYAXISMOTION),
("JoyBallMotion", pygame.JOYBALLMOTION),
("JoyHatMotion", pygame.JOYHATMOTION),
("JoyButtonDown", pygame.JOYBUTTONDOWN),
("JoyButtonUp", pygame.JOYBUTTONUP),
("VideoResize", pygame.VIDEORESIZE),
("VideoExpose", pygame.VIDEOEXPOSE),
("Quit", pygame.QUIT),
("SysWMEvent", pygame.SYSWMEVENT),
("MidiIn", pygame.MIDIIN),
("MidiOut", pygame.MIDIOUT),
("UserEvent", pygame.USEREVENT),
("Unknown", 0xFFFF),
)
# Add in any SDL 2 specific events.
if pygame.get_sdl_version()[0] >= 2:
NAMES_AND_EVENTS += (
("FingerMotion", pygame.FINGERMOTION),
("FingerDown", pygame.FINGERDOWN),
("FingerUp", pygame.FINGERUP),
("MultiGesture", pygame.MULTIGESTURE),
("MouseWheel", pygame.MOUSEWHEEL),
("TextInput", pygame.TEXTINPUT),
("TextEditing", pygame.TEXTEDITING),
("WindowEvent", pygame.WINDOWEVENT),
("ControllerAxisMotion", pygame.CONTROLLERAXISMOTION),
("ControllerButtonDown", pygame.CONTROLLERBUTTONDOWN),
("ControllerButtonUp", pygame.CONTROLLERBUTTONUP),
("ControllerDeviceAdded", pygame.CONTROLLERDEVICEADDED),
("ControllerDeviceRemoved", pygame.CONTROLLERDEVICEREMOVED),
("ControllerDeviceMapped", pygame.CONTROLLERDEVICEREMAPPED),
("DropFile", pygame.DROPFILE),
)
# Add in any SDL 2.0.4 specific events.
if pygame.get_sdl_version() >= (2, 0, 4):
NAMES_AND_EVENTS += (
("AudioDeviceAdded", pygame.AUDIODEVICEADDED),
("AudioDeviceRemoved", pygame.AUDIODEVICEREMOVED),
)
# Add in any SDL 2.0.5 specific events.
if pygame.get_sdl_version() >= (2, 0, 5):
NAMES_AND_EVENTS += (
("DropText", pygame.DROPTEXT),
("DropBegin", pygame.DROPBEGIN),
("DropComplete", pygame.DROPCOMPLETE),
)
class EventTypeTest(unittest.TestCase):
def test_Event(self):
"""Ensure an Event object can be created."""
e = pygame.event.Event(pygame.USEREVENT, some_attr=1, other_attr="1")
self.assertEqual(e.some_attr, 1)
self.assertEqual(e.other_attr, "1")
# Event now uses tp_dictoffset and tp_members: request 62
# on Motherhamster Bugzilla.
self.assertEqual(e.type, pygame.USEREVENT)
self.assertIs(e.dict, e.__dict__)
e.some_attr = 12
self.assertEqual(e.some_attr, 12)
e.new_attr = 15
self.assertEqual(e.new_attr, 15)
# For Python 2.x a TypeError is raised for a readonly member;
# for Python 3.x it is an AttributeError.
self.assertRaises((TypeError, AttributeError), setattr, e, "type", 0)
self.assertRaises((TypeError, AttributeError), setattr, e, "dict", None)
# Ensure attributes are visible to dir(), part of the original
# posted request.
d = dir(e)
attrs = ("type", "dict", "__dict__", "some_attr", "other_attr", "new_attr")
for attr in attrs:
self.assertIn(attr, d)
def test_as_str(self):
# Bug reported on Pygame mailing list July 24, 2011:
# For Python 3.x str(event) to raises an UnicodeEncodeError when
# an event attribute is a string with a non-ascii character.
try:
str(pygame.event.Event(EVENT_TYPES[0], a=as_unicode(r"\xed")))
except UnicodeEncodeError:
self.fail("Event object raised exception for non-ascii character")
# Passed.
race_condition_notification = """
This test is dependent on timing. The event queue is cleared in preparation for
tests. There is a small window where outside events from the OS may have effected
results. Try running the test again.
"""
class EventModuleArgsTest(unittest.TestCase):
def setUp(self):
pygame.display.init()
pygame.event.clear()
def tearDown(self):
pygame.display.quit()
def test_get(self):
pygame.event.get()
pygame.event.get(None)
pygame.event.get(None, True)
pygame.event.get(pump=False)
pygame.event.get(pump=True)
pygame.event.get(eventtype=None)
pygame.event.get(eventtype=[pygame.KEYUP, pygame.KEYDOWN])
pygame.event.get(eventtype=pygame.USEREVENT, pump=False)
def test_clear(self):
pygame.event.clear()
pygame.event.clear(None)
pygame.event.clear(None, True)
pygame.event.clear(pump=False)
pygame.event.clear(pump=True)
pygame.event.clear(eventtype=None)
pygame.event.clear(eventtype=[pygame.KEYUP, pygame.KEYDOWN])
pygame.event.clear(eventtype=pygame.USEREVENT, pump=False)
def test_peek(self):
pygame.event.peek()
pygame.event.peek(None)
pygame.event.peek(None, True)
pygame.event.peek(pump=False)
pygame.event.peek(pump=True)
pygame.event.peek(eventtype=None)
pygame.event.peek(eventtype=[pygame.KEYUP, pygame.KEYDOWN])
pygame.event.peek(eventtype=pygame.USEREVENT, pump=False)
class EventModuleTest(unittest.TestCase):
def _assertCountEqual(self, *args, **kwargs):
# Handle method name differences between Python versions.
if PY3:
self.assertCountEqual(*args, **kwargs)
else:
self.assertItemsEqual(*args, **kwargs)
def setUp(self):
pygame.display.init()
pygame.event.clear() # flush events
def tearDown(self):
pygame.event.clear() # flush events
pygame.display.quit()
def test_event_numevents(self):
"""Ensures NUMEVENTS does not exceed the maximum SDL number of events.
"""
# Ref: https://www.libsdl.org/tmp/SDL/include/SDL_events.h
MAX_SDL_EVENTS = 0xFFFF + 1 # SDL_LASTEVENT = 0xFFFF
self.assertLessEqual(pygame.NUMEVENTS, MAX_SDL_EVENTS)
def test_event_attribute(self):
e1 = pygame.event.Event(pygame.USEREVENT, attr1="attr1")
self.assertEqual(e1.attr1, "attr1")
def test_set_blocked(self):
"""Ensure events can be blocked from the queue."""
event = EVENT_TYPES[0]
pygame.event.set_blocked(event)
self.assertTrue(pygame.event.get_blocked(event))
pygame.event.post(pygame.event.Event(event))
ret = pygame.event.get()
should_be_blocked = [e for e in ret if e.type == event]
self.assertEqual(should_be_blocked, [])
def test_set_blocked__event_sequence(self):
"""Ensure a sequence of event types can be blocked."""
event_types = [
pygame.KEYDOWN,
pygame.KEYUP,
pygame.MOUSEMOTION,
pygame.MOUSEBUTTONDOWN,
pygame.MOUSEBUTTONUP,
]
pygame.event.set_blocked(event_types)
for etype in event_types:
self.assertTrue(pygame.event.get_blocked(etype))
def test_set_blocked_all(self):
"""Ensure all events can be unblocked at once."""
pygame.event.set_blocked(None)
for e in EVENT_TYPES:
self.assertTrue(pygame.event.get_blocked(e))
def test_post__and_poll(self):
"""Ensure events can be posted to the queue."""
e1 = pygame.event.Event(pygame.USEREVENT, attr1="attr1")
pygame.event.post(e1)
posted_event = pygame.event.poll()
self.assertEqual(e1.attr1, posted_event.attr1, race_condition_notification)
# fuzzing event types
for i in range(1, 11):
pygame.event.post(pygame.event.Event(EVENT_TYPES[i]))
self.assertEqual(
pygame.event.poll().type, EVENT_TYPES[i], race_condition_notification
)
def test_post_large_user_event(self):
pygame.event.post(pygame.event.Event(pygame.USEREVENT, {"a": "a" * 1024}))
e = pygame.event.poll()
self.assertEqual(e.type, pygame.USEREVENT)
self.assertEqual(e.a, "a" * 1024)
def test_get(self):
"""Ensure get() retrieves all the events on the queue."""
event_cnt = 10
for _ in range(event_cnt):
pygame.event.post(pygame.event.Event(pygame.USEREVENT))
queue = pygame.event.get()
self.assertEqual(len(queue), event_cnt)
self.assertTrue(all(e.type == pygame.USEREVENT for e in queue))
def test_get_type(self):
ev = pygame.event.Event(pygame.USEREVENT)
pygame.event.post(ev)
queue = pygame.event.get(pygame.USEREVENT)
self.assertEqual(len(queue), 1)
self.assertEqual(queue[0].type, pygame.USEREVENT)
def test_get__empty_queue(self):
"""Ensure get() works correctly on an empty queue."""
expected_events = []
pygame.event.clear()
# Ensure all events can be checked.
retrieved_events = pygame.event.get()
self.assertListEqual(retrieved_events, expected_events)
# Ensure events can be checked individually.
for event_type in EVENT_TYPES:
retrieved_events = pygame.event.get(event_type)
self.assertListEqual(retrieved_events, expected_events)
# Ensure events can be checked as a sequence.
retrieved_events = pygame.event.get(EVENT_TYPES)
self.assertListEqual(retrieved_events, expected_events)
def test_get__event_sequence(self):
"""Ensure get() can handle a sequence of event types."""
event_types = [pygame.KEYDOWN, pygame.KEYUP, pygame.MOUSEMOTION]
other_event_type = pygame.MOUSEBUTTONUP
# Test when no events in the queue.
expected_events = []
pygame.event.clear()
retrieved_events = pygame.event.get(event_types)
self._assertCountEqual(retrieved_events, expected_events)
# Test when an event type not in the list is in the queue.
expected_events = []
pygame.event.clear()
pygame.event.post(pygame.event.Event(other_event_type))
retrieved_events = pygame.event.get(event_types)
self._assertCountEqual(retrieved_events, expected_events)
# Test when 1 event type in the list is in the queue.
expected_events = [pygame.event.Event(event_types[0])]
pygame.event.clear()
pygame.event.post(expected_events[0])
retrieved_events = pygame.event.get(event_types)
self._assertCountEqual(retrieved_events, expected_events)
# Test all events in the list are in the queue.
pygame.event.clear()
expected_events = []
for etype in event_types:
expected_events.append(pygame.event.Event(etype))
pygame.event.post(expected_events[-1])
retrieved_events = pygame.event.get(event_types)
self._assertCountEqual(retrieved_events, expected_events)
def test_clear(self):
"""Ensure clear() removes all the events on the queue."""
for e in EVENT_TYPES:
pygame.event.post(pygame.event.Event(e))
poll_event = pygame.event.poll()
self.assertNotEqual(poll_event.type, pygame.NOEVENT)
pygame.event.clear()
poll_event = pygame.event.poll()
self.assertEqual(poll_event.type, pygame.NOEVENT, race_condition_notification)
def test_clear__empty_queue(self):
"""Ensure clear() works correctly on an empty queue."""
expected_events = []
pygame.event.clear()
# Test calling clear() on an already empty queue.
pygame.event.clear()
retrieved_events = pygame.event.get()
self.assertListEqual(retrieved_events, expected_events)
def test_clear__event_sequence(self):
"""Ensure a sequence of event types can be cleared from the queue."""
cleared_event_types = EVENT_TYPES[:5]
expected_event_types = EVENT_TYPES[5:10]
expected_events = []
# Add the events to the queue.
for etype in cleared_event_types:
pygame.event.post(pygame.event.Event(etype))
for etype in expected_events:
expected_events.append(pygame.event.Event(etype))
pygame.event.post(expected_events[-1])
# Clear the cleared_events from the queue.
pygame.event.clear(cleared_event_types)
# Check the rest of the events in the queue.
remaining_events = pygame.event.get()
self._assertCountEqual(remaining_events, expected_events)
def test_event_name(self):
"""Ensure event_name() returns the correct event name."""
for expected_name, event in NAMES_AND_EVENTS:
self.assertEqual(
pygame.event.event_name(event), expected_name, "0x{:X}".format(event)
)
def test_event_name__userevent_range(self):
"""Ensures event_name() returns the correct name for user events.
Tests the full range of user events.
"""
expected_name = "UserEvent"
for event in range(pygame.USEREVENT, pygame.NUMEVENTS):
self.assertEqual(
pygame.event.event_name(event), expected_name, "0x{:X}".format(event)
)
def test_event_name__userevent_boundary(self):
"""Ensures event_name() does not return 'UserEvent' for events
just outside the user event range.
"""
unexpected_name = "UserEvent"
for event in (pygame.USEREVENT - 1, pygame.NUMEVENTS):
self.assertNotEqual(
pygame.event.event_name(event), unexpected_name, "0x{:X}".format(event)
)
def test_wait(self):
"""Ensure wait() waits for an event on the queue."""
event = pygame.event.Event(EVENT_TYPES[0])
pygame.event.post(event)
wait_event = pygame.event.wait()
self.assertEqual(wait_event.type, event.type)
def test_peek(self):
"""Ensure queued events can be peeked at."""
event_types = [pygame.KEYDOWN, pygame.KEYUP, pygame.MOUSEMOTION]
for event_type in event_types:
pygame.event.post(pygame.event.Event(event_type))
# Ensure events can be checked individually.
for event_type in event_types:
self.assertTrue(pygame.event.peek(event_type))
# Ensure events can be checked as a sequence.
self.assertTrue(pygame.event.peek(event_types))
def test_peek__event_sequence(self):
"""Ensure peek() can handle a sequence of event types."""
event_types = [pygame.KEYDOWN, pygame.KEYUP, pygame.MOUSEMOTION]
other_event_type = pygame.MOUSEBUTTONUP
# Test when no events in the queue.
pygame.event.clear()
peeked = pygame.event.peek(event_types)
self.assertFalse(peeked)
# Test when an event type not in the list is in the queue.
pygame.event.clear()
pygame.event.post(pygame.event.Event(other_event_type))
peeked = pygame.event.peek(event_types)
self.assertFalse(peeked)
# Test when 1 event type in the list is in the queue.
pygame.event.clear()
pygame.event.post(pygame.event.Event(event_types[0]))
peeked = pygame.event.peek(event_types)
self.assertTrue(peeked)
# Test all events in the list are in the queue.
pygame.event.clear()
for etype in event_types:
pygame.event.post(pygame.event.Event(etype))
peeked = pygame.event.peek(event_types)
self.assertTrue(peeked)
def test_peek__empty_queue(self):
"""Ensure peek() works correctly on an empty queue."""
pygame.event.clear()
# Ensure all events can be checked.
peeked = pygame.event.peek()
self.assertFalse(peeked)
# Ensure events can be checked individually.
for event_type in EVENT_TYPES:
peeked = pygame.event.peek(event_type)
self.assertFalse(peeked)
# Ensure events can be checked as a sequence.
peeked = pygame.event.peek(EVENT_TYPES)
self.assertFalse(peeked)
def test_set_allowed(self):
"""Ensure a blocked event type can be unblocked/allowed."""
event = EVENT_TYPES[0]
pygame.event.set_blocked(event)
self.assertTrue(pygame.event.get_blocked(event))
pygame.event.set_allowed(event)
self.assertFalse(pygame.event.get_blocked(event))
def test_set_allowed__event_sequence(self):
"""Ensure a sequence of blocked event types can be unblocked/allowed.
"""
event_types = [
pygame.KEYDOWN,
pygame.KEYUP,
pygame.MOUSEMOTION,
pygame.MOUSEBUTTONDOWN,
pygame.MOUSEBUTTONUP,
]
pygame.event.set_blocked(event_types)
pygame.event.set_allowed(event_types)
for etype in event_types:
self.assertFalse(pygame.event.get_blocked(etype))
def test_set_allowed_all(self):
"""Ensure all events can be unblocked/allowed at once."""
pygame.event.set_blocked(None)
for e in EVENT_TYPES:
self.assertTrue(pygame.event.get_blocked(e))
pygame.event.set_allowed(None)
for e in EVENT_TYPES:
self.assertFalse(pygame.event.get_blocked(e))
def test_pump(self):
"""Ensure pump() functions properly."""
pygame.event.pump()
@unittest.skipIf(
os.environ.get("SDL_VIDEODRIVER") == "dummy",
'requires the SDL_VIDEODRIVER to be a non "dummy" value',
)
def test_set_grab__and_get_symmetric(self):
"""Ensure event grabbing can be enabled and disabled.
WARNING: Moving the mouse off the display during this test can cause it
to fail.
"""
surf = pygame.display.set_mode((10, 10))
pygame.event.set_grab(True)
self.assertTrue(pygame.event.get_grab())
pygame.event.set_grab(False)
self.assertFalse(pygame.event.get_grab())
def test_event_equality(self):
a = pygame.event.Event(EVENT_TYPES[0], a=1)
b = pygame.event.Event(EVENT_TYPES[0], a=1)
c = pygame.event.Event(EVENT_TYPES[1], a=1)
d = pygame.event.Event(EVENT_TYPES[0], a=2)
self.assertTrue(a == a)
self.assertFalse(a != a)
self.assertTrue(a == b)
self.assertFalse(a != b)
self.assertTrue(a != c)
self.assertFalse(a == c)
self.assertTrue(a != d)
self.assertFalse(a == d)
def test_custom_type(self):
atype = pygame.event.custom_type()
atype2 = pygame.event.custom_type()
self.assertEqual(atype, atype2 - 1)
ev = pygame.event.Event(atype)
pygame.event.post(ev)
queue = pygame.event.get(atype)
self.assertEqual(len(queue), 1)
self.assertEqual(queue[0].type, atype)
def test_get_blocked(self):
"""Ensure an event's blocked state can be retrieved."""
# Test each event is not blocked.
pygame.event.set_allowed(None)
for etype in EVENT_TYPES:
blocked = pygame.event.get_blocked(etype)
self.assertFalse(blocked)
# Test each event type is blocked.
pygame.event.set_blocked(None)
for etype in EVENT_TYPES:
blocked = pygame.event.get_blocked(etype)
self.assertTrue(blocked)
def test_get_blocked__event_sequence(self):
"""Ensure get_blocked() can handle a sequence of event types."""
event_types = [
pygame.KEYDOWN,
pygame.KEYUP,
pygame.MOUSEMOTION,
pygame.MOUSEBUTTONDOWN,
pygame.MOUSEBUTTONUP,
]
# Test no event types in the list are blocked.
blocked = pygame.event.get_blocked(event_types)
self.assertFalse(blocked)
# Test when 1 event type in the list is blocked.
pygame.event.set_blocked(event_types[2])
blocked = pygame.event.get_blocked(event_types)
self.assertTrue(blocked)
# Test all event types in the list are blocked.
pygame.event.set_blocked(event_types)
blocked = pygame.event.get_blocked(event_types)
self.assertTrue(blocked)
def todo_test_get_grab(self):
# __doc__ (as of 2008-08-02) for pygame.event.get_grab:
# pygame.event.get_grab(): return bool
# test if the program is sharing input devices
#
# Returns true when the input events are grabbed for this application.
# Use pygame.event.set_grab() to control this state.
#
self.fail()
def todo_test_poll(self):
# __doc__ (as of 2008-08-02) for pygame.event.poll:
# pygame.event.poll(): return Event
# get a single event from the queue
#
# Returns a single event from the queue. If the event queue is empty
# an event of type pygame.NOEVENT will be returned immediately. The
# returned event is removed from the queue.
#
self.fail()
################################################################################
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1 @@
__tags__ = []
@@ -0,0 +1,158 @@
import unittest
from pygame.tests.event_test import race_condition_notification
import pygame
from pygame import event, fastevent
from pygame.compat import geterror
################################################################################
class FasteventModuleTest(unittest.TestCase):
def setUp(self):
pygame.display.init()
fastevent.init()
event.clear()
def tearDown(self):
# fastevent.quit() # Does not exist!
pygame.display.quit()
def test_init(self):
# Test if module initialized after multiple init() calls.
fastevent.init()
fastevent.init()
self.assertTrue(fastevent.get_init())
def test_auto_quit(self):
# Test if module uninitialized after calling pygame.quit().
pygame.quit()
self.assertFalse(fastevent.get_init())
def test_get_init(self):
# Test if get_init() gets the init state.
self.assertTrue(fastevent.get_init())
def test_get(self):
# __doc__ (as of 2008-08-02) for pygame.fastevent.get:
# pygame.fastevent.get() -> list of Events
# get all events from the queue
for _ in range(1, 11):
event.post(event.Event(pygame.USEREVENT))
self.assertListEqual(
[e.type for e in fastevent.get()],
[pygame.USEREVENT] * 10,
race_condition_notification,
)
def test_poll(self):
# __doc__ (as of 2008-08-02) for pygame.fastevent.poll:
# pygame.fastevent.poll() -> Event
# get an available event
#
# Returns next event on queue. If there is no event waiting on the
# queue, this will return an event with type NOEVENT.
self.assertEqual(
fastevent.poll().type, pygame.NOEVENT, race_condition_notification
)
def test_post(self):
# __doc__ (as of 2008-08-02) for pygame.fastevent.post:
# pygame.fastevent.post(Event) -> None
# place an event on the queue
#
# This will post your own event objects onto the event queue.
# You can past any event type you want, but some care must be
# taken. For example, if you post a MOUSEBUTTONDOWN event to the
# queue, it is likely any code receiving the event will expect
# the standard MOUSEBUTTONDOWN attributes to be available, like
# 'pos' and 'button'.
#
# Because pygame.fastevent.post() may have to wait for the queue
# to empty, you can get into a dead lock if you try to append an
# event on to a full queue from the thread that processes events.
# For that reason I do not recommend using this function in the
# main thread of an SDL program.
for _ in range(1, 11):
fastevent.post(event.Event(pygame.USEREVENT))
self.assertListEqual(
[e.type for e in event.get()],
[pygame.USEREVENT] * 10,
race_condition_notification,
)
try:
# Special case for post: METH_O.
fastevent.post(1)
except TypeError:
e = geterror()
msg = "argument 1 must be %s, not %s" % (
fastevent.Event.__name__,
type(1).__name__,
)
self.assertEqual(str(e), msg)
else:
self.fail()
def test_post__clear(self):
"""Ensure posted events can be cleared."""
for _ in range(10):
fastevent.post(event.Event(pygame.USEREVENT))
event.clear()
self.assertListEqual(fastevent.get(), [])
self.assertListEqual(event.get(), [])
def todo_test_pump(self):
# __doc__ (as of 2008-08-02) for pygame.fastevent.pump:
# pygame.fastevent.pump() -> None
# update the internal messages
#
# For each frame of your game, you will need to make some sort
# of call to the event queue. This ensures your program can internally
# interact with the rest of the operating system. If you are not using
# other event functions in your game, you should call pump() to allow
# pygame to handle internal actions.
#
# There are important things that must be dealt with internally in the
# event queue. The main window may need to be repainted. Certain joysticks
# must be polled for their values. If you fail to make a call to the event
# queue for too long, the system may decide your program has locked up.
self.fail()
def test_wait(self):
# __doc__ (as of 2008-08-02) for pygame.fastevent.wait:
# pygame.fastevent.wait() -> Event
# wait for an event
#
# Returns the current event on the queue. If there are no messages
# waiting on the queue, this will not return until one is
# available. Sometimes it is important to use this wait to get
# events from the queue, it will allow your application to idle
# when the user isn't doing anything with it.
event.post(pygame.event.Event(1))
self.assertEqual(fastevent.wait().type, 1, race_condition_notification)
################################################################################
if __name__ == "__main__":
unittest.main()
Binary file not shown.

After

Width:  |  Height:  |  Size: 92 B

@@ -0,0 +1,165 @@
STARTFONT 2.1
FONT -FontForge-PyGameMono-Medium-R-Normal--25-180-100-100-M-250-ISO10646-1
SIZE 18 100 100
FONTBOUNDINGBOX 21 22 0 0
COMMENT "Generated by fontforge, http://fontforge.sourceforge.net"
COMMENT "Created by Lenard Lindstrom,,, with FontForge 2.0 (http://fontforge.sf.net)"
STARTPROPERTIES 29
FOUNDRY "FontForge"
FAMILY_NAME "PyGameMono"
WEIGHT_NAME "Medium"
SLANT "R"
SETWIDTH_NAME "Normal"
ADD_STYLE_NAME ""
PIXEL_SIZE 25
POINT_SIZE 180
RESOLUTION_X 100
RESOLUTION_Y 100
SPACING "M"
AVERAGE_WIDTH 250
CHARSET_REGISTRY "ISO10646"
CHARSET_ENCODING "1"
FONTNAME_REGISTRY ""
CHARSET_COLLECTIONS "ISO10646-1"
FONT_NAME "PyGameMono"
FACE_NAME "PyGame Mono"
FONT_VERSION "001.000"
FONT_ASCENT 20
FONT_DESCENT 5
UNDERLINE_POSITION -2
UNDERLINE_THICKNESS 2
RAW_ASCENT 800
RAW_DESCENT 200
RELATIVE_WEIGHT 50
RELATIVE_SETWIDTH 50
FIGURE_WIDTH -1
AVG_UPPERCASE_WIDTH 250
ENDPROPERTIES
CHARS 5
STARTCHAR .notdef
ENCODING 0
SWIDTH 1000 0
DWIDTH 25 0
BBX 20 20 0 0
BITMAP
FFFFF0
FFFFF0
FE07F0
F801F0
F000F0
E00070
E00070
C00030
C00030
C00030
C00030
C00030
C00030
E00070
E00070
F000F0
F801F0
FE07F0
FFFFF0
FFFFF0
ENDCHAR
STARTCHAR A
ENCODING 65
SWIDTH 1000 0
DWIDTH 25 0
BBX 20 21 0 1
BITMAP
03FC00
1FFF80
3FFFC0
7C03E0
F000F0
E00070
E00070
F000F0
FC03F0
FFFFF0
FFFFF0
FFFFF0
FF0FF0
7C03F0
7801E0
7800E0
7000E0
700060
600060
200040
200040
ENDCHAR
STARTCHAR B
ENCODING 66
SWIDTH 1000 0
DWIDTH 25 0
BBX 18 20 1 0
BITMAP
FFFE00
FFFF80
7E0780
7801C0
7000C0
3000C0
3000C0
3801C0
3E0780
3FFF00
3FFF00
3E0780
380180
3000C0
3000C0
3000C0
7801C0
7E07C0
FFFF80
FFFE00
ENDCHAR
STARTCHAR C
ENCODING 67
SWIDTH 1000 0
DWIDTH 25 0
BBX 20 20 0 0
BITMAP
00FC00
03FF00
0FFF80
1F03E0
3E0070
7C0010
780000
F80000
F00000
F00000
F00000
F00000
F80000
780000
7C0010
3E0070
1F01E0
0FFFC0
03FF80
00FE00
ENDCHAR
STARTCHAR u13079
ENCODING 77945
SWIDTH 1000 0
DWIDTH 25 0
BBX 21 10 0 5
BITMAP
03FC00
0FFF80
1E73C0
78F8F0
F0F878
70F870
3870E0
1E03C0
0FFF80
03FC00
ENDCHAR
ENDFONT
@@ -0,0 +1,143 @@
STARTFONT 2.1
FONT -FontForge-PyGameMono-Medium-R-Normal--19-180-75-75-M-190-ISO10646-1
SIZE 18 75 75
FONTBOUNDINGBOX 15 17 0 0
COMMENT "Generated by fontforge, http://fontforge.sourceforge.net"
COMMENT "Created by Lenard Lindstrom,,, with FontForge 2.0 (http://fontforge.sf.net)"
STARTPROPERTIES 29
FOUNDRY "FontForge"
FAMILY_NAME "PyGameMono"
WEIGHT_NAME "Medium"
SLANT "R"
SETWIDTH_NAME "Normal"
ADD_STYLE_NAME ""
PIXEL_SIZE 19
POINT_SIZE 180
RESOLUTION_X 75
RESOLUTION_Y 75
SPACING "M"
AVERAGE_WIDTH 190
CHARSET_REGISTRY "ISO10646"
CHARSET_ENCODING "1"
FONTNAME_REGISTRY ""
CHARSET_COLLECTIONS "ISO10646-1"
FONT_NAME "PyGameMono"
FACE_NAME "PyGame Mono"
FONT_VERSION "001.000"
FONT_ASCENT 15
FONT_DESCENT 4
UNDERLINE_POSITION -2
UNDERLINE_THICKNESS 1
RAW_ASCENT 800
RAW_DESCENT 200
RELATIVE_WEIGHT 50
RELATIVE_SETWIDTH 50
FIGURE_WIDTH -1
AVG_UPPERCASE_WIDTH 190
ENDPROPERTIES
CHARS 5
STARTCHAR .notdef
ENCODING 0
SWIDTH 1000 0
DWIDTH 19 0
BBX 15 15 0 0
BITMAP
FFFE
FFFE
FC7E
F01E
E00E
C006
C006
C006
C006
C006
E00E
F01E
FC7E
FFFE
FFFE
ENDCHAR
STARTCHAR A
ENCODING 65
SWIDTH 1000 0
DWIDTH 19 0
BBX 15 17 0 0
BITMAP
0FE0
3FF8
783C
F01E
E00E
E00E
F01E
F83E
FFFE
FFFE
FC7E
701C
701C
600C
600C
4004
4004
ENDCHAR
STARTCHAR B
ENCODING 66
SWIDTH 1000 0
DWIDTH 19 0
BBX 15 15 0 0
BITMAP
FFF8
7FFC
780E
3006
3006
380E
3FF8
3FF8
3FF8
380E
3006
3006
7C1E
7FFC
FFF8
ENDCHAR
STARTCHAR C
ENCODING 67
SWIDTH 1000 0
DWIDTH 19 0
BBX 15 15 0 0
BITMAP
03E0
0FF8
3C1C
7806
7000
E000
E000
E000
E000
E000
7000
7806
3C1C
0FF8
03E0
ENDCHAR
STARTCHAR u13079
ENCODING 77945
SWIDTH 1000 0
DWIDTH 19 0
BBX 15 7 0 4
BITMAP
0FE0
3838
638C
E38E
638C
3838
0FE0
ENDCHAR
ENDFONT
@@ -0,0 +1,103 @@
STARTFONT 2.1
FONT -FontForge-PyGameMono-Medium-R-Normal--8-80-75-75-C-80-ISO10646-1
SIZE 8 75 75
FONTBOUNDINGBOX 6 7 0 0
COMMENT "Generated by fontforge, http://fontforge.sourceforge.net"
COMMENT "Created by Lenard Lindstrom,,, with FontForge 2.0 (http://fontforge.sf.net)"
STARTPROPERTIES 29
FOUNDRY "FontForge"
FAMILY_NAME "PyGameMono"
WEIGHT_NAME "Medium"
SLANT "R"
SETWIDTH_NAME "Normal"
ADD_STYLE_NAME ""
PIXEL_SIZE 8
POINT_SIZE 80
RESOLUTION_X 75
RESOLUTION_Y 75
SPACING "C"
AVERAGE_WIDTH 80
CHARSET_REGISTRY "ISO10646"
CHARSET_ENCODING "1"
FONTNAME_REGISTRY ""
CHARSET_COLLECTIONS "ISO10646-1"
FONT_NAME "PyGameMono"
FACE_NAME "PyGame Mono"
FONT_VERSION "001.000"
FONT_ASCENT 6
FONT_DESCENT 2
UNDERLINE_POSITION -1
UNDERLINE_THICKNESS 1
RAW_ASCENT 800
RAW_DESCENT 200
RELATIVE_WEIGHT 50
RELATIVE_SETWIDTH 50
FIGURE_WIDTH -1
AVG_UPPERCASE_WIDTH 80
ENDPROPERTIES
CHARS 5
STARTCHAR .notdef
ENCODING 0
SWIDTH 1000 0
DWIDTH 8 0
BBX 6 6 0 0
BITMAP
FC
84
84
84
84
FC
ENDCHAR
STARTCHAR A
ENCODING 65
SWIDTH 1000 0
DWIDTH 8 0
BBX 6 7 0 0
BITMAP
78
84
84
FC
84
84
84
ENDCHAR
STARTCHAR B
ENCODING 66
SWIDTH 1000 0
DWIDTH 8 0
BBX 6 6 0 0
BITMAP
FC
44
78
4C
44
FC
ENDCHAR
STARTCHAR C
ENCODING 67
SWIDTH 1000 0
DWIDTH 8 0
BBX 6 6 0 0
BITMAP
78
C4
C0
C0
C4
78
ENDCHAR
STARTCHAR u13079
ENCODING 77945
SWIDTH 1000 0
DWIDTH 8 0
BBX 6 4 0 1
BITMAP
78
B4
B4
78
ENDCHAR
ENDFONT
Binary file not shown.

After

Width:  |  Height:  |  Size: 89 B

@@ -0,0 +1,8 @@
#define resize_white_width 16
#define resize_white_height 16
#define resize_white_x_hot 7
#define resize_white_y_hot 7
static unsigned char resize_white_bits[] = {
0xff, 0x03, 0x01, 0x02, 0xfd, 0x03, 0x05, 0x00, 0xf5, 0x0f, 0x15, 0x08,
0xd5, 0xeb, 0x55, 0xaa, 0x55, 0xaa, 0xd7, 0xab, 0x10, 0xa8, 0xf0, 0xb7,
0x00, 0xa8, 0xc0, 0x9f, 0x40, 0x80, 0xc0, 0xff};
@@ -0,0 +1,8 @@
#define resize_white_mask_width 16
#define resize_white_mask_height 16
#define resize_white_mask_x_hot 7
#define resize_white_mask_y_hot 7
static unsigned char resize_white_mask_bits[] = {
0xff, 0x03, 0xff, 0x03, 0xff, 0x03, 0x07, 0x00, 0xf7, 0x0f, 0xf7, 0x0f,
0xf7, 0xef, 0x77, 0xee, 0x77, 0xee, 0xf7, 0xef, 0xf0, 0xef, 0xf0, 0xff,
0x00, 0xf8, 0xc0, 0xff, 0xc0, 0xff, 0xc0, 0xff};
@@ -0,0 +1 @@
__tags__ = []
@@ -0,0 +1,541 @@
# -*- coding: utf8 -*-
import sys
import os
import unittest
import platform
import pygame
from pygame import font as pygame_font # So font can be replaced with ftfont
from pygame.compat import as_unicode, unicode_, as_bytes, xrange_, filesystem_errors
from pygame.compat import PY_MAJOR_VERSION
FONTDIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "fonts")
UCS_4 = sys.maxunicode > 0xFFFF
def equal_images(s1, s2):
size = s1.get_size()
if s2.get_size() != size:
return False
w, h = size
for x in xrange_(w):
for y in xrange_(h):
if s1.get_at((x, y)) != s2.get_at((x, y)):
return False
return True
IS_PYPY = "PyPy" == platform.python_implementation()
@unittest.skipIf(IS_PYPY, "pypy skip known failure") # TODO
class FontModuleTest(unittest.TestCase):
def setUp(self):
pygame_font.init()
def tearDown(self):
pygame_font.quit()
def test_SysFont(self):
# Can only check that a font object is returned.
fonts = pygame_font.get_fonts()
if "arial" in fonts:
# Try to use arial font if it is there, rather than a random font
# which can be different depending on installed fonts on the system.
font_name = "arial"
else:
font_name = sorted(fonts)[0]
o = pygame_font.SysFont(font_name, 20)
self.assertTrue(isinstance(o, pygame_font.FontType))
o = pygame_font.SysFont(font_name, 20, italic=True)
self.assertTrue(isinstance(o, pygame_font.FontType))
o = pygame_font.SysFont(font_name, 20, bold=True)
self.assertTrue(isinstance(o, pygame_font.FontType))
o = pygame_font.SysFont("thisisnotafont", 20)
self.assertTrue(isinstance(o, pygame_font.FontType))
def test_get_default_font(self):
self.assertEqual(pygame_font.get_default_font(), "freesansbold.ttf")
def test_get_fonts_returns_something(self):
fnts = pygame_font.get_fonts()
self.assertTrue(fnts)
# to test if some files exist...
# def XXtest_has_file_osx_10_5_sdk(self):
# import os
# f = "/Developer/SDKs/MacOSX10.5.sdk/usr/X11/include/ft2build.h"
# self.assertEqual(os.path.exists(f), True)
# def XXtest_has_file_osx_10_4_sdk(self):
# import os
# f = "/Developer/SDKs/MacOSX10.4u.sdk/usr/X11R6/include/ft2build.h"
# self.assertEqual(os.path.exists(f), True)
def test_get_fonts(self):
fnts = pygame_font.get_fonts()
self.assertTrue(fnts, msg=repr(fnts))
if PY_MAJOR_VERSION >= 3:
# For Python 3.x, names will always be unicode strings.
name_types = (str,)
else:
# For Python 2.x, names may be either unicode or ascii strings.
name_types = (str, unicode)
for name in fnts:
# note, on ubuntu 2.6 they are all unicode strings.
self.assertTrue(isinstance(name, name_types), name)
# Font names can be comprised of only numeric characters, so
# just checking name.islower() will not work as expected here.
self.assertFalse(any(c.isupper() for c in name))
self.assertTrue(name.isalnum(), name)
def test_get_init(self):
self.assertTrue(pygame_font.get_init())
pygame_font.quit()
self.assertFalse(pygame_font.get_init())
def test_init(self):
pygame_font.init()
def test_match_font_all_exist(self):
fonts = pygame_font.get_fonts()
# Ensure all listed fonts are in fact available, and the returned file
# name is a full path.
for font in fonts:
path = pygame_font.match_font(font)
self.assertFalse(path is None)
self.assertTrue(os.path.isabs(path))
def test_match_font_bold(self):
fonts = pygame_font.get_fonts()
# Look for a bold font.
self.assertTrue(any(pygame_font.match_font(font, bold=True) for font in fonts))
def test_match_font_italic(self):
fonts = pygame_font.get_fonts()
# Look for an italic font.
self.assertTrue(
any(pygame_font.match_font(font, italic=True) for font in fonts)
)
def test_match_font_comma_separated(self):
fonts = pygame_font.get_fonts()
# Check for not found.
self.assertTrue(pygame_font.match_font("thisisnotafont") is None)
# Check comma separated list.
names = ",".join(["thisisnotafont", fonts[-1], "anothernonfont"])
self.assertFalse(pygame_font.match_font(names) is None)
names = ",".join(["thisisnotafont1", "thisisnotafont2", "thisisnotafont3"])
self.assertTrue(pygame_font.match_font(names) is None)
def test_quit(self):
pygame_font.quit()
@unittest.skipIf(IS_PYPY, "pypy skip known failure") # TODO
class FontTest(unittest.TestCase):
def setUp(self):
pygame_font.init()
def tearDown(self):
pygame_font.quit()
def test_render_args(self):
screen = pygame.display.set_mode((600, 400))
rect = screen.get_rect()
f = pygame_font.Font(None, 20)
screen.fill((10, 10, 10))
font_surface = f.render(" bar", True, (0, 0, 0), (255, 255, 255))
font_rect = font_surface.get_rect()
font_rect.topleft = rect.topleft
self.assertTrue(font_surface)
screen.blit(font_surface, font_rect, font_rect)
pygame.display.update()
self.assertEqual(tuple(screen.get_at((0, 0)))[:3], (255, 255, 255))
self.assertEqual(tuple(screen.get_at(font_rect.topleft))[:3], (255, 255, 255))
# If we don't have a real display, don't do this test.
# Transparent background doesn't seem to work without a read video card.
if os.environ.get("SDL_VIDEODRIVER") != "dummy":
screen.fill((10, 10, 10))
font_surface = f.render(" bar", True, (0, 0, 0), None)
font_rect = font_surface.get_rect()
font_rect.topleft = rect.topleft
self.assertTrue(font_surface)
screen.blit(font_surface, font_rect, font_rect)
pygame.display.update()
self.assertEqual(tuple(screen.get_at((0, 0)))[:3], (10, 10, 10))
self.assertEqual(tuple(screen.get_at(font_rect.topleft))[:3], (10, 10, 10))
screen.fill((10, 10, 10))
font_surface = f.render(" bar", True, (0, 0, 0))
font_rect = font_surface.get_rect()
font_rect.topleft = rect.topleft
self.assertTrue(font_surface)
screen.blit(font_surface, font_rect, font_rect)
pygame.display.update(rect)
self.assertEqual(tuple(screen.get_at((0, 0)))[:3], (10, 10, 10))
self.assertEqual(tuple(screen.get_at(font_rect.topleft))[:3], (10, 10, 10))
@unittest.skipIf(IS_PYPY, "pypy skip known failure") # TODO
class FontTypeTest(unittest.TestCase):
def setUp(self):
pygame_font.init()
def tearDown(self):
pygame_font.quit()
def test_get_ascent(self):
# Ckecking ascent would need a custom test font to do properly.
f = pygame_font.Font(None, 20)
ascent = f.get_ascent()
self.assertTrue(isinstance(ascent, int))
self.assertTrue(ascent > 0)
s = f.render("X", False, (255, 255, 255))
self.assertTrue(s.get_size()[1] > ascent)
def test_get_descent(self):
# Ckecking descent would need a custom test font to do properly.
f = pygame_font.Font(None, 20)
descent = f.get_descent()
self.assertTrue(isinstance(descent, int))
self.assertTrue(descent < 0)
def test_get_height(self):
# Ckecking height would need a custom test font to do properly.
f = pygame_font.Font(None, 20)
height = f.get_height()
self.assertTrue(isinstance(height, int))
self.assertTrue(height > 0)
s = f.render("X", False, (255, 255, 255))
self.assertTrue(s.get_size()[1] == height)
def test_get_linesize(self):
# Ckecking linesize would need a custom test font to do properly.
# Questions: How do linesize, height and descent relate?
f = pygame_font.Font(None, 20)
linesize = f.get_linesize()
self.assertTrue(isinstance(linesize, int))
self.assertTrue(linesize > 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.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_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))
# 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_set_bold(self):
f = pygame_font.Font(None, 20)
self.assertFalse(f.get_bold())
f.set_bold(True)
self.assertTrue(f.get_bold())
f.set_bold(False)
self.assertFalse(f.get_bold())
def test_set_italic(self):
f = pygame_font.Font(None, 20)
self.assertFalse(f.get_italic())
f.set_italic(True)
self.assertTrue(f.get_italic())
f.set_italic(False)
self.assertFalse(f.get_italic())
def test_set_underline(self):
f = pygame_font.Font(None, 20)
self.assertFalse(f.get_underline())
f.set_underline(True)
self.assertTrue(f.get_underline())
f.set_underline(False)
self.assertFalse(f.get_underline())
def test_size(self):
f = pygame_font.Font(None, 20)
text = as_unicode("Xg")
size = f.size(text)
w, h = size
s = f.render(text, False, (255, 255, 255))
btext = text.encode("ascii")
self.assertIsInstance(w, int)
self.assertIsInstance(h, int)
self.assertEqual(s.get_size(), size)
self.assertEqual(f.size(btext), size)
text = as_unicode(r"\u212A")
btext = text.encode("UTF-16")[2:] # Keep the byte order consistent.
bsize = f.size(btext)
try: # FIXME why do we do this try/except ?
size = f.size(text)
except pygame.error:
pass
else:
self.assertNotEqual(size, bsize)
def test_font_file_not_found(self):
# A per BUG reported by Bo Jangeborg on pygame-user mailing list,
# http://www.mail-archive.com/pygame-users@seul.org/msg11675.html
pygame_font.init()
self.assertRaises(
IOError, pygame_font.Font, unicode_("some-fictional-font.ttf"), 20
)
def test_load_from_file(self):
font_name = pygame_font.get_default_font()
font_path = os.path.join(
os.path.split(pygame.__file__)[0], pygame_font.get_default_font()
)
f = pygame_font.Font(font_path, 20)
def test_load_from_file_obj(self):
font_name = pygame_font.get_default_font()
font_path = os.path.join(
os.path.split(pygame.__file__)[0], pygame_font.get_default_font()
)
with open(font_path, "rb") as f:
font = pygame_font.Font(f, 20)
def test_load_default_font_filename(self):
# In font_init, a special case is when the filename argument is
# identical to the default font file name.
f = pygame_font.Font(pygame_font.get_default_font(), 20)
def _load_unicode(self, path):
import shutil
fdir = unicode_(FONTDIR)
temp = os.path.join(fdir, path)
pgfont = os.path.join(fdir, u"test_sans.ttf")
shutil.copy(pgfont, temp)
try:
with open(temp, "rb") as f:
pass
except IOError:
raise unittest.SkipTest("the path cannot be opened")
try:
pygame_font.Font(temp, 20)
finally:
os.remove(temp)
def test_load_from_file_unicode_0(self):
"""ASCII string as a unicode object"""
self._load_unicode(u"temp_file.ttf")
def test_load_from_file_unicode_1(self):
self._load_unicode(u"你好.ttf")
def test_load_from_file_bytes(self):
font_path = os.path.join(
os.path.split(pygame.__file__)[0], pygame_font.get_default_font()
)
filesystem_encoding = sys.getfilesystemencoding()
try: # FIXME why do we do this try/except ?
font_path = font_path.decode(filesystem_encoding, filesystem_errors)
except AttributeError:
pass
bfont_path = font_path.encode(filesystem_encoding, filesystem_errors)
f = pygame_font.Font(bfont_path, 20)
@unittest.skipIf(IS_PYPY, "pypy skip known failure") # TODO
class VisualTests(unittest.TestCase):
__tags__ = ["interactive"]
screen = None
aborted = False
def setUp(self):
if self.screen is None:
pygame.init()
self.screen = pygame.display.set_mode((600, 200))
self.screen.fill((255, 255, 255))
pygame.display.flip()
self.f = pygame_font.Font(None, 32)
def abort(self):
if self.screen is not None:
pygame.quit()
self.aborted = True
def query(self, bold=False, italic=False, underline=False, antialiase=False):
if self.aborted:
return False
spacing = 10
offset = 20
y = spacing
f = self.f
screen = self.screen
screen.fill((255, 255, 255))
pygame.display.flip()
if not (bold or italic or underline or antialiase):
text = "normal"
else:
modes = []
if bold:
modes.append("bold")
if italic:
modes.append("italic")
if underline:
modes.append("underlined")
if antialiase:
modes.append("antialiased")
text = "%s (y/n):" % ("-".join(modes),)
f.set_bold(bold)
f.set_italic(italic)
f.set_underline(underline)
s = f.render(text, antialiase, (0, 0, 0))
screen.blit(s, (offset, y))
y += s.get_size()[1] + spacing
f.set_bold(False)
f.set_italic(False)
f.set_underline(False)
s = f.render("(some comparison text)", False, (0, 0, 0))
screen.blit(s, (offset, y))
pygame.display.flip()
while 1:
for evt in pygame.event.get():
if evt.type == pygame.KEYDOWN:
if evt.key == pygame.K_ESCAPE:
self.abort()
return False
if evt.key == pygame.K_y:
return True
if evt.key == pygame.K_n:
return False
if evt.type == pygame.QUIT:
self.abort()
return False
def test_bold(self):
self.assertTrue(self.query(bold=True))
def test_italic(self):
self.assertTrue(self.query(italic=True))
def test_underline(self):
self.assertTrue(self.query(underline=True))
def test_antialiase(self):
self.assertTrue(self.query(antialiase=True))
def test_bold_antialiase(self):
self.assertTrue(self.query(bold=True, antialiase=True))
def test_italic_underline(self):
self.assertTrue(self.query(italic=True, underline=True))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,11 @@
__tags__ = ["development"]
exclude = False
try:
import pygame.freetype
except ImportError:
exclude = True
if exclude:
__tags__.extend(["ignore", "subprocess_ignore"])
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,11 @@
__tags__ = ["development"]
exclude = False
try:
import pygame.ftfont
except ImportError:
exclude = True
if exclude:
__tags__.extend(["ignore", "subprocess_ignore"])
@@ -0,0 +1,19 @@
import sys
import os
import unittest
from pygame.tests import font_test
import pygame.ftfont
font_test.pygame_font = pygame.ftfont
# Disable UCS-4 specific tests as this "Font" type does accept UCS-4 codes.
font_test.UCS_4 = False
for name in dir(font_test):
obj = getattr(font_test, name)
if isinstance(obj, type) and issubclass(obj, unittest.TestCase): # conditional and
new_name = "Ft%s" % name
globals()[new_name] = type(new_name, (obj,), {})
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,879 @@
import unittest
import pygame
import pygame.gfxdraw
from pygame.locals import *
from pygame.tests.test_utils import SurfaceSubclass
def intensity(c, i):
"""Return color c changed by intensity i
For 0 <= i <= 127 the color is a shade, with 0 being black, 127 being the
unaltered color.
For 128 <= i <= 255 the color is a tint, with 255 being white, 128 the
unaltered color.
"""
r, g, b = c[0:3]
if 0 <= i <= 127:
# Darken
return ((r * i) // 127, (g * i) // 127, (b * i) // 127)
# Lighten
return (
r + ((255 - r) * (255 - i)) // 127,
g + ((255 - g) * (255 - i)) // 127,
b + ((255 - b) * (255 - i)) // 127,
)
class GfxdrawDefaultTest(unittest.TestCase):
is_started = False
foreground_color = (128, 64, 8)
background_color = (255, 255, 255)
def make_palette(base_color):
"""Return color palette that is various intensities of base_color"""
# Need this function for Python 3.x so the base_color
# is within the scope of the list comprehension.
return [intensity(base_color, i) for i in range(0, 256)]
default_palette = make_palette(foreground_color)
default_size = (100, 100)
def check_at(self, surf, posn, color):
sc = surf.get_at(posn)
fail_msg = "%s != %s at %s, bitsize: %i, flags: %i, masks: %s" % (
sc,
color,
posn,
surf.get_bitsize(),
surf.get_flags(),
surf.get_masks(),
)
self.assertEqual(sc, color, fail_msg)
def check_not_at(self, surf, posn, color):
sc = surf.get_at(posn)
fail_msg = "%s != %s at %s, bitsize: %i, flags: %i, masks: %s" % (
sc,
color,
posn,
surf.get_bitsize(),
surf.get_flags(),
surf.get_masks(),
)
self.assertNotEqual(sc, color, fail_msg)
@classmethod
def setUpClass(cls):
# Necessary for Surface.set_palette.
pygame.init()
pygame.display.set_mode((1, 1))
@classmethod
def tearDownClass(cls):
pygame.quit()
def setUp(self):
# This makes sure pygame is always initialized before each test (in
# case a test calls pygame.quit()).
if not pygame.get_init():
pygame.init()
Surface = pygame.Surface
size = self.default_size
palette = self.default_palette
if not self.is_started:
# Create test surfaces
self.surfaces = [
Surface(size, 0, 8),
Surface(size, SRCALPHA, 16),
Surface(size, SRCALPHA, 32),
]
self.surfaces[0].set_palette(palette)
nonpalette_fmts = (
# (8, (0xe0, 0x1c, 0x3, 0x0)),
(12, (0xF00, 0xF0, 0xF, 0x0)),
(15, (0x7C00, 0x3E0, 0x1F, 0x0)),
(15, (0x1F, 0x3E0, 0x7C00, 0x0)),
(16, (0xF00, 0xF0, 0xF, 0xF000)),
(16, (0xF000, 0xF00, 0xF0, 0xF)),
(16, (0xF, 0xF0, 0xF00, 0xF000)),
(16, (0xF0, 0xF00, 0xF000, 0xF)),
(16, (0x7C00, 0x3E0, 0x1F, 0x8000)),
(16, (0xF800, 0x7C0, 0x3E, 0x1)),
(16, (0x1F, 0x3E0, 0x7C00, 0x8000)),
(16, (0x3E, 0x7C0, 0xF800, 0x1)),
(16, (0xF800, 0x7E0, 0x1F, 0x0)),
(16, (0x1F, 0x7E0, 0xF800, 0x0)),
(24, (0xFF, 0xFF00, 0xFF0000, 0x0)),
(24, (0xFF0000, 0xFF00, 0xFF, 0x0)),
(32, (0xFF0000, 0xFF00, 0xFF, 0x0)),
(32, (0xFF000000, 0xFF0000, 0xFF00, 0x0)),
(32, (0xFF, 0xFF00, 0xFF0000, 0x0)),
(32, (0xFF00, 0xFF0000, 0xFF000000, 0x0)),
(32, (0xFF0000, 0xFF00, 0xFF, 0xFF000000)),
(32, (0xFF000000, 0xFF0000, 0xFF00, 0xFF)),
(32, (0xFF, 0xFF00, 0xFF0000, 0xFF000000)),
(32, (0xFF00, 0xFF0000, 0xFF000000, 0xFF)),
)
for bitsize, masks in nonpalette_fmts:
self.surfaces.append(Surface(size, 0, bitsize, masks))
for surf in self.surfaces:
surf.fill(self.background_color)
def test_gfxdraw__subclassed_surface(self):
"""Ensure pygame.gfxdraw works on subclassed surfaces."""
surface = SurfaceSubclass((11, 13), SRCALPHA, 32)
surface.fill(pygame.Color("blue"))
expected_color = pygame.Color("red")
x, y = 1, 2
pygame.gfxdraw.pixel(surface, x, y, expected_color)
self.assertEqual(surface.get_at((x, y)), expected_color)
def test_pixel(self):
"""pixel(surface, x, y, color): return None"""
fg = self.foreground_color
bg = self.background_color
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.pixel(surf, 2, 2, fg)
for x in range(1, 4):
for y in range(1, 4):
if x == 2 and y == 2:
self.check_at(surf, (x, y), fg_adjusted)
else:
self.check_at(surf, (x, y), bg_adjusted)
def test_hline(self):
"""hline(surface, x1, x2, y, color): return None"""
fg = self.foreground_color
bg = self.background_color
startx = 10
stopx = 80
y = 50
fg_test_points = [(startx, y), (stopx, y), ((stopx - startx) // 2, y)]
bg_test_points = [
(startx - 1, y),
(stopx + 1, y),
(startx, y - 1),
(startx, y + 1),
(stopx, y - 1),
(stopx, y + 1),
]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.hline(surf, startx, stopx, y, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_vline(self):
"""vline(surface, x, y1, y2, color): return None"""
fg = self.foreground_color
bg = self.background_color
x = 50
starty = 10
stopy = 80
fg_test_points = [(x, starty), (x, stopy), (x, (stopy - starty) // 2)]
bg_test_points = [
(x, starty - 1),
(x, stopy + 1),
(x - 1, starty),
(x + 1, starty),
(x - 1, stopy),
(x + 1, stopy),
]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.vline(surf, x, starty, stopy, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_rectangle(self):
"""rectangle(surface, rect, color): return None"""
fg = self.foreground_color
bg = self.background_color
rect = pygame.Rect(10, 15, 55, 62)
rect_tuple = tuple(rect)
fg_test_points = [
rect.topleft,
(rect.right - 1, rect.top),
(rect.left, rect.bottom - 1),
(rect.right - 1, rect.bottom - 1),
]
bg_test_points = [
(rect.left - 1, rect.top - 1),
(rect.left + 1, rect.top + 1),
(rect.right, rect.top - 1),
(rect.right - 2, rect.top + 1),
(rect.left - 1, rect.bottom),
(rect.left + 1, rect.bottom - 2),
(rect.right, rect.bottom),
(rect.right - 2, rect.bottom - 2),
]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.rectangle(surf, rect, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
surf.fill(bg)
pygame.gfxdraw.rectangle(surf, rect_tuple, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_box(self):
"""box(surface, rect, color): return None"""
fg = self.foreground_color
bg = self.background_color
rect = pygame.Rect(10, 15, 55, 62)
rect_tuple = tuple(rect)
fg_test_points = [
rect.topleft,
(rect.left + 1, rect.top + 1),
(rect.right - 1, rect.top),
(rect.right - 2, rect.top + 1),
(rect.left, rect.bottom - 1),
(rect.left + 1, rect.bottom - 2),
(rect.right - 1, rect.bottom - 1),
(rect.right - 2, rect.bottom - 2),
]
bg_test_points = [
(rect.left - 1, rect.top - 1),
(rect.right, rect.top - 1),
(rect.left - 1, rect.bottom),
(rect.right, rect.bottom),
]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.box(surf, rect, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
surf.fill(bg)
pygame.gfxdraw.box(surf, rect_tuple, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_line(self):
"""line(surface, x1, y1, x2, y2, color): return None"""
fg = self.foreground_color
bg = self.background_color
x1 = 10
y1 = 15
x2 = 92
y2 = 77
fg_test_points = [(x1, y1), (x2, y2)]
bg_test_points = [
(x1 - 1, y1),
(x1, y1 - 1),
(x1 - 1, y1 - 1),
(x2 + 1, y2),
(x2, y2 + 1),
(x2 + 1, y2 + 1),
]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.line(surf, x1, y1, x2, y2, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_circle(self):
"""circle(surface, x, y, r, color): return None"""
fg = self.foreground_color
bg = self.background_color
x = 45
y = 40
r = 30
fg_test_points = [(x, y - r), (x, y + r), (x - r, y), (x + r, y)]
bg_test_points = [
(x, y),
(x, y - r + 1),
(x, y - r - 1),
(x, y + r + 1),
(x, y + r - 1),
(x - r - 1, y),
(x - r + 1, y),
(x + r + 1, y),
(x + r - 1, y),
]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.circle(surf, x, y, r, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_arc(self):
"""arc(surface, x, y, r, start, end, color): return None"""
fg = self.foreground_color
bg = self.background_color
x = 45
y = 40
r = 30
start = 0 # +x direction, but not (x + r, y) (?)
end = 90 # -y direction, including (x, y + r)
fg_test_points = [(x, y + r), (x + r, y + 1)]
bg_test_points = [
(x, y),
(x, y - r),
(x - r, y),
(x, y + r + 1),
(x, y + r - 1),
(x - 1, y + r),
(x + r + 1, y),
(x + r - 1, y),
(x + r, y),
]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.arc(surf, x, y, r, start, end, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_aacircle(self):
"""aacircle(surface, x, y, r, color): return None"""
fg = self.foreground_color
bg = self.background_color
x = 45
y = 40
r = 30
fg_test_points = [(x, y - r), (x, y + r), (x - r, y), (x + r, y)]
bg_test_points = [
(x, y),
(x, y - r + 1),
(x, y - r - 1),
(x, y + r + 1),
(x, y + r - 1),
(x - r - 1, y),
(x - r + 1, y),
(x + r + 1, y),
(x + r - 1, y),
]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.aacircle(surf, x, y, r, fg)
for posn in fg_test_points:
self.check_not_at(surf, posn, bg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_filled_circle(self):
"""filled_circle(surface, x, y, r, color): return None"""
fg = self.foreground_color
bg = self.background_color
x = 45
y = 40
r = 30
fg_test_points = [
(x, y - r),
(x, y - r + 1),
(x, y + r),
(x, y + r - 1),
(x - r, y),
(x - r + 1, y),
(x + r, y),
(x + r - 1, y),
(x, y),
]
bg_test_points = [
(x, y - r - 1),
(x, y + r + 1),
(x - r - 1, y),
(x + r + 1, y),
]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.filled_circle(surf, x, y, r, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_ellipse(self):
"""ellipse(surface, x, y, rx, ry, color): return None"""
fg = self.foreground_color
bg = self.background_color
x = 45
y = 40
rx = 30
ry = 35
fg_test_points = [(x, y - ry), (x, y + ry), (x - rx, y), (x + rx, y)]
bg_test_points = [
(x, y),
(x, y - ry + 1),
(x, y - ry - 1),
(x, y + ry + 1),
(x, y + ry - 1),
(x - rx - 1, y),
(x - rx + 1, y),
(x + rx + 1, y),
(x + rx - 1, y),
]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.ellipse(surf, x, y, rx, ry, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_aaellipse(self):
"""aaellipse(surface, x, y, rx, ry, color): return None"""
fg = self.foreground_color
bg = self.background_color
x = 45
y = 40
rx = 30
ry = 35
fg_test_points = [(x, y - ry), (x, y + ry), (x - rx, y), (x + rx, y)]
bg_test_points = [
(x, y),
(x, y - ry + 1),
(x, y - ry - 1),
(x, y + ry + 1),
(x, y + ry - 1),
(x - rx - 1, y),
(x - rx + 1, y),
(x + rx + 1, y),
(x + rx - 1, y),
]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.aaellipse(surf, x, y, rx, ry, fg)
for posn in fg_test_points:
self.check_not_at(surf, posn, bg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_filled_ellipse(self):
"""filled_ellipse(surface, x, y, rx, ry, color): return None"""
fg = self.foreground_color
bg = self.background_color
x = 45
y = 40
rx = 30
ry = 35
fg_test_points = [
(x, y - ry),
(x, y - ry + 1),
(x, y + ry),
(x, y + ry - 1),
(x - rx, y),
(x - rx + 1, y),
(x + rx, y),
(x + rx - 1, y),
(x, y),
]
bg_test_points = [
(x, y - ry - 1),
(x, y + ry + 1),
(x - rx - 1, y),
(x + rx + 1, y),
]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.filled_ellipse(surf, x, y, rx, ry, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_pie(self):
"""pie(surface, x, y, r, start, end, color): return None"""
fg = self.foreground_color
bg = self.background_color
x = 45
y = 40
r = 30
start = 0 # +x direction, including (x + r, y)
end = 90 # -y direction, but not (x, y + r) (?)
fg_test_points = [(x, y), (x + 1, y), (x, y + 1), (x + r, y)]
bg_test_points = [
(x - 1, y),
(x, y - 1),
(x - 1, y - 1),
(x + 1, y + 1),
(x + r + 1, y),
(x + r, y - 1),
(x, y + r + 1),
]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.pie(surf, x, y, r, start, end, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_trigon(self):
"""trigon(surface, x1, y1, x2, y2, x3, y3, color): return None"""
fg = self.foreground_color
bg = self.background_color
x1 = 10
y1 = 15
x2 = 92
y2 = 77
x3 = 20
y3 = 60
fg_test_points = [(x1, y1), (x2, y2), (x3, y3)]
bg_test_points = [
(x1 - 1, y1 - 1),
(x2 + 1, y2 + 1),
(x3 - 1, y3 + 1),
(x1 + 10, y1 + 30),
]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.trigon(surf, x1, y1, x2, y2, x3, y3, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_aatrigon(self):
"""aatrigon(surface, x1, y1, x2, y2, x3, y3, color): return None"""
fg = self.foreground_color
bg = self.background_color
x1 = 10
y1 = 15
x2 = 92
y2 = 77
x3 = 20
y3 = 60
fg_test_points = [(x1, y1), (x2, y2), (x3, y3)]
bg_test_points = [
(x1 - 1, y1 - 1),
(x2 + 1, y2 + 1),
(x3 - 1, y3 + 1),
(x1 + 10, y1 + 30),
]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.aatrigon(surf, x1, y1, x2, y2, x3, y3, fg)
for posn in fg_test_points:
self.check_not_at(surf, posn, bg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
@unittest.expectedFailure
def test_aatrigon__with_horizontal_edge(self):
"""Ensure aatrigon draws horizontal edges correctly.
This test creates 2 surfaces and draws an aatrigon on each. The pixels
on each surface are compared to ensure they are the same. The only
difference between the 2 aatrigons is the order the points are drawn.
The order of the points should have no impact on the final drawing.
Related to issue #622.
"""
bg_color = pygame.Color("white")
line_color = pygame.Color("black")
width, height = 11, 10
expected_surface = pygame.Surface((width, height), 0, 32)
expected_surface.fill(bg_color)
surface = pygame.Surface((width, height), 0, 32)
surface.fill(bg_color)
x1, y1 = width - 1, 0
x2, y2 = (width - 1) // 2, height - 1
x3, y3 = 0, 0
# The points in this order draw as expected.
pygame.gfxdraw.aatrigon(expected_surface, x1, y1, x2, y2, x3, y3, line_color)
# The points in reverse order fail to draw the horizontal edge along
# the top.
pygame.gfxdraw.aatrigon(surface, x3, y3, x2, y2, x1, y1, line_color)
# The surfaces are locked for a possible speed up of pixel access.
expected_surface.lock()
surface.lock()
for x in range(width):
for y in range(height):
self.assertEqual(
expected_surface.get_at((x, y)),
surface.get_at((x, y)),
"pos=({}, {})".format(x, y),
)
surface.unlock()
expected_surface.unlock()
def test_filled_trigon(self):
"""filled_trigon(surface, x1, y1, x2, y2, x3, y3, color): return None"""
fg = self.foreground_color
bg = self.background_color
x1 = 10
y1 = 15
x2 = 92
y2 = 77
x3 = 20
y3 = 60
fg_test_points = [(x1, y1), (x2, y2), (x3, y3), (x1 + 10, y1 + 30)]
bg_test_points = [(x1 - 1, y1 - 1), (x2 + 1, y2 + 1), (x3 - 1, y3 + 1)]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.filled_trigon(surf, x1, y1, x2, y2, x3, y3, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_polygon(self):
"""polygon(surface, points, color): return None"""
fg = self.foreground_color
bg = self.background_color
points = [(10, 80), (10, 15), (92, 25), (92, 80)]
fg_test_points = points + [
(points[0][0], points[0][1] - 1),
(points[0][0] + 1, points[0][1]),
(points[3][0] - 1, points[3][1]),
(points[3][0], points[3][1] - 1),
(points[2][0], points[2][1] + 1),
]
bg_test_points = [
(points[0][0] - 1, points[0][1]),
(points[0][0], points[0][1] + 1),
(points[0][0] - 1, points[0][1] + 1),
(points[0][0] + 1, points[0][1] - 1),
(points[3][0] + 1, points[3][1]),
(points[3][0], points[3][1] + 1),
(points[3][0] + 1, points[3][1] + 1),
(points[3][0] - 1, points[3][1] - 1),
(points[2][0] + 1, points[2][1]),
(points[2][0] - 1, points[2][1] + 1),
(points[1][0] - 1, points[1][1]),
(points[1][0], points[1][1] - 1),
(points[1][0] - 1, points[1][1] - 1),
]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.polygon(surf, points, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_aapolygon(self):
"""aapolygon(surface, points, color): return None"""
fg = self.foreground_color
bg = self.background_color
points = [(10, 80), (10, 15), (92, 25), (92, 80)]
fg_test_points = points
bg_test_points = [
(points[0][0] - 1, points[0][1]),
(points[0][0], points[0][1] + 1),
(points[0][0] - 1, points[0][1] + 1),
(points[0][0] + 1, points[0][1] - 1),
(points[3][0] + 1, points[3][1]),
(points[3][0], points[3][1] + 1),
(points[3][0] + 1, points[3][1] + 1),
(points[3][0] - 1, points[3][1] - 1),
(points[2][0] + 1, points[2][1]),
(points[2][0] - 1, points[2][1] + 1),
(points[1][0] - 1, points[1][1]),
(points[1][0], points[1][1] - 1),
(points[1][0] - 1, points[1][1] - 1),
]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.aapolygon(surf, points, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_not_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
@unittest.expectedFailure
def test_aapolygon__with_horizontal_edge(self):
"""Ensure aapolygon draws horizontal edges correctly.
This test creates 2 surfaces and draws a polygon on each. The pixels
on each surface are compared to ensure they are the same. The only
difference between the 2 polygons is that one is drawn using
aapolygon() and the other using multiple line() calls. They should
produce the same final drawing.
Related to issue #622.
"""
bg_color = pygame.Color("white")
line_color = pygame.Color("black")
width, height = 11, 10
expected_surface = pygame.Surface((width, height), 0, 32)
expected_surface.fill(bg_color)
surface = pygame.Surface((width, height), 0, 32)
surface.fill(bg_color)
points = ((0, 0), (0, height - 1), (width - 1, height - 1), (width - 1, 0))
# The points are used to draw the expected aapolygon using the line()
# function.
for (x1, y1), (x2, y2) in zip(points, points[1:] + points[:1]):
pygame.gfxdraw.line(expected_surface, x1, y1, x2, y2, line_color)
# The points in this order fail to draw the horizontal edge along
# the top.
pygame.gfxdraw.aapolygon(surface, points, line_color)
# The surfaces are locked for a possible speed up of pixel access.
expected_surface.lock()
surface.lock()
for x in range(width):
for y in range(height):
self.assertEqual(
expected_surface.get_at((x, y)),
surface.get_at((x, y)),
"pos=({}, {})".format(x, y),
)
surface.unlock()
expected_surface.unlock()
def test_filled_polygon(self):
"""filled_polygon(surface, points, color): return None"""
fg = self.foreground_color
bg = self.background_color
points = [(10, 80), (10, 15), (92, 25), (92, 80)]
fg_test_points = points + [
(points[0][0], points[0][1] - 1),
(points[0][0] + 1, points[0][1]),
(points[0][0] + 1, points[0][1] - 1),
(points[3][0] - 1, points[3][1]),
(points[3][0], points[3][1] - 1),
(points[3][0] - 1, points[3][1] - 1),
(points[2][0], points[2][1] + 1),
(points[2][0] - 1, points[2][1] + 1),
]
bg_test_points = [
(points[0][0] - 1, points[0][1]),
(points[0][0], points[0][1] + 1),
(points[0][0] - 1, points[0][1] + 1),
(points[3][0] + 1, points[3][1]),
(points[3][0], points[3][1] + 1),
(points[3][0] + 1, points[3][1] + 1),
(points[2][0] + 1, points[2][1]),
(points[1][0] - 1, points[1][1]),
(points[1][0], points[1][1] - 1),
(points[1][0] - 1, points[1][1] - 1),
]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.filled_polygon(surf, points, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_textured_polygon(self):
"""textured_polygon(surface, points, texture, tx, ty): return None"""
w, h = self.default_size
fg = self.foreground_color
bg = self.background_color
tx = 0
ty = 0
texture = pygame.Surface((w + tx, h + ty), 0, 24)
texture.fill(fg, (0, 0, w, h))
points = [(10, 80), (10, 15), (92, 25), (92, 80)]
# Don't know how to really check this as boarder points may
# or may not be included in the textured polygon.
fg_test_points = [(points[1][0] + 30, points[1][1] + 40)]
bg_test_points = [
(points[0][0] - 1, points[0][1]),
(points[0][0], points[0][1] + 1),
(points[0][0] - 1, points[0][1] + 1),
(points[3][0] + 1, points[3][1]),
(points[3][0], points[3][1] + 1),
(points[3][0] + 1, points[3][1] + 1),
(points[2][0] + 1, points[2][1]),
(points[1][0] - 1, points[1][1]),
(points[1][0], points[1][1] - 1),
(points[1][0] - 1, points[1][1] - 1),
]
for surf in self.surfaces[1:]:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.textured_polygon(surf, points, texture, -tx, -ty)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
# Alpha blit to 8 bits-per-pixel surface forbidden.
texture = pygame.Surface(self.default_size, SRCALPHA, 32)
self.assertRaises(
ValueError,
pygame.gfxdraw.textured_polygon,
self.surfaces[0],
points,
texture,
0,
0,
)
def test_bezier(self):
"""bezier(surface, points, steps, color): return None"""
fg = self.foreground_color
bg = self.background_color
points = [(10, 50), (25, 15), (60, 80), (92, 30)]
fg_test_points = [points[0], points[3]]
bg_test_points = [
(points[0][0] - 1, points[0][1]),
(points[3][0] + 1, points[3][1]),
(points[1][0], points[1][1] + 3),
(points[2][0], points[2][1] - 3),
]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.bezier(surf, points, 30, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,46 @@
import os
import unittest
from pygame.tests import test_utils
import pygame
from pygame.locals import *
@unittest.skipIf(
os.environ.get("SDL_VIDEODRIVER") == "dummy",
'OpenGL requires a non-"dummy" SDL_VIDEODRIVER',
)
class GL_ImageSave(unittest.TestCase):
def test_image_save_works_with_opengl_surfaces(self):
"""
|tags:display,slow,opengl|
"""
pygame.display.init()
screen = pygame.display.set_mode((640, 480), OPENGL | DOUBLEBUF)
pygame.display.flip()
tmp_dir = test_utils.get_tmp_dir()
# Try the imageext module.
tmp_file = os.path.join(tmp_dir, "opengl_save_surface_test.png")
pygame.image.save(screen, tmp_file)
self.assertTrue(os.path.exists(tmp_file))
os.remove(tmp_file)
# Only test the image module.
tmp_file = os.path.join(tmp_dir, "opengl_save_surface_test.bmp")
pygame.image.save(screen, tmp_file)
self.assertTrue(os.path.exists(tmp_file))
os.remove(tmp_file)
# stops tonnes of tmp dirs building up in trunk dir
os.rmdir(tmp_dir)
pygame.display.quit()
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,7 @@
__tags__ = []
import pygame
import sys
if "pygame.image" not in sys.modules:
__tags__.extend(("ignore", "subprocess_ignore"))
@@ -0,0 +1,586 @@
# -*- coding: utf-8 -*-
import array
import os
import tempfile
import unittest
import glob
from pygame.tests.test_utils import example_path, png, tostring
import pygame, pygame.image, pygame.pkgdata
from pygame.compat import xrange_, ord_, unicode_
def test_magic(f, magic_hex):
""" tests a given file to see if the magic hex matches.
"""
data = f.read(len(magic_hex))
if len(data) != len(magic_hex):
return 0
for i in range(len(magic_hex)):
if magic_hex[i] != ord_(data[i]):
return 0
return 1
class ImageModuleTest(unittest.TestCase):
def testLoadIcon(self):
""" see if we can load the pygame icon.
"""
f = pygame.pkgdata.getResource("pygame_icon.bmp")
self.assertEqual(f.mode, "rb")
surf = pygame.image.load_basic(f)
self.assertEqual(surf.get_at((0, 0)), (5, 4, 5, 255))
self.assertEqual(surf.get_height(), 32)
self.assertEqual(surf.get_width(), 32)
def testLoadPNG(self):
""" see if we can load a png with color values in the proper channels.
"""
# Create a PNG file with known colors
reddish_pixel = (210, 0, 0, 255)
greenish_pixel = (0, 220, 0, 255)
bluish_pixel = (0, 0, 230, 255)
greyish_pixel = (110, 120, 130, 140)
pixel_array = [reddish_pixel + greenish_pixel, bluish_pixel + greyish_pixel]
f_descriptor, f_path = tempfile.mkstemp(suffix=".png")
with os.fdopen(f_descriptor, "wb") as f:
w = png.Writer(2, 2, alpha=True)
w.write(f, pixel_array)
# Read the PNG file and verify that pygame interprets it correctly
surf = pygame.image.load(f_path)
self.assertEqual(surf.get_at((0, 0)), reddish_pixel)
self.assertEqual(surf.get_at((1, 0)), greenish_pixel)
self.assertEqual(surf.get_at((0, 1)), bluish_pixel)
self.assertEqual(surf.get_at((1, 1)), greyish_pixel)
# Read the PNG file obj. and verify that pygame interprets it correctly
with open(f_path, "rb") as f:
surf = pygame.image.load(f)
self.assertEqual(surf.get_at((0, 0)), reddish_pixel)
self.assertEqual(surf.get_at((1, 0)), greenish_pixel)
self.assertEqual(surf.get_at((0, 1)), bluish_pixel)
self.assertEqual(surf.get_at((1, 1)), greyish_pixel)
os.remove(f_path)
def testLoadJPG(self):
""" see if we can load a jpg.
"""
f = example_path("data/alien1.jpg") # normalized
# f = os.path.join("examples", "data", "alien1.jpg")
surf = pygame.image.load(f)
with open(f, "rb") as f:
surf = pygame.image.load(f)
# with open(os.path.join("examples", "data", "alien1.jpg"), "rb") as f:
# surf = pygame.image.load(open(os.path.join("examples", "data",
# "alien1.jpg"), "rb"))
def testSaveJPG(self):
""" JPG equivalent to issue #211 - color channel swapping
Make sure the SDL surface color masks represent the rgb memory format
required by the JPG library. The masks are machine endian dependent
"""
from pygame import Color, Rect
# The source image is a 2 by 2 square of four colors. Since JPEG is
# lossy, there can be color bleed. Make each color square 16 by 16,
# to avoid the significantly color value distorts found at color
# boundaries due to the compression value set by Pygame.
square_len = 16
sz = 2 * square_len, 2 * square_len
# +---------------------------------+
# | red | green |
# |----------------+----------------|
# | blue | (255, 128, 64) |
# +---------------------------------+
#
# as (rect, color) pairs.
def as_rect(square_x, square_y):
return Rect(
square_x * square_len, square_y * square_len, square_len, square_len
)
squares = [
(as_rect(0, 0), Color("red")),
(as_rect(1, 0), Color("green")),
(as_rect(0, 1), Color("blue")),
(as_rect(1, 1), Color(255, 128, 64)),
]
# A surface format which is not directly usable with libjpeg.
surf = pygame.Surface(sz, 0, 32)
for rect, color in squares:
surf.fill(color, rect)
# Assume pygame.image.Load works correctly as it is handled by the
# third party SDL_image library.
f_path = tempfile.mktemp(suffix=".jpg")
pygame.image.save(surf, f_path)
jpg_surf = pygame.image.load(f_path)
# Allow for small differences in the restored colors.
def approx(c):
mask = 0xFC
return pygame.Color(c.r & mask, c.g & mask, c.b & mask)
offset = square_len // 2
for rect, color in squares:
posn = rect.move((offset, offset)).topleft
self.assertEqual(approx(jpg_surf.get_at(posn)), approx(color))
def testSavePNG32(self):
""" see if we can save a png with color values in the proper channels.
"""
# Create a PNG file with known colors
reddish_pixel = (215, 0, 0, 255)
greenish_pixel = (0, 225, 0, 255)
bluish_pixel = (0, 0, 235, 255)
greyish_pixel = (115, 125, 135, 145)
surf = pygame.Surface((1, 4), pygame.SRCALPHA, 32)
surf.set_at((0, 0), reddish_pixel)
surf.set_at((0, 1), greenish_pixel)
surf.set_at((0, 2), bluish_pixel)
surf.set_at((0, 3), greyish_pixel)
f_path = tempfile.mktemp(suffix=".png")
pygame.image.save(surf, f_path)
try:
# Read the PNG file and verify that pygame saved it correctly
reader = png.Reader(filename=f_path)
width, height, pixels, metadata = reader.asRGBA8()
# pixels is a generator
self.assertEqual(tuple(next(pixels)), reddish_pixel)
self.assertEqual(tuple(next(pixels)), greenish_pixel)
self.assertEqual(tuple(next(pixels)), bluish_pixel)
self.assertEqual(tuple(next(pixels)), greyish_pixel)
finally:
# Ensures proper clean up.
if not reader.file.closed:
reader.file.close()
del reader
os.remove(f_path)
def testSavePNG24(self):
""" see if we can save a png with color values in the proper channels.
"""
# Create a PNG file with known colors
reddish_pixel = (215, 0, 0)
greenish_pixel = (0, 225, 0)
bluish_pixel = (0, 0, 235)
greyish_pixel = (115, 125, 135)
surf = pygame.Surface((1, 4), 0, 24)
surf.set_at((0, 0), reddish_pixel)
surf.set_at((0, 1), greenish_pixel)
surf.set_at((0, 2), bluish_pixel)
surf.set_at((0, 3), greyish_pixel)
f_path = tempfile.mktemp(suffix=".png")
pygame.image.save(surf, f_path)
try:
# Read the PNG file and verify that pygame saved it correctly
reader = png.Reader(filename=f_path)
width, height, pixels, metadata = reader.asRGB8()
# pixels is a generator
self.assertEqual(tuple(next(pixels)), reddish_pixel)
self.assertEqual(tuple(next(pixels)), greenish_pixel)
self.assertEqual(tuple(next(pixels)), bluish_pixel)
self.assertEqual(tuple(next(pixels)), greyish_pixel)
finally:
# Ensures proper clean up.
if not reader.file.closed:
reader.file.close()
del reader
os.remove(f_path)
def test_save(self):
s = pygame.Surface((10, 10))
s.fill((23, 23, 23))
magic_hex = {}
magic_hex["jpg"] = [0xFF, 0xD8, 0xFF, 0xE0]
magic_hex["png"] = [0x89, 0x50, 0x4E, 0x47]
# magic_hex['tga'] = [0x0, 0x0, 0xa]
magic_hex["bmp"] = [0x42, 0x4D]
formats = ["jpg", "png", "bmp"]
# uppercase too... JPG
formats = formats + [x.upper() for x in formats]
for fmt in formats:
try:
temp_filename = "%s.%s" % ("tmpimg", fmt)
pygame.image.save(s, temp_filename)
# Using 'with' ensures the file is closed even if test fails.
with open(temp_filename, "rb") as handle:
# Test the magic numbers at the start of the file to ensure
# they are saved as the correct file type.
self.assertEqual(
(1, fmt), (test_magic(handle, magic_hex[fmt.lower()]), fmt)
)
# load the file to make sure it was saved correctly.
# Note load can load a jpg saved with a .png file name.
s2 = pygame.image.load(temp_filename)
# compare contents, might only work reliably for png...
# but because it's all one color it seems to work with jpg.
self.assertEqual(s2.get_at((0, 0)), s.get_at((0, 0)))
finally:
# clean up the temp file, comment out to leave tmp file after run.
os.remove(temp_filename)
def test_save_colorkey(self):
""" make sure the color key is not changed when saving.
"""
s = pygame.Surface((10, 10), pygame.SRCALPHA, 32)
s.fill((23, 23, 23))
s.set_colorkey((0, 0, 0))
colorkey1 = s.get_colorkey()
p1 = s.get_at((0, 0))
temp_filename = "tmpimg.png"
try:
pygame.image.save(s, temp_filename)
s2 = pygame.image.load(temp_filename)
finally:
os.remove(temp_filename)
colorkey2 = s.get_colorkey()
# check that the pixel and the colorkey is correct.
self.assertEqual(colorkey1, colorkey2)
self.assertEqual(p1, s2.get_at((0, 0)))
def test_load_unicode_path(self):
import shutil
orig = unicode_(example_path("data/asprite.bmp"))
temp = os.path.join(unicode_(example_path("data")), u"你好.bmp")
shutil.copy(orig, temp)
try:
im = pygame.image.load(temp)
finally:
os.remove(temp)
def _unicode_save(self, temp_file):
im = pygame.Surface((10, 10), 0, 32)
try:
with open(temp_file, "w") as f:
pass
os.remove(temp_file)
except IOError:
raise unittest.SkipTest("the path cannot be opened")
self.assertFalse(os.path.exists(temp_file))
try:
pygame.image.save(im, temp_file)
self.assertGreater(os.path.getsize(temp_file), 10)
finally:
try:
os.remove(temp_file)
except EnvironmentError:
pass
def test_save_unicode_path(self):
"""save unicode object with non-ASCII chars"""
self._unicode_save(u"你好.bmp")
def assertPremultipliedAreEqual(self, string1, string2, source_string):
self.assertEqual(len(string1), len(string2))
block_size = 20
if string1 != string2:
for block_start in xrange_(0, len(string1), block_size):
block_end = min(block_start + block_size, len(string1))
block1 = string1[block_start:block_end]
block2 = string2[block_start:block_end]
if block1 != block2:
source_block = source_string[block_start:block_end]
msg = (
"string difference in %d to %d of %d:\n%s\n%s\nsource:\n%s"
% (
block_start,
block_end,
len(string1),
block1.encode("hex"),
block2.encode("hex"),
source_block.encode("hex"),
)
)
self.fail(msg)
def test_to_string__premultiplied(self):
""" test to make sure we can export a surface to a premultiplied alpha string
"""
def convertRGBAtoPremultiplied(surface_to_modify):
for x in xrange_(surface_to_modify.get_width()):
for y in xrange_(surface_to_modify.get_height()):
color = surface_to_modify.get_at((x, y))
premult_color = (
color[0] * color[3] / 255,
color[1] * color[3] / 255,
color[2] * color[3] / 255,
color[3],
)
surface_to_modify.set_at((x, y), premult_color)
test_surface = pygame.Surface((256, 256), pygame.SRCALPHA, 32)
for x in xrange_(test_surface.get_width()):
for y in xrange_(test_surface.get_height()):
i = x + y * test_surface.get_width()
test_surface.set_at(
(x, y), ((i * 7) % 256, (i * 13) % 256, (i * 27) % 256, y)
)
premultiplied_copy = test_surface.copy()
convertRGBAtoPremultiplied(premultiplied_copy)
self.assertPremultipliedAreEqual(
pygame.image.tostring(test_surface, "RGBA_PREMULT"),
pygame.image.tostring(premultiplied_copy, "RGBA"),
pygame.image.tostring(test_surface, "RGBA"),
)
self.assertPremultipliedAreEqual(
pygame.image.tostring(test_surface, "ARGB_PREMULT"),
pygame.image.tostring(premultiplied_copy, "ARGB"),
pygame.image.tostring(test_surface, "ARGB"),
)
no_alpha_surface = pygame.Surface((256, 256), 0, 24)
self.assertRaises(
ValueError, pygame.image.tostring, no_alpha_surface, "RGBA_PREMULT"
)
# Custom assert method to check for identical surfaces.
def _assertSurfaceEqual(self, surf_a, surf_b, msg=None):
a_width, a_height = surf_a.get_width(), surf_a.get_height()
# Check a few things to see if the surfaces are equal.
self.assertEqual(a_width, surf_b.get_width(), msg)
self.assertEqual(a_height, surf_b.get_height(), msg)
self.assertEqual(surf_a.get_size(), surf_b.get_size(), msg)
self.assertEqual(surf_a.get_rect(), surf_b.get_rect(), msg)
self.assertEqual(surf_a.get_colorkey(), surf_b.get_colorkey(), msg)
self.assertEqual(surf_a.get_alpha(), surf_b.get_alpha(), msg)
self.assertEqual(surf_a.get_flags(), surf_b.get_flags(), msg)
self.assertEqual(surf_a.get_bitsize(), surf_b.get_bitsize(), msg)
self.assertEqual(surf_a.get_bytesize(), surf_b.get_bytesize(), msg)
# Anything else?
# Making the method lookups local for a possible speed up.
surf_a_get_at = surf_a.get_at
surf_b_get_at = surf_b.get_at
for y in xrange_(a_height):
for x in xrange_(a_width):
self.assertEqual(surf_a_get_at((x, y)), surf_b_get_at((x, y)), msg)
def test_fromstring__and_tostring(self):
"""Ensure methods tostring() and fromstring() are symmetric."""
####################################################################
def RotateRGBAtoARGB(str_buf):
byte_buf = array.array("B", str_buf)
num_quads = len(byte_buf) // 4
for i in xrange_(num_quads):
alpha = byte_buf[i * 4 + 3]
byte_buf[i * 4 + 3] = byte_buf[i * 4 + 2]
byte_buf[i * 4 + 2] = byte_buf[i * 4 + 1]
byte_buf[i * 4 + 1] = byte_buf[i * 4 + 0]
byte_buf[i * 4 + 0] = alpha
return tostring(byte_buf)
####################################################################
def RotateARGBtoRGBA(str_buf):
byte_buf = array.array("B", str_buf)
num_quads = len(byte_buf) // 4
for i in xrange_(num_quads):
alpha = byte_buf[i * 4 + 0]
byte_buf[i * 4 + 0] = byte_buf[i * 4 + 1]
byte_buf[i * 4 + 1] = byte_buf[i * 4 + 2]
byte_buf[i * 4 + 2] = byte_buf[i * 4 + 3]
byte_buf[i * 4 + 3] = alpha
return tostring(byte_buf)
####################################################################
test_surface = pygame.Surface((64, 256), flags=pygame.SRCALPHA, depth=32)
for i in xrange_(256):
for j in xrange_(16):
intensity = j * 16 + 15
test_surface.set_at((j + 0, i), (intensity, i, i, i))
test_surface.set_at((j + 16, i), (i, intensity, i, i))
test_surface.set_at((j + 32, i), (i, i, intensity, i))
test_surface.set_at((j + 32, i), (i, i, i, intensity))
self._assertSurfaceEqual(
test_surface, test_surface, "failing with identical surfaces"
)
rgba_buf = pygame.image.tostring(test_surface, "RGBA")
rgba_buf = RotateARGBtoRGBA(RotateRGBAtoARGB(rgba_buf))
test_rotate_functions = pygame.image.fromstring(
rgba_buf, test_surface.get_size(), "RGBA"
)
self._assertSurfaceEqual(
test_surface, test_rotate_functions, "rotate functions are not symmetric"
)
rgba_buf = pygame.image.tostring(test_surface, "RGBA")
argb_buf = RotateRGBAtoARGB(rgba_buf)
test_from_argb_string = pygame.image.fromstring(
argb_buf, test_surface.get_size(), "ARGB"
)
self._assertSurfaceEqual(
test_surface, test_from_argb_string, '"RGBA" rotated to "ARGB" failed'
)
argb_buf = pygame.image.tostring(test_surface, "ARGB")
rgba_buf = RotateARGBtoRGBA(argb_buf)
test_to_argb_string = pygame.image.fromstring(
rgba_buf, test_surface.get_size(), "RGBA"
)
self._assertSurfaceEqual(
test_surface, test_to_argb_string, '"ARGB" rotated to "RGBA" failed'
)
for fmt in ("ARGB", "RGBA"):
fmt_buf = pygame.image.tostring(test_surface, fmt)
test_to_from_fmt_string = pygame.image.fromstring(
fmt_buf, test_surface.get_size(), fmt
)
self._assertSurfaceEqual(
test_surface,
test_to_from_fmt_string,
"tostring/fromstring functions are not "
'symmetric with "{}" format'.format(fmt),
)
def test_tostring_depth_24(self):
test_surface = pygame.Surface((64, 256), depth=24)
for i in xrange_(256):
for j in xrange_(16):
intensity = j * 16 + 15
test_surface.set_at((j + 0, i), (intensity, i, i, i))
test_surface.set_at((j + 16, i), (i, intensity, i, i))
test_surface.set_at((j + 32, i), (i, i, intensity, i))
test_surface.set_at((j + 32, i), (i, i, i, intensity))
fmt = 'RGB'
fmt_buf = pygame.image.tostring(test_surface, fmt)
test_to_from_fmt_string = pygame.image.fromstring(
fmt_buf, test_surface.get_size(), fmt
)
self._assertSurfaceEqual(
test_surface,
test_to_from_fmt_string,
"tostring/fromstring functions are not "
'symmetric with "{}" format'.format(fmt),
)
def todo_test_frombuffer(self):
# __doc__ (as of 2008-08-02) for pygame.image.frombuffer:
# pygame.image.frombuffer(string, size, format): return Surface
# create a new Surface that shares data inside a string buffer
#
# Create a new Surface that shares pixel data directly from the string
# buffer. This method takes the same arguments as
# pygame.image.fromstring(), but is unable to vertically flip the
# source data.
#
# This will run much faster than pygame.image.fromstring, since no
# pixel data must be allocated and copied.
self.fail()
def todo_test_get_extended(self):
# __doc__ (as of 2008-08-02) for pygame.image.get_extended:
# pygame.image.get_extended(): return bool
# test if extended image formats can be loaded
#
# If pygame is built with extended image formats this function will
# return True. It is still not possible to determine which formats
# will be available, but generally you will be able to load them all.
self.fail()
def todo_test_load_basic(self):
# __doc__ (as of 2008-08-02) for pygame.image.load_basic:
# pygame.image.load(filename): return Surface
# pygame.image.load(fileobj, namehint=): return Surface
# load new image from a file
self.fail()
def todo_test_load_extended(self):
# __doc__ (as of 2008-08-02) for pygame.image.load_extended:
# pygame module for image transfer
self.fail()
def todo_test_save_extended(self):
# __doc__ (as of 2008-08-02) for pygame.image.save_extended:
# pygame module for image transfer
self.fail()
def threads_load(self, images):
import pygame.threads
for i in range(10):
surfs = pygame.threads.tmap(pygame.image.load, images)
for s in surfs:
self.assertIsInstance(s, pygame.Surface)
def test_load_png_threads(self):
self.threads_load(glob.glob(example_path("data/*.png")))
def test_load_jpg_threads(self):
self.threads_load(glob.glob(example_path("data/*.jpg")))
def test_load_bmp_threads(self):
self.threads_load(glob.glob(example_path("data/*.bmp")))
def test_load_gif_threads(self):
self.threads_load(glob.glob(example_path("data/*.gif")))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,7 @@
__tags__ = []
import pygame
import sys
if "pygame.imageext" not in sys.modules:
__tags__.extend(("ignore", "subprocess_ignore"))
@@ -0,0 +1,102 @@
# -*- coding: utf8 -*-
import os
import os.path
import sys
import unittest
from pygame.tests.test_utils import example_path
import pygame, pygame.image, pygame.pkgdata
from pygame.compat import as_unicode, unicode_
imageext = sys.modules["pygame.imageext"]
class ImageextModuleTest(unittest.TestCase):
# Most of the testing is done indirectly through image_test.py
# This just confirms file path encoding and error handling.
def test_save_non_string_file(self):
im = pygame.Surface((10, 10), 0, 32)
self.assertRaises(TypeError, imageext.save_extended, im, [])
def test_load_non_string_file(self):
self.assertRaises(TypeError, imageext.load_extended, [])
@unittest.skip("SDL silently removes invalid characters")
def test_save_bad_filename(self):
im = pygame.Surface((10, 10), 0, 32)
u = u"a\x00b\x00c.png"
self.assertRaises(pygame.error, imageext.save_extended, im, u)
@unittest.skip("SDL silently removes invalid characters")
def test_load_bad_filename(self):
u = u"a\x00b\x00c.png"
self.assertRaises(pygame.error, imageext.load_extended, u)
def test_save_unknown_extension(self):
im = pygame.Surface((10, 10), 0, 32)
s = "foo.bar"
self.assertRaises(pygame.error, imageext.save_extended, im, s)
if sys.version_info >= (3, 0):
def test_load_unknown_extension(self):
s = "foo.bar"
self.assertRaises(FileNotFoundError, imageext.load_extended, s)
def test_load_unknown_file(self):
s = "nonexistent.png"
self.assertRaises(FileNotFoundError, imageext.load_extended, s)
else:
def test_load_unknown_extension(self):
s = "foo.bar"
self.assertRaises(IOError, imageext.load_extended, s)
def test_load_unknown_file(self):
s = "nonexistent.png"
self.assertRaises(IOError, imageext.load_extended, s)
def test_load_unicode_path_0(self):
u = unicode_(example_path("data/alien1.png"))
im = imageext.load_extended(u)
def test_load_unicode_path_1(self):
"""non-ASCII unicode"""
import shutil
orig = unicode_(example_path("data/alien1.png"))
temp = os.path.join(unicode_(example_path("data")), u"你好.png")
shutil.copy(orig, temp)
try:
im = imageext.load_extended(temp)
finally:
os.remove(temp)
def _unicode_save(self, temp_file):
im = pygame.Surface((10, 10), 0, 32)
try:
with open(temp_file, "w") as f:
pass
os.remove(temp_file)
except IOError:
raise unittest.SkipTest("the path cannot be opened")
self.assertFalse(os.path.exists(temp_file))
try:
imageext.save_extended(im, temp_file)
self.assertGreater(os.path.getsize(temp_file), 10)
finally:
try:
os.remove(temp_file)
except EnvironmentError:
pass
def test_save_unicode_path_0(self):
"""unicode object with ASCII chars"""
self._unicode_save(u"temp_file.png")
def test_save_unicode_path_1(self):
self._unicode_save(u"你好.png")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,94 @@
import unittest
class JoystickTypeTest(unittest.TestCase):
def todo_test_Joystick(self):
# __doc__ (as of 2008-08-02) for pygame.joystick.Joystick:
# pygame.joystick.Joystick(id): return Joystick
# create a new Joystick object
#
# Create a new joystick to access a physical device. The id argument
# must be a value from 0 to pygame.joystick.get_count()-1.
#
# To access most of the Joystick methods, you'll need to init() the
# Joystick. This is separate from making sure the joystick module is
# initialized. When multiple Joysticks objects are created for the
# same physical joystick device (i.e., they have the same ID number),
# the state and values for those Joystick objects will be shared.
#
# The Joystick object allows you to get information about the types of
# controls on a joystick device. Once the device is initialized the
# Pygame event queue will start receiving events about its input.
#
# You can call the Joystick.get_name() and Joystick.get_id() functions
# without initializing the Joystick object.
#
self.fail()
class JoytickModuleTest(unittest.TestCase):
def todo_test_get_count(self):
# __doc__ (as of 2008-08-02) for pygame.joystick.get_count:
# pygame.joystick.get_count(): return count
# number of joysticks on the system
#
# Return the number of joystick devices on the system. The count will
# be 0 if there are no joysticks on the system.
#
# When you create Joystick objects using Joystick(id), you pass an
# integer that must be lower than this count.
#
self.fail()
def todo_test_get_init(self):
# __doc__ (as of 2008-08-02) for pygame.joystick.get_init:
# pygame.joystick.get_init(): return bool
# true if the joystick module is initialized
#
# Test if the pygame.joystick.init() function has been called.
self.fail()
def todo_test_init(self):
# __doc__ (as of 2008-08-02) for pygame.joystick.init:
# pygame.joystick.init(): return None
# initialize the joystick module
#
# This function is called automatically by pygame.init().
# It initializes the joystick module. This will scan the system for
# all joystick devices. The module must be initialized before any
# other functions will work.
#
# It is safe to call this function more than once.
self.fail()
def todo_test_quit(self):
# __doc__ (as of 2008-08-02) for pygame.joystick.quit:
# pygame.joystick.quit(): return None
# uninitialize the joystick module
#
# Uninitialize the joystick module. After you call this any existing
# joystick objects will no longer work.
#
# It is safe to call this function more than once.
self.fail()
################################################################################
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,81 @@
import unittest
import pygame
import pygame.key
SDL1 = pygame.get_sdl_version()[0] < 2
class KeyModuleTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
pygame.init()
@classmethod
def tearDownClass(cls):
pygame.quit()
def setUp(cls):
# This makes sure pygame is always initialized before each test (in
# case a test calls pygame.quit()).
if not pygame.get_init():
pygame.init()
def test_import(self):
"does it import"
import pygame.key
def todo_test_get_focused(self):
# __doc__ (as of 2008-08-02) for pygame.key.get_focused:
# pygame.key.get_focused(): return bool
# true if the display is receiving keyboard input from the system
#
# This is true when the display window has keyboard focus from the
# system. If the display needs to ensure it does not lose keyboard
# focus, it can use pygame.event.set_grab() to grab all input.
#
self.fail()
def test_get_pressed(self):
states = pygame.key.get_pressed()
self.assertEqual(states[pygame.K_RIGHT], 0)
def test_name(self):
self.assertEqual(pygame.key.name(pygame.K_RETURN), "return")
self.assertEqual(pygame.key.name(pygame.K_0), "0")
self.assertEqual(pygame.key.name(pygame.K_SPACE), "space")
def test_key_code(self):
if SDL1:
self.assertRaises(NotImplementedError, pygame.key.key_code,
"return")
else:
self.assertEqual(pygame.key.key_code("return"), pygame.K_RETURN)
self.assertEqual(pygame.key.key_code("0"), pygame.K_0)
self.assertEqual(pygame.key.key_code("space"), pygame.K_SPACE)
self.assertRaises(ValueError, pygame.key.key_code, "fizzbuzz")
def test_set_and_get_mods(self):
pygame.key.set_mods(pygame.KMOD_CTRL)
self.assertEqual(pygame.key.get_mods(), pygame.KMOD_CTRL)
pygame.key.set_mods(pygame.KMOD_ALT)
self.assertEqual(pygame.key.get_mods(), pygame.KMOD_ALT)
pygame.key.set_mods(pygame.KMOD_CTRL | pygame.KMOD_ALT)
self.assertEqual(pygame.key.get_mods(), pygame.KMOD_CTRL | pygame.KMOD_ALT)
def test_set_and_get_repeat(self):
self.assertEqual(pygame.key.get_repeat(), (0, 0))
pygame.key.set_repeat(10, 15)
self.assertEqual(pygame.key.get_repeat(), (10, 15))
pygame.key.set_repeat()
self.assertEqual(pygame.key.get_repeat(), (0, 0))
if __name__ == "__main__":
unittest.main()
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,469 @@
import unittest
import os
import sys
import time
import pygame
import pygame.midi
import pygame.compat
from pygame.locals import *
class MidiInputTest(unittest.TestCase):
__tags__ = ["interactive"]
def setUp(self):
pygame.midi.init()
in_id = pygame.midi.get_default_input_id()
if in_id != -1:
self.midi_input = pygame.midi.Input(in_id)
else:
self.midi_input = None
def tearDown(self):
if self.midi_input:
self.midi_input.close()
pygame.midi.quit()
def test_Input(self):
i = pygame.midi.get_default_input_id()
if self.midi_input:
self.assertEqual(self.midi_input.device_id, i)
# try feeding it an input id.
i = pygame.midi.get_default_output_id()
# can handle some invalid input too.
self.assertRaises(pygame.midi.MidiException, pygame.midi.Input, i)
self.assertRaises(pygame.midi.MidiException, pygame.midi.Input, 9009)
self.assertRaises(pygame.midi.MidiException, pygame.midi.Input, -1)
self.assertRaises(TypeError, pygame.midi.Input, "1234")
self.assertRaises(OverflowError, pygame.midi.Input, pow(2, 99))
def test_poll(self):
if not self.midi_input:
self.skipTest("No midi Input device")
self.assertFalse(self.midi_input.poll())
# TODO fake some incoming data
pygame.midi.quit()
self.assertRaises(RuntimeError, self.midi_input.poll)
# set midi_input to None to avoid error in tearDown
self.midi_input = None
def test_read(self):
if not self.midi_input:
self.skipTest("No midi Input device")
read = self.midi_input.read(5)
self.assertEqual(read, [])
# TODO fake some incoming data
pygame.midi.quit()
self.assertRaises(RuntimeError, self.midi_input.read, 52)
# set midi_input to None to avoid error in tearDown
self.midi_input = None
def test_close(self):
if not self.midi_input:
self.skipTest("No midi Input device")
self.assertIsNotNone(self.midi_input._input)
self.midi_input.close()
self.assertIsNone(self.midi_input._input)
class MidiOutputTest(unittest.TestCase):
__tags__ = ["interactive"]
def setUp(self):
pygame.midi.init()
m_out_id = pygame.midi.get_default_output_id()
if m_out_id != -1:
self.midi_output = pygame.midi.Output(m_out_id)
else:
self.midi_output = None
def tearDown(self):
if self.midi_output:
self.midi_output.close()
pygame.midi.quit()
def test_Output(self):
i = pygame.midi.get_default_output_id()
if self.midi_output:
self.assertEqual(self.midi_output.device_id, i)
# try feeding it an input id.
i = pygame.midi.get_default_input_id()
# can handle some invalid input too.
self.assertRaises(pygame.midi.MidiException, pygame.midi.Output, i)
self.assertRaises(pygame.midi.MidiException, pygame.midi.Output, 9009)
self.assertRaises(pygame.midi.MidiException, pygame.midi.Output, -1)
self.assertRaises(TypeError, pygame.midi.Output, "1234")
self.assertRaises(OverflowError, pygame.midi.Output, pow(2, 99))
def test_note_off(self):
if self.midi_output:
out = self.midi_output
out.note_on(5, 30, 0)
out.note_off(5, 30, 0)
with self.assertRaises(ValueError) as cm:
out.note_off(5, 30, 25)
self.assertEqual(str(cm.exception), "Channel not between 0 and 15.")
with self.assertRaises(ValueError) as cm:
out.note_off(5, 30, -1)
self.assertEqual(str(cm.exception), "Channel not between 0 and 15.")
def test_note_on(self):
if self.midi_output:
out = self.midi_output
out.note_on(5, 30, 0)
out.note_on(5, 42, 10)
with self.assertRaises(ValueError) as cm:
out.note_on(5, 30, 25)
self.assertEqual(str(cm.exception), "Channel not between 0 and 15.")
with self.assertRaises(ValueError) as cm:
out.note_on(5, 30, -1)
self.assertEqual(str(cm.exception), "Channel not between 0 and 15.")
def test_set_instrument(self):
if not self.midi_output:
self.skipTest("No midi device")
out = self.midi_output
out.set_instrument(5)
out.set_instrument(42, channel=2)
with self.assertRaises(ValueError) as cm:
out.set_instrument(-6)
self.assertEqual(str(cm.exception), "Undefined instrument id: -6")
with self.assertRaises(ValueError) as cm:
out.set_instrument(156)
self.assertEqual(str(cm.exception), "Undefined instrument id: 156")
with self.assertRaises(ValueError) as cm:
out.set_instrument(5, -1)
self.assertEqual(str(cm.exception), "Channel not between 0 and 15.")
with self.assertRaises(ValueError) as cm:
out.set_instrument(5, 16)
self.assertEqual(str(cm.exception), "Channel not between 0 and 15.")
def test_write(self):
if not self.midi_output:
self.skipTest("No midi device")
out = self.midi_output
out.write([[[0xC0, 0, 0], 20000]])
# is equivalent to
out.write([[[0xC0], 20000]])
# example from the docstring :
# 1. choose program change 1 at time 20000 and
# 2. send note 65 with velocity 100 500 ms later
out.write([[[0xC0, 0, 0], 20000], [[0x90, 60, 100], 20500]])
out.write([])
verrry_long = [[[0x90, 60, i % 100], 20000 + 100 * i] for i in range(1024)]
out.write(verrry_long)
too_long = [[[0x90, 60, i % 100], 20000 + 100 * i] for i in range(1025)]
self.assertRaises(IndexError, out.write, too_long)
# test wrong data
with self.assertRaises(TypeError) as cm:
out.write("Non sens ?")
error_msg = "unsupported operand type(s) for &: 'str' and 'int'"
self.assertEqual(str(cm.exception), error_msg)
with self.assertRaises(TypeError) as cm:
out.write(["Hey what's that?"])
self.assertEqual(str(cm.exception), error_msg)
def test_write_short(self):
if not self.midi_output:
self.skipTest("No midi device")
out = self.midi_output
# program change
out.write_short(0xC0)
# put a note on, then off.
out.write_short(0x90, 65, 100)
out.write_short(0x80, 65, 100)
out.write_short(0x90)
def test_write_sys_ex(self):
if not self.midi_output:
self.skipTest("No midi device")
out = self.midi_output
out.write_sys_ex(pygame.midi.time(), [0xF0, 0x7D, 0x10, 0x11, 0x12, 0x13, 0xF7])
def test_pitch_bend(self):
# FIXME : pitch_bend in the code, but not in documentation
if not self.midi_output:
self.skipTest("No midi device")
out = self.midi_output
with self.assertRaises(ValueError) as cm:
out.pitch_bend(5, channel=-1)
self.assertEqual(str(cm.exception), "Channel not between 0 and 15.")
with self.assertRaises(ValueError) as cm:
out.pitch_bend(5, channel=16)
with self.assertRaises(ValueError) as cm:
out.pitch_bend(-10001, 1)
self.assertEqual(
str(cm.exception),
"Pitch bend value must be between " "-8192 and +8191, not -10001.",
)
with self.assertRaises(ValueError) as cm:
out.pitch_bend(10665, 2)
def test_close(self):
if not self.midi_output:
self.skipTest("No midi device")
self.assertIsNotNone(self.midi_output._output)
self.midi_output.close()
self.assertIsNone(self.midi_output._output)
def test_abort(self):
if not self.midi_output:
self.skipTest("No midi device")
self.assertEqual(self.midi_output._aborted, 0)
self.midi_output.abort()
self.assertEqual(self.midi_output._aborted, 1)
class MidiModuleTest(unittest.TestCase):
"""Midi module tests that require midi hardware or midi.init().
See MidiModuleNonInteractiveTest for non-interactive module tests.
"""
__tags__ = ["interactive"]
def setUp(self):
pygame.midi.init()
def tearDown(self):
pygame.midi.quit()
def test_get_count(self):
c = pygame.midi.get_count()
self.assertIsInstance(c, int)
self.assertTrue(c >= 0)
def test_get_default_input_id(self):
midin_id = pygame.midi.get_default_input_id()
# if there is a not None return make sure it is an int.
self.assertIsInstance(midin_id, int)
self.assertTrue(midin_id >= -1)
pygame.midi.quit()
self.assertRaises(RuntimeError, pygame.midi.get_default_output_id)
def test_get_default_output_id(self):
c = pygame.midi.get_default_output_id()
self.assertIsInstance(c, int)
self.assertTrue(c >= -1)
pygame.midi.quit()
self.assertRaises(RuntimeError, pygame.midi.get_default_output_id)
def test_get_device_info(self):
an_id = pygame.midi.get_default_output_id()
if an_id != -1:
interf, name, input, output, opened = pygame.midi.get_device_info(an_id)
self.assertEqual(output, 1)
self.assertEqual(input, 0)
self.assertEqual(opened, 0)
an_in_id = pygame.midi.get_default_input_id()
if an_in_id != -1:
r = pygame.midi.get_device_info(an_in_id)
# if r is None, it means that the id is out of range.
interf, name, input, output, opened = r
self.assertEqual(output, 0)
self.assertEqual(input, 1)
self.assertEqual(opened, 0)
out_of_range = pygame.midi.get_count()
for num in range(out_of_range):
self.assertIsNotNone(pygame.midi.get_device_info(num))
info = pygame.midi.get_device_info(out_of_range)
self.assertIsNone(info)
def test_init(self):
pygame.midi.quit()
self.assertRaises(RuntimeError, pygame.midi.get_count)
# initialising many times should be fine.
pygame.midi.init()
pygame.midi.init()
pygame.midi.init()
pygame.midi.init()
self.assertTrue(pygame.midi.get_init())
def test_quit(self):
# It is safe to call this more than once.
pygame.midi.quit()
pygame.midi.init()
pygame.midi.quit()
pygame.midi.quit()
pygame.midi.init()
pygame.midi.init()
pygame.midi.quit()
self.assertFalse(pygame.midi.get_init())
def test_get_init(self):
# Already initialized as pygame.midi.init() was called in setUp().
self.assertTrue(pygame.midi.get_init())
def test_time(self):
mtime = pygame.midi.time()
self.assertIsInstance(mtime, int)
# should be close to 2-3... since the timer is just init'd.
self.assertTrue(0 <= mtime < 100)
class MidiModuleNonInteractiveTest(unittest.TestCase):
"""Midi module tests that do not require midi hardware or midi.init().
See MidiModuleTest for interactive module tests.
"""
def test_midiin(self):
"""Ensures the MIDIIN event id exists in the midi module.
The MIDIIN event id can be accessed via the midi module for backward
compatibility.
"""
self.assertEqual(pygame.midi.MIDIIN, pygame.MIDIIN)
self.assertEqual(pygame.midi.MIDIIN, pygame.locals.MIDIIN)
self.assertNotEqual(pygame.midi.MIDIIN, pygame.MIDIOUT)
self.assertNotEqual(pygame.midi.MIDIIN, pygame.locals.MIDIOUT)
def test_midiout(self):
"""Ensures the MIDIOUT event id exists in the midi module.
The MIDIOUT event id can be accessed via the midi module for backward
compatibility.
"""
self.assertEqual(pygame.midi.MIDIOUT, pygame.MIDIOUT)
self.assertEqual(pygame.midi.MIDIOUT, pygame.locals.MIDIOUT)
self.assertNotEqual(pygame.midi.MIDIOUT, pygame.MIDIIN)
self.assertNotEqual(pygame.midi.MIDIOUT, pygame.locals.MIDIIN)
def test_MidiException(self):
"""Ensures the MidiException is raised as expected."""
def raiseit():
raise pygame.midi.MidiException("Hello Midi param")
with self.assertRaises(pygame.midi.MidiException) as cm:
raiseit()
self.assertEqual(cm.exception.parameter, "Hello Midi param")
def test_midis2events(self):
"""Ensures midi events are properly converted to pygame events."""
# List/tuple indexes.
MIDI_DATA = 0
MD_STATUS = 0
MD_DATA1 = 1
MD_DATA2 = 2
MD_DATA3 = 3
TIMESTAMP = 1
# Midi events take the form of:
# ((status, data1, data2, data3), timestamp)
midi_events = (
((0xC0, 0, 1, 2), 20000),
((0x90, 60, 1000, "string_data"), 20001),
(("0", "1", "2", "3"), "4"),
)
expected_num_events = len(midi_events)
# Test different device ids.
for device_id in range(3):
pg_events = pygame.midi.midis2events(midi_events, device_id)
self.assertEqual(len(pg_events), expected_num_events)
for i, pg_event in enumerate(pg_events):
# Get the original midi data for comparison.
midi_event = midi_events[i]
midi_event_data = midi_event[MIDI_DATA]
# Can't directly check event instance as pygame.event.Event is
# a function.
# self.assertIsInstance(pg_event, pygame.event.Event)
self.assertEqual(pg_event.__class__.__name__, "Event")
self.assertEqual(pg_event.type, pygame.MIDIIN)
self.assertEqual(pg_event.status, midi_event_data[MD_STATUS])
self.assertEqual(pg_event.data1, midi_event_data[MD_DATA1])
self.assertEqual(pg_event.data2, midi_event_data[MD_DATA2])
self.assertEqual(pg_event.data3, midi_event_data[MD_DATA3])
self.assertEqual(pg_event.timestamp, midi_event[TIMESTAMP])
self.assertEqual(pg_event.vice_id, device_id)
def test_midis2events__missing_event_data(self):
"""Ensures midi events with missing values are handled properly."""
midi_event_missing_data = ((0xC0, 0, 1), 20000)
midi_event_missing_timestamp = ((0xC0, 0, 1, 2),)
for midi_event in (midi_event_missing_data, midi_event_missing_timestamp):
with self.assertRaises(ValueError):
events = pygame.midi.midis2events([midi_event], 0)
def test_midis2events__extra_event_data(self):
"""Ensures midi events with extra values are handled properly."""
midi_event_extra_data = ((0xC0, 0, 1, 2, "extra"), 20000)
midi_event_extra_timestamp = ((0xC0, 0, 1, 2), 20000, "extra")
for midi_event in (midi_event_extra_data, midi_event_extra_timestamp):
with self.assertRaises(ValueError):
events = pygame.midi.midis2events([midi_event], 0)
def test_midis2events__extra_event_data_missing_timestamp(self):
"""Ensures midi events with extra data and no timestamps are handled
properly.
"""
midi_event_extra_data_no_timestamp = ((0xC0, 0, 1, 2, "extra"),)
with self.assertRaises(ValueError):
events = pygame.midi.midis2events([midi_event_extra_data_no_timestamp], 0)
def test_conversions(self):
""" of frequencies to midi note numbers and ansi note names.
"""
from pygame.midi import frequency_to_midi, midi_to_frequency, midi_to_ansi_note
self.assertEqual(frequency_to_midi(27.5), 21)
self.assertEqual(frequency_to_midi(36.7), 26)
self.assertEqual(frequency_to_midi(4186.0), 108)
self.assertEqual(midi_to_frequency(21), 27.5)
self.assertEqual(midi_to_frequency(26), 36.7)
self.assertEqual(midi_to_frequency(108), 4186.0)
self.assertEqual(midi_to_ansi_note(21), "A0")
self.assertEqual(midi_to_ansi_note(71), "B4")
self.assertEqual(midi_to_ansi_note(82), "A#5")
self.assertEqual(midi_to_ansi_note(83), "B5")
self.assertEqual(midi_to_ansi_note(93), "A6")
self.assertEqual(midi_to_ansi_note(94), "A#6")
self.assertEqual(midi_to_ansi_note(95), "B6")
self.assertEqual(midi_to_ansi_note(96), "C7")
self.assertEqual(midi_to_ansi_note(102), "F#7")
self.assertEqual(midi_to_ansi_note(108), "C8")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,7 @@
__tags__ = []
import pygame
import sys
if "pygame.mixer_music" not in sys.modules:
__tags__.extend(("ignore", "subprocess_ignore"))
@@ -0,0 +1,336 @@
# -*- coding: utf-8 -*-
import os
import sys
import platform
import unittest
from pygame.tests.test_utils import example_path
import pygame
from pygame.compat import as_unicode, unicode_, filesystem_encode
class MixerMusicModuleTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
# Initializing the mixer is slow, so minimize the times it is called.
pygame.mixer.init()
@classmethod
def tearDownClass(cls):
pygame.mixer.quit()
def setUp(cls):
# This makes sure the mixer is always initialized before each test (in
# case a test calls pygame.mixer.quit()).
if pygame.mixer.get_init() is None:
pygame.mixer.init()
@unittest.skipIf(
"Darwin" in platform.system(), "SDL2_mixer not loading mp3 on travisci"
)
def test_load_mp3(self):
"|tags:music|"
self.music_load("mp3")
def test_load_ogg(self):
"|tags:music|"
self.music_load("ogg")
def test_load_wav(self):
"|tags:music|"
self.music_load("wav")
def music_load(self, format):
data_fname = example_path("data")
path = os.path.join(data_fname, "house_lo.%s" % format)
if os.sep == "\\":
path = path.replace("\\", "\\\\")
umusfn = as_unicode(path)
bmusfn = filesystem_encode(umusfn)
pygame.mixer.music.load(umusfn)
pygame.mixer.music.load(bmusfn)
def test_load_object(self):
"""test loading music from file-like objects."""
formats = ["ogg", "wav"]
data_fname = example_path("data")
for f in formats:
path = os.path.join(data_fname, "house_lo.%s" % f)
if os.sep == "\\":
path = path.replace("\\", "\\\\")
bmusfn = filesystem_encode(path)
with open(bmusfn, "rb") as musf:
pygame.mixer.music.load(musf)
def test_load_unicode(self):
"""test non-ASCII unicode path"""
import shutil
ep = unicode_(example_path("data"))
temp_file = os.path.join(ep, u"你好.wav")
org_file = os.path.join(ep, u"house_lo.wav")
try:
with open(temp_file, "w") as f:
pass
os.remove(temp_file)
except IOError:
raise unittest.SkipTest("the path cannot be opened")
shutil.copy(org_file, temp_file)
try:
pygame.mixer.music.load(temp_file)
pygame.mixer.music.load(org_file) # unload
finally:
os.remove(temp_file)
def test_unload(self):
import shutil
import tempfile
ep = unicode_(example_path("data"))
org_file = os.path.join(ep, u"house_lo.wav")
tmpfd, tmppath = tempfile.mkstemp(".wav")
os.close(tmpfd)
shutil.copy(org_file, tmppath)
try:
pygame.mixer.music.load(tmppath)
pygame.mixer.music.unload()
finally:
os.remove(tmppath)
@unittest.skipIf(
"Darwin" in platform.system(), "SDL2_mixer issue with mp3 files on Travis CI"
)
def test_queue_mp3(self):
"""Ensures queue() accepts mp3 files.
|tags:music|
"""
filename = example_path(os.path.join("data", "house_lo.mp3"))
pygame.mixer.music.queue(filename)
def test_queue_ogg(self):
"""Ensures queue() accepts ogg files.
|tags:music|
"""
filename = example_path(os.path.join("data", "house_lo.ogg"))
pygame.mixer.music.queue(filename)
def test_queue_wav(self):
"""Ensures queue() accepts wav files.
|tags:music|
"""
filename = example_path(os.path.join("data", "house_lo.wav"))
pygame.mixer.music.queue(filename)
def test_queue__multiple_calls(self):
"""Ensures queue() can be called multiple times."""
ogg_file = example_path(os.path.join("data", "house_lo.ogg"))
wav_file = example_path(os.path.join("data", "house_lo.wav"))
pygame.mixer.music.queue(ogg_file)
pygame.mixer.music.queue(wav_file)
def test_queue__no_file(self):
"""Ensures queue() correctly handles missing the file argument."""
with self.assertRaises(TypeError):
pygame.mixer.music.queue()
def test_queue__invalid_sound_type(self):
"""Ensures queue() correctly handles invalid file types."""
not_a_sound_file = example_path(os.path.join("data", "city.png"))
with self.assertRaises(pygame.error):
pygame.mixer.music.queue(not_a_sound_file)
def test_queue__invalid_filename(self):
"""Ensures queue() correctly handles invalid filenames."""
with self.assertRaises(pygame.error):
pygame.mixer.music.queue("")
def todo_test_stop(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.stop:
# Stops the music playback if it is currently playing.
self.fail()
def todo_test_rewind(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.rewind:
# Resets playback of the current music to the beginning.
self.fail()
def todo_test_get_pos(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.get_pos:
# This gets the number of milliseconds that the music has been playing
# for. The returned time only represents how long the music has been
# playing; it does not take into account any starting position
# offsets.
#
self.fail()
def todo_test_fadeout(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.fadeout:
# This will stop the music playback after it has been faded out over
# the specified time (measured in milliseconds).
#
# Note, that this function blocks until the music has faded out.
self.fail()
def todo_test_play(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.play:
# This will play the loaded music stream. If the music is already
# playing it will be restarted.
#
# The loops argument controls the number of repeats a music will play.
# play(5) will cause the music to played once, then repeated five
# times, for a total of six. If the loops is -1 then the music will
# repeat indefinitely.
#
# The starting position argument controls where in the music the song
# starts playing. The starting position is dependent on the format of
# music playing. MP3 and OGG use the position as time (in seconds).
# MOD music it is the pattern order number. Passing a startpos will
# raise a NotImplementedError if it cannot set the start position
#
self.fail()
def todo_test_load(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.load:
# This will load a music file and prepare it for playback. If a music
# stream is already playing it will be stopped. This does not start
# the music playing.
#
# Music can only be loaded from filenames, not python file objects
# like the other pygame loading functions.
#
self.fail()
def todo_test_get_volume(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.get_volume:
# Returns the current volume for the mixer. The value will be between
# 0.0 and 1.0.
#
self.fail()
def todo_test_set_endevent(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.set_endevent:
# This causes Pygame to signal (by means of the event queue) when the
# music is done playing. The argument determines the type of event
# that will be queued.
#
# The event will be queued every time the music finishes, not just the
# first time. To stop the event from being queued, call this method
# with no argument.
#
self.fail()
def todo_test_pause(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.pause:
# Temporarily stop playback of the music stream. It can be resumed
# with the pygame.mixer.music.unpause() function.
#
self.fail()
def todo_test_get_busy(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.get_busy:
# Returns True when the music stream is actively playing. When the
# music is idle this returns False.
#
self.fail()
def todo_test_get_endevent(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.get_endevent:
# Returns the event type to be sent every time the music finishes
# playback. If there is no endevent the function returns
# pygame.NOEVENT.
#
self.fail()
def todo_test_unpause(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.unpause:
# This will resume the playback of a music stream after it has been paused.
self.fail()
def todo_test_set_volume(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.set_volume:
# Set the volume of the music playback. The value argument is between
# 0.0 and 1.0. When new music is loaded the volume is reset.
#
self.fail()
def todo_test_set_pos(self):
# __doc__ (as of 2010-24-05) for pygame.mixer_music.set_pos:
# This sets the position in the music file where playback will start. The
# meaning of "pos", a float (or a number that can be converted to a float),
# depends on the music format. Newer versions of SDL_mixer have better
# positioning support than earlier. An SDLError is raised if a particular
# format does not support positioning.
#
self.fail()
def test_init(self):
"""issue #955. unload music whenever mixer.quit() is called"""
import tempfile
import shutil
testfile = example_path(os.path.join("data", "house_lo.wav"))
tempcopy = os.path.join(tempfile.gettempdir(), "tempfile.wav")
for i in range(10):
pygame.mixer.init()
try:
shutil.copy2(testfile, tempcopy)
pygame.mixer.music.load(tempcopy)
pygame.mixer.quit()
finally:
os.remove(tempcopy)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,7 @@
__tags__ = []
import pygame
import sys
if "pygame.mixer" not in sys.modules:
__tags__.extend(("ignore", "subprocess_ignore"))
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,103 @@
import unittest
import pygame
class MouseModuleTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
# The display needs to be initialized for mouse functions.
pygame.display.init()
@classmethod
def tearDownClass(cls):
pygame.display.quit()
def todo_test_get_cursor(self):
"""Ensures get_cursor works correctly."""
self.fail()
def todo_test_set_cursor(self):
"""Ensures set_cursor works correctly."""
self.fail()
def test_get_focused(self):
"""Ensures get_focused returns the correct type."""
focused = pygame.mouse.get_focused()
self.assertIsInstance(focused, int)
def test_get_pressed(self):
"""Ensures get_pressed returns the correct types."""
expected_length = 3
buttons_pressed = pygame.mouse.get_pressed()
self.assertIsInstance(buttons_pressed, tuple)
self.assertEqual(len(buttons_pressed), expected_length)
for value in buttons_pressed:
self.assertIsInstance(value, int)
def test_get_pos(self):
"""Ensures get_pos returns the correct types."""
expected_length = 2
pos = pygame.mouse.get_pos()
self.assertIsInstance(pos, tuple)
self.assertEqual(len(pos), expected_length)
for value in pos:
self.assertIsInstance(value, int)
def test_set_pos__invalid_pos(self):
"""Ensures set_pos handles invalid positions correctly."""
for invalid_pos in ((1,), [1, 2, 3], 1, "1", (1, "1"), []):
with self.assertRaises(TypeError):
pygame.mouse.set_pos(invalid_pos)
def todo_test_set_pos(self):
"""Ensures set_pos works correctly."""
self.fail()
def test_get_rel(self):
"""Ensures get_rel returns the correct types."""
expected_length = 2
rel = pygame.mouse.get_rel()
self.assertIsInstance(rel, tuple)
self.assertEqual(len(rel), expected_length)
for value in rel:
self.assertIsInstance(value, int)
def test_get_visible(self):
"""Ensures get_visible works correctly."""
for expected_value in (False, True):
pygame.mouse.set_visible(expected_value)
visible = pygame.mouse.get_visible()
self.assertEqual(visible, expected_value)
def test_set_visible(self):
"""Ensures set_visible returns the correct values."""
# Set to a known state.
pygame.mouse.set_visible(True)
for expected_visible in (False, True):
prev_visible = pygame.mouse.set_visible(expected_visible)
self.assertEqual(prev_visible, not expected_visible)
def test_set_visible__invalid_value(self):
"""Ensures set_visible handles invalid positions correctly."""
for invalid_value in ((1,), [1, 2, 3], 1.1, "1", (1, "1"), []):
with self.assertRaises(TypeError):
prev_visible = pygame.mouse.set_visible(invalid_value)
################################################################################
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,2 @@
# Overlay support was removed in SDL 2
__tags__ = ["SDL2_ignore"]
@@ -0,0 +1,37 @@
import unittest
class OverlayTypeTest(unittest.TestCase):
def todo_test_display(self):
# __doc__ (as of 2008-08-02) for pygame.overlay.overlay.display:
# Overlay.display((y, u, v)): return None
# Overlay.display(): return None
# set the overlay pixel data
self.fail()
def todo_test_get_hardware(self):
# __doc__ (as of 2008-08-02) for pygame.overlay.overlay.get_hardware:
# Overlay.get_hardware(rect): return int
# test if the Overlay is hardware accelerated
self.fail()
def todo_test_set_location(self):
# __doc__ (as of 2008-08-02) for pygame.overlay.overlay.set_location:
# Overlay.set_location(rect): return None
# control where the overlay is displayed
self.fail()
################################################################################
if __name__ == "__main__":
unittest.main()
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,710 @@
import ctypes
import platform
import unittest
try:
from pygame.tests.test_utils import arrinter
except NameError:
pass
import pygame
from pygame.locals import *
from pygame.pixelcopy import surface_to_array, map_array, array_to_surface, make_surface
IS_PYPY = "PyPy" == platform.python_implementation()
def unsigned32(i):
"""cast signed 32 bit integer to an unsigned integer"""
return i & 0xFFFFFFFF
class PixelcopyModuleTest(unittest.TestCase):
bitsizes = [8, 16, 32]
test_palette = [
(0, 0, 0, 255),
(10, 30, 60, 255),
(25, 75, 100, 255),
(100, 150, 200, 255),
(0, 100, 200, 255),
]
surf_size = (10, 12)
test_points = [
((0, 0), 1),
((4, 5), 1),
((9, 0), 2),
((5, 5), 2),
((0, 11), 3),
((4, 6), 3),
((9, 11), 4),
((5, 6), 4),
]
def __init__(self, *args, **kwds):
pygame.display.init()
try:
unittest.TestCase.__init__(self, *args, **kwds)
self.sources = [
self._make_src_surface(8),
self._make_src_surface(16),
self._make_src_surface(16, srcalpha=True),
self._make_src_surface(24),
self._make_src_surface(32),
self._make_src_surface(32, srcalpha=True),
]
finally:
pygame.display.quit()
def _make_surface(self, bitsize, srcalpha=False, palette=None):
if palette is None:
palette = self.test_palette
flags = 0
if srcalpha:
flags |= SRCALPHA
surf = pygame.Surface(self.surf_size, flags, bitsize)
if bitsize == 8:
surf.set_palette([c[:3] for c in palette])
return surf
def _fill_surface(self, surf, palette=None):
if palette is None:
palette = self.test_palette
surf.fill(palette[1], (0, 0, 5, 6))
surf.fill(palette[2], (5, 0, 5, 6))
surf.fill(palette[3], (0, 6, 5, 6))
surf.fill(palette[4], (5, 6, 5, 6))
def _make_src_surface(self, bitsize, srcalpha=False, palette=None):
surf = self._make_surface(bitsize, srcalpha, palette)
self._fill_surface(surf, palette)
return surf
def setUp(self):
pygame.display.init()
def tearDown(self):
pygame.display.quit()
def test_surface_to_array_2d(self):
alpha_color = (0, 0, 0, 128)
for surf in self.sources:
src_bitsize = surf.get_bitsize()
for dst_bitsize in self.bitsizes:
# dst in a surface standing in for a 2 dimensional array
# of unsigned integers. The byte order is system dependent.
dst = pygame.Surface(surf.get_size(), 0, dst_bitsize)
dst.fill((0, 0, 0, 0))
view = dst.get_view("2")
self.assertFalse(surf.get_locked())
if dst_bitsize < src_bitsize:
self.assertRaises(ValueError, surface_to_array, view, surf)
self.assertFalse(surf.get_locked())
continue
surface_to_array(view, surf)
self.assertFalse(surf.get_locked())
for posn, i in self.test_points:
sp = surf.get_at_mapped(posn)
dp = dst.get_at_mapped(posn)
self.assertEqual(
dp,
sp,
"%s != %s: flags: %i"
", bpp: %i, posn: %s"
% (dp, sp, surf.get_flags(), surf.get_bitsize(), posn),
)
del view
if surf.get_masks()[3]:
dst.fill((0, 0, 0, 0))
view = dst.get_view("2")
posn = (2, 1)
surf.set_at(posn, alpha_color)
self.assertFalse(surf.get_locked())
surface_to_array(view, surf)
self.assertFalse(surf.get_locked())
sp = surf.get_at_mapped(posn)
dp = dst.get_at_mapped(posn)
self.assertEqual(
dp, sp, "%s != %s: bpp: %i" % (dp, sp, surf.get_bitsize())
)
if IS_PYPY:
return
# Swapped endian destination array
pai_flags = arrinter.PAI_ALIGNED | arrinter.PAI_WRITEABLE
for surf in self.sources:
for itemsize in [1, 2, 4, 8]:
if itemsize < surf.get_bytesize():
continue
a = arrinter.Array(surf.get_size(), "u", itemsize, flags=pai_flags)
surface_to_array(a, surf)
for posn, i in self.test_points:
sp = unsigned32(surf.get_at_mapped(posn))
dp = a[posn]
self.assertEqual(
dp,
sp,
"%s != %s: itemsize: %i, flags: %i"
", bpp: %i, posn: %s"
% (
dp,
sp,
itemsize,
surf.get_flags(),
surf.get_bitsize(),
posn,
),
)
def test_surface_to_array_3d(self):
self.iter_surface_to_array_3d((0xFF, 0xFF00, 0xFF0000, 0))
self.iter_surface_to_array_3d((0xFF0000, 0xFF00, 0xFF, 0))
def iter_surface_to_array_3d(self, rgba_masks):
dst = pygame.Surface(self.surf_size, 0, 24, masks=rgba_masks)
for surf in self.sources:
dst.fill((0, 0, 0, 0))
src_bitsize = surf.get_bitsize()
view = dst.get_view("3")
self.assertFalse(surf.get_locked())
surface_to_array(view, surf)
self.assertFalse(surf.get_locked())
for posn, i in self.test_points:
sc = surf.get_at(posn)[0:3]
dc = dst.get_at(posn)[0:3]
self.assertEqual(
dc,
sc,
"%s != %s: flags: %i"
", bpp: %i, posn: %s"
% (dc, sc, surf.get_flags(), surf.get_bitsize(), posn),
)
view = None
def test_map_array(self):
targets = [
self._make_surface(8),
self._make_surface(16),
self._make_surface(16, srcalpha=True),
self._make_surface(24),
self._make_surface(32),
self._make_surface(32, srcalpha=True),
]
source = pygame.Surface(
self.surf_size, 0, 24, masks=[0xFF, 0xFF00, 0xFF0000, 0]
)
self._fill_surface(source)
source_view = source.get_view("3") # (w, h, 3)
for t in targets:
map_array(t.get_view("2"), source_view, t)
for posn, i in self.test_points:
sc = t.map_rgb(source.get_at(posn))
dc = t.get_at_mapped(posn)
self.assertEqual(
dc,
sc,
"%s != %s: flags: %i"
", bpp: %i, posn: %s"
% (dc, sc, t.get_flags(), t.get_bitsize(), posn),
)
color = pygame.Color("salmon")
color.set_length(3)
for t in targets:
map_array(t.get_view("2"), color, t)
sc = t.map_rgb(color)
for posn, i in self.test_points:
dc = t.get_at_mapped(posn)
self.assertEqual(
dc,
sc,
"%s != %s: flags: %i"
", bpp: %i, posn: %s"
% (dc, sc, t.get_flags(), t.get_bitsize(), posn),
)
# mismatched shapes
w, h = source.get_size()
target = pygame.Surface((w, h + 1), 0, 32)
self.assertRaises(ValueError, map_array, target, source, target)
target = pygame.Surface((w - 1, h), 0, 32)
self.assertRaises(ValueError, map_array, target, source, target)
def test_array_to_surface_broadcasting(self):
# target surfaces
targets = [
self._make_surface(8),
self._make_surface(16),
self._make_surface(16, srcalpha=True),
self._make_surface(24),
self._make_surface(32),
self._make_surface(32, srcalpha=True),
]
w, h = self.surf_size
# broadcast column
column = pygame.Surface((1, h), 0, 32)
for target in targets:
source = pygame.Surface((1, h), 0, target)
for y in range(h):
source.set_at((0, y), pygame.Color(y + 1, y + h + 1, y + 2 * h + 1))
pygame.pixelcopy.surface_to_array(column.get_view("2"), source)
pygame.pixelcopy.array_to_surface(target, column.get_view("2"))
for x in range(w):
for y in range(h):
self.assertEqual(
target.get_at_mapped((x, y)), column.get_at_mapped((0, y))
)
# broadcast row
row = pygame.Surface((w, 1), 0, 32)
for target in targets:
source = pygame.Surface((w, 1), 0, target)
for x in range(w):
source.set_at((x, 0), pygame.Color(x + 1, x + w + 1, x + 2 * w + 1))
pygame.pixelcopy.surface_to_array(row.get_view("2"), source)
pygame.pixelcopy.array_to_surface(target, row.get_view("2"))
for x in range(w):
for y in range(h):
self.assertEqual(
target.get_at_mapped((x, y)), row.get_at_mapped((x, 0))
)
# broadcast pixel
pixel = pygame.Surface((1, 1), 0, 32)
for target in targets:
source = pygame.Surface((1, 1), 0, target)
source.set_at((0, 0), pygame.Color(13, 47, 101))
pygame.pixelcopy.surface_to_array(pixel.get_view("2"), source)
pygame.pixelcopy.array_to_surface(target, pixel.get_view("2"))
p = pixel.get_at_mapped((0, 0))
for x in range(w):
for y in range(h):
self.assertEqual(target.get_at_mapped((x, y)), p)
class PixelCopyTestWithArray(unittest.TestCase):
try:
import numpy
except ImportError:
__tags__ = ["ignore", "subprocess_ignore"]
else:
pygame.surfarray.use_arraytype("numpy")
bitsizes = [8, 16, 32]
test_palette = [
(0, 0, 0, 255),
(10, 30, 60, 255),
(25, 75, 100, 255),
(100, 150, 200, 255),
(0, 100, 200, 255),
]
surf_size = (10, 12)
test_points = [
((0, 0), 1),
((4, 5), 1),
((9, 0), 2),
((5, 5), 2),
((0, 11), 3),
((4, 6), 3),
((9, 11), 4),
((5, 6), 4),
]
pixels2d = set([8, 16, 32])
pixels3d = set([24, 32])
array2d = set([8, 16, 24, 32])
array3d = set([24, 32])
def __init__(self, *args, **kwds):
import numpy
self.dst_types = [numpy.uint8, numpy.uint16, numpy.uint32]
try:
self.dst_types.append(numpy.uint64)
except AttributeError:
pass
pygame.display.init()
try:
unittest.TestCase.__init__(self, *args, **kwds)
self.sources = [
self._make_src_surface(8),
self._make_src_surface(16),
self._make_src_surface(16, srcalpha=True),
self._make_src_surface(24),
self._make_src_surface(32),
self._make_src_surface(32, srcalpha=True),
]
finally:
pygame.display.quit()
def _make_surface(self, bitsize, srcalpha=False, palette=None):
if palette is None:
palette = self.test_palette
flags = 0
if srcalpha:
flags |= SRCALPHA
surf = pygame.Surface(self.surf_size, flags, bitsize)
if bitsize == 8:
surf.set_palette([c[:3] for c in palette])
return surf
def _fill_surface(self, surf, palette=None):
if palette is None:
palette = self.test_palette
surf.fill(palette[1], (0, 0, 5, 6))
surf.fill(palette[2], (5, 0, 5, 6))
surf.fill(palette[3], (0, 6, 5, 6))
surf.fill(palette[4], (5, 6, 5, 6))
def _make_src_surface(self, bitsize, srcalpha=False, palette=None):
surf = self._make_surface(bitsize, srcalpha, palette)
self._fill_surface(surf, palette)
return surf
def setUp(self):
pygame.display.init()
def tearDown(self):
pygame.display.quit()
def test_surface_to_array_2d(self):
try:
from numpy import empty, dtype
except ImportError:
return
palette = self.test_palette
alpha_color = (0, 0, 0, 128)
dst_dims = self.surf_size
destinations = [empty(dst_dims, t) for t in self.dst_types]
if pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN:
swapped_dst = empty(dst_dims, dtype(">u4"))
else:
swapped_dst = empty(dst_dims, dtype("<u4"))
for surf in self.sources:
src_bytesize = surf.get_bytesize()
for dst in destinations:
if dst.itemsize < src_bytesize:
self.assertRaises(ValueError, surface_to_array, dst, surf)
continue
dst[...] = 0
self.assertFalse(surf.get_locked())
surface_to_array(dst, surf)
self.assertFalse(surf.get_locked())
for posn, i in self.test_points:
sp = unsigned32(surf.get_at_mapped(posn))
dp = dst[posn]
self.assertEqual(
dp,
sp,
"%s != %s: flags: %i"
", bpp: %i, dtype: %s, posn: %s"
% (
dp,
sp,
surf.get_flags(),
surf.get_bitsize(),
dst.dtype,
posn,
),
)
if surf.get_masks()[3]:
posn = (2, 1)
surf.set_at(posn, alpha_color)
surface_to_array(dst, surf)
sp = unsigned32(surf.get_at_mapped(posn))
dp = dst[posn]
self.assertEqual(
dp, sp, "%s != %s: bpp: %i" % (dp, sp, surf.get_bitsize())
)
swapped_dst[...] = 0
self.assertFalse(surf.get_locked())
surface_to_array(swapped_dst, surf)
self.assertFalse(surf.get_locked())
for posn, i in self.test_points:
sp = unsigned32(surf.get_at_mapped(posn))
dp = swapped_dst[posn]
self.assertEqual(
dp,
sp,
"%s != %s: flags: %i"
", bpp: %i, dtype: %s, posn: %s"
% (dp, sp, surf.get_flags(), surf.get_bitsize(), dst.dtype, posn),
)
if surf.get_masks()[3]:
posn = (2, 1)
surf.set_at(posn, alpha_color)
self.assertFalse(surf.get_locked())
surface_to_array(swapped_dst, surf)
self.assertFalse(surf.get_locked())
sp = unsigned32(surf.get_at_mapped(posn))
dp = swapped_dst[posn]
self.assertEqual(
dp, sp, "%s != %s: bpp: %i" % (dp, sp, surf.get_bitsize())
)
def test_surface_to_array_3d(self):
try:
from numpy import empty, dtype
except ImportError:
return
palette = self.test_palette
dst_dims = self.surf_size + (3,)
destinations = [empty(dst_dims, t) for t in self.dst_types]
if pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN:
swapped_dst = empty(dst_dims, dtype(">u4"))
else:
swapped_dst = empty(dst_dims, dtype("<u4"))
for surf in self.sources:
src_bitsize = surf.get_bitsize()
for dst in destinations:
dst[...] = 0
self.assertFalse(surf.get_locked())
surface_to_array(dst, surf)
self.assertFalse(surf.get_locked())
for posn, i in self.test_points:
r_surf, g_surf, b_surf, a_surf = surf.get_at(posn)
r_arr, g_arr, b_arr = dst[posn]
self.assertEqual(
r_arr,
r_surf,
"%i != %i, color: red, flags: %i"
", bpp: %i, posn: %s"
% (r_arr, r_surf, surf.get_flags(), surf.get_bitsize(), posn),
)
self.assertEqual(
g_arr,
g_surf,
"%i != %i, color: green, flags: %i"
", bpp: %i, posn: %s"
% (r_arr, r_surf, surf.get_flags(), surf.get_bitsize(), posn),
)
self.assertEqual(
b_arr,
b_surf,
"%i != %i, color: blue, flags: %i"
", bpp: %i, posn: %s"
% (r_arr, r_surf, surf.get_flags(), surf.get_bitsize(), posn),
)
swapped_dst[...] = 0
self.assertFalse(surf.get_locked())
surface_to_array(swapped_dst, surf)
self.assertFalse(surf.get_locked())
for posn, i in self.test_points:
r_surf, g_surf, b_surf, a_surf = surf.get_at(posn)
r_arr, g_arr, b_arr = swapped_dst[posn]
self.assertEqual(
r_arr,
r_surf,
"%i != %i, color: red, flags: %i"
", bpp: %i, posn: %s"
% (r_arr, r_surf, surf.get_flags(), surf.get_bitsize(), posn),
)
self.assertEqual(
g_arr,
g_surf,
"%i != %i, color: green, flags: %i"
", bpp: %i, posn: %s"
% (r_arr, r_surf, surf.get_flags(), surf.get_bitsize(), posn),
)
self.assertEqual(
b_arr,
b_surf,
"%i != %i, color: blue, flags: %i"
", bpp: %i, posn: %s"
% (r_arr, r_surf, surf.get_flags(), surf.get_bitsize(), posn),
)
def test_map_array(self):
try:
from numpy import array, zeros, uint8, int32, alltrue
except ImportError:
return
surf = pygame.Surface((1, 1), 0, 32)
# color fill
color = array([11, 17, 59], uint8)
target = zeros((5, 7), int32)
map_array(target, color, surf)
self.assertTrue(alltrue(target == surf.map_rgb(color)))
# array column stripes
stripe = array([[2, 5, 7], [11, 19, 23], [37, 53, 101]], uint8)
target = zeros((4, stripe.shape[0]), int32)
map_array(target, stripe, surf)
target_stripe = array([surf.map_rgb(c) for c in stripe], int32)
self.assertTrue(alltrue(target == target_stripe))
# array row stripes
stripe = array(
[[[2, 5, 7]], [[11, 19, 24]], [[10, 20, 30]], [[37, 53, 101]]], uint8
)
target = zeros((stripe.shape[0], 3), int32)
map_array(target, stripe, surf)
target_stripe = array([[surf.map_rgb(c)] for c in stripe[:, 0]], int32)
self.assertTrue(alltrue(target == target_stripe))
# mismatched shape
w = 4
h = 5
source = zeros((w, h, 3), uint8)
target = zeros((w,), int32)
self.assertRaises(ValueError, map_array, target, source, surf)
source = zeros((12, w, h + 1), uint8)
self.assertRaises(ValueError, map_array, target, source, surf)
source = zeros((12, w - 1, 5), uint8)
self.assertRaises(ValueError, map_array, target, source, surf)
## def test_array_to_surface(self):
## array_to_surface gets a good workout in the surfarray module's
## unit tests under the alias blit_array.
try:
numpy
except NameError:
# Ensure no methods requiring numpy are run when
# pixelcopy_test is '__main__'.
del __init__
del test_surface_to_array_2d
del test_surface_to_array_3d
del test_map_array
else:
del numpy
@unittest.skipIf(not pygame.HAVE_NEWBUF, "newbuf not implemented")
class PixelCopyTestWithArray(unittest.TestCase):
if pygame.HAVE_NEWBUF:
from pygame.tests.test_utils import buftools
class Array2D(buftools.Exporter):
def __init__(self, initializer):
from ctypes import cast, POINTER, c_uint32
Array2D = PixelCopyTestWithArray.Array2D
super(Array2D, self).__init__((3, 5), format="=I", strides=(20, 4))
self.content = cast(self.buf, POINTER(c_uint32))
for i, v in enumerate(initializer):
self.content[i] = v
def __getitem__(self, key):
byte_index = key[0] * 5 + key[1]
if not (0 <= byte_index < 15):
raise IndexError("%s is out of range", key)
return self.content[byte_index]
class Array3D(buftools.Exporter):
def __init__(self, initializer):
from ctypes import cast, POINTER, c_uint8
Array3D = PixelCopyTestWithArray.Array3D
super(Array3D, self).__init__((3, 5, 3), format="B", strides=(20, 4, 1))
self.content = cast(self.buf, POINTER(c_uint8))
for i, v in enumerate(initializer):
self.content[i] = v
def __getitem__(self, key):
byte_index = key[0] * 20 + key[1] * 4 + key[2]
if not (0 <= byte_index < 60):
raise IndexError("%s is out of range", key)
return self.content[byte_index]
surface = pygame.Surface((3, 5), 0, 32)
def setUp(self):
surf = self.surface
for y in range(5):
for x in range(3):
surf.set_at((x, y), (x + 1, 0, y + 1))
def assertCopy2D(self, surface, array):
for x in range(0, 3):
for y in range(0, 5):
self.assertEqual(surface.get_at_mapped((x, y)), array[x, y])
def test_surface_to_array_newbuf(self):
array = self.Array2D(range(0, 15))
self.assertNotEqual(array.content[0], self.surface.get_at_mapped((0, 0)))
surface_to_array(array, self.surface)
self.assertCopy2D(self.surface, array)
def test_array_to_surface_newbuf(self):
array = self.Array2D(range(0, 15))
self.assertNotEqual(array.content[0], self.surface.get_at_mapped((0, 0)))
array_to_surface(self.surface, array)
self.assertCopy2D(self.surface, array)
def test_map_array_newbuf(self):
array2D = self.Array2D([0] * 15)
elements = [i + (255 - i << 8) + (99 << 16) for i in range(0, 15)]
array3D = self.Array3D(elements)
map_array(array2D, array3D, self.surface)
for x in range(0, 3):
for y in range(0, 5):
p = array3D[x, y, 0], array3D[x, y, 1], array3D[x, y, 2]
self.assertEqual(self.surface.unmap_rgb(array2D[x, y]), p)
def test_make_surface_newbuf(self):
array = self.Array2D(range(10, 160, 10))
surface = make_surface(array)
self.assertCopy2D(surface, array)
def test_format_newbuf(self):
Exporter = self.buftools.Exporter
surface = self.surface
shape = surface.get_size()
w, h = shape
for format in [
"=i",
"=I",
"=l",
"=L",
"=q",
"=Q",
"<i",
">i",
"!i",
"1i",
"=1i",
"@q",
"q",
"4x",
"8x",
]:
surface.fill((255, 254, 253))
exp = Exporter(shape, format=format)
exp._buf[:] = [42] * exp.buflen
array_to_surface(surface, exp)
for x in range(w):
for y in range(h):
self.assertEqual(surface.get_at((x, y)), (42, 42, 42, 255))
# Some unsupported formats for array_to_surface and a 32 bit surface
for format in ["f", "d", "?", "x", "1x", "2x", "3x", "5x", "6x", "7x", "9x"]:
exp = Exporter(shape, format=format)
self.assertRaises(ValueError, array_to_surface, surface, exp)
if __name__ == "__main__":
unittest.main()
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,39 @@
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
self.assertTrue(True)
def test_get_pressed(self):
self.assertTrue(True)
def test_name(self):
self.assertTrue(True)
def test_set_mods(self):
self.assertTrue(True)
def test_set_repeat(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,39 @@
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
self.assertTrue(True)
def test_get_pressed(self):
self.assertTrue(True)
def test_name(self):
self.assertTrue(True)
def test_set_mods(self):
self.assertTrue(True)
def test_set_repeat(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,39 @@
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
self.assertTrue(True)
def test_get_pressed(self):
self.assertTrue(True)
def test_name(self):
self.assertTrue(True)
def test_set_mods(self):
self.assertTrue(True)
def test_set_repeat(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,39 @@
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
self.assertTrue(True)
def test_get_pressed(self):
self.assertTrue(True)
def test_name(self):
self.assertTrue(True)
def test_set_mods(self):
self.assertTrue(True)
def test_set_repeat(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,39 @@
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
self.assertTrue(True)
def test_get_pressed(self):
self.assertTrue(True)
def test_name(self):
self.assertTrue(True)
def test_set_mods(self):
self.assertTrue(True)
def test_set_repeat(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,39 @@
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
pass
def test_get_mods(self):
pass
def test_get_pressed(self):
pass
def test_name(self):
pass
def test_set_mods(self):
pass
def test_set_repeat(self):
pass
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,23 @@
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
pass
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,39 @@
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
self.assertTrue(True)
def test_get_pressed(self):
self.assertTrue(True)
def test_name(self):
self.assertTrue(True)
def test_set_mods(self):
self.assertTrue(True)
def test_set_repeat(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,39 @@
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
self.assertTrue(True)
def todo_test_get_pressed(self):
self.assertTrue(True)
def test_name(self):
self.assertTrue(True)
def todo_test_set_mods(self):
self.assertTrue(True)
def test_set_repeat(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,38 @@
__tags__ = ["magic"]
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
self.assertTrue(True)
def test_get_pressed(self):
self.assertTrue(True)
def test_name(self):
self.assertTrue(True)
def test_set_mods(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,29 @@
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
import time
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
stop_time = time.time() + 10.0
while time.time() < stop_time:
time.sleep(1)
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,39 @@
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
self.assertTrue(True)
def test_get_pressed(self):
self.assertTrue(True)
def test_name(self):
self.assertTrue(True)
def test_set_mods(self):
self.assertTrue(True)
def test_set_repeat(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,41 @@
__tags__ = ["invisible"]
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
self.assertTrue(True)
def test_get_pressed(self):
self.assertTrue(True)
def test_name(self):
self.assertTrue(True)
def test_set_mods(self):
self.assertTrue(True)
def test_set_repeat(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,38 @@
__tags__ = ["magic"]
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
self.assertTrue(True)
def test_get_pressed(self):
self.assertTrue(True)
def test_name(self):
self.assertTrue(True)
def test_set_mods(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,39 @@
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
self.assertTrue(True)
def test_get_pressed(self):
self.assertTrue(True)
def test_name(self):
self.assertTrue(True)
def test_set_mods(self):
self.assertTrue(True)
def test_set_repeat(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,39 @@
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
self.assertTrue(True)
def test_get_pressed(self):
self.assertTrue(True)
def test_name(self):
self.assertTrue(True)
def test_set_mods(self):
self.assertTrue(True)
def test_set_repeat(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,41 @@
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
self.assertTrue(True)
def test_get_pressed(self):
self.assertTrue(False, "Some Jibberish")
def test_name(self):
self.assertTrue(True)
def test_set_mods(self):
if 1:
if 1:
assert False
def test_set_repeat(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,39 @@
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
self.assertTrue(True)
def todo_test_get_pressed(self):
self.fail()
def test_name(self):
self.assertTrue(True)
def todo_test_set_mods(self):
self.fail()
def test_set_repeat(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,39 @@
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
self.assertTrue(True)
def test_get_pressed(self):
self.assertTrue(True)
def test_name(self):
self.assertTrue(True)
def test_set_mods(self):
self.assertTrue(True)
def test_set_repeat(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,39 @@
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
self.assertTrue(True)
def todo_test_get_pressed(self):
self.assertTrue(True)
def test_name(self):
self.assertTrue(True)
def todo_test_set_mods(self):
self.assertTrue(True)
def test_set_repeat(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,39 @@
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
self.assertTrue(True)
def test_get_pressed(self):
self.assertTrue(True)
def test_name(self):
self.assertTrue(True)
def test_set_mods(self):
self.assertTrue(True)
def test_set_repeat(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,40 @@
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
while True:
pass
def test_get_pressed(self):
self.assertTrue(True)
def test_name(self):
self.assertTrue(True)
def test_set_mods(self):
self.assertTrue(True)
def test_set_repeat(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,39 @@
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
self.assertTrue(True)
def test_get_pressed(self):
self.assertTrue(True)
def test_name(self):
self.assertTrue(True)
def test_set_mods(self):
self.assertTrue(True)
def test_set_repeat(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,39 @@
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
self.assertTrue(True)
def test_get_pressed(self):
self.assertTrue(True)
def test_name(self):
self.assertTrue(True)
def test_set_mods(self):
self.assertTrue(True)
def test_set_repeat(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,41 @@
import sys
if __name__ == "__main__":
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
self.assertTrue(True)
def test_get_pressed(self):
self.assertTrue(True)
def test_name(self):
sys.stderr.write("jibberish messes things up\n")
self.assertTrue(False)
def test_set_mods(self):
self.assertTrue(True)
def test_set_repeat(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,41 @@
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
self.assertTrue(True)
def test_get_pressed(self):
self.assertTrue(False, "Some Jibberish")
def test_name(self):
self.assertTrue(True)
def test_set_mods(self):
if 1:
if 1:
assert False
def test_set_repeat(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,39 @@
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
self.assertTrue(True)
def test_get_pressed(self):
self.assertTrue(True)
def test_name(self):
self.assertTrue(True)
def test_set_mods(self):
self.assertTrue(True)
def test_set_repeat(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,42 @@
import sys
if __name__ == "__main__":
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
self.assertTrue(True)
def test_get_pressed(self):
sys.stdout.write("jibberish ruins everything\n")
self.assertTrue(False)
def test_name(self):
sys.stdout.write("forgot to remove debug crap\n")
self.assertTrue(True)
def test_set_mods(self):
self.assertTrue(True)
def test_set_repeat(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,41 @@
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
self.assertTrue(True)
def test_get_pressed(self):
self.assertTrue(False, "Some Jibberish")
def test_name(self):
self.assertTrue(True)
def test_set_mods(self):
if 1:
if 1:
assert False
def test_set_repeat(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,145 @@
################################################################################
import subprocess, os, sys, re, difflib
################################################################################
IGNORE = (".svn", "infinite_loop")
NORMALIZERS = (
(r"Ran (\d+) tests in (\d+\.\d+)s", "Ran \\1 tests in X.XXXs"),
(r'File ".*?([^/\\.]+\.py)"', 'File "\\1"'),
)
################################################################################
def norm_result(result):
"normalize differences, such as timing between output"
for normalizer, replacement in NORMALIZERS:
if hasattr(normalizer, "__call__"):
result = normalizer(result)
else:
result = re.sub(normalizer, replacement, result)
return result
def call_proc(cmd, cd=None):
proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
cwd=cd,
universal_newlines=True,
)
if proc.wait():
print("%s %s" % (cmd, proc.wait()))
raise Exception(proc.stdout.read())
return proc.stdout.read()
################################################################################
unnormed_diff = "-u" in sys.argv
verbose = "-v" in sys.argv or unnormed_diff
if "-h" in sys.argv or "--help" in sys.argv:
sys.exit(
"\nCOMPARES OUTPUT OF SINGLE VS SUBPROCESS MODE OF RUN_TESTS.PY\n\n"
"-v, to output diffs even on success\n"
"-u, to output diffs of unnormalized tests\n\n"
"Each line of a Differ delta begins with a two-letter code:\n\n"
" '- ' line unique to sequence 1\n"
" '+ ' line unique to sequence 2\n"
" ' ' line common to both sequences\n"
" '? ' line not present in either input sequence\n"
)
main_dir = os.path.split(os.path.abspath(sys.argv[0]))[0]
trunk_dir = os.path.normpath(os.path.join(main_dir, "../../"))
test_suite_dirs = [
x
for x in os.listdir(main_dir)
if os.path.isdir(os.path.join(main_dir, x)) and x not in IGNORE
]
################################################################################
def assert_on_results(suite, single, sub):
test = globals().get("%s_test" % suite)
if hasattr(test, "__call_"):
test(suite, single, sub)
print("assertions on %s OK" % (suite,))
# Don't modify tests in suites below. These assertions are in place to make sure
# that tests are actually being ran
def all_ok_test(uite, *args):
for results in args:
assert "Ran 36 tests" in results # some tests are runing
assert "OK" in results # OK
def failures1_test(suite, *args):
for results in args:
assert "FAILED (failures=2)" in results
assert "Ran 18 tests" in results
################################################################################
# Test that output is the same in single process and subprocess modes
#
base_cmd = [sys.executable, "run_tests.py", "-i"]
cmd = base_cmd + ["-n", "-f"]
sub_cmd = base_cmd + ["-f"]
time_out_cmd = base_cmd + ["-t", "4", "-f", "infinite_loop"]
passes = 0
failed = False
for suite in test_suite_dirs:
single = call_proc(cmd + [suite], trunk_dir)
subs = call_proc(sub_cmd + [suite], trunk_dir)
normed_single, normed_subs = map(norm_result, (single, subs))
failed = normed_single != normed_subs
if failed:
print("%s suite comparison FAILED\n" % (suite,))
else:
passes += 1
print("%s suite comparison OK" % (suite,))
assert_on_results(suite, single, subs)
if verbose or failed:
print("difflib.Differ().compare(single, suprocessed):\n")
print(
"".join(
list(
difflib.Differ().compare(
(unnormed_diff and single or normed_single).splitlines(1),
(unnormed_diff and subs or normed_subs).splitlines(1),
)
)
)
)
sys.stdout.write("infinite_loop suite (subprocess mode timeout) ")
loop_test = call_proc(time_out_cmd, trunk_dir)
assert "successfully terminated" in loop_test
passes += 1
print("OK")
print("\n%s/%s suites pass" % (passes, len(test_suite_dirs) + 1))
print("\n-h for help")
################################################################################
@@ -0,0 +1,39 @@
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
self.assertTrue(True)
def test_get_mods(self):
self.assertTrue(True)
def test_get_pressed(self):
self.assertTrue(True)
def test_name(self):
self.assertTrue(True)
def test_set_mods(self):
self.assertTrue(True)
def test_set_repeat(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,30 @@
if __name__ == "__main__":
import sys
import os
pkg_dir = os.path.split(
os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
)[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = pkg_name == "tests" and os.path.split(parent_dir)[1] == "pygame"
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith("pygame.tests.")
import unittest
import time
class KeyModuleTest(unittest.TestCase):
def test_get_focused(self):
stop_time = time.time() + 10.0
while time.time() < stop_time:
time.sleep(1)
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,132 @@
import sys
import unittest
from pygame import encode_string, encode_file_path
from pygame.compat import bytes_, as_bytes, as_unicode
class RWopsEncodeStringTest(unittest.TestCase):
global getrefcount
def test_obj_None(self):
encoded_string = encode_string(None)
self.assertIsNone(encoded_string)
def test_returns_bytes(self):
u = as_unicode(r"Hello")
encoded_string = encode_string(u)
self.assertIsInstance(encoded_string, bytes_)
def test_obj_bytes(self):
b = as_bytes("encyclop\xE6dia")
encoded_string = encode_string(b, "ascii", "strict")
self.assertIs(encoded_string, b)
def test_encode_unicode(self):
u = as_unicode(r"\u00DEe Olde Komp\u00FCter Shoppe")
b = u.encode("utf-8")
self.assertEqual(encode_string(u, "utf-8"), b)
def test_error_fowarding(self):
self.assertRaises(SyntaxError, encode_string)
def test_errors(self):
s = r"abc\u0109defg\u011Dh\u0125ij\u0135klmnoprs\u015Dtu\u016Dvz"
u = as_unicode(s)
b = u.encode("ascii", "ignore")
self.assertEqual(encode_string(u, "ascii", "ignore"), b)
def test_encoding_error(self):
u = as_unicode(r"a\x80b")
encoded_string = encode_string(u, "ascii", "strict")
self.assertIsNone(encoded_string)
def test_check_defaults(self):
u = as_unicode(r"a\u01F7b")
b = u.encode("unicode_escape", "backslashreplace")
encoded_string = encode_string(u)
self.assertEqual(encoded_string, b)
def test_etype(self):
u = as_unicode(r"a\x80b")
self.assertRaises(SyntaxError, encode_string, u, "ascii", "strict", SyntaxError)
def test_etype__invalid(self):
"""Ensures invalid etypes are properly handled."""
for etype in ("SyntaxError", self):
self.assertRaises(TypeError, encode_string, "test", etype=etype)
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)
try:
from sys import getrefcount as _g
getrefcount = _g # This nonsense is for Python 3.x
except ImportError:
pass
else:
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_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)
# For Python 3.1, surrogate pair handling depends on whether the
# interpreter was built with UCS-2 or USC-4 unicode strings.
##u = as_unicode(r"a\uD80C\uDCA7b")
##b = encode_string(u, 'utf-8', 'strict', AssertionError)
##self.assertEqual(b, utf_8)
class RWopsEncodeFilePathTest(unittest.TestCase):
# Most tests can be skipped since RWopsEncodeFilePath wraps
# RWopsEncodeString
def test_encoding(self):
u = as_unicode(r"Hello")
encoded_file_path = encode_file_path(u)
self.assertIsInstance(encoded_file_path, bytes_)
def test_error_fowarding(self):
self.assertRaises(SyntaxError, encode_file_path)
def test_path_with_null_bytes(self):
b = as_bytes("a\x00b\x00c")
encoded_file_path = encode_file_path(b)
self.assertIsNone(encoded_file_path)
def test_etype(self):
b = as_bytes("a\x00b\x00c")
self.assertRaises(TypeError, encode_file_path, b, TypeError)
def test_etype__invalid(self):
"""Ensures invalid etypes are properly handled."""
for etype in ("SyntaxError", self):
self.assertRaises(TypeError, encode_file_path, "test", etype)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,21 @@
# For now the scrap module has not been updated for SDL 2
__tags__ = ["SDL2_ignore"]
import sys
exclude = False
if sys.platform == "win32" or sys.platform.startswith("linux"):
try:
import pygame
pygame.scrap._NOT_IMPLEMENTED_
except AttributeError:
pass
else:
exclude = True
else:
exclude = True
if exclude:
__tags__.extend(["ignore", "subprocess_ignore"])
@@ -0,0 +1,302 @@
import os
import sys
if os.environ.get("SDL_VIDEODRIVER") == "dummy":
__tags__ = ("ignore", "subprocess_ignore")
import unittest
from pygame.tests.test_utils import trunk_relative_path
import pygame
from pygame import scrap
from pygame.compat import as_bytes
class ScrapModuleTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
pygame.display.init()
pygame.display.set_mode((1, 1))
scrap.init()
@classmethod
def tearDownClass(cls):
# scrap.quit() # Does not exist!
pygame.display.quit()
def test_init(self):
"""Ensures scrap module still initialized after multiple init calls."""
scrap.init()
scrap.init()
self.assertTrue(scrap.get_init())
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_init(self):
"""Ensures get_init gets the init state."""
self.assertTrue(scrap.get_init())
def todo_test_contains(self):
"""Ensures contains works as expected."""
self.fail()
def todo_test_get(self):
"""Ensures get works as expected."""
self.fail()
def test_get__owned_empty_type(self):
"""Ensures get works when there is no data of the requested type
in the clipboard and the clipboard is owned by the pygame application.
"""
# Use a unique data type identifier to ensure there is no preexisting
# data.
DATA_TYPE = "test_get__owned_empty_type"
if scrap.lost():
# Try to acquire the clipboard.
scrap.put(pygame.SCRAP_TEXT, b"text to clipboard")
if scrap.lost():
self.skipTest("requires the pygame application to own the " "clipboard")
data = scrap.get(DATA_TYPE)
self.assertIsNone(data)
def todo_test_get_types(self):
"""Ensures get_types works as expected."""
self.fail()
def todo_test_lost(self):
"""Ensures lost works as expected."""
self.fail()
def test_set_mode(self):
"""Ensures set_mode works as expected."""
scrap.set_mode(pygame.SCRAP_SELECTION)
scrap.set_mode(pygame.SCRAP_CLIPBOARD)
self.assertRaises(ValueError, scrap.set_mode, 1099)
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"))
@unittest.skipIf("pygame.image" not in sys.modules, "requires pygame.image module")
def test_put__bmp_image(self):
"""Ensures put can place a BMP image into the clipboard."""
sf = pygame.image.load(trunk_relative_path("examples/data/asprite.bmp"))
expected_string = pygame.image.tostring(sf, "RGBA")
scrap.put(pygame.SCRAP_BMP, expected_string)
self.assertEqual(scrap.get(pygame.SCRAP_BMP), expected_string)
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"))
class ScrapModuleClipboardNotOwnedTest(unittest.TestCase):
"""Test the scrap module's functionality when the pygame application is
not the current owner of the clipboard.
A separate class is used to prevent tests that acquire the clipboard from
interfering with these tests.
"""
@classmethod
def setUpClass(cls):
pygame.display.init()
pygame.display.set_mode((1, 1))
scrap.init()
@classmethod
def tearDownClass(cls):
# scrap.quit() # Does not exist!
pygame.quit()
pygame.display.quit()
def _skip_if_clipboard_owned(self):
# Skip test if the pygame application owns the clipboard. Currently,
# there is no way to give up ownership.
if not scrap.lost():
self.skipTest("requires the pygame application to not own the " "clipboard")
def test_get__not_owned(self):
"""Ensures get works when there is no data of the requested type
in the clipboard and the clipboard is not owned by the pygame
application.
"""
self._skip_if_clipboard_owned()
# Use a unique data type identifier to ensure there is no preexisting
# data.
DATA_TYPE = "test_get__not_owned"
data = scrap.get(DATA_TYPE)
self.assertIsNone(data)
def test_get_types__not_owned(self):
"""Ensures get_types works when the clipboard is not owned
by the pygame application.
"""
self._skip_if_clipboard_owned()
data_types = scrap.get_types()
self.assertIsInstance(data_types, list)
def test_contains__not_owned(self):
"""Ensures contains works when the clipboard is not owned
by the pygame application.
"""
self._skip_if_clipboard_owned()
# Use a unique data type identifier to ensure there is no preexisting
# data.
DATA_TYPE = "test_contains__not_owned"
contains = scrap.contains(DATA_TYPE)
self.assertFalse(contains)
def test_lost__not_owned(self):
"""Ensures lost works when the clipboard is not owned
by the pygame application.
"""
self._skip_if_clipboard_owned()
lost = scrap.lost()
self.assertTrue(lost)
class X11InteractiveTest(unittest.TestCase):
__tags__ = ["ignore", "subprocess_ignore"]
try:
pygame.display.init()
except Exception:
pass
else:
if pygame.display.get_driver() == "x11":
__tags__ = ["interactive"]
pygame.display.quit()
def test_issue_208(self):
"""PATCH: pygame.scrap on X11, fix copying into PRIMARY selection
Copying into theX11 PRIMARY selection (mouse copy/paste) would not
work due to a confusion between content type and clipboard type.
"""
from pygame import display, event, freetype
from pygame.locals import SCRAP_SELECTION, SCRAP_TEXT
from pygame.locals import KEYDOWN, K_y, QUIT
success = False
freetype.init()
font = freetype.Font(None, 24)
display.init()
display.set_caption("Interactive X11 Paste Test")
screen = display.set_mode((600, 200))
screen.fill(pygame.Color("white"))
text = "Scrap put() succeeded."
msg = (
"Some text has been placed into the X11 clipboard."
" Please click the center mouse button in an open"
" text window to retrieve it."
'\n\nDid you get "{}"? (y/n)'
).format(text)
word_wrap(screen, msg, font, 6)
display.flip()
event.pump()
scrap.init()
scrap.set_mode(SCRAP_SELECTION)
scrap.put(SCRAP_TEXT, text.encode("UTF-8"))
while True:
e = event.wait()
if e.type == QUIT:
break
if e.type == KEYDOWN:
success = e.key == K_y
break
pygame.display.quit()
self.assertTrue(success)
def word_wrap(surf, text, font, margin=0, color=(0, 0, 0)):
font.origin = True
surf_width, surf_height = surf.get_size()
width = surf_width - 2 * margin
height = surf_height - 2 * margin
line_spacing = int(1.25 * font.get_sized_height())
x, y = margin, margin + line_spacing
space = font.get_rect(" ")
for word in iwords(text):
if word == "\n":
x, y = margin, y + line_spacing
else:
bounds = font.get_rect(word)
if x + bounds.width + bounds.x >= width:
x, y = margin, y + line_spacing
if x + bounds.width + bounds.x >= width:
raise ValueError("word too wide for the surface")
if y + bounds.height - bounds.y >= height:
raise ValueError("text to long for the surface")
font.render_to(surf, (x, y), None, color)
x += bounds.width + space.width
return x, y
def iwords(text):
# r"\n|[^ ]+"
#
head = 0
tail = head
end = len(text)
while head < end:
if text[head] == " ":
head += 1
tail = head + 1
elif text[head] == "\n":
head += 1
yield "\n"
tail = head + 1
elif tail == end:
yield text[head:]
head = end
elif text[tail] == "\n":
yield text[head:tail]
head = tail
elif text[tail] == " ":
yield text[head:tail]
head = tail
else:
tail += 1
if __name__ == "__main__":
unittest.main()

Some files were not shown because too many files have changed in this diff Show More