Erste Version
This commit is contained in:
commit
782b1850a3
1641 files changed
+512713
No files matched your search
@@ -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 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,143 @@
|
||||
"""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 = f'python -c "import {test_pkg_name}.go"'
|
||||
|
||||
###########################################################################
|
||||
# Set additional command line options
|
||||
#
|
||||
# Defined in test_runner.py as it shares options, added to here
|
||||
|
||||
opt_parser.set_usage(
|
||||
f"""
|
||||
|
||||
Runs all or some of the {test_pkg_name}.xxxx_test tests.
|
||||
|
||||
$ {program_name} sprite threads -sd
|
||||
|
||||
Runs the sprite and threads module tests isolated in subprocesses, dumping
|
||||
all failing tests info in the form of a dict.
|
||||
|
||||
"""
|
||||
)
|
||||
|
||||
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 executable 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 arguments according to command line arguments.
|
||||
# args will be the test module list, passed as positional arguments.
|
||||
|
||||
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,619 @@
|
||||
import platform
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
IS_PYPY = "PyPy" == platform.python_implementation()
|
||||
|
||||
try:
|
||||
from pygame.tests.test_utils import arrinter
|
||||
except NameError:
|
||||
pass
|
||||
import pygame
|
||||
|
||||
quit_count = 0
|
||||
|
||||
|
||||
def quit_hook():
|
||||
global quit_count
|
||||
quit_count += 1
|
||||
|
||||
|
||||
class BaseModuleTest(unittest.TestCase):
|
||||
def tearDown(self):
|
||||
# Clean up after each test method.
|
||||
pygame.quit()
|
||||
|
||||
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:
|
||||
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 gc
|
||||
import weakref
|
||||
|
||||
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().__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)
|
||||
|
||||
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(IS_PYPY, "pypy no likey")
|
||||
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)
|
||||
|
||||
def test_bad_format(self):
|
||||
from ctypes import addressof, create_string_buffer
|
||||
|
||||
from pygame.bufferproxy import BufferProxy
|
||||
from pygame.newbuffer import BufferMixin
|
||||
|
||||
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(IS_PYPY, "fails on pypy")
|
||||
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, "newbuf with ctypes")
|
||||
def test_PgObject_AsBuffer_PyBUF_flags(self):
|
||||
import ctypes
|
||||
|
||||
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
|
||||
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.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.assertEqual(quit_count, 0)
|
||||
|
||||
pygame.init()
|
||||
pygame.register_quit(quit_hook)
|
||||
pygame.quit()
|
||||
|
||||
self.assertEqual(quit_count, 1)
|
||||
|
||||
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):
|
||||
pygame.set_error("你好")
|
||||
self.assertEqual("你好", pygame.get_error())
|
||||
|
||||
def test_init(self):
|
||||
"""Ensures init() works properly."""
|
||||
# Make sure nothing initialized.
|
||||
self.not_init_assertions()
|
||||
|
||||
# display and joystick must init, at minimum
|
||||
expected_min_passes = 2
|
||||
|
||||
# All modules should pass.
|
||||
expected_fails = 0
|
||||
|
||||
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())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,253 @@
|
||||
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(f"python blits: {t1 - t0}")
|
||||
|
||||
dst.fill((230, 230, 230))
|
||||
t0 = time()
|
||||
results = dst.blits(blit_list)
|
||||
t1 = time()
|
||||
if PRINT_TIMING:
|
||||
print(f"Surface.blits :{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(f"Surface.blits doreturn=0: {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(f"Surface.blits generator: {t1 - t0}")
|
||||
|
||||
def test_fblits(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
|
||||
|
||||
# tests for number of parameters
|
||||
self.assertRaises(ValueError, dst.fblits) # no params
|
||||
|
||||
# tests for the blit_sequence parameter
|
||||
self.assertRaises(ValueError, dst.fblits, [-1])
|
||||
self.assertRaises(ValueError, dst.fblits, (-1,))
|
||||
self.assertRaises(ValueError, dst.fblits, "str")
|
||||
self.assertRaises(ValueError, dst.fblits, 1)
|
||||
|
||||
# tests for the special_flags parameter
|
||||
self.assertRaises(TypeError, dst.fblits, blit_list, -999) # not impl. flag
|
||||
self.assertRaises(TypeError, dst.fblits, blit_list, 12.245) # float flag
|
||||
self.assertRaises(TypeError, dst.fblits, blit_list, None)
|
||||
self.assertRaises(TypeError, dst.fblits, blit_list, [])
|
||||
self.assertRaises(TypeError, dst.fblits, blit_list, ())
|
||||
self.assertRaises(TypeError, dst.fblits, blit_list, "str")
|
||||
self.assertRaises(TypeError, dst.fblits, blit_list, "str")
|
||||
|
||||
# tests for return value
|
||||
self.assertEqual(dst.fblits(blit_list, 0), None)
|
||||
self.assertEqual(dst.fblits(blit_list, 1), dst.blits(blit_list, doreturn=0))
|
||||
|
||||
# make sure this doesn't segfault
|
||||
dst.fblits((dst, dst.get_rect().topleft) for _ in range(1))
|
||||
|
||||
t0 = time()
|
||||
results = blits(blit_list)
|
||||
t1 = time()
|
||||
if PRINT_TIMING:
|
||||
print(f"python blits: {t1 - t0}")
|
||||
|
||||
dst.fill((230, 230, 230))
|
||||
t0 = time()
|
||||
dst.fblits(blit_list, 0)
|
||||
t1 = time()
|
||||
if PRINT_TIMING:
|
||||
print(f"Surface.fblits :{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)
|
||||
|
||||
t0 = time()
|
||||
result = dst.fblits(blit_list)
|
||||
t1 = time()
|
||||
if PRINT_TIMING:
|
||||
print(f"Surface.fblits: {t1 - t0}")
|
||||
self.assertEqual(result, None)
|
||||
|
||||
t0 = time()
|
||||
dst.fblits(((surf, dest) for surf, dest in blit_list))
|
||||
t1 = time()
|
||||
if PRINT_TIMING:
|
||||
print(f"Surface.fblits generator: {t1 - t0}")
|
||||
|
||||
def test_fblits_not_sequence(self):
|
||||
dst = pygame.Surface((100, 10), SRCALPHA, 32)
|
||||
self.assertRaises(ValueError, dst.fblits, None)
|
||||
|
||||
def test_fblits_wrong_length(self):
|
||||
dst = pygame.Surface((100, 10), SRCALPHA, 32)
|
||||
self.assertRaises(
|
||||
ValueError, dst.fblits, [pygame.Surface((10, 10), SRCALPHA, 32)]
|
||||
)
|
||||
|
||||
def test_fblits_bad_surf_args(self):
|
||||
dst = pygame.Surface((100, 10), SRCALPHA, 32)
|
||||
self.assertRaises(TypeError, dst.fblits, [(None, None)])
|
||||
|
||||
def test_fblits_bad_dest(self):
|
||||
dst = pygame.Surface((100, 10), SRCALPHA, 32)
|
||||
self.assertRaises(
|
||||
TypeError, dst.fblits, [(pygame.Surface((10, 10), SRCALPHA, 32), None)]
|
||||
)
|
||||
|
||||
def test_fblits_generator_exception(self):
|
||||
dst = pygame.Surface((100, 10), SRCALPHA, 32)
|
||||
exc_type = Exception
|
||||
|
||||
def generate_exception():
|
||||
yield pygame.Surface((10, 10)), (0, 0)
|
||||
raise exc_type
|
||||
|
||||
self.assertRaises(exc_type, dst.fblits, generate_exception())
|
||||
|
||||
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,502 @@
|
||||
import ctypes
|
||||
import gc
|
||||
import re
|
||||
import unittest
|
||||
import weakref
|
||||
|
||||
import pygame
|
||||
from pygame.bufferproxy import BufferProxy
|
||||
|
||||
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:
|
||||
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 f"*{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:], ">*")
|
||||
|
||||
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 = f"{'<' if lil_endian else '>'}i{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 read 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_read_buffer, get_segcount, get_write_buffer
|
||||
|
||||
content = b"\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 = b"\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 addressof, c_byte, memset, sizeof, string_at
|
||||
|
||||
nullbyte = b"\x00"
|
||||
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, b"123")
|
||||
finally:
|
||||
# Make sure bp is garbage collected before buf
|
||||
bp = None
|
||||
gc.collect()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,5 @@
|
||||
import unittest
|
||||
|
||||
|
||||
class CameraModuleTest(unittest.TestCase):
|
||||
pass
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,426 @@
|
||||
import unittest
|
||||
|
||||
import pygame.constants
|
||||
|
||||
# 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",
|
||||
"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 = (
|
||||
("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 frozensets:
|
||||
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",
|
||||
"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), f"missing constant {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 = {
|
||||
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)
|
||||
|
||||
|
||||
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), f"missing constant {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 = {
|
||||
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",
|
||||
"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), f"missing constant {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 = {
|
||||
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"),
|
||||
"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,271 @@
|
||||
import unittest
|
||||
|
||||
import pygame
|
||||
import pygame._sdl2.controller as controller
|
||||
from pygame.tests.test_utils import prompt, question
|
||||
|
||||
|
||||
class ControllerModuleTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
controller.init()
|
||||
|
||||
def tearDown(self):
|
||||
controller.quit()
|
||||
|
||||
def test_init(self):
|
||||
controller.quit()
|
||||
controller.init()
|
||||
self.assertTrue(controller.get_init())
|
||||
|
||||
def test_init__multiple(self):
|
||||
controller.init()
|
||||
controller.init()
|
||||
self.assertTrue(controller.get_init())
|
||||
|
||||
def test_quit(self):
|
||||
controller.quit()
|
||||
self.assertFalse(controller.get_init())
|
||||
|
||||
def test_quit__multiple(self):
|
||||
controller.quit()
|
||||
controller.quit()
|
||||
self.assertFalse(controller.get_init())
|
||||
|
||||
def test_get_init(self):
|
||||
self.assertTrue(controller.get_init())
|
||||
|
||||
def test_get_count(self):
|
||||
self.assertGreaterEqual(controller.get_count(), 0)
|
||||
|
||||
def test_is_controller(self):
|
||||
for i in range(controller.get_count()):
|
||||
if controller.is_controller(i):
|
||||
c = controller.Controller(i)
|
||||
self.assertIsInstance(c, controller.Controller)
|
||||
c.quit()
|
||||
else:
|
||||
with self.assertRaises(pygame.error):
|
||||
c = controller.Controller(i)
|
||||
|
||||
with self.assertRaises(TypeError):
|
||||
controller.is_controller("Test")
|
||||
|
||||
|
||||
class ControllerTypeTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
controller.init()
|
||||
|
||||
def tearDown(self):
|
||||
controller.quit()
|
||||
|
||||
def _get_first_controller(self):
|
||||
for i in range(controller.get_count()):
|
||||
if controller.is_controller(i):
|
||||
return controller.Controller(i)
|
||||
|
||||
def test_construction(self):
|
||||
if c := self._get_first_controller():
|
||||
self.assertIsInstance(c, controller.Controller)
|
||||
else:
|
||||
self.skipTest("No controller connected")
|
||||
|
||||
def test__auto_init(self):
|
||||
if c := self._get_first_controller():
|
||||
self.assertTrue(c.get_init())
|
||||
else:
|
||||
self.skipTest("No controller connected")
|
||||
|
||||
def test_get_init(self):
|
||||
if c := self._get_first_controller():
|
||||
self.assertTrue(c.get_init())
|
||||
c.quit()
|
||||
self.assertFalse(c.get_init())
|
||||
else:
|
||||
self.skipTest("No controller connected")
|
||||
|
||||
def test_from_joystick(self):
|
||||
for i in range(controller.get_count()):
|
||||
if controller.is_controller(i):
|
||||
joy = pygame.joystick.Joystick(i)
|
||||
break
|
||||
else:
|
||||
self.skipTest("No controller connected")
|
||||
|
||||
c = controller.Controller.from_joystick(joy)
|
||||
self.assertIsInstance(c, controller.Controller)
|
||||
|
||||
def test_as_joystick(self):
|
||||
if c := self._get_first_controller():
|
||||
joy = c.as_joystick()
|
||||
self.assertIsInstance(joy, type(pygame.joystick.Joystick(0)))
|
||||
else:
|
||||
self.skipTest("No controller connected")
|
||||
|
||||
def test_get_mapping(self):
|
||||
if c := self._get_first_controller():
|
||||
mapping = c.get_mapping()
|
||||
self.assertIsInstance(mapping, dict)
|
||||
self.assertIsNotNone(mapping["a"])
|
||||
else:
|
||||
self.skipTest("No controller connected")
|
||||
|
||||
def test_set_mapping(self):
|
||||
if c := self._get_first_controller():
|
||||
mapping = c.get_mapping()
|
||||
mapping["a"] = "b3"
|
||||
mapping["y"] = "b0"
|
||||
c.set_mapping(mapping)
|
||||
new_mapping = c.get_mapping()
|
||||
|
||||
self.assertEqual(len(mapping), len(new_mapping))
|
||||
for i in mapping:
|
||||
if mapping[i] not in ("a", "y"):
|
||||
self.assertEqual(mapping[i], new_mapping[i])
|
||||
else:
|
||||
if i == "a":
|
||||
self.assertEqual(new_mapping[i], mapping["y"])
|
||||
else:
|
||||
self.assertEqual(new_mapping[i], mapping["a"])
|
||||
else:
|
||||
self.skipTest("No controller connected")
|
||||
|
||||
|
||||
class ControllerInteractiveTest(unittest.TestCase):
|
||||
__tags__ = ["interactive"]
|
||||
|
||||
def _get_first_controller(self):
|
||||
for i in range(controller.get_count()):
|
||||
if controller.is_controller(i):
|
||||
return controller.Controller(i)
|
||||
|
||||
def setUp(self):
|
||||
controller.init()
|
||||
|
||||
def tearDown(self):
|
||||
controller.quit()
|
||||
|
||||
def test__get_count_interactive(self):
|
||||
prompt(
|
||||
"Please connect at least one controller "
|
||||
"before the test for controller.get_count() starts"
|
||||
)
|
||||
|
||||
# Reset the number of joysticks counted
|
||||
controller.quit()
|
||||
controller.init()
|
||||
|
||||
joystick_num = controller.get_count()
|
||||
ans = question(
|
||||
"get_count() thinks there are {} joysticks "
|
||||
"connected. Is that correct?".format(joystick_num)
|
||||
)
|
||||
|
||||
self.assertTrue(ans)
|
||||
|
||||
def test_get_button_interactive(self):
|
||||
c = self._get_first_controller()
|
||||
if not c:
|
||||
self.skipTest("No controller connected")
|
||||
|
||||
pygame.display.init()
|
||||
pygame.font.init()
|
||||
|
||||
screen = pygame.display.set_mode((400, 400))
|
||||
font = pygame.font.Font(None, 20)
|
||||
running = True
|
||||
|
||||
label1 = font.render(
|
||||
"Press button 'x' (on ps4) or 'a' (on xbox).", True, (0, 0, 0)
|
||||
)
|
||||
|
||||
label2 = font.render(
|
||||
'The two values should match up. Press "y" or "n" to confirm.',
|
||||
True,
|
||||
(0, 0, 0),
|
||||
)
|
||||
|
||||
is_pressed = [False, False] # event, get_button()
|
||||
while running:
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
running = False
|
||||
if event.type == pygame.CONTROLLERBUTTONDOWN and event.button == 0:
|
||||
is_pressed[0] = True
|
||||
if event.type == pygame.CONTROLLERBUTTONUP and event.button == 0:
|
||||
is_pressed[0] = False
|
||||
|
||||
if event.type == pygame.KEYDOWN:
|
||||
if event.key == pygame.K_y:
|
||||
running = False
|
||||
if event.key == pygame.K_n:
|
||||
running = False
|
||||
pygame.display.quit()
|
||||
pygame.font.quit()
|
||||
self.fail()
|
||||
|
||||
is_pressed[1] = c.get_button(pygame.CONTROLLER_BUTTON_A)
|
||||
|
||||
screen.fill((255, 255, 255))
|
||||
screen.blit(label1, (0, 0))
|
||||
screen.blit(label2, (0, 20))
|
||||
screen.blit(font.render(str(is_pressed), True, (0, 0, 0)), (0, 40))
|
||||
pygame.display.update()
|
||||
|
||||
pygame.display.quit()
|
||||
pygame.font.quit()
|
||||
|
||||
def test_get_axis_interactive(self):
|
||||
c = self._get_first_controller()
|
||||
if not c:
|
||||
self.skipTest("No controller connected")
|
||||
|
||||
pygame.display.init()
|
||||
pygame.font.init()
|
||||
|
||||
screen = pygame.display.set_mode((400, 400))
|
||||
font = pygame.font.Font(None, 20)
|
||||
running = True
|
||||
|
||||
label1 = font.render(
|
||||
"Press down the right trigger. The value on-screen should", True, (0, 0, 0)
|
||||
)
|
||||
|
||||
label2 = font.render(
|
||||
"indicate how far the trigger is pressed down. This value should",
|
||||
True,
|
||||
(0, 0, 0),
|
||||
)
|
||||
|
||||
label3 = font.render(
|
||||
'be in the range of 0-32767. Press "y" or "n" to confirm.', True, (0, 0, 0)
|
||||
)
|
||||
|
||||
while running:
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
running = False
|
||||
|
||||
if event.type == pygame.KEYDOWN:
|
||||
if event.key == pygame.K_y:
|
||||
running = False
|
||||
if event.key == pygame.K_n:
|
||||
running = False
|
||||
pygame.display.quit()
|
||||
pygame.font.quit()
|
||||
self.fail()
|
||||
|
||||
right_trigger = c.get_axis(pygame.CONTROLLER_AXIS_TRIGGERRIGHT)
|
||||
|
||||
screen.fill((255, 255, 255))
|
||||
screen.blit(label1, (0, 0))
|
||||
screen.blit(label2, (0, 20))
|
||||
screen.blit(label3, (0, 40))
|
||||
screen.blit(font.render(str(right_trigger), True, (0, 0, 0)), (0, 60))
|
||||
pygame.display.update()
|
||||
|
||||
pygame.display.quit()
|
||||
pygame.font.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,17 @@
|
||||
import unittest
|
||||
|
||||
base_ctest = None
|
||||
try:
|
||||
import pygame.base_ctest as base_ctest
|
||||
except ModuleNotFoundError:
|
||||
pass
|
||||
|
||||
|
||||
class Ctest(unittest.TestCase):
|
||||
@unittest.skipIf(base_ctest is None, "base_ctest not built")
|
||||
def test_run_base_ctests(self):
|
||||
self.assertEqual(base_ctest.run_tests(), 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,294 @@
|
||||
import unittest
|
||||
|
||||
import pygame
|
||||
from pygame.tests.test_utils import fixture_path
|
||||
|
||||
|
||||
class CursorsModuleTest(unittest.TestCase):
|
||||
def 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().
|
||||
|
||||
# Various types of input strings
|
||||
test_cursor1 = ("X.X.XXXX", "XXXXXX..", " XXXX ")
|
||||
|
||||
test_cursor2 = (
|
||||
"X.X.XXXX",
|
||||
"XXXXXX..",
|
||||
"XXXXXX ",
|
||||
"XXXXXX..",
|
||||
"XXXXXX..",
|
||||
"XXXXXX",
|
||||
"XXXXXX..",
|
||||
"XXXXXX..",
|
||||
)
|
||||
test_cursor3 = (".XX.", " ", ".. ", "X.. X")
|
||||
|
||||
# Test such that total number of strings is not divisible by 8
|
||||
with self.assertRaises(ValueError):
|
||||
pygame.cursors.compile(test_cursor1)
|
||||
|
||||
# Test such that size of individual string is not divisible by 8
|
||||
with self.assertRaises(ValueError):
|
||||
pygame.cursors.compile(test_cursor2)
|
||||
|
||||
# Test such that neither size of individual string nor total number of strings is divisible by 8
|
||||
with self.assertRaises(ValueError):
|
||||
pygame.cursors.compile(test_cursor3)
|
||||
|
||||
# Test that checks whether the byte data from compile function is equal to actual byte data
|
||||
actual_byte_data = (
|
||||
(
|
||||
192,
|
||||
0,
|
||||
0,
|
||||
224,
|
||||
0,
|
||||
0,
|
||||
240,
|
||||
0,
|
||||
0,
|
||||
216,
|
||||
0,
|
||||
0,
|
||||
204,
|
||||
0,
|
||||
0,
|
||||
198,
|
||||
0,
|
||||
0,
|
||||
195,
|
||||
0,
|
||||
0,
|
||||
193,
|
||||
128,
|
||||
0,
|
||||
192,
|
||||
192,
|
||||
0,
|
||||
192,
|
||||
96,
|
||||
0,
|
||||
192,
|
||||
48,
|
||||
0,
|
||||
192,
|
||||
56,
|
||||
0,
|
||||
192,
|
||||
248,
|
||||
0,
|
||||
220,
|
||||
192,
|
||||
0,
|
||||
246,
|
||||
96,
|
||||
0,
|
||||
198,
|
||||
96,
|
||||
0,
|
||||
6,
|
||||
96,
|
||||
0,
|
||||
3,
|
||||
48,
|
||||
0,
|
||||
3,
|
||||
48,
|
||||
0,
|
||||
1,
|
||||
224,
|
||||
0,
|
||||
1,
|
||||
128,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
),
|
||||
(
|
||||
192,
|
||||
0,
|
||||
0,
|
||||
224,
|
||||
0,
|
||||
0,
|
||||
240,
|
||||
0,
|
||||
0,
|
||||
248,
|
||||
0,
|
||||
0,
|
||||
252,
|
||||
0,
|
||||
0,
|
||||
254,
|
||||
0,
|
||||
0,
|
||||
255,
|
||||
0,
|
||||
0,
|
||||
255,
|
||||
128,
|
||||
0,
|
||||
255,
|
||||
192,
|
||||
0,
|
||||
255,
|
||||
224,
|
||||
0,
|
||||
255,
|
||||
240,
|
||||
0,
|
||||
255,
|
||||
248,
|
||||
0,
|
||||
255,
|
||||
248,
|
||||
0,
|
||||
255,
|
||||
192,
|
||||
0,
|
||||
247,
|
||||
224,
|
||||
0,
|
||||
199,
|
||||
224,
|
||||
0,
|
||||
7,
|
||||
224,
|
||||
0,
|
||||
3,
|
||||
240,
|
||||
0,
|
||||
3,
|
||||
240,
|
||||
0,
|
||||
1,
|
||||
224,
|
||||
0,
|
||||
1,
|
||||
128,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
),
|
||||
)
|
||||
|
||||
cursor = pygame.cursors.compile(pygame.cursors.thickarrow_strings)
|
||||
self.assertEqual(cursor, actual_byte_data)
|
||||
|
||||
# Test such that cursor byte data obtained from compile function is valid in pygame.mouse.set_cursor()
|
||||
pygame.display.init()
|
||||
try:
|
||||
pygame.mouse.set_cursor((24, 24), (0, 0), *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()
|
||||
|
||||
################################################################################
|
||||
|
||||
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)
|
||||
|
||||
# Can it load using pathlib.Path?
|
||||
import pathlib
|
||||
|
||||
cursor = pygame.cursors.load_xbm(
|
||||
pathlib.Path(cursorfile), pathlib.Path(maskfile)
|
||||
)
|
||||
|
||||
# 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()
|
||||
|
||||
def test_Cursor(self):
|
||||
"""Ensure that the cursor object parses information properly"""
|
||||
|
||||
c1 = pygame.cursors.Cursor(pygame.SYSTEM_CURSOR_CROSSHAIR)
|
||||
|
||||
self.assertEqual(c1.data, (pygame.SYSTEM_CURSOR_CROSSHAIR,))
|
||||
self.assertEqual(c1.type, "system")
|
||||
|
||||
c2 = pygame.cursors.Cursor(c1)
|
||||
|
||||
self.assertEqual(c1, c2)
|
||||
|
||||
with self.assertRaises(TypeError):
|
||||
pygame.cursors.Cursor(-34002)
|
||||
with self.assertRaises(TypeError):
|
||||
pygame.cursors.Cursor("a", "b", "c", "d")
|
||||
with self.assertRaises(TypeError):
|
||||
pygame.cursors.Cursor((2,))
|
||||
|
||||
c3 = pygame.cursors.Cursor((0, 0), pygame.Surface((20, 20)))
|
||||
|
||||
self.assertEqual(c3.data[0], (0, 0))
|
||||
self.assertEqual(c3.data[1].get_size(), (20, 20))
|
||||
self.assertEqual(c3.type, "color")
|
||||
|
||||
xormask, andmask = pygame.cursors.compile(pygame.cursors.thickarrow_strings)
|
||||
c4 = pygame.cursors.Cursor((24, 24), (0, 0), xormask, andmask)
|
||||
|
||||
self.assertEqual(c4.data, ((24, 24), (0, 0), xormask, andmask))
|
||||
self.assertEqual(c4.type, "bitmap")
|
||||
|
||||
|
||||
################################################################################
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
################################################################################
|
||||
@@ -0,0 +1,24 @@
|
||||
import io
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
import pygame
|
||||
|
||||
|
||||
class DebugTest(unittest.TestCase):
|
||||
@unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
|
||||
def assert_stdout(self, expected_output, mock_stdout):
|
||||
pygame.print_debug_info()
|
||||
self.assertEqual(mock_stdout.getvalue(), expected_output)
|
||||
|
||||
def test_print_debug(self):
|
||||
import os
|
||||
|
||||
pygame.print_debug_info("temp_file.txt")
|
||||
with open("temp_file.txt", "r") as temp_file:
|
||||
text = temp_file.read()
|
||||
|
||||
self.assertNotEqual(text, "")
|
||||
self.assert_stdout(text + "\n")
|
||||
|
||||
os.remove("temp_file.txt")
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,35 @@
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
|
||||
class DocsIncludedTest(unittest.TestCase):
|
||||
def test_doc_import_works(self):
|
||||
from pygame.docs import PKG_DIR, has_local_docs
|
||||
|
||||
@unittest.skipIf("CI" not in os.environ, "Docs not required for local builds")
|
||||
def test_docs_included(self):
|
||||
from pygame.docs import has_local_docs
|
||||
|
||||
self.assertTrue(has_local_docs())
|
||||
|
||||
@unittest.skipIf("CI" not in os.environ, "Docs not required for local builds")
|
||||
def test_docs_command(self):
|
||||
try:
|
||||
subprocess.run(
|
||||
[sys.executable, "-m", "pygame.docs"],
|
||||
timeout=5,
|
||||
# check ensures an exception is raised when the process fails
|
||||
check=True,
|
||||
# pipe stdout/stderr so that they don't clutter main stdout
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
# timeout errors are not an issue
|
||||
pass
|
||||
|
||||
|
||||
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
BIN
Binary file not shown.
|
After Width: | Height: | Size: 92 B |
BIN
Binary file not shown.
+165
@@ -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
|
||||
+143
@@ -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
|
||||
+103
@@ -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
|
||||
BIN
Binary file not shown.
+238
@@ -0,0 +1,238 @@
|
||||
SplineFontDB: 3.0
|
||||
FontName: PyGameMono
|
||||
FullName: PyGame Mono
|
||||
FamilyName: PyGameMono
|
||||
Weight: Medium
|
||||
Copyright: Created by Lenard Lindstrom,,, with FontForge 2.0 (http://fontforge.sf.net)
|
||||
UComments: "2013-10-11: Created.+AAoACgAA-pygame - Python Game Library+AAoA-Test font PyGameMono, Copyright (C) 2013 Lenard Lindstrom+AAoACgAA-This library is free software; you can redistribute it and/or+AAoA-modify it under the terms of the GNU Library General Public+AAoA-License as published by the Free Software Foundation; either+AAoA-version 2 of the License, or (at your option) any later version.+AAoACgAA-This library is distributed in the hope that it will be useful,+AAoA-but WITHOUT ANY WARRANTY; without even the implied warranty of+AAoA-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU+AAoA-Library General Public License for more details.+AAoACgAA-You should have received a copy of the GNU Library General Public+AAoA-License along with this library; if not, write to the Free+AAoA-Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA+AAoACgAA"
|
||||
Version: 001.000
|
||||
ItalicAngle: 0
|
||||
UnderlinePosition: -100
|
||||
UnderlineWidth: 50
|
||||
Ascent: 800
|
||||
Descent: 200
|
||||
LayerCount: 2
|
||||
Layer: 0 0 "Back" 1
|
||||
Layer: 1 0 "Fore" 0
|
||||
XUID: [1021 912 78401767 10725709]
|
||||
FSType: 8
|
||||
OS2Version: 0
|
||||
OS2_WeightWidthSlopeOnly: 0
|
||||
OS2_UseTypoMetrics: 1
|
||||
CreationTime: 1381544181
|
||||
ModificationTime: 1381781368
|
||||
PfmFamily: 49
|
||||
TTFWeight: 500
|
||||
TTFWidth: 5
|
||||
LineGap: 90
|
||||
VLineGap: 0
|
||||
OS2TypoAscent: 0
|
||||
OS2TypoAOffset: 1
|
||||
OS2TypoDescent: 0
|
||||
OS2TypoDOffset: 1
|
||||
OS2TypoLinegap: 90
|
||||
OS2WinAscent: 0
|
||||
OS2WinAOffset: 1
|
||||
OS2WinDescent: 0
|
||||
OS2WinDOffset: 1
|
||||
HheadAscent: 0
|
||||
HheadAOffset: 1
|
||||
HheadDescent: 0
|
||||
HheadDOffset: 1
|
||||
OS2FamilyClass: 2319
|
||||
OS2Vendor: 'PfEd'
|
||||
MarkAttachClasses: 1
|
||||
DEI: 91125
|
||||
LangName: 1033
|
||||
Encoding: UnicodeFull
|
||||
UnicodeInterp: none
|
||||
NameList: Adobe Glyph List
|
||||
DisplaySize: -24
|
||||
AntiAlias: 1
|
||||
FitToEm: 1
|
||||
WinInfo: 77904 24 18
|
||||
BeginPrivate: 0
|
||||
EndPrivate
|
||||
TeXData: 1 0 0 346030 173015 115343 0 1048576 115343 783286 444596 497025 792723 393216 433062 380633 303038 157286 324010 404750 52429 2506097 1059062 262144
|
||||
BeginChars: 1114112 5
|
||||
|
||||
StartChar: A
|
||||
Encoding: 65 65 0
|
||||
Width: 1000
|
||||
VWidth: 0
|
||||
HStem: 0 21G<72.5 119.695 682.5 726.5> 384 111<312.148 495.257> 777 123<264.353 535.647>
|
||||
VStem: 0 139<585.021 689.951> 661 139<585.002 688.082>
|
||||
LayerCount: 2
|
||||
Fore
|
||||
SplineSet
|
||||
139 636 m 0
|
||||
139 558.168 255.928 495 400 495 c 0
|
||||
544.072 495 661 558.168 661 636 c 0
|
||||
661 713.832 544.072 777 400 777 c 0
|
||||
255.928 777 139 713.832 139 636 c 0
|
||||
100 0 m 1
|
||||
45 234 0 361.682 0 600 c 0
|
||||
0 834 205 900 400 900 c 24
|
||||
595 900 800 822 800 600 c 0
|
||||
800 360.834 753 234 700 0 c 1
|
||||
665 180 590.045 384 400 384 c 24
|
||||
209.955 384 139.39 149.76 100 0 c 1
|
||||
EndSplineSet
|
||||
Validated: 1
|
||||
EndChar
|
||||
|
||||
StartChar: B
|
||||
Encoding: 66 66 1
|
||||
Width: 1000
|
||||
VWidth: 0
|
||||
HStem: 0 91<307.884 570.044> 355 97<317.65 572.008> 724 76.4445<315.347 574.736>
|
||||
VStem: 120 80<174.135 277.365 535.109 572> 694 106<173.306 274.441 532.71 643.215>
|
||||
LayerCount: 2
|
||||
Fore
|
||||
SplineSet
|
||||
200 223 m 0
|
||||
200 150 303 91 437 91 c 0
|
||||
571 91 694 150 694 223 c 0
|
||||
694 296 571 355 437 355 c 0
|
||||
303 355 200 296 200 223 c 0
|
||||
202 588 m 0
|
||||
202 513 312 452 448 452 c 0
|
||||
584 452 694 513 694 588 c 0
|
||||
694 663 584 724 448 724 c 0
|
||||
312 724 202 663 202 588 c 0
|
||||
800 200 m 0
|
||||
800 92 749 1 552 0 c 0
|
||||
430 -0 253 -0 0 0 c 1
|
||||
85 41 120 216 120 400 c 0
|
||||
120 572 73 756 0 800 c 1
|
||||
150 800 273.778 800.444 372.519 800.444 c 0
|
||||
421.889 800.444 465 800.333 502 800 c 0
|
||||
785 799 800 665 800 600 c 0
|
||||
800 540 781 510 760 490 c 0
|
||||
730 461 694 453 694 400 c 0
|
||||
694 358 723 339 760 310 c 0
|
||||
781 294 800 259 800 200 c 0
|
||||
EndSplineSet
|
||||
Validated: 1
|
||||
EndChar
|
||||
|
||||
StartChar: .notdef
|
||||
Encoding: 0 0 2
|
||||
Width: 1000
|
||||
VWidth: 0
|
||||
HStem: 0 88<283.168 514.832> 712 88<283.168 514.832>
|
||||
VStem: 0 83<285.634 514.366> 715 85<285.634 514.366>
|
||||
LayerCount: 2
|
||||
Fore
|
||||
SplineSet
|
||||
83 400 m 0
|
||||
83 227.776 224.568 88 399 88 c 0
|
||||
573.432 88 715 227.776 715 400 c 0
|
||||
715 572.224 573.432 712 399 712 c 0
|
||||
224.568 712 83 572.224 83 400 c 0
|
||||
0 800 m 1
|
||||
800 800 l 1
|
||||
800 0 l 1
|
||||
0 0 l 1
|
||||
0 800 l 1
|
||||
EndSplineSet
|
||||
Validated: 1
|
||||
Comment: "Default character"
|
||||
EndChar
|
||||
|
||||
StartChar: C
|
||||
Encoding: 67 67 3
|
||||
Width: 1000
|
||||
VWidth: 0
|
||||
HStem: 0 110<323.65 572.264> 690 110<326.99 550.385>
|
||||
VStem: 0 147<291.893 504.85>
|
||||
LayerCount: 2
|
||||
Fore
|
||||
SplineSet
|
||||
425 110 m 0
|
||||
564 110 687 167 788 230 c 1
|
||||
796 230 796 230 800 230 c 1
|
||||
800 222 800 224 800 216 c 1
|
||||
753 98 621 -0 450 0 c 0
|
||||
227 0 0 165 0 400 c 24
|
||||
0 635 235 800 450 800 c 1
|
||||
580 800 745 668 800 584 c 1
|
||||
800 575 799 576 800 570 c 1
|
||||
796 570 796 570 791 570 c 1
|
||||
684 628 535 690 425 690 c 0
|
||||
277 690 147 557 147 400 c 0
|
||||
147 243 268 110 425 110 c 0
|
||||
EndSplineSet
|
||||
Validated: 1
|
||||
EndChar
|
||||
|
||||
StartChar: u13079
|
||||
Encoding: 77945 77945 4
|
||||
Width: 1000
|
||||
VWidth: 0
|
||||
HStem: 200 66<262.666 534.533> 302 196<339.508 460.492> 534 66<262.278 535.629>
|
||||
VStem: 302 196<339.508 460.492>
|
||||
CounterMasks: 1 e0
|
||||
LayerCount: 2
|
||||
Fore
|
||||
SplineSet
|
||||
302 400 m 0
|
||||
302 454.096 345.904 498 400 498 c 0
|
||||
454.096 498 498 454.096 498 400 c 0
|
||||
498 345.904 454.096 302 400 302 c 0
|
||||
345.904 302 302 345.904 302 400 c 0
|
||||
146 400 m 0
|
||||
146 326.032 259.792 266 400 266 c 0
|
||||
540.208 266 654 326.032 654 400 c 0
|
||||
654 473.968 540.208 534 400 534 c 0
|
||||
259.792 534 146 473.968 146 400 c 0
|
||||
0 400 m 1
|
||||
124 550 225.587 600 400 600 c 24
|
||||
574.413 600 690 532 800 400 c 1
|
||||
720 254 574.413 200 400 200 c 24
|
||||
225.587 200 90 234 0 400 c 1
|
||||
EndSplineSet
|
||||
Validated: 1
|
||||
EndChar
|
||||
EndChars
|
||||
BitmapFont: 8 6 6 2 1
|
||||
BDFChar: 0 65 8 0 5 0 6
|
||||
G_CbJKS5!Y
|
||||
BDFChar: 1 66 8 0 5 0 5
|
||||
r'Yd'7/R#b
|
||||
BDFChar: 2 0 8 0 5 0 5
|
||||
r.K`VK_tfM
|
||||
BDFChar: 3 67 8 0 5 0 5
|
||||
Gf7D5`-;7^
|
||||
BDFChar: 4 77945 8 0 5 1 4
|
||||
GdOi&
|
||||
EndBitmapFont
|
||||
BitmapFont: 19 6 15 4 1
|
||||
BDFChar: 0 65 19 0 14 0 16
|
||||
&)]\IGWbI:i""ZTn/h?gs8N&tr-iT)E#`6o?jo:'5Qh&e
|
||||
BDFChar: 1 66 19 0 14 0 14
|
||||
s7h*AGRcD30EsKH5PRJ<5PR2J0Es38Hlde8s7cQo
|
||||
BDFChar: 2 0 19 0 14 0 14
|
||||
s8N&tr-n,Vi"!O,^]qRY^]qRYi"#5tr-n\Fs8Duu
|
||||
BDFChar: 3 67 19 0 14 0 14
|
||||
"5j^b4</SMDueerhuM[8huM[8Dub+e4<+n,"5j.Z
|
||||
BDFChar: 4 77945 19 0 14 4 10
|
||||
&)]E,@uTH.@uNB,&)[Ef
|
||||
EndBitmapFont
|
||||
BitmapFont: 25 5 20 5 1
|
||||
BDFChar: 0 65 25 0 19 1 21
|
||||
"8i-@s+!?6^jH7Bn,Vt9!-$irE:<ksqucHgs7$'gnGiOXrt"UH"7UO9i-57[Dueg8!+917?m#G7
|
||||
+94Y,
|
||||
BDFChar: 1 66 25 1 18 0 19
|
||||
s8E#us+#P'J9V+1Dud[-!5L8g^c2A14pQU&rr>:`!'UX<3!"O`!5L8g^b>c(GQGU/#JgB>JH,TK
|
||||
|
||||
BDFChar: 2 0 25 0 19 0 19
|
||||
s8VTgs7$!mnG!%Rn,Vt9!-$irE52H-^]6((!&21g0YdZB^]6(H!-$irE:<ksp]9m`#OqcnnGiOX
|
||||
|
||||
BDFChar: 3 67 25 0 19 0 19
|
||||
!;lg!rr<T0J0+mO4ofPL!"aAT!;HNon,NIX!!)Kg!:Tsgp](;=!!%BH&3^)5*s(:1s1ea:J,oQK
|
||||
|
||||
BDFChar: 4 77945 25 0 20 5 14
|
||||
"8i-0s*u/3^j,YDnG%6Ipi&33i#W!9&-%.^qu?]s
|
||||
EndBitmapFont
|
||||
EndSplineFont
|
||||
BIN
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
|
After Width: | Height: | Size: 89 B |
+8
@@ -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};
|
||||
+8
@@ -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};
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,18 @@
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import pygame.ftfont
|
||||
|
||||
from . import font_test
|
||||
|
||||
font_test.pygame_font = pygame.ftfont
|
||||
|
||||
for name in dir(font_test):
|
||||
obj = getattr(font_test, name)
|
||||
if isinstance(obj, type) and issubclass(obj, unittest.TestCase): # conditional and
|
||||
new_name = f"Ft{name}"
|
||||
globals()[new_name] = type(new_name, (obj,), {})
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,917 @@
|
||||
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)
|
||||
|
||||
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 pygame-ce issue #506.
|
||||
"""
|
||||
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)),
|
||||
f"pos=({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)
|
||||
|
||||
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 pygame-ce issue #506.
|
||||
"""
|
||||
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)),
|
||||
f"pos=({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)
|
||||
|
||||
def test_no_pal_8bit_surf(self):
|
||||
"""
|
||||
Test that gfxdraw methods do not segfault when passed with no palette
|
||||
8 bit surface.
|
||||
"""
|
||||
s = pygame.Surface(
|
||||
size=(512, 512), flags=0, depth=8, masks=(0xE0, 0x1C, 0x03, 0x00)
|
||||
)
|
||||
|
||||
fg = (255, 255, 255)
|
||||
points = [(10, 10), (100, 50), (50, 100)]
|
||||
for name, args in (
|
||||
("pixel", (s, 2, 2, fg)),
|
||||
("hline", (s, 5, 50, 10, fg)),
|
||||
("vline", (s, 10, 5, 50, fg)),
|
||||
("line", (s, 0, 0, 100, 100, fg)),
|
||||
("rectangle", (s, pygame.Rect(50, 50, 80, 40), fg)),
|
||||
("box", (s, pygame.Rect(60, 60, 80, 40), fg)),
|
||||
("circle", (s, 256, 256, 64, fg)),
|
||||
("aacircle", (s, 256, 256, 64, fg)),
|
||||
("filled_circle", (s, 256, 256, 32, fg)),
|
||||
("ellipse", (s, 200, 200, 50, 30, fg)),
|
||||
("aaellipse", (s, 200, 200, 50, 30, fg)),
|
||||
("filled_ellipse", (s, 200, 200, 50, 30, fg)),
|
||||
("arc", (s, 256, 256, 60, 0, 180, fg)),
|
||||
("pie", (s, 300, 300, 60, 0, 270, fg)),
|
||||
("trigon", (s, 100, 100, 150, 200, 50, 200, fg)),
|
||||
("aatrigon", (s, 100, 100, 150, 200, 50, 200, fg)),
|
||||
("filled_trigon", (s, 100, 100, 150, 200, 50, 200, fg)),
|
||||
("polygon", (s, points, fg)),
|
||||
("aapolygon", (s, points, fg)),
|
||||
("filled_polygon", (s, points, fg)),
|
||||
("textured_polygon", (s, points, s, 0, 0)), # use same surface as texture
|
||||
):
|
||||
try:
|
||||
func = getattr(pygame.gfxdraw, name)
|
||||
func(*args)
|
||||
except Exception as e:
|
||||
self.fail(f"gfxdraw.{name} raised an exception: {e}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,46 @@
|
||||
import os
|
||||
import unittest
|
||||
|
||||
import pygame
|
||||
from pygame.locals import *
|
||||
from pygame.tests import test_utils
|
||||
|
||||
|
||||
@unittest.skipIf(
|
||||
os.environ.get("SDL_VIDEODRIVER") == pygame.NULL_VIDEODRIVER,
|
||||
"OpenGL requires a non-null 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()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,80 @@
|
||||
import os
|
||||
import os.path
|
||||
import sys
|
||||
import unittest
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
import pygame
|
||||
import pygame.image
|
||||
import pygame.pkgdata
|
||||
from pygame.tests.test_utils import example_path
|
||||
|
||||
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 = "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 = "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)
|
||||
|
||||
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)
|
||||
|
||||
def test_load_unicode_path_0(self):
|
||||
u = example_path("data/alien1.png")
|
||||
im = imageext.load_extended(u)
|
||||
|
||||
def test_load_unicode_path_1(self):
|
||||
"""non-ASCII unicode"""
|
||||
import shutil
|
||||
|
||||
with TemporaryDirectory() as tmpdir:
|
||||
orig = example_path("data/alien1.png")
|
||||
temp = os.path.join(tmpdir, "你好.png")
|
||||
shutil.copy(orig, temp)
|
||||
imageext.load_extended(temp)
|
||||
|
||||
def _unicode_save(self, temp_file):
|
||||
im = pygame.Surface((10, 10), 0, 32)
|
||||
self.assertFalse(os.path.exists(temp_file))
|
||||
imageext.save_extended(im, temp_file)
|
||||
self.assertGreater(os.path.getsize(temp_file), 10)
|
||||
|
||||
def test_save_unicode_path_0(self):
|
||||
"""unicode object with ASCII chars"""
|
||||
with TemporaryDirectory() as tmpdir:
|
||||
self._unicode_save(os.path.join(tmpdir, "temp_file.png"))
|
||||
|
||||
def test_save_unicode_path_1(self):
|
||||
with TemporaryDirectory() as tmpdir:
|
||||
self._unicode_save(os.path.join(tmpdir, "你好.png"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,170 @@
|
||||
import unittest
|
||||
|
||||
import pygame
|
||||
import pygame._sdl2.controller
|
||||
from pygame.tests.test_utils import prompt, question
|
||||
|
||||
|
||||
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()
|
||||
|
||||
def test_Joystick_alias(self):
|
||||
"""Check if pygame.Joystick is present and the correct type."""
|
||||
self.assertIs(pygame.Joystick, pygame.joystick.Joystick)
|
||||
|
||||
|
||||
class JoystickModuleTest(unittest.TestCase):
|
||||
def test_get_init(self):
|
||||
# Check that get_init() matches what is actually happening
|
||||
def error_check_get_init():
|
||||
try:
|
||||
pygame.joystick.get_count()
|
||||
except pygame.error:
|
||||
return False
|
||||
return True
|
||||
|
||||
# Start uninitialised
|
||||
self.assertEqual(pygame.joystick.get_init(), False)
|
||||
|
||||
pygame.joystick.init()
|
||||
self.assertEqual(pygame.joystick.get_init(), error_check_get_init()) # True
|
||||
pygame.joystick.quit()
|
||||
self.assertEqual(pygame.joystick.get_init(), error_check_get_init()) # False
|
||||
|
||||
pygame.joystick.init()
|
||||
pygame.joystick.init()
|
||||
self.assertEqual(pygame.joystick.get_init(), error_check_get_init()) # True
|
||||
pygame.joystick.quit()
|
||||
self.assertEqual(pygame.joystick.get_init(), error_check_get_init()) # False
|
||||
|
||||
pygame.joystick.quit()
|
||||
self.assertEqual(pygame.joystick.get_init(), error_check_get_init()) # False
|
||||
|
||||
for i in range(100):
|
||||
pygame.joystick.init()
|
||||
self.assertEqual(pygame.joystick.get_init(), error_check_get_init()) # True
|
||||
pygame.joystick.quit()
|
||||
self.assertEqual(pygame.joystick.get_init(), error_check_get_init()) # False
|
||||
|
||||
for i in range(100):
|
||||
pygame.joystick.quit()
|
||||
self.assertEqual(pygame.joystick.get_init(), error_check_get_init()) # False
|
||||
|
||||
def test_init(self):
|
||||
"""
|
||||
This unit test is for joystick.init()
|
||||
It was written to help reduce maintenance costs
|
||||
and to help test against changes to the code or
|
||||
different platforms.
|
||||
"""
|
||||
pygame.quit()
|
||||
# test that pygame.init automatically calls joystick.init
|
||||
pygame.init()
|
||||
self.assertEqual(pygame.joystick.get_init(), True)
|
||||
|
||||
# Controller module interferes with the joystick module.
|
||||
pygame._sdl2.controller.quit()
|
||||
|
||||
# test that get_count doesn't work w/o joystick init
|
||||
# this is done before and after an init to test
|
||||
# that init activates the joystick functions
|
||||
pygame.joystick.quit()
|
||||
with self.assertRaises(pygame.error):
|
||||
pygame.joystick.get_count()
|
||||
|
||||
# test explicit call(s) to joystick.init.
|
||||
# Also test that get_count works once init is called
|
||||
iterations = 20
|
||||
for i in range(iterations):
|
||||
pygame.joystick.init()
|
||||
self.assertEqual(pygame.joystick.get_init(), True)
|
||||
self.assertIsNotNone(pygame.joystick.get_count())
|
||||
|
||||
def test_quit(self):
|
||||
"""Test if joystick.quit works."""
|
||||
|
||||
pygame.joystick.init()
|
||||
|
||||
self.assertIsNotNone(pygame.joystick.get_count()) # Is not None before quit
|
||||
|
||||
pygame.joystick.quit()
|
||||
|
||||
with self.assertRaises(pygame.error): # Raises error if quit worked
|
||||
pygame.joystick.get_count()
|
||||
|
||||
def test_get_count(self):
|
||||
# Test that get_count correctly returns a non-negative number of joysticks
|
||||
pygame.joystick.init()
|
||||
|
||||
try:
|
||||
count = pygame.joystick.get_count()
|
||||
self.assertGreaterEqual(
|
||||
count, 0, ("joystick.get_count() must return a value >= 0")
|
||||
)
|
||||
finally:
|
||||
pygame.joystick.quit()
|
||||
|
||||
|
||||
class JoystickInteractiveTest(unittest.TestCase):
|
||||
__tags__ = ["interactive"]
|
||||
|
||||
def test_get_count_interactive(self):
|
||||
# Test get_count correctly identifies number of connected joysticks
|
||||
prompt(
|
||||
"Please connect any joysticks/controllers now before starting the "
|
||||
"joystick.get_count() test."
|
||||
)
|
||||
|
||||
pygame.joystick.init()
|
||||
# pygame.joystick.get_count(): return count
|
||||
# number of joysticks on the system, 0 means no joysticks connected
|
||||
count = pygame.joystick.get_count()
|
||||
|
||||
response = question(
|
||||
"NOTE: Having Steam open may add an extra virtual controller for "
|
||||
"each joystick/controller physically plugged in.\n"
|
||||
f"joystick.get_count() thinks there is [{count}] joystick(s)/controller(s)"
|
||||
"connected to this system. Is this correct?"
|
||||
)
|
||||
|
||||
self.assertTrue(response)
|
||||
|
||||
# When you create Joystick objects using Joystick(id), you pass an
|
||||
# integer that must be lower than this count.
|
||||
# Test Joystick(id) for each connected joystick
|
||||
if count != 0:
|
||||
for x in range(count):
|
||||
pygame.joystick.Joystick(x)
|
||||
with self.assertRaises(pygame.error):
|
||||
pygame.joystick.Joystick(count)
|
||||
|
||||
pygame.joystick.quit()
|
||||
|
||||
|
||||
################################################################################
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,319 @@
|
||||
import os
|
||||
import platform
|
||||
import time
|
||||
import unittest
|
||||
|
||||
import pygame
|
||||
import pygame.key
|
||||
|
||||
# keys that are not tested for const-name match
|
||||
SKIPPED_KEYS = {"K_UNKNOWN"}
|
||||
SKIPPED_KEYS_NEW = {"K_MODE"}
|
||||
|
||||
# This is the expected compat output
|
||||
KEY_NAME_COMPAT = {
|
||||
"K_0": "0",
|
||||
"K_1": "1",
|
||||
"K_2": "2",
|
||||
"K_3": "3",
|
||||
"K_4": "4",
|
||||
"K_5": "5",
|
||||
"K_6": "6",
|
||||
"K_7": "7",
|
||||
"K_8": "8",
|
||||
"K_9": "9",
|
||||
"K_AC_BACK": "AC Back",
|
||||
"K_AMPERSAND": "&",
|
||||
"K_ASTERISK": "*",
|
||||
"K_AT": "@",
|
||||
"K_BACKQUOTE": "`",
|
||||
"K_BACKSLASH": "\\",
|
||||
"K_BACKSPACE": "backspace",
|
||||
"K_BREAK": "break",
|
||||
"K_CAPSLOCK": "caps lock",
|
||||
"K_CARET": "^",
|
||||
"K_CLEAR": "clear",
|
||||
"K_COLON": ":",
|
||||
"K_COMMA": ",",
|
||||
"K_CURRENCYSUBUNIT": "CurrencySubUnit",
|
||||
"K_CURRENCYUNIT": "euro",
|
||||
"K_DELETE": "delete",
|
||||
"K_DOLLAR": "$",
|
||||
"K_DOWN": "down",
|
||||
"K_END": "end",
|
||||
"K_EQUALS": "=",
|
||||
"K_ESCAPE": "escape",
|
||||
"K_EURO": "euro",
|
||||
"K_EXCLAIM": "!",
|
||||
"K_F1": "f1",
|
||||
"K_F10": "f10",
|
||||
"K_F11": "f11",
|
||||
"K_F12": "f12",
|
||||
"K_F13": "f13",
|
||||
"K_F14": "f14",
|
||||
"K_F15": "f15",
|
||||
"K_F2": "f2",
|
||||
"K_F3": "f3",
|
||||
"K_F4": "f4",
|
||||
"K_F5": "f5",
|
||||
"K_F6": "f6",
|
||||
"K_F7": "f7",
|
||||
"K_F8": "f8",
|
||||
"K_F9": "f9",
|
||||
"K_GREATER": ">",
|
||||
"K_HASH": "#",
|
||||
"K_HELP": "help",
|
||||
"K_HOME": "home",
|
||||
"K_INSERT": "insert",
|
||||
"K_KP0": "[0]",
|
||||
"K_KP1": "[1]",
|
||||
"K_KP2": "[2]",
|
||||
"K_KP3": "[3]",
|
||||
"K_KP4": "[4]",
|
||||
"K_KP5": "[5]",
|
||||
"K_KP6": "[6]",
|
||||
"K_KP7": "[7]",
|
||||
"K_KP8": "[8]",
|
||||
"K_KP9": "[9]",
|
||||
"K_KP_0": "[0]",
|
||||
"K_KP_1": "[1]",
|
||||
"K_KP_2": "[2]",
|
||||
"K_KP_3": "[3]",
|
||||
"K_KP_4": "[4]",
|
||||
"K_KP_5": "[5]",
|
||||
"K_KP_6": "[6]",
|
||||
"K_KP_7": "[7]",
|
||||
"K_KP_8": "[8]",
|
||||
"K_KP_9": "[9]",
|
||||
"K_KP_DIVIDE": "[/]",
|
||||
"K_KP_ENTER": "enter",
|
||||
"K_KP_EQUALS": "equals",
|
||||
"K_KP_MINUS": "[-]",
|
||||
"K_KP_MULTIPLY": "[*]",
|
||||
"K_KP_PERIOD": "[.]",
|
||||
"K_KP_PLUS": "[+]",
|
||||
"K_LALT": "left alt",
|
||||
"K_LCTRL": "left ctrl",
|
||||
"K_LEFT": "left",
|
||||
"K_LEFTBRACKET": "[",
|
||||
"K_LEFTPAREN": "(",
|
||||
"K_LESS": "<",
|
||||
"K_LGUI": "left meta",
|
||||
"K_LMETA": "left meta",
|
||||
"K_LSHIFT": "left shift",
|
||||
"K_LSUPER": "left meta",
|
||||
"K_MENU": "menu",
|
||||
"K_MINUS": "-",
|
||||
"K_MODE": "alt gr",
|
||||
"K_NUMLOCK": "numlock",
|
||||
"K_NUMLOCKCLEAR": "numlock",
|
||||
"K_PAGEDOWN": "page down",
|
||||
"K_PAGEUP": "page up",
|
||||
"K_PAUSE": "break",
|
||||
"K_PERCENT": "%",
|
||||
"K_PERIOD": ".",
|
||||
"K_PLUS": "+",
|
||||
"K_POWER": "power",
|
||||
"K_PRINT": "print screen",
|
||||
"K_PRINTSCREEN": "print screen",
|
||||
"K_QUESTION": "?",
|
||||
"K_QUOTE": "'",
|
||||
"K_QUOTEDBL": '"',
|
||||
"K_RALT": "right alt",
|
||||
"K_RCTRL": "right ctrl",
|
||||
"K_RETURN": "return",
|
||||
"K_RGUI": "right meta",
|
||||
"K_RIGHT": "right",
|
||||
"K_RIGHTBRACKET": "]",
|
||||
"K_RIGHTPAREN": ")",
|
||||
"K_RMETA": "right meta",
|
||||
"K_RSHIFT": "right shift",
|
||||
"K_RSUPER": "right meta",
|
||||
"K_SCROLLLOCK": "scroll lock",
|
||||
"K_SCROLLOCK": "scroll lock",
|
||||
"K_SEMICOLON": ";",
|
||||
"K_SLASH": "/",
|
||||
"K_SPACE": "space",
|
||||
"K_SYSREQ": "sys req",
|
||||
"K_TAB": "tab",
|
||||
"K_UNDERSCORE": "_",
|
||||
"K_UP": "up",
|
||||
"K_a": "a",
|
||||
"K_b": "b",
|
||||
"K_c": "c",
|
||||
"K_d": "d",
|
||||
"K_e": "e",
|
||||
"K_f": "f",
|
||||
"K_g": "g",
|
||||
"K_h": "h",
|
||||
"K_i": "i",
|
||||
"K_j": "j",
|
||||
"K_k": "k",
|
||||
"K_l": "l",
|
||||
"K_m": "m",
|
||||
"K_n": "n",
|
||||
"K_o": "o",
|
||||
"K_p": "p",
|
||||
"K_q": "q",
|
||||
"K_r": "r",
|
||||
"K_s": "s",
|
||||
"K_t": "t",
|
||||
"K_u": "u",
|
||||
"K_v": "v",
|
||||
"K_w": "w",
|
||||
"K_x": "x",
|
||||
"K_y": "y",
|
||||
"K_z": "z",
|
||||
}
|
||||
|
||||
|
||||
class KeyModuleTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
pygame.quit()
|
||||
pygame.init()
|
||||
|
||||
@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()
|
||||
if not pygame.display.get_init():
|
||||
pygame.display.init()
|
||||
|
||||
def test_import(self):
|
||||
"""does it import?"""
|
||||
import pygame.key
|
||||
|
||||
@unittest.skipIf(
|
||||
not ("Windows" in platform.system() or "Darwin" in platform.system()),
|
||||
"Not windows or macOS - we skip.",
|
||||
)
|
||||
def test_get_focused(self):
|
||||
# This test fails in SDL2 in some linux
|
||||
# This test was skipped in SDL1.
|
||||
focused = pygame.key.get_focused()
|
||||
self.assertFalse(focused) # No window to focus
|
||||
self.assertIsInstance(focused, int)
|
||||
# Dummy video driver never gets keyboard focus.
|
||||
if os.environ.get("SDL_VIDEODRIVER") != pygame.NULL_VIDEODRIVER:
|
||||
# Positive test, fullscreen with events grabbed
|
||||
display_sizes = pygame.display.list_modes()
|
||||
if display_sizes == -1:
|
||||
display_sizes = [(500, 500)]
|
||||
pygame.display.set_mode(size=display_sizes[-1], flags=pygame.FULLSCREEN)
|
||||
pygame.event.set_grab(True)
|
||||
# Pump event queue to get window focus on macOS
|
||||
pygame.event.pump()
|
||||
focused = pygame.key.get_focused()
|
||||
self.assertIsInstance(focused, int)
|
||||
self.assertTrue(focused)
|
||||
# Now test negative, iconify takes away focus
|
||||
pygame.event.clear()
|
||||
# TODO: iconify test fails in windows
|
||||
if os.name != "nt":
|
||||
pygame.display.iconify()
|
||||
# Apparent need to pump event queue in order to make sure iconify
|
||||
# happens. See display_test.py's test_get_active_iconify
|
||||
for _ in range(50):
|
||||
time.sleep(0.01)
|
||||
pygame.event.pump()
|
||||
self.assertFalse(pygame.key.get_focused())
|
||||
# Test if focus is returned when iconify is gone
|
||||
pygame.display.set_mode(size=display_sizes[-1], flags=pygame.FULLSCREEN)
|
||||
for i in range(50):
|
||||
time.sleep(0.01)
|
||||
pygame.event.pump()
|
||||
self.assertTrue(pygame.key.get_focused())
|
||||
# Test if a quit display raises an error:
|
||||
pygame.display.quit()
|
||||
with self.assertRaises(pygame.error) as cm:
|
||||
pygame.key.get_focused()
|
||||
|
||||
def test_get_pressed(self):
|
||||
states = pygame.key.get_pressed()
|
||||
self.assertEqual(states[pygame.K_RIGHT], 0)
|
||||
|
||||
def test_get_just_pressed(self):
|
||||
pressed_keys = pygame.key.get_just_pressed()
|
||||
self.assertEqual(pressed_keys[pygame.K_RIGHT], 0)
|
||||
|
||||
def test_get_just_released(self):
|
||||
released_keys = pygame.key.get_just_released()
|
||||
self.assertEqual(released_keys[pygame.K_RIGHT], 0)
|
||||
|
||||
def test_get_pressed_not_iter(self):
|
||||
states = pygame.key.get_pressed()
|
||||
with self.assertRaises(TypeError):
|
||||
next(states)
|
||||
with self.assertRaises(TypeError):
|
||||
for k in states:
|
||||
pass
|
||||
|
||||
def test_name_and_key_code(self):
|
||||
for const_name in dir(pygame):
|
||||
if not const_name.startswith("K_") or const_name in SKIPPED_KEYS:
|
||||
continue
|
||||
|
||||
try:
|
||||
expected_str_name = KEY_NAME_COMPAT[const_name]
|
||||
except KeyError:
|
||||
self.fail(
|
||||
"If you are seeing this error in a test run, you probably added a "
|
||||
"new pygame key constant, but forgot to update key_test unitests"
|
||||
)
|
||||
|
||||
const_val = getattr(pygame, const_name)
|
||||
|
||||
# with these tests below, we also make sure that key.name and key.key_code
|
||||
# can work together and handle each other's outputs
|
||||
|
||||
# test positional args
|
||||
self.assertEqual(pygame.key.name(const_val), expected_str_name)
|
||||
# test kwarg
|
||||
self.assertEqual(pygame.key.name(key=const_val), expected_str_name)
|
||||
|
||||
# test positional args
|
||||
self.assertEqual(pygame.key.key_code(expected_str_name), const_val)
|
||||
# test kwarg
|
||||
self.assertEqual(pygame.key.key_code(name=expected_str_name), const_val)
|
||||
|
||||
alt_name = pygame.key.name(const_val, use_compat=False)
|
||||
self.assertIsInstance(alt_name, str)
|
||||
|
||||
# This is a test for an implementation detail of name with use_compat=False
|
||||
# If this test breaks in the future for any key, it is safe to put skips on
|
||||
# failing keys (the implementation detail is documented as being unreliable)
|
||||
if const_name not in SKIPPED_KEYS_NEW:
|
||||
self.assertEqual(pygame.key.key_code(alt_name), const_val)
|
||||
|
||||
self.assertRaises(TypeError, pygame.key.name, "fizzbuzz")
|
||||
self.assertRaises(TypeError, pygame.key.key_code, pygame.K_a)
|
||||
|
||||
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()
|
||||
@@ -0,0 +1,17 @@
|
||||
import unittest
|
||||
|
||||
import pygame.constants
|
||||
import pygame.locals
|
||||
|
||||
|
||||
class LocalsTest(unittest.TestCase):
|
||||
def test_locals_has_all_constants(self):
|
||||
constants_set = set(pygame.constants.__all__)
|
||||
locals_set = set(pygame.locals.__all__)
|
||||
|
||||
# locals should have everything that constants has
|
||||
self.assertEqual(constants_set - locals_set, set())
|
||||
|
||||
|
||||
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,462 @@
|
||||
import unittest
|
||||
|
||||
import pygame
|
||||
|
||||
|
||||
class MidiInputTest(unittest.TestCase):
|
||||
__tags__ = ["interactive"]
|
||||
|
||||
def setUp(self):
|
||||
import pygame.midi
|
||||
|
||||
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):
|
||||
import pygame.midi
|
||||
|
||||
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):
|
||||
import pygame.midi
|
||||
|
||||
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 setUp(self):
|
||||
import pygame.midi
|
||||
|
||||
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_ansi_note, midi_to_frequency
|
||||
|
||||
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,531 @@
|
||||
import os
|
||||
import platform
|
||||
import sys
|
||||
import time
|
||||
import unittest
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
import pygame
|
||||
from pygame.tests.test_utils import example_path
|
||||
|
||||
|
||||
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()
|
||||
|
||||
def test_load_mp3(self):
|
||||
"|tags:music|"
|
||||
self.music_load("house_lo.mp3")
|
||||
|
||||
def test_load_ogg(self):
|
||||
"|tags:music|"
|
||||
self.music_load("house_lo.ogg")
|
||||
|
||||
def test_load_wav(self):
|
||||
"|tags:music|"
|
||||
self.music_load("house_lo.wav")
|
||||
|
||||
def test_load_flac(self):
|
||||
"|tags:music|"
|
||||
self.music_load("house_lo.flac")
|
||||
|
||||
# system installed SDL_mixer may not support wavpack
|
||||
@unittest.skipIf(
|
||||
pygame.mixer.get_sdl_mixer_version() < (2, 8, 0)
|
||||
or "PG_DEPS_FROM_SYSTEM" in os.environ,
|
||||
"WavPack support added in SDL_mixer 2.8.0",
|
||||
)
|
||||
def test_load_wv(self):
|
||||
"|tags:music|"
|
||||
self.music_load("house_lo.wv")
|
||||
|
||||
def test_load_opus(self):
|
||||
"|tags:music|"
|
||||
self.music_load("house_lo.opus")
|
||||
|
||||
def test_load_midi(self):
|
||||
"|tags:music|"
|
||||
if pygame.mixer.get_soundfont() is not None:
|
||||
self.music_load("MIDI_sample.mid")
|
||||
|
||||
def test_load_xm(self):
|
||||
"|tags:music|"
|
||||
self.music_load("surfonasinewave.xm")
|
||||
|
||||
def music_load(self, filename):
|
||||
data_fname = example_path("data")
|
||||
|
||||
path = os.path.join(data_fname, filename)
|
||||
if os.sep == "\\":
|
||||
path = path.replace("\\", "\\\\")
|
||||
umusfn = str(path)
|
||||
bmusfn = umusfn.encode()
|
||||
|
||||
pygame.mixer.music.load(umusfn)
|
||||
pygame.mixer.music.load(bmusfn)
|
||||
|
||||
def test_load_object(self):
|
||||
"""test loading music from file-like objects."""
|
||||
filenames = [
|
||||
"house_lo.ogg",
|
||||
"house_lo.wav",
|
||||
"house_lo.flac",
|
||||
"house_lo.opus",
|
||||
"surfonasinewave.xm",
|
||||
]
|
||||
if pygame.mixer.get_sdl_mixer_version() >= (2, 6, 0):
|
||||
filenames.append("house_lo.mp3")
|
||||
|
||||
if (
|
||||
pygame.mixer.get_sdl_mixer_version() >= (2, 8, 0)
|
||||
and "PG_DEPS_FROM_SYSTEM" not in os.environ
|
||||
):
|
||||
filenames.append("house_lo.wv")
|
||||
|
||||
if pygame.mixer.get_soundfont() is not None:
|
||||
filenames.append("MIDI_sample.mid")
|
||||
|
||||
data_fname = example_path("data")
|
||||
for file in filenames:
|
||||
path = os.path.join(data_fname, file)
|
||||
if os.sep == "\\":
|
||||
path = path.replace("\\", "\\\\")
|
||||
bmusfn = path.encode()
|
||||
|
||||
with open(bmusfn, "rb") as musf:
|
||||
pygame.mixer.music.load(musf)
|
||||
|
||||
def test_object_namehint(self):
|
||||
"""test loading & queuing music from file-like objects with namehint argument."""
|
||||
filenames = [
|
||||
"house_lo.ogg",
|
||||
"house_lo.wav",
|
||||
"house_lo.flac",
|
||||
"house_lo.opus",
|
||||
"surfonasinewave.xm",
|
||||
]
|
||||
if pygame.mixer.get_sdl_mixer_version() >= (2, 6, 0):
|
||||
filenames.append("house_lo.mp3")
|
||||
|
||||
if (
|
||||
pygame.mixer.get_sdl_mixer_version() >= (2, 8, 0)
|
||||
and "PG_DEPS_FROM_SYSTEM" not in os.environ
|
||||
):
|
||||
filenames.append("house_lo.wv")
|
||||
|
||||
if pygame.mixer.get_soundfont() is not None:
|
||||
filenames.append("MIDI_sample.mid")
|
||||
|
||||
data_fname = example_path("data")
|
||||
for file in filenames:
|
||||
path = os.path.join(data_fname, file)
|
||||
if os.sep == "\\":
|
||||
path = path.replace("\\", "\\\\")
|
||||
bmusfn = path.encode()
|
||||
|
||||
*_, format = file.split(".")
|
||||
|
||||
# these two "with open" blocks need to be separate, which is kinda weird
|
||||
with open(bmusfn, "rb") as musf:
|
||||
pygame.mixer.music.load(musf, format)
|
||||
|
||||
with open(bmusfn, "rb") as musf:
|
||||
pygame.mixer.music.queue(musf, format)
|
||||
|
||||
with open(bmusfn, "rb") as musf:
|
||||
pygame.mixer.music.load(musf, namehint=format)
|
||||
|
||||
with open(bmusfn, "rb") as musf:
|
||||
pygame.mixer.music.queue(musf, namehint=format)
|
||||
|
||||
def test_load_unicode(self):
|
||||
"""test non-ASCII unicode path"""
|
||||
import shutil
|
||||
|
||||
ep = example_path("data")
|
||||
|
||||
with TemporaryDirectory() as tmpdir:
|
||||
temp_file = os.path.join(tmpdir, "你好.wav")
|
||||
org_file = os.path.join(ep, "house_lo.wav")
|
||||
shutil.copy(org_file, temp_file)
|
||||
pygame.mixer.music.load(temp_file)
|
||||
pygame.mixer.music.load(org_file) # unload
|
||||
|
||||
def test_unload(self):
|
||||
import shutil
|
||||
import tempfile
|
||||
|
||||
ep = example_path("data")
|
||||
org_file = os.path.join(ep, "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)
|
||||
|
||||
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_flac(self):
|
||||
"""Ensures queue() accepts flac files.
|
||||
|
||||
|tags:music|
|
||||
"""
|
||||
filename = example_path(os.path.join("data", "house_lo.flac"))
|
||||
pygame.mixer.music.queue(filename)
|
||||
|
||||
# system installed SDL_mixer may not support wavpack
|
||||
@unittest.skipIf(
|
||||
pygame.mixer.get_sdl_mixer_version() < (2, 8, 0)
|
||||
or "PG_DEPS_FROM_SYSTEM" in os.environ,
|
||||
"WavPack support added in SDL_mixer 2.8.0",
|
||||
)
|
||||
def test_queue_wv(self):
|
||||
"""Ensures queue() accepts wv files.
|
||||
|
||||
|tags:music|
|
||||
"""
|
||||
filename = example_path(os.path.join("data", "house_lo.wv"))
|
||||
pygame.mixer.music.queue(filename)
|
||||
|
||||
def test_queue_opus(self):
|
||||
"""Ensures queue() accepts opus files.
|
||||
|
||||
|tags:music|
|
||||
"""
|
||||
filename = example_path(os.path.join("data", "house_lo.opus"))
|
||||
pygame.mixer.music.queue(filename)
|
||||
|
||||
def test_queue_midi(self):
|
||||
"""Ensures queue() accepts midi files.
|
||||
|
||||
|tags:music|
|
||||
"""
|
||||
if pygame.mixer.get_soundfont() is not None:
|
||||
filename = example_path(os.path.join("data", "MIDI_sample.mid"))
|
||||
pygame.mixer.music.queue(filename)
|
||||
|
||||
def test_queue_xm(self):
|
||||
"""Ensures queue() accepts xm files (tracker music files).
|
||||
|
||||
|tags:music|
|
||||
"""
|
||||
filename = example_path(os.path.join("data", "surfonasinewave.xm"))
|
||||
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__arguments(self):
|
||||
"""Ensures queue() can be called with proper arguments."""
|
||||
wav_file = example_path(os.path.join("data", "house_lo.wav"))
|
||||
|
||||
pygame.mixer.music.queue(wav_file, loops=2)
|
||||
pygame.mixer.music.queue(wav_file, namehint="")
|
||||
pygame.mixer.music.queue(wav_file, "")
|
||||
pygame.mixer.music.queue(wav_file, "", 2)
|
||||
|
||||
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(FileNotFoundError):
|
||||
pygame.mixer.music.queue("")
|
||||
|
||||
def test_music_pause__unpause(self):
|
||||
"""Ensure music has the correct position immediately after unpausing
|
||||
|
||||
|tags:music|
|
||||
"""
|
||||
filename = example_path(os.path.join("data", "house_lo.mp3"))
|
||||
pygame.mixer.music.load(filename)
|
||||
pygame.mixer.music.play()
|
||||
|
||||
# Wait 0.05s, then pause
|
||||
time.sleep(0.05)
|
||||
pygame.mixer.music.pause()
|
||||
# Wait 0.05s, get position, unpause, then get position again
|
||||
time.sleep(0.05)
|
||||
before_unpause = pygame.mixer.music.get_pos()
|
||||
pygame.mixer.music.unpause()
|
||||
after_unpause = pygame.mixer.music.get_pos()
|
||||
|
||||
self.assertAlmostEqual(before_unpause, after_unpause, delta=2)
|
||||
|
||||
def test_music_get_metadata(self):
|
||||
file_dir = example_path("data")
|
||||
path = os.path.join(file_dir, "metadata.mp3")
|
||||
pygame.mixer.music.load(path)
|
||||
|
||||
if pygame.mixer.get_sdl_mixer_version() >= (2, 6, 0):
|
||||
file_metadata = {
|
||||
"title": "Small Tone",
|
||||
"album": "Tones",
|
||||
"artist": "Audacity Generator",
|
||||
"copyright": "2023 Nobody",
|
||||
}
|
||||
else:
|
||||
file_metadata = {
|
||||
"title": "",
|
||||
"album": "",
|
||||
"artist": "",
|
||||
"copyright": "",
|
||||
}
|
||||
|
||||
retrieved_metadata = pygame.mixer.music.get_metadata()
|
||||
self.assertDictEqual(file_metadata, retrieved_metadata)
|
||||
pygame.mixer.music.unload()
|
||||
|
||||
retrieved_metadata = pygame.mixer.music.get_metadata(path)
|
||||
self.assertDictEqual(file_metadata, retrieved_metadata)
|
||||
|
||||
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()
|
||||
|
||||
@unittest.skipIf(
|
||||
os.environ.get("SDL_AUDIODRIVER") == "disk",
|
||||
'disk audio driver "playback" writing to disk is slow',
|
||||
)
|
||||
def test_play__start_time(self):
|
||||
pygame.display.init()
|
||||
|
||||
# music file is 7 seconds long
|
||||
filename = example_path(os.path.join("data", "house_lo.ogg"))
|
||||
pygame.mixer.music.load(filename)
|
||||
start_time_in_seconds = 6.0 # 6 seconds
|
||||
|
||||
music_finished = False
|
||||
clock = pygame.time.Clock()
|
||||
start_time_in_ms = clock.tick()
|
||||
# should play the last 1 second
|
||||
pygame.mixer.music.play(0, start=start_time_in_seconds)
|
||||
running = True
|
||||
while running:
|
||||
pygame.event.pump()
|
||||
|
||||
if not (pygame.mixer.music.get_busy() or music_finished):
|
||||
music_finished = True
|
||||
time_to_finish = (clock.tick() - start_time_in_ms) // 1000
|
||||
self.assertEqual(time_to_finish, 1)
|
||||
running = False
|
||||
|
||||
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 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.music_load("house_lo.ogg")
|
||||
self.assertFalse(pygame.mixer.music.get_busy())
|
||||
pygame.mixer.music.play()
|
||||
self.assertTrue(pygame.mixer.music.get_busy())
|
||||
pygame.mixer.music.pause()
|
||||
self.assertFalse(pygame.mixer.music.get_busy())
|
||||
|
||||
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):
|
||||
"""pygame-ce issue #622. unload music whenever mixer.quit() is called"""
|
||||
import shutil
|
||||
import tempfile
|
||||
|
||||
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()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,420 @@
|
||||
import os
|
||||
import platform
|
||||
import unittest
|
||||
import warnings
|
||||
|
||||
import pygame
|
||||
|
||||
DARWIN = "Darwin" in platform.platform()
|
||||
|
||||
|
||||
class MouseTests(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()
|
||||
|
||||
|
||||
class MouseModuleInteractiveTest(MouseTests):
|
||||
__tags__ = ["interactive"]
|
||||
|
||||
def test_set_pos(self):
|
||||
"""Ensures set_pos works correctly.
|
||||
Requires tester to move the mouse to be on the window.
|
||||
"""
|
||||
pygame.display.set_mode((500, 500))
|
||||
pygame.event.get() # Pump event queue to make window get focus on macOS.
|
||||
|
||||
if not pygame.mouse.get_focused():
|
||||
# The window needs to be focused for the mouse.set_pos to work on macOS.
|
||||
return
|
||||
clock = pygame.time.Clock()
|
||||
|
||||
expected_pos = ((10, 0), (0, 0), (499, 0), (499, 499), (341, 143), (94, 49))
|
||||
|
||||
for x, y in expected_pos:
|
||||
pygame.mouse.set_pos(x, y)
|
||||
pygame.event.get()
|
||||
found_pos = pygame.mouse.get_pos()
|
||||
|
||||
clock.tick()
|
||||
time_passed = 0.0
|
||||
ready_to_test = False
|
||||
|
||||
while not ready_to_test and time_passed <= 1000.0: # Avoid endless loop
|
||||
time_passed += clock.tick()
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.MOUSEMOTION:
|
||||
ready_to_test = True
|
||||
|
||||
self.assertEqual(found_pos, (x, y))
|
||||
|
||||
|
||||
class MouseModuleTest(MouseTests):
|
||||
@unittest.skipIf(
|
||||
os.environ.get("SDL_VIDEODRIVER", "") == pygame.NULL_VIDEODRIVER,
|
||||
"Cursors not supported on headless test machines",
|
||||
)
|
||||
def test_get_cursor(self):
|
||||
"""Ensures get_cursor works correctly."""
|
||||
|
||||
# error should be raised when the display is uninitialized
|
||||
with self.assertRaises(pygame.error):
|
||||
pygame.display.quit()
|
||||
pygame.mouse.get_cursor()
|
||||
|
||||
pygame.display.init()
|
||||
|
||||
size = (8, 8)
|
||||
hotspot = (0, 0)
|
||||
xormask = (0, 96, 120, 126, 112, 96, 0, 0)
|
||||
andmask = (224, 240, 254, 255, 254, 240, 96, 0)
|
||||
|
||||
expected_length = 4
|
||||
expected_cursor = pygame.cursors.Cursor(size, hotspot, xormask, andmask)
|
||||
pygame.mouse.set_cursor(expected_cursor)
|
||||
|
||||
try:
|
||||
cursor = pygame.mouse.get_cursor()
|
||||
|
||||
self.assertIsInstance(cursor, pygame.cursors.Cursor)
|
||||
self.assertEqual(len(cursor), expected_length)
|
||||
|
||||
for info in cursor:
|
||||
self.assertIsInstance(info, tuple)
|
||||
|
||||
pygame.mouse.set_cursor(size, hotspot, xormask, andmask)
|
||||
self.assertEqual(pygame.mouse.get_cursor(), expected_cursor)
|
||||
|
||||
# SDLError should be raised when the mouse cursor is NULL
|
||||
except pygame.error:
|
||||
with self.assertRaises(pygame.error):
|
||||
pygame.mouse.get_cursor()
|
||||
|
||||
@unittest.skipIf(
|
||||
os.environ.get("SDL_VIDEODRIVER", "") == pygame.NULL_VIDEODRIVER,
|
||||
"mouse.set_system_cursor only available in SDL2",
|
||||
)
|
||||
def test_set_system_cursor(self):
|
||||
"""Ensures set_system_cursor works correctly."""
|
||||
|
||||
with warnings.catch_warnings(record=True) as w:
|
||||
"""From Pygame 2.0.1, set_system_cursor() should raise a deprecation warning"""
|
||||
# Cause all warnings to always be triggered.
|
||||
warnings.simplefilter("always")
|
||||
|
||||
# Error should be raised when the display is uninitialized
|
||||
with self.assertRaises(pygame.error):
|
||||
pygame.display.quit()
|
||||
pygame.mouse.set_system_cursor(pygame.SYSTEM_CURSOR_HAND)
|
||||
|
||||
pygame.display.init()
|
||||
|
||||
# TypeError raised when PyArg_ParseTuple fails to parse parameters
|
||||
with self.assertRaises(TypeError):
|
||||
pygame.mouse.set_system_cursor("b")
|
||||
with self.assertRaises(TypeError):
|
||||
pygame.mouse.set_system_cursor(None)
|
||||
with self.assertRaises(TypeError):
|
||||
pygame.mouse.set_system_cursor((8, 8), (0, 0))
|
||||
|
||||
# Right type, invalid value
|
||||
with self.assertRaises(pygame.error):
|
||||
pygame.mouse.set_system_cursor(2000)
|
||||
|
||||
# Working as intended
|
||||
self.assertEqual(
|
||||
pygame.mouse.set_system_cursor(pygame.SYSTEM_CURSOR_ARROW), None
|
||||
)
|
||||
|
||||
# Making sure the warnings are working properly
|
||||
self.assertEqual(len(w), 6)
|
||||
self.assertTrue(
|
||||
all(issubclass(warn.category, DeprecationWarning) for warn in w)
|
||||
)
|
||||
|
||||
@unittest.skipIf(
|
||||
os.environ.get("SDL_VIDEODRIVER", "") == pygame.NULL_VIDEODRIVER,
|
||||
"Cursors not supported on headless test machines",
|
||||
)
|
||||
def test_set_cursor(self):
|
||||
"""Ensures set_cursor works correctly."""
|
||||
|
||||
# Bitmap cursor information
|
||||
size = (8, 8)
|
||||
hotspot = (0, 0)
|
||||
xormask = (0, 126, 64, 64, 32, 16, 0, 0)
|
||||
andmask = (254, 255, 254, 112, 56, 28, 12, 0)
|
||||
bitmap_cursor = pygame.cursors.Cursor(size, hotspot, xormask, andmask)
|
||||
|
||||
# System cursor information
|
||||
constant = pygame.SYSTEM_CURSOR_ARROW
|
||||
system_cursor = pygame.cursors.Cursor(constant)
|
||||
|
||||
# Color cursor information (also uses hotspot variable from Bitmap cursor info)
|
||||
surface = pygame.Surface((10, 10))
|
||||
color_cursor = pygame.cursors.Cursor(hotspot, surface)
|
||||
|
||||
pygame.display.quit()
|
||||
|
||||
# Bitmap: Error should be raised when the display is uninitialized
|
||||
with self.assertRaises(pygame.error):
|
||||
pygame.mouse.set_cursor(bitmap_cursor)
|
||||
|
||||
# System: Error should be raised when the display is uninitialized
|
||||
with self.assertRaises(pygame.error):
|
||||
pygame.mouse.set_cursor(system_cursor)
|
||||
|
||||
# Color: Error should be raised when the display is uninitialized
|
||||
with self.assertRaises(pygame.error):
|
||||
pygame.mouse.set_cursor(color_cursor)
|
||||
|
||||
pygame.display.init()
|
||||
|
||||
# Bitmap: TypeError raised when PyArg_ParseTuple fails to parse parameters
|
||||
with self.assertRaises(TypeError):
|
||||
pygame.mouse.set_cursor(("w", "h"), hotspot, xormask, andmask)
|
||||
with self.assertRaises(TypeError):
|
||||
pygame.mouse.set_cursor(size, ("0", "0"), xormask, andmask)
|
||||
with self.assertRaises(TypeError):
|
||||
pygame.mouse.set_cursor(size, ("x", "y", "z"), xormask, andmask)
|
||||
|
||||
# Bitmap: TypeError raised when either mask is not a sequence
|
||||
with self.assertRaises(TypeError):
|
||||
pygame.mouse.set_cursor(size, hotspot, 12345678, andmask)
|
||||
with self.assertRaises(TypeError):
|
||||
pygame.mouse.set_cursor(size, hotspot, xormask, 12345678)
|
||||
|
||||
# Bitmap: TypeError raised when element of mask is not an integer
|
||||
with self.assertRaises(TypeError):
|
||||
pygame.mouse.set_cursor(size, hotspot, "00000000", andmask)
|
||||
with self.assertRaises(TypeError):
|
||||
pygame.mouse.set_cursor(size, hotspot, xormask, (2, [0], 4, 0, 0, 8, 0, 1))
|
||||
|
||||
# Bitmap: ValueError raised when width not divisible by 8
|
||||
with self.assertRaises(ValueError):
|
||||
pygame.mouse.set_cursor((3, 8), hotspot, xormask, andmask)
|
||||
|
||||
# Bitmap: ValueError raised when length of either mask != width * height / 8
|
||||
with self.assertRaises(ValueError):
|
||||
pygame.mouse.set_cursor((16, 2), hotspot, (128, 64, 32), andmask)
|
||||
with self.assertRaises(ValueError):
|
||||
pygame.mouse.set_cursor((16, 2), hotspot, xormask, (192, 96, 48, 0, 1))
|
||||
|
||||
# Bitmap: Working as intended
|
||||
self.assertEqual(
|
||||
pygame.mouse.set_cursor((16, 1), hotspot, (8, 0), (0, 192)), None
|
||||
)
|
||||
pygame.mouse.set_cursor(size, hotspot, xormask, andmask)
|
||||
self.assertEqual(pygame.mouse.get_cursor(), bitmap_cursor)
|
||||
|
||||
# Bitmap: Working as intended + lists + masks with no references
|
||||
pygame.mouse.set_cursor(size, hotspot, list(xormask), list(andmask))
|
||||
self.assertEqual(pygame.mouse.get_cursor(), bitmap_cursor)
|
||||
|
||||
# System: TypeError raised when constant is invalid
|
||||
with self.assertRaises(TypeError):
|
||||
pygame.mouse.set_cursor(-50021232)
|
||||
with self.assertRaises(TypeError):
|
||||
pygame.mouse.set_cursor("yellow")
|
||||
|
||||
# System: Working as intended
|
||||
self.assertEqual(pygame.mouse.set_cursor(constant), None)
|
||||
pygame.mouse.set_cursor(constant)
|
||||
self.assertEqual(pygame.mouse.get_cursor(), system_cursor)
|
||||
pygame.mouse.set_cursor(system_cursor)
|
||||
self.assertEqual(pygame.mouse.get_cursor(), system_cursor)
|
||||
|
||||
# Color: TypeError raised with invalid parameters
|
||||
with self.assertRaises(TypeError):
|
||||
pygame.mouse.set_cursor(("x", "y"), surface)
|
||||
with self.assertRaises(TypeError):
|
||||
pygame.mouse.set_cursor(hotspot, "not_a_surface")
|
||||
|
||||
# Color: Working as intended
|
||||
self.assertEqual(pygame.mouse.set_cursor(hotspot, surface), None)
|
||||
pygame.mouse.set_cursor(hotspot, surface)
|
||||
self.assertEqual(pygame.mouse.get_cursor(), color_cursor)
|
||||
pygame.mouse.set_cursor(color_cursor)
|
||||
self.assertEqual(pygame.mouse.get_cursor(), color_cursor)
|
||||
|
||||
# Color: Working as intended + Surface with no references is returned okay
|
||||
pygame.mouse.set_cursor((0, 0), pygame.Surface((20, 20)))
|
||||
cursor = pygame.mouse.get_cursor()
|
||||
self.assertEqual(cursor.type, "color")
|
||||
self.assertEqual(cursor.data[0], (0, 0))
|
||||
self.assertEqual(cursor.data[1].get_size(), (20, 20))
|
||||
|
||||
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, bool)
|
||||
|
||||
expected_length = 5
|
||||
buttons_pressed = pygame.mouse.get_pressed(num_buttons=5)
|
||||
self.assertIsInstance(buttons_pressed, tuple)
|
||||
self.assertEqual(len(buttons_pressed), expected_length)
|
||||
for value in buttons_pressed:
|
||||
self.assertIsInstance(value, bool)
|
||||
|
||||
expected_length = 3
|
||||
buttons_pressed = pygame.mouse.get_pressed(3)
|
||||
self.assertIsInstance(buttons_pressed, tuple)
|
||||
self.assertEqual(len(buttons_pressed), expected_length)
|
||||
for value in buttons_pressed:
|
||||
self.assertIsInstance(value, bool)
|
||||
|
||||
expected_length = 5
|
||||
buttons_pressed = pygame.mouse.get_pressed(5)
|
||||
self.assertIsInstance(buttons_pressed, tuple)
|
||||
self.assertEqual(len(buttons_pressed), expected_length)
|
||||
for value in buttons_pressed:
|
||||
self.assertIsInstance(value, bool)
|
||||
|
||||
desktop_pressed1 = pygame.mouse.get_pressed(desktop=True)
|
||||
desktop_pressed2 = pygame.mouse.get_pressed(5, desktop=True)
|
||||
desktop_pressed3 = pygame.mouse.get_pressed(3, True)
|
||||
self.assertEqual(len(desktop_pressed1), 3)
|
||||
self.assertEqual(len(desktop_pressed2), 5)
|
||||
self.assertEqual(len(desktop_pressed3), 3)
|
||||
for desktop_pressed in [desktop_pressed1, desktop_pressed2, desktop_pressed3]:
|
||||
self.assertIsInstance(desktop_pressed, tuple)
|
||||
for value in desktop_pressed:
|
||||
self.assertIsInstance(value, bool)
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
pygame.mouse.get_pressed(4)
|
||||
|
||||
def test_get_just_pressed(self):
|
||||
mouse_buttons = pygame.mouse.get_just_pressed()
|
||||
self.assertIsInstance(mouse_buttons, tuple)
|
||||
self.assertEqual(len(mouse_buttons), 5)
|
||||
for value in mouse_buttons:
|
||||
self.assertIsInstance(value, bool)
|
||||
self.assertEqual(value, False)
|
||||
|
||||
def test_get_just_released(self):
|
||||
mouse_buttons = pygame.mouse.get_just_released()
|
||||
self.assertIsInstance(mouse_buttons, tuple)
|
||||
self.assertEqual(len(mouse_buttons), 5)
|
||||
for value in mouse_buttons:
|
||||
self.assertIsInstance(value, bool)
|
||||
self.assertEqual(value, False)
|
||||
|
||||
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)
|
||||
|
||||
desktop_pos1 = pygame.mouse.get_pos(True)
|
||||
desktop_pos2 = pygame.mouse.get_pos(desktop=True)
|
||||
self.assertEqual(desktop_pos1, desktop_pos2)
|
||||
|
||||
for desktop_pos in [desktop_pos1, desktop_pos2]:
|
||||
self.assertIsInstance(desktop_pos, tuple)
|
||||
self.assertEqual(len(desktop_pos), expected_length)
|
||||
for value in desktop_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 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)
|
||||
|
||||
@unittest.skipIf(
|
||||
os.environ.get("SDL_VIDEODRIVER", "") == pygame.NULL_VIDEODRIVER,
|
||||
"mouse.set_relative_mode requires non-null video driver",
|
||||
)
|
||||
def test_set_relative_mode(self):
|
||||
"""Tests that set_relative_mode hides the cursor."""
|
||||
for val in (True, False):
|
||||
if pygame.version.SDL >= (3, 0, 0):
|
||||
with self.assertRaises(pygame.error):
|
||||
pygame.mouse.set_relative_mode(val)
|
||||
else:
|
||||
with self.assertWarns(DeprecationWarning):
|
||||
pygame.mouse.set_relative_mode(val)
|
||||
|
||||
pygame.display.set_mode((100, 100))
|
||||
pygame.mouse.set_visible(True)
|
||||
pygame.mouse.set_relative_mode(True) # sets the mouse invisible
|
||||
visible = pygame.mouse.get_visible()
|
||||
self.assertEqual(visible, False)
|
||||
pygame.mouse.set_relative_mode(False) # sets the mouse visible
|
||||
visible = pygame.mouse.get_visible()
|
||||
self.assertEqual(visible, True)
|
||||
|
||||
@unittest.skipIf(
|
||||
os.environ.get("SDL_VIDEODRIVER", "") == pygame.NULL_VIDEODRIVER,
|
||||
"mouse.set_relative_mode requires non-null video driver",
|
||||
)
|
||||
def test_get_relative_mode(self):
|
||||
"""Tests that get_relative_mode correctly reports the relative mode"""
|
||||
pygame.display.set_mode((100, 100))
|
||||
pygame.mouse.set_relative_mode(True)
|
||||
self.assertEqual(pygame.mouse.get_relative_mode(), True)
|
||||
pygame.mouse.set_relative_mode(False)
|
||||
self.assertEqual(pygame.mouse.get_relative_mode(), False)
|
||||
|
||||
|
||||
################################################################################
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,708 @@
|
||||
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 array_to_surface, make_surface, map_array, surface_to_array
|
||||
|
||||
IS_PYPY = "PyPy" == platform.python_implementation()
|
||||
|
||||
|
||||
def unsigned32(i):
|
||||
"""cast signed 32 bit integer to an unsigned integer"""
|
||||
return i & 0xFFFFFFFF
|
||||
|
||||
|
||||
@unittest.skipIf(IS_PYPY, "pypy having illegal instruction on mac")
|
||||
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)
|
||||
|
||||
|
||||
@unittest.skipIf(IS_PYPY, "pypy having illegal instruction on mac")
|
||||
class PixelCopyTestWithArrayNumpy(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 = {8, 16, 32}
|
||||
pixels3d = {24, 32}
|
||||
array2d = {8, 16, 24, 32}
|
||||
array3d = {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 dtype, empty
|
||||
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 dtype, empty
|
||||
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 all as np_all, array, int32, uint8, zeros
|
||||
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(np_all(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(np_all(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(np_all(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(IS_PYPY, "pypy having illegal instruction on mac")
|
||||
class PixelCopyTestWithArrayNewBuf(unittest.TestCase):
|
||||
from pygame.tests.test_utils import buftools
|
||||
|
||||
class Array2D(buftools.Exporter):
|
||||
def __init__(self, initializer):
|
||||
from ctypes import POINTER, c_uint32, cast
|
||||
|
||||
Array2D = PixelCopyTestWithArrayNewBuf.Array2D
|
||||
super().__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 POINTER, c_uint8, cast
|
||||
|
||||
Array3D = PixelCopyTestWithArrayNewBuf.Array3D
|
||||
super().__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,490 @@
|
||||
import gc
|
||||
import unittest
|
||||
import weakref
|
||||
|
||||
import pygame
|
||||
import pygame._render as _render
|
||||
|
||||
|
||||
class DrawableObject:
|
||||
def __init__(self):
|
||||
self.drawn = False
|
||||
self.area = None
|
||||
self.dest = None
|
||||
|
||||
def draw(self, area, dest):
|
||||
self.drawn = True
|
||||
self.area = area
|
||||
self.dest = dest
|
||||
|
||||
|
||||
class RendererTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.window = pygame.Window(size=(100, 100))
|
||||
self.renderer = _render.Renderer(self.window)
|
||||
|
||||
init_draw_color = self.renderer.draw_color
|
||||
self.renderer.draw_color = "BLACK"
|
||||
self.renderer.clear()
|
||||
self.renderer.draw_color = init_draw_color
|
||||
|
||||
def test_to_surface(self):
|
||||
self.renderer.draw_color = "YELLOW"
|
||||
self.renderer.draw_point((10, 10)) # assumes Renderer.draw_point works
|
||||
surf1 = self.renderer.to_surface()
|
||||
self.assertEqual(surf1.get_at((10, 10)), pygame.Color(255, 255, 0, 255))
|
||||
self.assertEqual(surf1.size, (100, 100))
|
||||
|
||||
surf2 = pygame.Surface((150, 150))
|
||||
self.renderer.to_surface(surf2)
|
||||
self.assertEqual(surf2.get_at((10, 10)), pygame.Color(255, 255, 0, 255))
|
||||
|
||||
surf3 = self.renderer.to_surface(area=pygame.Rect(5, 5, 20, 20))
|
||||
self.assertEqual(surf3.get_at((5, 5)), pygame.Color(255, 255, 0, 255))
|
||||
self.assertEqual(surf3.size, (20, 20))
|
||||
|
||||
surf4 = pygame.Surface((150, 150))
|
||||
self.renderer.to_surface(surf4, pygame.Rect(7, 7, 40, 40))
|
||||
self.assertEqual(surf4.get_at((3, 3)), pygame.Color(255, 255, 0, 255))
|
||||
|
||||
small_surf = pygame.Surface((50, 50))
|
||||
with self.assertRaises(ValueError):
|
||||
self.renderer.to_surface(small_surf)
|
||||
|
||||
def test_blit(self):
|
||||
surface = pygame.Surface((10, 10))
|
||||
surface.fill((80, 120, 160, 200))
|
||||
texture = _render.Texture.from_surface(self.renderer, surface)
|
||||
image = _render.Image(texture)
|
||||
drawable_object = DrawableObject()
|
||||
dest = pygame.Rect(10, 10, 20, 20)
|
||||
area = pygame.Rect(0, 0, 15, 15)
|
||||
|
||||
self.renderer.blit(texture, dest, area)
|
||||
result = self.renderer.to_surface()
|
||||
self.assertEqual(pygame.Color(0, 0, 0, 255), result.get_at((9, 20)))
|
||||
for x in range(10, 30):
|
||||
self.assertEqual(pygame.Color(80, 120, 160, 255), result.get_at((x, 20)))
|
||||
self.assertEqual(pygame.Color(0, 0, 0, 255), result.get_at((30, 20)))
|
||||
self.renderer.clear()
|
||||
|
||||
self.renderer.blit(image, dest, area) # TODO Assert after Image implementation
|
||||
|
||||
self.renderer.blit(drawable_object, dest, area)
|
||||
self.assertEqual(drawable_object.drawn, True)
|
||||
self.assertEqual(drawable_object.area, area)
|
||||
self.assertEqual(drawable_object.dest, dest)
|
||||
|
||||
def test_clear(self):
|
||||
self.renderer.draw_color = "YELLOW"
|
||||
self.renderer.clear()
|
||||
surf = self.renderer.to_surface()
|
||||
for x in range(surf.width):
|
||||
for y in range(surf.height):
|
||||
self.assertEqual(surf.get_at((x, y)), pygame.Color(255, 255, 0, 255))
|
||||
|
||||
def test_draw_point(self):
|
||||
self.renderer.draw_color = "YELLOW"
|
||||
self.renderer.draw_point((10, 10))
|
||||
surf = self.renderer.to_surface()
|
||||
for x in range(-1, 2):
|
||||
for y in range(-1, 2):
|
||||
if x or y:
|
||||
self.assertEqual(
|
||||
surf.get_at((10 + x, 10 + y)), pygame.Color(0, 0, 0, 255)
|
||||
)
|
||||
else:
|
||||
self.assertEqual(
|
||||
surf.get_at((10, 10)), pygame.Color(255, 255, 0, 255)
|
||||
)
|
||||
|
||||
def test_draw_line(self):
|
||||
self.renderer.draw_color = "YELLOW"
|
||||
self.renderer.draw_line((10, 10), (40, 40))
|
||||
surf = self.renderer.to_surface()
|
||||
test_points = ((10, 10), (20, 20), (30, 30), (40, 40))
|
||||
for point in test_points:
|
||||
self.assertEqual(surf.get_at(point), pygame.Color(255, 255, 0, 255))
|
||||
|
||||
def test_draw_triangle(self):
|
||||
self.renderer.draw_color = "YELLOW"
|
||||
self.renderer.draw_triangle((10, 10), (10, 40), (40, 10))
|
||||
surf = self.renderer.to_surface()
|
||||
test_points = (
|
||||
(10, 10),
|
||||
(20, 10),
|
||||
(30, 10),
|
||||
(40, 10),
|
||||
(10, 20),
|
||||
(30, 20),
|
||||
(10, 30),
|
||||
(20, 30),
|
||||
(10, 40),
|
||||
)
|
||||
for point in test_points:
|
||||
self.assertEqual(surf.get_at(point), pygame.Color(255, 255, 0, 255))
|
||||
|
||||
def test_draw_rect(self):
|
||||
self.renderer.draw_color = "YELLOW"
|
||||
self.renderer.draw_rect(pygame.Rect(10, 10, 11, 11))
|
||||
surf = self.renderer.to_surface()
|
||||
test_points = ((10, 15), (15, 10), (20, 15), (15, 20))
|
||||
for point in test_points:
|
||||
self.assertEqual(surf.get_at(point), pygame.Color(255, 255, 0, 255))
|
||||
|
||||
def test_draw_quad(self):
|
||||
self.renderer.draw_color = "YELLOW"
|
||||
self.renderer.draw_quad((10, 40), (40, 10), (70, 40), (40, 70))
|
||||
surf = self.renderer.to_surface()
|
||||
test_points = ((30, 20), (50, 20), (30, 60), (50, 60))
|
||||
for point in test_points:
|
||||
self.assertEqual(surf.get_at(point), pygame.Color(255, 255, 0, 255))
|
||||
|
||||
def test_fill_triangle(self):
|
||||
self.renderer.draw_color = "YELLOW"
|
||||
self.renderer.fill_triangle((10, 10), (10, 40), (40, 10))
|
||||
surf = self.renderer.to_surface()
|
||||
for x in range(10, 29):
|
||||
self.assertEqual(surf.get_at((x, 20)), pygame.Color(255, 255, 0, 255))
|
||||
for x in range(10, 19):
|
||||
self.assertEqual(surf.get_at((x, 30)), pygame.Color(255, 255, 0, 255))
|
||||
|
||||
def test_fill_rect(self):
|
||||
self.renderer.draw_color = "YELLOW"
|
||||
self.renderer.fill_rect(pygame.Rect(10, 10, 11, 11))
|
||||
surf = self.renderer.to_surface()
|
||||
for x in range(10, 21):
|
||||
for y in range(10, 21):
|
||||
self.assertEqual(surf.get_at((x, y)), pygame.Color(255, 255, 0, 255))
|
||||
|
||||
def test_fill_quad(self):
|
||||
self.renderer.draw_color = "GREEN"
|
||||
self.renderer.draw_quad((10, 40), (40, 10), (70, 40), (40, 70))
|
||||
self.renderer.draw_color = "YELLOW"
|
||||
self.renderer.fill_quad((10, 40), (40, 10), (70, 40), (40, 70))
|
||||
surf = self.renderer.to_surface()
|
||||
for x in range(30, 50):
|
||||
self.assertEqual(surf.get_at((x, 20)), pygame.Color(255, 255, 0, 255))
|
||||
self.assertEqual(surf.get_at((x, 59)), pygame.Color(255, 255, 0, 255))
|
||||
|
||||
def test_viewport(self):
|
||||
self.assertEqual(self.renderer.get_viewport(), pygame.Rect(0, 0, 100, 100))
|
||||
self.renderer.set_viewport(pygame.Rect(20, 20, 60, 60))
|
||||
self.assertEqual(self.renderer.get_viewport(), pygame.Rect(20, 20, 60, 60))
|
||||
self.renderer.set_viewport(None)
|
||||
self.assertEqual(self.renderer.get_viewport(), pygame.Rect(0, 0, 100, 100))
|
||||
|
||||
def test_logical_size(self):
|
||||
self.assertEqual(self.renderer.logical_size, (0, 0))
|
||||
self.renderer.logical_size = (10, 10)
|
||||
self.assertEqual(self.renderer.logical_size, (10, 10))
|
||||
|
||||
def test_logical_window_mapping(self):
|
||||
self.renderer.logical_size = (10, 10)
|
||||
self.assertEqual(self.renderer.coordinates_to_window((10, 10)), (100, 100))
|
||||
self.assertEqual(self.renderer.coordinates_from_window((100, 100)), (10, 10))
|
||||
with self.assertRaises(TypeError):
|
||||
self.renderer.coordinates_to_window(42, 42)
|
||||
with self.assertRaises(TypeError):
|
||||
self.renderer.coordinates_from_window(42, 42)
|
||||
|
||||
def test_scale(self):
|
||||
self.assertEqual(self.renderer.scale, (1.0, 1.0))
|
||||
self.renderer.scale = (0.5, 2)
|
||||
self.assertEqual(self.renderer.scale, (0.5, 2.0))
|
||||
|
||||
def test_target(self):
|
||||
self.assertEqual(self.renderer.target, None)
|
||||
texture = _render.Texture(self.renderer, (10, 10), target=True)
|
||||
self.renderer.target = texture
|
||||
self.assertEqual(id(self.renderer.target), id(texture))
|
||||
self.renderer.target = None
|
||||
self.assertEqual(self.renderer.target, None)
|
||||
|
||||
@unittest.skip("Unable to create that blend_mode on all devices")
|
||||
def test_compose_custom_blend_mode(self):
|
||||
color_mode, alpha_mode = (
|
||||
(
|
||||
pygame.BLENDFACTOR_SRC_COLOR,
|
||||
pygame.BLENDFACTOR_ONE_MINUS_DST_COLOR,
|
||||
pygame.BLENDOPERATION_MAXIMUM,
|
||||
),
|
||||
(
|
||||
pygame.BLENDFACTOR_ONE_MINUS_SRC_ALPHA,
|
||||
pygame.BLENDFACTOR_DST_ALPHA,
|
||||
pygame.BLENDOPERATION_MINIMUM,
|
||||
),
|
||||
)
|
||||
custom_blend_mode = self.renderer.compose_custom_blend_mode(
|
||||
color_mode, alpha_mode
|
||||
)
|
||||
self.assertEqual(custom_blend_mode, 157550645)
|
||||
self.renderer.draw_blend_mode = custom_blend_mode
|
||||
self.assertEqual(self.renderer.draw_blend_mode, custom_blend_mode)
|
||||
|
||||
def test_draw_blend_mode(self):
|
||||
self.assertEqual(self.renderer.draw_blend_mode, pygame.BLENDMODE_NONE)
|
||||
self.renderer.draw_blend_mode = pygame.BLENDMODE_MUL
|
||||
self.assertEqual(self.renderer.draw_blend_mode, pygame.BLENDMODE_MUL)
|
||||
unsupported_blend_mode = pygame.BLENDMODE_MUL + 1
|
||||
with self.assertRaises(Exception):
|
||||
self.renderer.draw_blend_mode = unsupported_blend_mode
|
||||
|
||||
def test_draw_color(self):
|
||||
self.assertEqual(self.renderer.draw_color, pygame.Color(0, 0, 0, 0))
|
||||
self.renderer.draw_color = "YELLOW"
|
||||
self.assertEqual(self.renderer.draw_color, pygame.Color(255, 255, 0, 255))
|
||||
|
||||
|
||||
class TextureTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.window = pygame.Window(size=(100, 100))
|
||||
self.renderer = _render.Renderer(self.window)
|
||||
self.renderer.clear()
|
||||
self.texture = _render.Texture(self.renderer, (80, 60))
|
||||
|
||||
def create_texture_from_surface(self):
|
||||
surface = pygame.Surface((100, 100))
|
||||
surface.fill(pygame.Color(80, 120, 160, 128))
|
||||
return _render.Texture.from_surface(self.renderer, surface)
|
||||
|
||||
def test_init(self):
|
||||
_render.Texture(self.renderer, (100, 100))
|
||||
_render.Texture(self.renderer, (100, 100), depth=32)
|
||||
with self.assertRaises(ValueError):
|
||||
_render.Texture(self.renderer, (100, 100), depth=33)
|
||||
_render.Texture(self.renderer, (100, 100), depth=32, static=True)
|
||||
_render.Texture(self.renderer, (100, 100), depth=32, streaming=True)
|
||||
_render.Texture(self.renderer, (100, 100), depth=32, target=True)
|
||||
with self.assertRaises(ValueError):
|
||||
_render.Texture(
|
||||
self.renderer, (100, 100), depth=32, static=True, target=True
|
||||
)
|
||||
with self.assertRaises(ValueError):
|
||||
_render.Texture(
|
||||
self.renderer, (100, 100), depth=32, target=True, streaming=True
|
||||
)
|
||||
with self.assertRaises(ValueError):
|
||||
_render.Texture(
|
||||
self.renderer, (100, 100), depth=32, static=True, streaming=True
|
||||
)
|
||||
|
||||
def test_alpha(self):
|
||||
self.assertEqual(255, self.texture.alpha)
|
||||
self.texture.alpha = 128
|
||||
self.assertEqual(128, self.texture.alpha)
|
||||
|
||||
def test_blend_mode(self):
|
||||
self.assertEqual(pygame.BLENDMODE_NONE, self.texture.blend_mode)
|
||||
self.texture.blend_mode = pygame.BLENDMODE_BLEND
|
||||
self.assertEqual(pygame.BLENDMODE_BLEND, self.texture.blend_mode)
|
||||
|
||||
def test_color(self):
|
||||
self.assertEqual(pygame.Color(255, 255, 255, 255), self.texture.color)
|
||||
self.texture.color = pygame.Color(100, 110, 120, 130)
|
||||
self.assertEqual(pygame.Color(100, 110, 120, 255), self.texture.color)
|
||||
|
||||
def test_width(self):
|
||||
self.assertEqual(80, self.texture.width)
|
||||
with self.assertRaises(AttributeError):
|
||||
self.texture.width = 100
|
||||
|
||||
def test_height(self):
|
||||
self.assertEqual(60, self.texture.height)
|
||||
with self.assertRaises(AttributeError):
|
||||
self.texture.height = 100
|
||||
|
||||
def test_renderer(self):
|
||||
self.assertEqual(self.renderer, self.texture.renderer)
|
||||
window2 = pygame.Window(size=(128, 128))
|
||||
renderer2 = _render.Renderer(window2)
|
||||
with self.assertRaises(AttributeError):
|
||||
self.texture.renderer = renderer2
|
||||
|
||||
def test_get_rect(self):
|
||||
self.assertEqual(pygame.Rect(0, 0, 80, 60), self.texture.get_rect())
|
||||
self.assertEqual(
|
||||
pygame.Rect(10, 20, 80, 60), self.texture.get_rect(center=(50, 50))
|
||||
)
|
||||
|
||||
def test_from_surface(self):
|
||||
surf_size = (50, 40)
|
||||
surface = pygame.Surface(surf_size)
|
||||
texture2 = _render.Texture.from_surface(self.renderer, surface)
|
||||
self.assertEqual(surf_size, (texture2.width, texture2.height))
|
||||
|
||||
def test_draw_triangle(self):
|
||||
texture2 = self.create_texture_from_surface()
|
||||
texture2.draw_triangle(
|
||||
(50, 10),
|
||||
(10, 90),
|
||||
(90, 90),
|
||||
(0.5, 0.5),
|
||||
(0.8, 0.2),
|
||||
(1, 1),
|
||||
(100, 100, 100, 100),
|
||||
(80, 60, 40, 20),
|
||||
(150, 170, 190, 210),
|
||||
)
|
||||
result = self.renderer.to_surface()
|
||||
expected = [
|
||||
(0, 0, 0),
|
||||
(0, 0, 0),
|
||||
(0, 0, 0),
|
||||
(0, 0, 0),
|
||||
(0, 0, 0),
|
||||
(28, 38, 45),
|
||||
(29, 39, 46),
|
||||
(29, 39, 47),
|
||||
(29, 40, 48),
|
||||
(29, 41, 49),
|
||||
(30, 41, 50),
|
||||
(30, 42, 52),
|
||||
(30, 43, 53),
|
||||
(31, 43, 54),
|
||||
(31, 44, 55),
|
||||
(31, 44, 56),
|
||||
(31, 45, 57),
|
||||
(32, 46, 59),
|
||||
(32, 46, 60),
|
||||
(32, 47, 61),
|
||||
(32, 48, 62),
|
||||
(33, 48, 63),
|
||||
(33, 49, 65),
|
||||
(33, 50, 66),
|
||||
(34, 50, 67),
|
||||
(34, 51, 68),
|
||||
(34, 52, 69),
|
||||
(34, 52, 70),
|
||||
(35, 53, 72),
|
||||
(35, 54, 73),
|
||||
(35, 54, 74),
|
||||
(35, 55, 75),
|
||||
(36, 55, 76),
|
||||
(36, 56, 78),
|
||||
(36, 57, 79),
|
||||
(37, 57, 80),
|
||||
(37, 58, 81),
|
||||
(37, 59, 82),
|
||||
(37, 59, 83),
|
||||
(38, 60, 85),
|
||||
(38, 61, 86),
|
||||
(38, 61, 87),
|
||||
(39, 62, 88),
|
||||
(39, 63, 89),
|
||||
(39, 63, 90),
|
||||
(0, 0, 0),
|
||||
(0, 0, 0),
|
||||
(0, 0, 0),
|
||||
(0, 0, 0),
|
||||
(0, 0, 0),
|
||||
]
|
||||
start = 25
|
||||
for x in range(start, start + len(expected)):
|
||||
value = result.get_at((x, 50))
|
||||
for color_index in range(3):
|
||||
expected_value = expected[x - start][color_index]
|
||||
self.assertTrue(
|
||||
expected_value - 1 <= value[color_index] <= expected_value + 1
|
||||
)
|
||||
|
||||
def test_draw_quad(self):
|
||||
texture2 = self.create_texture_from_surface()
|
||||
texture2.draw_quad(
|
||||
(10, 10),
|
||||
(90, 10),
|
||||
(90, 90),
|
||||
(10, 90),
|
||||
(0.5, 0.5),
|
||||
(0.8, 0.2),
|
||||
(0.2, 0.8),
|
||||
(0.9, 0.9),
|
||||
(100, 100, 100, 100),
|
||||
(80, 60, 40, 20),
|
||||
(150, 170, 190, 210),
|
||||
(128, 128, 128, 128),
|
||||
)
|
||||
result = self.renderer.to_surface()
|
||||
expected = [
|
||||
(37, 58, 79),
|
||||
(37, 58, 80),
|
||||
(37, 58, 80),
|
||||
(37, 58, 81),
|
||||
(37, 59, 81),
|
||||
(38, 59, 82),
|
||||
(38, 59, 82),
|
||||
(38, 59, 83),
|
||||
(38, 60, 83),
|
||||
(38, 60, 84),
|
||||
(38, 60, 84),
|
||||
(38, 60, 84),
|
||||
(38, 61, 85),
|
||||
(38, 61, 85),
|
||||
(38, 61, 86),
|
||||
(38, 61, 86),
|
||||
(39, 62, 87),
|
||||
(39, 62, 87),
|
||||
(39, 62, 88),
|
||||
(39, 62, 88),
|
||||
(39, 62, 89),
|
||||
(39, 63, 89),
|
||||
(39, 63, 90),
|
||||
(39, 63, 90),
|
||||
(39, 63, 91),
|
||||
(39, 64, 91),
|
||||
(39, 63, 91),
|
||||
(39, 63, 90),
|
||||
(39, 63, 90),
|
||||
(39, 63, 89),
|
||||
(39, 63, 89),
|
||||
(39, 62, 88),
|
||||
(39, 62, 88),
|
||||
(39, 62, 88),
|
||||
(39, 62, 87),
|
||||
(38, 61, 87),
|
||||
(38, 61, 86),
|
||||
(38, 61, 86),
|
||||
(38, 61, 85),
|
||||
(38, 60, 85),
|
||||
(38, 60, 84),
|
||||
(38, 60, 84),
|
||||
(38, 60, 83),
|
||||
(38, 59, 83),
|
||||
(38, 59, 82),
|
||||
(38, 59, 82),
|
||||
(38, 59, 81),
|
||||
(38, 59, 81),
|
||||
(37, 58, 80),
|
||||
(37, 58, 80),
|
||||
]
|
||||
start = 25
|
||||
for x in range(start, start + len(expected)):
|
||||
value = result.get_at((x, 50))
|
||||
for color_index in range(3):
|
||||
expected_value = expected[x - start][color_index]
|
||||
self.assertTrue(
|
||||
expected_value - 1 <= value[color_index] <= expected_value + 1
|
||||
)
|
||||
|
||||
def test_draw(self):
|
||||
texture2 = self.create_texture_from_surface()
|
||||
texture2.draw(pygame.Rect(10, 20, 40, 40), pygame.Rect(50, 30, 35, 20), 45)
|
||||
result = self.renderer.to_surface()
|
||||
for x in range(64, 82):
|
||||
self.assertEqual(pygame.Color(80, 120, 160, 255), result.get_at((x, 50)))
|
||||
|
||||
def test_garbage_collection(self):
|
||||
reference = weakref.ref(self.texture)
|
||||
self.assertTrue(reference() is self.texture)
|
||||
del self.texture
|
||||
gc.collect()
|
||||
self.assertIsNone(reference())
|
||||
|
||||
def test_update(self):
|
||||
surface = pygame.Surface((100, 100))
|
||||
surface.fill(pygame.Color(80, 120, 160, 128))
|
||||
self.texture.update(surface, pygame.Rect(10, 10, 80, 80))
|
||||
self.texture.draw()
|
||||
result = self.renderer.to_surface()
|
||||
for x in range(25, 75):
|
||||
self.assertEqual(pygame.Color(80, 120, 160, 255), result.get_at((x, 50)))
|
||||
@@ -0,0 +1,134 @@
|
||||
import pathlib
|
||||
import platform
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
from pygame import encode_file_path, encode_string
|
||||
|
||||
IS_PYPY = "PyPy" == platform.python_implementation()
|
||||
|
||||
|
||||
class RWopsEncodeStringTest(unittest.TestCase):
|
||||
def test_obj_None(self):
|
||||
encoded_string = encode_string(None)
|
||||
|
||||
self.assertIsNone(encoded_string)
|
||||
|
||||
def test_returns_bytes(self):
|
||||
u = "Hello"
|
||||
encoded_string = encode_string(u)
|
||||
|
||||
self.assertIsInstance(encoded_string, bytes)
|
||||
|
||||
def test_obj_bytes(self):
|
||||
b = b"encyclop\xe6dia"
|
||||
encoded_string = encode_string(b, "ascii", "strict")
|
||||
|
||||
self.assertIs(encoded_string, b)
|
||||
|
||||
def test_encode_unicode(self):
|
||||
u = "\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):
|
||||
u = "abc\u0109defg\u011dh\u0125ij\u0135klmnoprs\u015dtu\u016dvz"
|
||||
b = u.encode("ascii", "ignore")
|
||||
self.assertEqual(encode_string(u, "ascii", "ignore"), b)
|
||||
|
||||
def test_encoding_error(self):
|
||||
u = "a\x80b"
|
||||
encoded_string = encode_string(u, "ascii", "strict")
|
||||
|
||||
self.assertIsNone(encoded_string)
|
||||
|
||||
def test_check_defaults(self):
|
||||
u = "a\u01f7b"
|
||||
b = u.encode("unicode_escape", "backslashreplace")
|
||||
encoded_string = encode_string(u)
|
||||
|
||||
self.assertEqual(encoded_string, b)
|
||||
|
||||
def test_etype(self):
|
||||
u = "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 = b"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)
|
||||
|
||||
@unittest.skipIf(IS_PYPY, "getrefcount not available on pypy")
|
||||
def test_refcount(self):
|
||||
bpath = b" This is a string that is not cached."[1:]
|
||||
upath = bpath.decode("ascii")
|
||||
before = sys.getrefcount(bpath)
|
||||
bpath = encode_string(bpath)
|
||||
self.assertEqual(sys.getrefcount(bpath), 2)
|
||||
bpath = encode_string(upath)
|
||||
self.assertIn(sys.getrefcount(bpath), (before, before - 1))
|
||||
|
||||
def test_smp(self):
|
||||
utf_8 = b"a\xf0\x93\x82\xa7b"
|
||||
u = "a\U000130a7b"
|
||||
b = encode_string(u, "utf-8", "strict", AssertionError)
|
||||
self.assertEqual(b, utf_8)
|
||||
|
||||
def test_pathlib_obj(self):
|
||||
"""Test loading string representation of pathlib object"""
|
||||
"""
|
||||
We do this because pygame functions internally use pg_EncodeString
|
||||
to decode the filenames passed to them. So if we test that here, we
|
||||
can safely assume that all those functions do not have any issues
|
||||
with pathlib objects
|
||||
"""
|
||||
encoded = encode_string(pathlib.PurePath("foo"), "utf-8")
|
||||
self.assertEqual(encoded, b"foo")
|
||||
|
||||
encoded = encode_string(pathlib.Path("baz"))
|
||||
self.assertEqual(encoded, b"baz")
|
||||
|
||||
|
||||
class RWopsEncodeFilePathTest(unittest.TestCase):
|
||||
# Most tests can be skipped since RWopsEncodeFilePath wraps
|
||||
# RWopsEncodeString
|
||||
def test_encoding(self):
|
||||
u = "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 = b"a\x00b\x00c"
|
||||
encoded_file_path = encode_file_path(b)
|
||||
|
||||
self.assertIsNone(encoded_file_path)
|
||||
|
||||
def test_etype(self):
|
||||
b = b"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,221 @@
|
||||
import os
|
||||
import platform
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import pygame
|
||||
from pygame import scrap
|
||||
from pygame.tests.test_utils import trunk_relative_path
|
||||
|
||||
if os.environ.get("SDL_VIDEODRIVER") == pygame.NULL_VIDEODRIVER:
|
||||
__tags__ = ("ignore", "subprocess_ignore")
|
||||
|
||||
|
||||
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 = b"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()
|
||||
|
||||
@unittest.skipIf(
|
||||
platform.system() != "Windows",
|
||||
"scrap features are broken on non windows platforms",
|
||||
)
|
||||
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, b"Hello world")
|
||||
|
||||
self.assertEqual(scrap.get(pygame.SCRAP_TEXT), b"Hello world")
|
||||
|
||||
scrap.put(pygame.SCRAP_TEXT, b"Another String")
|
||||
|
||||
self.assertEqual(scrap.get(pygame.SCRAP_TEXT), b"Another String")
|
||||
|
||||
@unittest.skipIf(
|
||||
platform.system() != "Windows",
|
||||
"scrap features are broken on non windows platforms",
|
||||
)
|
||||
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_bytes = pygame.image.tobytes(sf, "RGBA")
|
||||
scrap.put(pygame.SCRAP_BMP, expected_bytes)
|
||||
|
||||
self.assertEqual(scrap.get(pygame.SCRAP_BMP), expected_bytes)
|
||||
|
||||
@unittest.skipIf(
|
||||
platform.system() != "Windows",
|
||||
"scrap features are broken on non windows platforms",
|
||||
)
|
||||
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, b"buf")
|
||||
r = scrap.get(DATA_TYPE)
|
||||
|
||||
self.assertEqual(r, b"buf")
|
||||
|
||||
def test_new_put(self):
|
||||
"""Ensures that text can be placed into the clipboard"""
|
||||
text = "Welcome to scrap!"
|
||||
scrap.put_text(text)
|
||||
self.assertTrue(scrap.has_text())
|
||||
self.assertEqual(scrap.get_text(), text)
|
||||
|
||||
def test_has_text_when_empty(self):
|
||||
"""Ensures that has_text returns False when clipboard is empty"""
|
||||
scrap.put_text("")
|
||||
self.assertFalse(scrap.has_text())
|
||||
self.assertEqual(scrap.get_text(), "")
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,11 @@
|
||||
__tags__ = ["array"]
|
||||
|
||||
exclude = False
|
||||
|
||||
try:
|
||||
import numpy
|
||||
except ImportError:
|
||||
exclude = True
|
||||
|
||||
if exclude:
|
||||
__tags__.extend(("ignore", "subprocess_ignore"))
|
||||
@@ -0,0 +1,153 @@
|
||||
import unittest
|
||||
|
||||
import pygame
|
||||
import pygame.sndarray
|
||||
from numpy import all as np_all, array, float32, int8, int16, uint8, uint16
|
||||
|
||||
|
||||
class SndarrayTest(unittest.TestCase):
|
||||
array_dtypes = {8: uint8, -8: int8, 16: uint16, -16: int16, 32: float32}
|
||||
|
||||
def _assert_compatible(self, arr, size):
|
||||
dtype = self.array_dtypes[size]
|
||||
self.assertEqual(arr.dtype, dtype)
|
||||
|
||||
def test_array(self):
|
||||
def check_array(size, channels, test_data):
|
||||
try:
|
||||
pygame.mixer.init(22050, size, channels, allowedchanges=0)
|
||||
except pygame.error:
|
||||
# Not all sizes are supported on all systems.
|
||||
return
|
||||
try:
|
||||
__, sz, __ = pygame.mixer.get_init()
|
||||
if sz == size:
|
||||
srcarr = array(test_data, self.array_dtypes[size])
|
||||
snd = pygame.sndarray.make_sound(srcarr)
|
||||
arr = pygame.sndarray.array(snd)
|
||||
self._assert_compatible(arr, size)
|
||||
self.assertTrue(
|
||||
np_all(arr == srcarr),
|
||||
"size: %i\n%s\n%s" % (size, arr, test_data),
|
||||
)
|
||||
finally:
|
||||
pygame.mixer.quit()
|
||||
|
||||
check_array(8, 1, [0, 0x0F, 0xF0, 0xFF])
|
||||
check_array(8, 2, [[0, 0x80], [0x2D, 0x41], [0x64, 0xA1], [0xFF, 0x40]])
|
||||
check_array(16, 1, [0, 0x00FF, 0xFF00, 0xFFFF])
|
||||
check_array(
|
||||
16, 2, [[0, 0xFFFF], [0xFFFF, 0], [0x00FF, 0xFF00], [0x0F0F, 0xF0F0]]
|
||||
)
|
||||
check_array(-8, 1, [0, -0x80, 0x7F, 0x64])
|
||||
check_array(-8, 2, [[0, -0x80], [-0x64, 0x64], [0x25, -0x50], [0x7F, 0]])
|
||||
check_array(-16, 1, [0, 0x7FFF, -0x7FFF, -1])
|
||||
check_array(-16, 2, [[0, -0x7FFF], [-0x7FFF, 0], [0x7FFF, 0], [0, 0x7FFF]])
|
||||
|
||||
def test_get_arraytype(self):
|
||||
array_type = pygame.sndarray.get_arraytype()
|
||||
|
||||
self.assertEqual(array_type, "numpy", f"unknown array type {array_type}")
|
||||
|
||||
def test_get_arraytypes(self):
|
||||
arraytypes = pygame.sndarray.get_arraytypes()
|
||||
self.assertIn("numpy", arraytypes)
|
||||
|
||||
for atype in arraytypes:
|
||||
self.assertEqual(atype, "numpy", f"unknown array type {atype}")
|
||||
|
||||
def test_make_sound(self):
|
||||
def check_sound(size, channels, test_data):
|
||||
try:
|
||||
pygame.mixer.init(22050, size, channels, allowedchanges=0)
|
||||
except pygame.error:
|
||||
# Not all sizes are supported on all systems.
|
||||
return
|
||||
try:
|
||||
__, sz, __ = pygame.mixer.get_init()
|
||||
if sz == size:
|
||||
srcarr = array(test_data, self.array_dtypes[size])
|
||||
snd = pygame.sndarray.make_sound(srcarr)
|
||||
arr = pygame.sndarray.samples(snd)
|
||||
self.assertTrue(
|
||||
np_all(arr == srcarr),
|
||||
"size: %i\n%s\n%s" % (size, arr, test_data),
|
||||
)
|
||||
finally:
|
||||
pygame.mixer.quit()
|
||||
|
||||
check_sound(8, 1, [0, 0x0F, 0xF0, 0xFF])
|
||||
check_sound(8, 2, [[0, 0x80], [0x2D, 0x41], [0x64, 0xA1], [0xFF, 0x40]])
|
||||
check_sound(16, 1, [0, 0x00FF, 0xFF00, 0xFFFF])
|
||||
check_sound(
|
||||
16, 2, [[0, 0xFFFF], [0xFFFF, 0], [0x00FF, 0xFF00], [0x0F0F, 0xF0F0]]
|
||||
)
|
||||
check_sound(-8, 1, [0, -0x80, 0x7F, 0x64])
|
||||
check_sound(-8, 2, [[0, -0x80], [-0x64, 0x64], [0x25, -0x50], [0x7F, 0]])
|
||||
check_sound(-16, 1, [0, 0x7FFF, -0x7FFF, -1])
|
||||
check_sound(-16, 2, [[0, -0x7FFF], [-0x7FFF, 0], [0x7FFF, 0], [0, 0x7FFF]])
|
||||
check_sound(32, 2, [[0.0, -1.0], [-1.0, 0], [1.0, 0], [0, 1.0]])
|
||||
|
||||
def test_samples(self):
|
||||
null_byte = b"\x00"
|
||||
|
||||
def check_sample(size, channels, test_data):
|
||||
try:
|
||||
pygame.mixer.init(22050, size, channels, allowedchanges=0)
|
||||
except pygame.error:
|
||||
# Not all sizes are supported on all systems.
|
||||
return
|
||||
try:
|
||||
__, sz, __ = pygame.mixer.get_init()
|
||||
if sz == size:
|
||||
zeroed = null_byte * ((abs(size) // 8) * len(test_data) * channels)
|
||||
snd = pygame.mixer.Sound(buffer=zeroed)
|
||||
samples = pygame.sndarray.samples(snd)
|
||||
self._assert_compatible(samples, size)
|
||||
##print('X %s' % (samples.shape,))
|
||||
##print('Y %s' % (test_data,))
|
||||
samples[...] = test_data
|
||||
arr = pygame.sndarray.array(snd)
|
||||
self.assertTrue(
|
||||
np_all(samples == arr),
|
||||
"size: %i\n%s\n%s" % (size, arr, test_data),
|
||||
)
|
||||
finally:
|
||||
pygame.mixer.quit()
|
||||
|
||||
check_sample(8, 1, [0, 0x0F, 0xF0, 0xFF])
|
||||
check_sample(8, 2, [[0, 0x80], [0x2D, 0x41], [0x64, 0xA1], [0xFF, 0x40]])
|
||||
check_sample(16, 1, [0, 0x00FF, 0xFF00, 0xFFFF])
|
||||
check_sample(
|
||||
16, 2, [[0, 0xFFFF], [0xFFFF, 0], [0x00FF, 0xFF00], [0x0F0F, 0xF0F0]]
|
||||
)
|
||||
check_sample(-8, 1, [0, -0x80, 0x7F, 0x64])
|
||||
check_sample(-8, 2, [[0, -0x80], [-0x64, 0x64], [0x25, -0x50], [0x7F, 0]])
|
||||
check_sample(-16, 1, [0, 0x7FFF, -0x7FFF, -1])
|
||||
check_sample(-16, 2, [[0, -0x7FFF], [-0x7FFF, 0], [0x7FFF, 0], [0, 0x7FFF]])
|
||||
check_sample(32, 2, [[0.0, -1.0], [-1.0, 0], [1.0, 0], [0, 1.0]])
|
||||
|
||||
def test_use_arraytype(self):
|
||||
def do_use_arraytype(atype):
|
||||
pygame.sndarray.use_arraytype(atype)
|
||||
|
||||
pygame.sndarray.use_arraytype("numpy")
|
||||
self.assertEqual(pygame.sndarray.get_arraytype(), "numpy")
|
||||
|
||||
self.assertRaises(ValueError, do_use_arraytype, "not an option")
|
||||
|
||||
def test_float32(self):
|
||||
"""sized arrays work with Sounds and 32bit float arrays."""
|
||||
try:
|
||||
pygame.mixer.init(22050, 32, 2, allowedchanges=0)
|
||||
except pygame.error:
|
||||
# Not all sizes are supported on all systems.
|
||||
self.skipTest("unsupported mixer configuration")
|
||||
|
||||
arr = array([[0.0, -1.0], [-1.0, 0], [1.0, 0], [0, 1.0]], float32)
|
||||
newsound = pygame.mixer.Sound(array=arr)
|
||||
pygame.mixer.quit()
|
||||
|
||||
|
||||
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,11 @@
|
||||
__tags__ = ["array"]
|
||||
|
||||
exclude = False
|
||||
|
||||
try:
|
||||
import numpy
|
||||
except ImportError:
|
||||
exclude = True
|
||||
|
||||
if exclude:
|
||||
__tags__.extend(("ignore", "subprocess_ignore"))
|
||||
@@ -0,0 +1,733 @@
|
||||
import platform
|
||||
import unittest
|
||||
|
||||
import pygame
|
||||
import pygame.surfarray
|
||||
from numpy import (
|
||||
__version__ as np_version,
|
||||
all as np_all,
|
||||
arange,
|
||||
float32,
|
||||
float64,
|
||||
rint,
|
||||
uint8,
|
||||
uint16,
|
||||
uint32,
|
||||
uint64,
|
||||
zeros,
|
||||
)
|
||||
from pygame.locals import *
|
||||
|
||||
IS_PYPY = "PyPy" == platform.python_implementation()
|
||||
|
||||
|
||||
@unittest.skipIf(IS_PYPY, "pypy skip known failure") # TODO
|
||||
class SurfarrayModuleTest(unittest.TestCase):
|
||||
pixels2d = {8: True, 16: True, 24: False, 32: True}
|
||||
pixels3d = {8: False, 16: False, 24: True, 32: True}
|
||||
array2d = {8: True, 16: True, 24: True, 32: True}
|
||||
array3d = {8: False, 16: False, 24: True, 32: True}
|
||||
|
||||
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),
|
||||
]
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
# Needed for 8 bits-per-pixel color palette surface tests.
|
||||
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 _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 _assert_surface(self, surf, palette=None, msg=""):
|
||||
if palette is None:
|
||||
palette = self.test_palette
|
||||
if surf.get_bitsize() == 16:
|
||||
palette = [surf.unmap_rgb(surf.map_rgb(c)) for c in palette]
|
||||
for posn, i in self.test_points:
|
||||
self.assertEqual(
|
||||
surf.get_at(posn),
|
||||
palette[i],
|
||||
"%s != %s: flags: %i, bpp: %i, posn: %s%s"
|
||||
% (
|
||||
surf.get_at(posn),
|
||||
palette[i],
|
||||
surf.get_flags(),
|
||||
surf.get_bitsize(),
|
||||
posn,
|
||||
msg,
|
||||
),
|
||||
)
|
||||
|
||||
def _make_array3d(self, dtype):
|
||||
return zeros((self.surf_size[0], self.surf_size[1], 3), dtype)
|
||||
|
||||
def _fill_array2d(self, arr, surf):
|
||||
palette = self.test_palette
|
||||
arr[:5, :6] = surf.map_rgb(palette[1])
|
||||
arr[5:, :6] = surf.map_rgb(palette[2])
|
||||
arr[:5, 6:] = surf.map_rgb(palette[3])
|
||||
arr[5:, 6:] = surf.map_rgb(palette[4])
|
||||
|
||||
def _fill_array3d(self, arr):
|
||||
palette = self.test_palette
|
||||
arr[:5, :6] = palette[1][:3]
|
||||
arr[5:, :6] = palette[2][:3]
|
||||
arr[:5, 6:] = palette[3][:3]
|
||||
arr[5:, 6:] = palette[4][:3]
|
||||
|
||||
def _make_src_array3d(self, dtype):
|
||||
arr = self._make_array3d(dtype)
|
||||
self._fill_array3d(arr)
|
||||
return arr
|
||||
|
||||
def _make_array2d(self, dtype):
|
||||
return zeros(self.surf_size, dtype)
|
||||
|
||||
def test_array2d(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),
|
||||
]
|
||||
palette = self.test_palette
|
||||
alpha_color = (0, 0, 0, 128)
|
||||
|
||||
for surf in sources:
|
||||
arr = pygame.surfarray.array2d(surf)
|
||||
for posn, i in self.test_points:
|
||||
self.assertEqual(
|
||||
arr[posn],
|
||||
surf.get_at_mapped(posn),
|
||||
"%s != %s: flags: %i, bpp: %i, posn: %s"
|
||||
% (
|
||||
arr[posn],
|
||||
surf.get_at_mapped(posn),
|
||||
surf.get_flags(),
|
||||
surf.get_bitsize(),
|
||||
posn,
|
||||
),
|
||||
)
|
||||
|
||||
if surf.get_masks()[3]:
|
||||
surf.fill(alpha_color)
|
||||
arr = pygame.surfarray.array2d(surf)
|
||||
posn = (0, 0)
|
||||
self.assertEqual(
|
||||
arr[posn],
|
||||
surf.get_at_mapped(posn),
|
||||
"%s != %s: bpp: %i"
|
||||
% (arr[posn], surf.get_at_mapped(posn), surf.get_bitsize()),
|
||||
)
|
||||
|
||||
def test_array3d(self):
|
||||
sources = [
|
||||
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),
|
||||
]
|
||||
palette = self.test_palette
|
||||
|
||||
for surf in sources:
|
||||
arr = pygame.surfarray.array3d(surf)
|
||||
|
||||
def same_color(ac, sc):
|
||||
return ac[0] == sc[0] and ac[1] == sc[1] and ac[2] == sc[2]
|
||||
|
||||
for posn, i in self.test_points:
|
||||
self.assertTrue(
|
||||
same_color(arr[posn], surf.get_at(posn)),
|
||||
"%s != %s: flags: %i, bpp: %i, posn: %s"
|
||||
% (
|
||||
tuple(arr[posn]),
|
||||
surf.get_at(posn),
|
||||
surf.get_flags(),
|
||||
surf.get_bitsize(),
|
||||
posn,
|
||||
),
|
||||
)
|
||||
|
||||
def test_array_alpha(self):
|
||||
palette = [
|
||||
(0, 0, 0, 0),
|
||||
(10, 50, 100, 255),
|
||||
(60, 120, 240, 130),
|
||||
(64, 128, 255, 0),
|
||||
(255, 128, 0, 65),
|
||||
]
|
||||
targets = [
|
||||
self._make_src_surface(8, palette=palette),
|
||||
self._make_src_surface(16, palette=palette),
|
||||
self._make_src_surface(16, palette=palette, srcalpha=True),
|
||||
self._make_src_surface(24, palette=palette),
|
||||
self._make_src_surface(32, palette=palette),
|
||||
self._make_src_surface(32, palette=palette, srcalpha=True),
|
||||
]
|
||||
|
||||
for surf in targets:
|
||||
p = palette
|
||||
if surf.get_bitsize() == 16:
|
||||
p = [surf.unmap_rgb(surf.map_rgb(c)) for c in p]
|
||||
arr = pygame.surfarray.array_alpha(surf)
|
||||
if surf.get_masks()[3]:
|
||||
for (x, y), i in self.test_points:
|
||||
self.assertEqual(
|
||||
arr[x, y],
|
||||
p[i][3],
|
||||
(
|
||||
"%i != %i, posn: (%i, %i), "
|
||||
"bitsize: %i"
|
||||
% (arr[x, y], p[i][3], x, y, surf.get_bitsize())
|
||||
),
|
||||
)
|
||||
else:
|
||||
self.assertTrue(np_all(arr == 255))
|
||||
|
||||
# No per-pixel alpha when blanket alpha is None.
|
||||
for surf in targets:
|
||||
blanket_alpha = surf.get_alpha()
|
||||
surf.set_alpha(None)
|
||||
arr = pygame.surfarray.array_alpha(surf)
|
||||
self.assertTrue(
|
||||
np_all(arr == 255),
|
||||
"All alpha values should be 255 when"
|
||||
" surf.set_alpha(None) has been set."
|
||||
" bitsize: %i, flags: %i" % (surf.get_bitsize(), surf.get_flags()),
|
||||
)
|
||||
surf.set_alpha(blanket_alpha)
|
||||
|
||||
# Bug for per-pixel alpha surface when blanket alpha 0.
|
||||
for surf in targets:
|
||||
blanket_alpha = surf.get_alpha()
|
||||
surf.set_alpha(0)
|
||||
arr = pygame.surfarray.array_alpha(surf)
|
||||
if surf.get_masks()[3]:
|
||||
self.assertFalse(
|
||||
np_all(arr == 255),
|
||||
"bitsize: %i, flags: %i" % (surf.get_bitsize(), surf.get_flags()),
|
||||
)
|
||||
else:
|
||||
self.assertTrue(
|
||||
np_all(arr == 255),
|
||||
"bitsize: %i, flags: %i" % (surf.get_bitsize(), surf.get_flags()),
|
||||
)
|
||||
surf.set_alpha(blanket_alpha)
|
||||
|
||||
def test_array_colorkey(self):
|
||||
palette = [
|
||||
(0, 0, 0, 0),
|
||||
(10, 50, 100, 255),
|
||||
(60, 120, 240, 130),
|
||||
(64, 128, 255, 0),
|
||||
(255, 128, 0, 65),
|
||||
]
|
||||
targets = [
|
||||
self._make_src_surface(8, palette=palette),
|
||||
self._make_src_surface(16, palette=palette),
|
||||
self._make_src_surface(16, palette=palette, srcalpha=True),
|
||||
self._make_src_surface(24, palette=palette),
|
||||
self._make_src_surface(32, palette=palette),
|
||||
self._make_src_surface(32, palette=palette, srcalpha=True),
|
||||
]
|
||||
|
||||
for surf in targets:
|
||||
p = palette
|
||||
if surf.get_bitsize() == 16:
|
||||
p = [surf.unmap_rgb(surf.map_rgb(c)) for c in p]
|
||||
surf.set_colorkey(None)
|
||||
arr = pygame.surfarray.array_colorkey(surf)
|
||||
self.assertTrue(np_all(arr == 255))
|
||||
|
||||
for i in range(1, len(palette)):
|
||||
surf.set_colorkey(p[i])
|
||||
alphas = [255] * len(p)
|
||||
alphas[i] = 0
|
||||
arr = pygame.surfarray.array_colorkey(surf)
|
||||
for (x, y), j in self.test_points:
|
||||
self.assertEqual(
|
||||
arr[x, y],
|
||||
alphas[j],
|
||||
(
|
||||
"%i != %i, posn: (%i, %i), "
|
||||
"bitsize: %i"
|
||||
% (arr[x, y], alphas[j], x, y, surf.get_bitsize())
|
||||
),
|
||||
)
|
||||
|
||||
def test_array_red(self):
|
||||
self._test_array_rgb("red", 0)
|
||||
|
||||
def test_array_green(self):
|
||||
self._test_array_rgb("green", 1)
|
||||
|
||||
def test_array_blue(self):
|
||||
self._test_array_rgb("blue", 2)
|
||||
|
||||
def _test_array_rgb(self, operation, mask_posn):
|
||||
method_name = "array_" + operation
|
||||
|
||||
array_rgb = getattr(pygame.surfarray, method_name)
|
||||
palette = [
|
||||
(0, 0, 0, 255),
|
||||
(5, 13, 23, 255),
|
||||
(29, 31, 37, 255),
|
||||
(131, 157, 167, 255),
|
||||
(179, 191, 251, 255),
|
||||
]
|
||||
plane = [c[mask_posn] for c in palette]
|
||||
|
||||
targets = [
|
||||
self._make_src_surface(24, palette=palette),
|
||||
self._make_src_surface(32, palette=palette),
|
||||
self._make_src_surface(32, palette=palette, srcalpha=True),
|
||||
]
|
||||
|
||||
for surf in targets:
|
||||
self.assertFalse(surf.get_locked())
|
||||
for (x, y), i in self.test_points:
|
||||
surf.fill(palette[i])
|
||||
arr = array_rgb(surf)
|
||||
self.assertEqual(arr[x, y], plane[i])
|
||||
surf.fill((100, 100, 100, 250))
|
||||
self.assertEqual(arr[x, y], plane[i])
|
||||
self.assertFalse(surf.get_locked())
|
||||
del arr
|
||||
|
||||
def test_blit_array(self):
|
||||
s = pygame.Surface((10, 10), 0, 24)
|
||||
a = pygame.surfarray.array3d(s)
|
||||
pygame.surfarray.blit_array(s, a)
|
||||
|
||||
# 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),
|
||||
]
|
||||
|
||||
# source arrays
|
||||
arrays3d = []
|
||||
dtypes = [(8, uint8), (16, uint16), (32, uint32)]
|
||||
try:
|
||||
dtypes.append((64, uint64))
|
||||
except NameError:
|
||||
pass
|
||||
arrays3d = [(self._make_src_array3d(dtype), None) for __, dtype in dtypes]
|
||||
for bitsize in [8, 16, 24, 32]:
|
||||
palette = None
|
||||
if bitsize == 16:
|
||||
s = pygame.Surface((1, 1), 0, 16)
|
||||
palette = [s.unmap_rgb(s.map_rgb(c)) for c in self.test_palette]
|
||||
if self.pixels3d[bitsize]:
|
||||
surf = self._make_src_surface(bitsize)
|
||||
arr = pygame.surfarray.pixels3d(surf)
|
||||
arrays3d.append((arr, palette))
|
||||
if self.array3d[bitsize]:
|
||||
surf = self._make_src_surface(bitsize)
|
||||
arr = pygame.surfarray.array3d(surf)
|
||||
arrays3d.append((arr, palette))
|
||||
for sz, dtype in dtypes:
|
||||
arrays3d.append((arr.astype(dtype), palette))
|
||||
|
||||
# tests on arrays
|
||||
def do_blit(surf, arr):
|
||||
pygame.surfarray.blit_array(surf, arr)
|
||||
|
||||
for surf in targets:
|
||||
bitsize = surf.get_bitsize()
|
||||
for arr, palette in arrays3d:
|
||||
surf.fill((0, 0, 0, 0))
|
||||
if bitsize == 8:
|
||||
self.assertRaises(ValueError, do_blit, surf, arr)
|
||||
else:
|
||||
pygame.surfarray.blit_array(surf, arr)
|
||||
self._assert_surface(surf, palette)
|
||||
|
||||
if self.pixels2d[bitsize]:
|
||||
surf.fill((0, 0, 0, 0))
|
||||
s = self._make_src_surface(bitsize, surf.get_flags() & SRCALPHA)
|
||||
arr = pygame.surfarray.pixels2d(s)
|
||||
pygame.surfarray.blit_array(surf, arr)
|
||||
self._assert_surface(surf)
|
||||
|
||||
if self.array2d[bitsize]:
|
||||
s = self._make_src_surface(bitsize, surf.get_flags() & SRCALPHA)
|
||||
arr = pygame.surfarray.array2d(s)
|
||||
for sz, dtype in dtypes:
|
||||
surf.fill((0, 0, 0, 0))
|
||||
if sz >= bitsize:
|
||||
pygame.surfarray.blit_array(surf, arr.astype(dtype))
|
||||
self._assert_surface(surf)
|
||||
else:
|
||||
self.assertRaises(
|
||||
ValueError, do_blit, surf, self._make_array2d(dtype)
|
||||
)
|
||||
|
||||
# Check alpha for 2D arrays
|
||||
surf = self._make_surface(16, srcalpha=True)
|
||||
arr = zeros(surf.get_size(), uint16)
|
||||
arr[...] = surf.map_rgb((0, 128, 255, 64))
|
||||
color = surf.unmap_rgb(arr[0, 0])
|
||||
pygame.surfarray.blit_array(surf, arr)
|
||||
self.assertEqual(surf.get_at((5, 5)), color)
|
||||
|
||||
surf = self._make_surface(32, srcalpha=True)
|
||||
arr = zeros(surf.get_size(), uint32)
|
||||
color = (0, 111, 255, 63)
|
||||
arr[...] = surf.map_rgb(color)
|
||||
pygame.surfarray.blit_array(surf, arr)
|
||||
self.assertEqual(surf.get_at((5, 5)), color)
|
||||
|
||||
# Check shifts
|
||||
arr3d = self._make_src_array3d(uint8)
|
||||
|
||||
shift_tests = [
|
||||
(16, [12, 0, 8, 4], [0xF000, 0xF, 0xF00, 0xF0]),
|
||||
(24, [16, 0, 8, 0], [0xFF0000, 0xFF, 0xFF00, 0]),
|
||||
(32, [0, 16, 24, 8], [0xFF, 0xFF0000, 0xFF000000, 0xFF00]),
|
||||
]
|
||||
|
||||
for bitsize, shifts, masks in shift_tests:
|
||||
surf = self._make_surface(bitsize, srcalpha=(shifts[3] != 0))
|
||||
palette = None
|
||||
if bitsize == 16:
|
||||
palette = [surf.unmap_rgb(surf.map_rgb(c)) for c in self.test_palette]
|
||||
|
||||
self.assertRaises(TypeError, surf.set_shifts, shifts)
|
||||
self.assertRaises(TypeError, surf.set_masks, masks)
|
||||
|
||||
# Invalid arrays
|
||||
surf = pygame.Surface((1, 1), 0, 32)
|
||||
t = "abcd"
|
||||
self.assertRaises(ValueError, do_blit, surf, t)
|
||||
|
||||
surf_size = self.surf_size
|
||||
surf = pygame.Surface(surf_size, 0, 32)
|
||||
arr = zeros([surf_size[0], surf_size[1] + 1, 3], uint32)
|
||||
self.assertRaises(ValueError, do_blit, surf, arr)
|
||||
arr = zeros([surf_size[0] + 1, surf_size[1], 3], uint32)
|
||||
self.assertRaises(ValueError, do_blit, surf, arr)
|
||||
|
||||
surf = pygame.Surface((1, 4), 0, 32)
|
||||
arr = zeros((4,), uint32)
|
||||
self.assertRaises(ValueError, do_blit, surf, arr)
|
||||
arr.shape = (1, 1, 1, 4)
|
||||
self.assertRaises(ValueError, do_blit, surf, arr)
|
||||
|
||||
# pygame-ce issue #96: round from float to int
|
||||
surf = pygame.Surface((10, 10), pygame.SRCALPHA, 32)
|
||||
w, h = surf.get_size()
|
||||
length = w * h
|
||||
for dtype in [float32, float64]:
|
||||
surf.fill((255, 255, 255, 0))
|
||||
farr = arange(0, length, dtype=dtype)
|
||||
farr.shape = w, h
|
||||
pygame.surfarray.blit_array(surf, farr)
|
||||
for x in range(w):
|
||||
for y in range(h):
|
||||
self.assertEqual(surf.get_at_mapped((x, y)), int(rint(farr[x, y])))
|
||||
|
||||
# this test should be removed soon, when the function is deleted
|
||||
def test_get_arraytype(self):
|
||||
with self.assertWarns(DeprecationWarning):
|
||||
array_type = pygame.surfarray.get_arraytype()
|
||||
|
||||
self.assertEqual(array_type, "numpy", f"unknown array type {array_type}")
|
||||
|
||||
# this test should be removed soon, when the function is deleted
|
||||
def test_get_arraytypes(self):
|
||||
with self.assertWarns(DeprecationWarning):
|
||||
arraytypes = pygame.surfarray.get_arraytypes()
|
||||
self.assertIn("numpy", arraytypes)
|
||||
|
||||
for atype in arraytypes:
|
||||
self.assertEqual(atype, "numpy", f"unknown array type {atype}")
|
||||
|
||||
def test_make_surface(self):
|
||||
# How does one properly test this with 2d arrays. It makes no sense
|
||||
# since the pixel format is not entirely dependent on element size.
|
||||
# Just make sure the surface pixel size is at least as large as the
|
||||
# array element size I guess.
|
||||
#
|
||||
for bitsize, dtype in [(8, uint8), (16, uint16), (24, uint32)]:
|
||||
## Even this simple assertion fails for 2d arrays. Where's the problem?
|
||||
## surf = pygame.surfarray.make_surface(self._make_array2d(dtype))
|
||||
## self.assertGreaterEqual(surf.get_bitsize(), bitsize,
|
||||
## "not %i >= %i)" % (surf.get_bitsize(), bitsize))
|
||||
##
|
||||
surf = pygame.surfarray.make_surface(self._make_src_array3d(dtype))
|
||||
self._assert_surface(surf)
|
||||
|
||||
# pygame-ce issue #96: round from float to int
|
||||
w = 9
|
||||
h = 11
|
||||
length = w * h
|
||||
for dtype in [float32, float64]:
|
||||
farr = arange(0, length, dtype=dtype)
|
||||
farr.shape = w, h
|
||||
surf = pygame.surfarray.make_surface(farr)
|
||||
for x in range(w):
|
||||
for y in range(h):
|
||||
self.assertEqual(surf.get_at_mapped((x, y)), int(rint(farr[x, y])))
|
||||
|
||||
def test_map_array(self):
|
||||
arr3d = self._make_src_array3d(uint8)
|
||||
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),
|
||||
]
|
||||
palette = self.test_palette
|
||||
|
||||
for surf in targets:
|
||||
arr2d = pygame.surfarray.map_array(surf, arr3d)
|
||||
for posn, i in self.test_points:
|
||||
self.assertEqual(
|
||||
arr2d[posn],
|
||||
surf.map_rgb(palette[i]),
|
||||
"%i != %i, bitsize: %i, flags: %i"
|
||||
% (
|
||||
arr2d[posn],
|
||||
surf.map_rgb(palette[i]),
|
||||
surf.get_bitsize(),
|
||||
surf.get_flags(),
|
||||
),
|
||||
)
|
||||
|
||||
# Exception checks
|
||||
self.assertRaises(
|
||||
ValueError,
|
||||
pygame.surfarray.map_array,
|
||||
self._make_surface(32),
|
||||
self._make_array2d(uint8),
|
||||
)
|
||||
|
||||
@unittest.skipIf(
|
||||
int(np_version.split(".")[0]) >= 2,
|
||||
"This test fails due to a change in numpy 2.0.0, and a 'proper fix' "
|
||||
"requires an API/behaviour change",
|
||||
)
|
||||
def test_pixels2d(self):
|
||||
sources = [
|
||||
self._make_surface(8),
|
||||
self._make_surface(16, srcalpha=True),
|
||||
self._make_surface(32, srcalpha=True),
|
||||
]
|
||||
|
||||
for surf in sources:
|
||||
self.assertFalse(surf.get_locked())
|
||||
arr = pygame.surfarray.pixels2d(surf)
|
||||
self.assertTrue(surf.get_locked())
|
||||
self._fill_array2d(arr, surf)
|
||||
surf.unlock()
|
||||
self.assertTrue(surf.get_locked())
|
||||
del arr
|
||||
self.assertFalse(surf.get_locked())
|
||||
self.assertEqual(surf.get_locks(), ())
|
||||
self._assert_surface(surf)
|
||||
|
||||
# Error checks
|
||||
self.assertRaises(ValueError, pygame.surfarray.pixels2d, self._make_surface(24))
|
||||
|
||||
def test_pixels3d(self):
|
||||
sources = [self._make_surface(24), self._make_surface(32)]
|
||||
|
||||
for surf in sources:
|
||||
self.assertFalse(surf.get_locked())
|
||||
arr = pygame.surfarray.pixels3d(surf)
|
||||
self.assertTrue(surf.get_locked())
|
||||
self._fill_array3d(arr)
|
||||
surf.unlock()
|
||||
self.assertTrue(surf.get_locked())
|
||||
del arr
|
||||
self.assertFalse(surf.get_locked())
|
||||
self.assertEqual(surf.get_locks(), ())
|
||||
self._assert_surface(surf)
|
||||
|
||||
# Alpha check
|
||||
color = (1, 2, 3, 0)
|
||||
surf = self._make_surface(32, srcalpha=True)
|
||||
arr = pygame.surfarray.pixels3d(surf)
|
||||
arr[0, 0] = color[:3]
|
||||
self.assertEqual(surf.get_at((0, 0)), color)
|
||||
|
||||
# Error checks
|
||||
def do_pixels3d(surf):
|
||||
pygame.surfarray.pixels3d(surf)
|
||||
|
||||
self.assertRaises(ValueError, do_pixels3d, self._make_surface(8))
|
||||
self.assertRaises(ValueError, do_pixels3d, self._make_surface(16))
|
||||
|
||||
def test_pixels_alpha(self):
|
||||
palette = [
|
||||
(0, 0, 0, 0),
|
||||
(127, 127, 127, 0),
|
||||
(127, 127, 127, 85),
|
||||
(127, 127, 127, 170),
|
||||
(127, 127, 127, 255),
|
||||
]
|
||||
alphas = [0, 45, 86, 99, 180]
|
||||
|
||||
surf = self._make_src_surface(32, srcalpha=True, palette=palette)
|
||||
|
||||
self.assertFalse(surf.get_locked())
|
||||
arr = pygame.surfarray.pixels_alpha(surf)
|
||||
self.assertTrue(surf.get_locked())
|
||||
surf.unlock()
|
||||
self.assertTrue(surf.get_locked())
|
||||
|
||||
for (x, y), i in self.test_points:
|
||||
self.assertEqual(arr[x, y], palette[i][3])
|
||||
|
||||
for (x, y), i in self.test_points:
|
||||
alpha = alphas[i]
|
||||
arr[x, y] = alpha
|
||||
color = (127, 127, 127, alpha)
|
||||
self.assertEqual(surf.get_at((x, y)), color, "posn: (%i, %i)" % (x, y))
|
||||
|
||||
del arr
|
||||
self.assertFalse(surf.get_locked())
|
||||
self.assertEqual(surf.get_locks(), ())
|
||||
|
||||
# Check exceptions.
|
||||
def do_pixels_alpha(surf):
|
||||
pygame.surfarray.pixels_alpha(surf)
|
||||
|
||||
targets = [(8, False), (16, False), (16, True), (24, False), (32, False)]
|
||||
|
||||
for bitsize, srcalpha in targets:
|
||||
self.assertRaises(
|
||||
ValueError, do_pixels_alpha, self._make_surface(bitsize, srcalpha)
|
||||
)
|
||||
|
||||
def test_pixels_red(self):
|
||||
self._test_pixels_rgb("red", 0)
|
||||
|
||||
def test_pixels_green(self):
|
||||
self._test_pixels_rgb("green", 1)
|
||||
|
||||
def test_pixels_blue(self):
|
||||
self._test_pixels_rgb("blue", 2)
|
||||
|
||||
def _test_pixels_rgb(self, operation, mask_posn):
|
||||
method_name = "pixels_" + operation
|
||||
|
||||
pixels_rgb = getattr(pygame.surfarray, method_name)
|
||||
palette = [
|
||||
(0, 0, 0, 255),
|
||||
(5, 13, 23, 255),
|
||||
(29, 31, 37, 255),
|
||||
(131, 157, 167, 255),
|
||||
(179, 191, 251, 255),
|
||||
]
|
||||
plane = [c[mask_posn] for c in palette]
|
||||
|
||||
surf24 = self._make_src_surface(24, srcalpha=False, palette=palette)
|
||||
surf32 = self._make_src_surface(32, srcalpha=False, palette=palette)
|
||||
surf32a = self._make_src_surface(32, srcalpha=True, palette=palette)
|
||||
|
||||
for surf in [surf24, surf32, surf32a]:
|
||||
self.assertFalse(surf.get_locked())
|
||||
arr = pixels_rgb(surf)
|
||||
self.assertTrue(surf.get_locked())
|
||||
surf.unlock()
|
||||
self.assertTrue(surf.get_locked())
|
||||
|
||||
for (x, y), i in self.test_points:
|
||||
self.assertEqual(arr[x, y], plane[i])
|
||||
|
||||
del arr
|
||||
self.assertFalse(surf.get_locked())
|
||||
self.assertEqual(surf.get_locks(), ())
|
||||
|
||||
# Check exceptions.
|
||||
targets = [(8, False), (16, False), (16, True)]
|
||||
|
||||
for bitsize, srcalpha in targets:
|
||||
self.assertRaises(
|
||||
ValueError, pixels_rgb, self._make_surface(bitsize, srcalpha)
|
||||
)
|
||||
|
||||
def test_use_arraytype(self):
|
||||
def do_use_arraytype(atype):
|
||||
pygame.surfarray.use_arraytype(atype)
|
||||
|
||||
with self.assertWarns(DeprecationWarning):
|
||||
pygame.surfarray.use_arraytype("numpy")
|
||||
self.assertEqual(pygame.surfarray.get_arraytype(), "numpy")
|
||||
self.assertRaises(ValueError, do_use_arraytype, "not an option")
|
||||
|
||||
def test_surf_lock(self):
|
||||
sf = pygame.Surface((5, 5), 0, 32)
|
||||
|
||||
ar = pygame.surfarray.pixels2d(sf)
|
||||
self.assertTrue(sf.get_locked())
|
||||
|
||||
sf.unlock()
|
||||
self.assertTrue(sf.get_locked())
|
||||
|
||||
del ar
|
||||
self.assertFalse(sf.get_locked())
|
||||
self.assertEqual(sf.get_locks(), ())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,144 @@
|
||||
import platform
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import pygame
|
||||
|
||||
IS_PYPY = "PyPy" == platform.python_implementation()
|
||||
|
||||
|
||||
@unittest.skipIf(IS_PYPY, "pypy skip known failure") # TODO
|
||||
class SurfaceLockTest(unittest.TestCase):
|
||||
def test_lock(self):
|
||||
sf = pygame.Surface((5, 5))
|
||||
|
||||
sf.lock()
|
||||
self.assertEqual(sf.get_locked(), True)
|
||||
self.assertEqual(sf.get_locks(), (sf,))
|
||||
|
||||
sf.lock()
|
||||
self.assertEqual(sf.get_locked(), True)
|
||||
self.assertEqual(sf.get_locks(), (sf, sf))
|
||||
|
||||
sf.unlock()
|
||||
self.assertEqual(sf.get_locked(), True)
|
||||
self.assertEqual(sf.get_locks(), (sf,))
|
||||
|
||||
sf.unlock()
|
||||
self.assertEqual(sf.get_locked(), False)
|
||||
self.assertEqual(sf.get_locks(), ())
|
||||
|
||||
def test_subsurface_lock(self):
|
||||
sf = pygame.Surface((5, 5))
|
||||
subsf = sf.subsurface((1, 1, 2, 2))
|
||||
sf2 = pygame.Surface((5, 5))
|
||||
|
||||
# Simple blits, nothing should happen here.
|
||||
sf2.blit(subsf, (0, 0))
|
||||
sf2.blit(sf, (0, 0))
|
||||
|
||||
# Test blitting on self:
|
||||
self.assertRaises(pygame.error, sf.blit, subsf, (0, 0))
|
||||
# self.assertRaises(pygame.error, subsf.blit, sf, (0, 0))
|
||||
# ^ Fails although it should not in my opinion. If I cannot
|
||||
# blit the subsurface to the surface, it should not be allowed
|
||||
# the other way around as well.
|
||||
|
||||
# Test additional locks.
|
||||
sf.lock()
|
||||
sf2.blit(subsf, (0, 0))
|
||||
self.assertRaises(pygame.error, sf2.blit, sf, (0, 0))
|
||||
|
||||
subsf.lock()
|
||||
self.assertRaises(pygame.error, sf2.blit, subsf, (0, 0))
|
||||
self.assertRaises(pygame.error, sf2.blit, sf, (0, 0))
|
||||
|
||||
# sf and subsf are now explicitly locked. Unlock sf, so we can
|
||||
# (assume) to blit it.
|
||||
# It will fail though as the subsurface still has a lock around,
|
||||
# which is okay and correct behaviour.
|
||||
sf.unlock()
|
||||
self.assertRaises(pygame.error, sf2.blit, subsf, (0, 0))
|
||||
self.assertRaises(pygame.error, sf2.blit, sf, (0, 0))
|
||||
|
||||
# Run a second unlock on the surface. This should ideally have
|
||||
# no effect as the subsurface is the locking reason!
|
||||
sf.unlock()
|
||||
self.assertRaises(pygame.error, sf2.blit, sf, (0, 0))
|
||||
self.assertRaises(pygame.error, sf2.blit, subsf, (0, 0))
|
||||
subsf.unlock()
|
||||
|
||||
sf.lock()
|
||||
self.assertEqual(sf.get_locked(), True)
|
||||
self.assertEqual(sf.get_locks(), (sf,))
|
||||
self.assertEqual(subsf.get_locked(), False)
|
||||
self.assertEqual(subsf.get_locks(), ())
|
||||
|
||||
subsf.lock()
|
||||
self.assertEqual(sf.get_locked(), True)
|
||||
self.assertEqual(sf.get_locks(), (sf, subsf))
|
||||
self.assertEqual(subsf.get_locked(), True)
|
||||
self.assertEqual(subsf.get_locks(), (subsf,))
|
||||
|
||||
sf.unlock()
|
||||
self.assertEqual(sf.get_locked(), True)
|
||||
self.assertEqual(sf.get_locks(), (subsf,))
|
||||
self.assertEqual(subsf.get_locked(), True)
|
||||
self.assertEqual(subsf.get_locks(), (subsf,))
|
||||
|
||||
subsf.unlock()
|
||||
self.assertEqual(sf.get_locked(), False)
|
||||
self.assertEqual(sf.get_locks(), ())
|
||||
self.assertEqual(subsf.get_locked(), False)
|
||||
self.assertEqual(subsf.get_locks(), ())
|
||||
|
||||
subsf.lock()
|
||||
self.assertEqual(sf.get_locked(), True)
|
||||
self.assertEqual(sf.get_locks(), (subsf,))
|
||||
self.assertEqual(subsf.get_locked(), True)
|
||||
self.assertEqual(subsf.get_locks(), (subsf,))
|
||||
|
||||
subsf.lock()
|
||||
self.assertEqual(sf.get_locked(), True)
|
||||
self.assertEqual(sf.get_locks(), (subsf, subsf))
|
||||
self.assertEqual(subsf.get_locked(), True)
|
||||
self.assertEqual(subsf.get_locks(), (subsf, subsf))
|
||||
|
||||
def test_pxarray_ref(self):
|
||||
sf = pygame.Surface((5, 5))
|
||||
ar = pygame.PixelArray(sf)
|
||||
ar2 = pygame.PixelArray(sf)
|
||||
|
||||
self.assertEqual(sf.get_locked(), True)
|
||||
self.assertEqual(sf.get_locks(), (ar, ar2))
|
||||
|
||||
del ar
|
||||
self.assertEqual(sf.get_locked(), True)
|
||||
self.assertEqual(sf.get_locks(), (ar2,))
|
||||
|
||||
ar = ar2[:]
|
||||
self.assertEqual(sf.get_locked(), True)
|
||||
self.assertEqual(sf.get_locks(), (ar2,))
|
||||
|
||||
del ar
|
||||
self.assertEqual(sf.get_locked(), True)
|
||||
self.assertEqual(len(sf.get_locks()), 1)
|
||||
|
||||
def test_buffer(self):
|
||||
sf = pygame.Surface((5, 5))
|
||||
buf = sf.get_buffer()
|
||||
|
||||
self.assertEqual(sf.get_locked(), True)
|
||||
self.assertEqual(sf.get_locks(), (buf,))
|
||||
|
||||
sf.unlock()
|
||||
self.assertEqual(sf.get_locked(), True)
|
||||
self.assertEqual(sf.get_locks(), (buf,))
|
||||
|
||||
del buf
|
||||
self.assertEqual(sf.get_locked(), False)
|
||||
self.assertEqual(sf.get_locks(), ())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,95 @@
|
||||
import platform
|
||||
import unittest
|
||||
|
||||
|
||||
class SysfontModuleTest(unittest.TestCase):
|
||||
def test_create_aliases(self):
|
||||
import pygame.sysfont
|
||||
|
||||
pygame.sysfont.initsysfonts()
|
||||
pygame.sysfont.create_aliases()
|
||||
self.assertTrue(len(pygame.sysfont.Sysalias) > 0)
|
||||
|
||||
def test_initsysfonts(self):
|
||||
import pygame.sysfont
|
||||
|
||||
pygame.sysfont.initsysfonts()
|
||||
self.assertTrue(len(pygame.sysfont.get_fonts()) > 0)
|
||||
|
||||
@unittest.skipIf("Darwin" not in platform.platform(), "Not mac we skip.")
|
||||
def test_initsysfonts_darwin(self):
|
||||
import pygame.sysfont
|
||||
|
||||
self.assertTrue(len(pygame.sysfont.get_fonts()) > 10)
|
||||
|
||||
def test_sysfont(self):
|
||||
import pygame.font
|
||||
|
||||
pygame.font.init()
|
||||
arial = pygame.font.SysFont("Arial", 40)
|
||||
self.assertTrue(isinstance(arial, pygame.font.Font))
|
||||
|
||||
pygame.font.SysFont(None, 40)
|
||||
|
||||
@unittest.skipIf("Windows" not in platform.platform(), "Just for windows")
|
||||
def test_sysfont_settings(self):
|
||||
import pygame.font
|
||||
|
||||
pygame.font.init()
|
||||
|
||||
# The idea of this test is that we know we can expect Arial bold, Arial italic
|
||||
# Arial, and Arial italic bold to load different fonts on Windows. If that
|
||||
# isn't happening it may indicate a problem like
|
||||
# https://github.com/pygame-community/pygame-ce/issues/2677
|
||||
|
||||
arial = pygame.font.SysFont("Arial", 40)
|
||||
arial_bold = pygame.font.SysFont("Arial", 40, bold=True)
|
||||
arial_italic = pygame.font.SysFont("Arial", 40, italic=True)
|
||||
arial_bold_italic = pygame.font.SysFont("Arial", 40, bold=True, italic=True)
|
||||
|
||||
self.assertNotEqual(arial.style_name, arial_bold.style_name)
|
||||
self.assertNotEqual(arial.style_name, arial_italic.style_name)
|
||||
self.assertNotEqual(arial.style_name, arial_bold_italic.style_name)
|
||||
self.assertNotEqual(arial_bold.style_name, arial_italic.style_name)
|
||||
self.assertNotEqual(arial_italic.style_name, arial_bold_italic.style_name)
|
||||
self.assertNotEqual(arial_bold.style_name, arial_bold_italic.style_name)
|
||||
|
||||
@unittest.skipIf(
|
||||
("Darwin" in platform.platform() or "Windows" in platform.platform()),
|
||||
"Not unix we skip.",
|
||||
)
|
||||
def test_initsysfonts_unix(self):
|
||||
import pygame.sysfont
|
||||
|
||||
self.assertTrue(len(pygame.sysfont.get_fonts()) > 0)
|
||||
|
||||
@unittest.skipIf("Windows" not in platform.platform(), "Not windows we skip.")
|
||||
def test_initsysfonts_win32(self):
|
||||
import pygame.sysfont
|
||||
|
||||
self.assertTrue(len(pygame.sysfont.get_fonts()) > 10)
|
||||
|
||||
def test_sysfont_warnings(self):
|
||||
import pygame.font
|
||||
|
||||
pygame.font.init()
|
||||
|
||||
with self.assertWarns(UserWarning):
|
||||
pygame.font.SysFont("non-existent font", 40)
|
||||
|
||||
with self.assertWarns(UserWarning):
|
||||
pygame.font.SysFont(bytes("non-existent font", "utf-8"), 40)
|
||||
|
||||
with self.assertWarns(UserWarning):
|
||||
pygame.font.SysFont(("non-existent font", "non-existent font2"), 40)
|
||||
|
||||
with self.assertWarns(UserWarning):
|
||||
pygame.font.SysFont(
|
||||
(bytes("non-existent font", "utf-8"), "non-existent font2"), 40
|
||||
)
|
||||
|
||||
|
||||
###############################################################################
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,123 @@
|
||||
import os
|
||||
import unittest
|
||||
|
||||
import pygame
|
||||
|
||||
|
||||
class SystemModuleTest(unittest.TestCase):
|
||||
def test_get_cpu_instruction_sets(self):
|
||||
instruction_sets = pygame.system.get_cpu_instruction_sets()
|
||||
|
||||
for name in instruction_sets:
|
||||
self.assertIsInstance(name, str)
|
||||
self.assertIsInstance(instruction_sets[name], bool)
|
||||
|
||||
def test_get_total_ram(self):
|
||||
ram = pygame.system.get_total_ram()
|
||||
|
||||
self.assertIsInstance(ram, int)
|
||||
|
||||
def test_get_pref_path(self):
|
||||
get_pref_path = pygame.system.get_pref_path
|
||||
|
||||
""" test the argument validation """
|
||||
# wrong arg count
|
||||
self.assertRaises(TypeError, get_pref_path, "one arg")
|
||||
# wrong arg types
|
||||
self.assertRaises(TypeError, get_pref_path, 0, 1)
|
||||
# wrong kwargs
|
||||
self.assertRaises(TypeError, get_pref_path, norg="test", napp="app")
|
||||
# not enough info
|
||||
self.assertRaises(TypeError, get_pref_path, "testorg", org="testorg")
|
||||
|
||||
org = "pygame test organization"
|
||||
app = "the best app"
|
||||
|
||||
# gets the path, creates the folder
|
||||
path = get_pref_path(org, app)
|
||||
try: # try removing the folder, it should work fine
|
||||
os.rmdir(path)
|
||||
except FileNotFoundError: # if the folder isn't found
|
||||
raise FileNotFoundError("pygame.system.get_pref_path folder not created")
|
||||
except OSError: # if the dir isn't empty (shouldn't happen)
|
||||
raise OSError("pygame.system.get_pref_path folder already occupied")
|
||||
|
||||
# gets the path, creates the folder, uses kwargs
|
||||
path = get_pref_path(org=org, app=app)
|
||||
try: # try removing the folder, it should work fine
|
||||
os.rmdir(path)
|
||||
except FileNotFoundError: # if the folder isn't found
|
||||
raise FileNotFoundError("pygame.system.get_pref_path folder not created")
|
||||
except OSError: # if the dir isn't empty (shouldn't happen)
|
||||
raise OSError("pygame.system.get_pref_path folder already occupied")
|
||||
|
||||
def test_get_pref_locales(self):
|
||||
locales = pygame.system.get_pref_locales()
|
||||
|
||||
# check type of return first
|
||||
self.assertIsInstance(locales, list)
|
||||
for lc in locales:
|
||||
self.assertIsInstance(lc, dict)
|
||||
lang = lc["language"]
|
||||
self.assertIsInstance(lang, str)
|
||||
|
||||
# length of language code should be greater than 1
|
||||
self.assertTrue(len(lang) > 1)
|
||||
|
||||
country = lc["country"]
|
||||
if country is not None:
|
||||
# country field is optional, but when defined it should be a
|
||||
# string
|
||||
self.assertIsInstance(country, str)
|
||||
|
||||
# length of country code should be greater than 1
|
||||
self.assertTrue(len(country) > 1)
|
||||
|
||||
# passing args should raise error
|
||||
for arg in (None, 1, "hello"):
|
||||
self.assertRaises(TypeError, pygame.system.get_pref_locales, arg)
|
||||
|
||||
def test_get_power_state(self):
|
||||
power_state = pygame.system.get_power_state()
|
||||
self.assertIsInstance(power_state, (type(None), pygame.system.PowerState))
|
||||
|
||||
expected_types = {
|
||||
"battery_seconds": (type(None), int),
|
||||
"battery_percent": (type(None), int),
|
||||
"on_battery": bool,
|
||||
"no_battery": bool,
|
||||
"charging": bool,
|
||||
"charged": bool,
|
||||
"plugged_in": bool,
|
||||
"has_battery": bool,
|
||||
}
|
||||
|
||||
if power_state is not None:
|
||||
for attr_name in expected_types:
|
||||
self.assertTrue(hasattr(power_state, attr_name))
|
||||
self.assertIsInstance(
|
||||
getattr(power_state, attr_name), expected_types[attr_name]
|
||||
)
|
||||
|
||||
self.assertTrue(power_state.plugged_in == (not power_state.on_battery))
|
||||
self.assertTrue(
|
||||
power_state.has_battery
|
||||
== (power_state.on_battery or not power_state.no_battery)
|
||||
)
|
||||
|
||||
# There should be only one `True`
|
||||
self.assertEqual(
|
||||
sum(
|
||||
[
|
||||
power_state.on_battery,
|
||||
power_state.no_battery,
|
||||
power_state.charged,
|
||||
power_state.charging,
|
||||
]
|
||||
),
|
||||
1,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,180 @@
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
import pygame
|
||||
|
||||
###############################################################################
|
||||
|
||||
|
||||
def tostring(row):
|
||||
"""Convert row of bytes to string. Expects `row` to be an
|
||||
``array``.
|
||||
"""
|
||||
return row.tobytes()
|
||||
|
||||
|
||||
def geterror():
|
||||
return sys.exc_info()[1]
|
||||
|
||||
|
||||
###############################################################################
|
||||
|
||||
this_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
this_dir_parent = os.path.split(this_dir)[0]
|
||||
trunk_dir = os.path.split(this_dir_parent)[0]
|
||||
|
||||
|
||||
def trunk_relative_path(relative):
|
||||
return os.path.normpath(os.path.join(trunk_dir, relative))
|
||||
|
||||
|
||||
def fixture_path(path):
|
||||
return os.path.join(this_dir_parent, "fixtures", path)
|
||||
|
||||
|
||||
def example_path(path):
|
||||
return trunk_relative_path(os.path.join("examples", path))
|
||||
|
||||
|
||||
sys.path.insert(0, trunk_relative_path("."))
|
||||
|
||||
|
||||
################################## TEMP FILES #################################
|
||||
|
||||
|
||||
def get_tmp_dir():
|
||||
return tempfile.mkdtemp()
|
||||
|
||||
|
||||
###############################################################################
|
||||
|
||||
|
||||
def question(q):
|
||||
return input(f"\n{q.rstrip(' ')} (y/n): ").lower().strip() == "y"
|
||||
|
||||
|
||||
def prompt(p):
|
||||
return input(f"\n{p.rstrip(' ')} (press enter to continue): ")
|
||||
|
||||
|
||||
#################################### HELPERS ##################################
|
||||
|
||||
|
||||
def rgba_between(value, minimum=0, maximum=255):
|
||||
if value < minimum:
|
||||
return minimum
|
||||
elif value > maximum:
|
||||
return maximum
|
||||
else:
|
||||
return value
|
||||
|
||||
|
||||
def gradient(width, height):
|
||||
"""
|
||||
|
||||
Yields a pt and corresponding RGBA tuple, for every (width, height) combo.
|
||||
Useful for generating gradients.
|
||||
|
||||
Actual gradient may be changed, no tests rely on specific values.
|
||||
|
||||
Used in transform.rotate lossless tests to generate a fixture.
|
||||
|
||||
"""
|
||||
|
||||
for l in range(width):
|
||||
for t in range(height):
|
||||
yield (l, t), tuple(map(rgba_between, (l, t, l, l + t)))
|
||||
|
||||
|
||||
def rect_area_pts(rect):
|
||||
for l in range(rect.left, rect.right):
|
||||
for t in range(rect.top, rect.bottom):
|
||||
yield l, t
|
||||
|
||||
|
||||
def rect_perimeter_pts(rect):
|
||||
"""
|
||||
|
||||
Returns pts ((L, T) tuples) encompassing the perimeter of a rect.
|
||||
|
||||
The order is clockwise:
|
||||
|
||||
topleft to topright
|
||||
topright to bottomright
|
||||
bottomright to bottomleft
|
||||
bottomleft to topleft
|
||||
|
||||
Duplicate pts are not returned
|
||||
|
||||
"""
|
||||
clock_wise_from_top_left = (
|
||||
[(l, rect.top) for l in range(rect.left, rect.right)],
|
||||
[(rect.right - 1, t) for t in range(rect.top + 1, rect.bottom)],
|
||||
[(l, rect.bottom - 1) for l in range(rect.right - 2, rect.left - 1, -1)],
|
||||
[(rect.left, t) for t in range(rect.bottom - 2, rect.top, -1)],
|
||||
)
|
||||
|
||||
for line in clock_wise_from_top_left:
|
||||
yield from line
|
||||
|
||||
|
||||
def rect_outer_bounds(rect):
|
||||
"""
|
||||
|
||||
Returns topleft outerbound if possible and then the other pts, that are
|
||||
"exclusive" bounds of the rect
|
||||
|
||||
?------O
|
||||
|RECT| ?|0)uterbound
|
||||
|----|
|
||||
O O
|
||||
|
||||
"""
|
||||
return ([(rect.left - 1, rect.top)] if rect.left else []) + [
|
||||
rect.topright,
|
||||
rect.bottomleft,
|
||||
rect.bottomright,
|
||||
]
|
||||
|
||||
|
||||
def import_submodule(module):
|
||||
m = __import__(module)
|
||||
for n in module.split(".")[1:]:
|
||||
m = getattr(m, n)
|
||||
return m
|
||||
|
||||
|
||||
class SurfaceSubclass(pygame.Surface):
|
||||
"""A subclassed Surface to test inheritance."""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.test_attribute = True
|
||||
|
||||
|
||||
def test():
|
||||
"""
|
||||
|
||||
Lightweight test for helpers
|
||||
|
||||
"""
|
||||
|
||||
r = pygame.Rect(0, 0, 10, 10)
|
||||
assert rect_outer_bounds(r) == [(10, 0), (0, 10), (10, 10)] # tr # bl # br
|
||||
|
||||
assert len(list(rect_area_pts(r))) == 100
|
||||
|
||||
r = pygame.Rect(0, 0, 3, 3)
|
||||
assert list(rect_perimeter_pts(r)) == [
|
||||
(0, 0),
|
||||
(1, 0),
|
||||
(2, 0), # tl -> tr
|
||||
(2, 1),
|
||||
(2, 2), # tr -> br
|
||||
(1, 2),
|
||||
(0, 2), # br -> bl
|
||||
(0, 1), # bl -> tl
|
||||
]
|
||||
|
||||
print("Tests: OK")
|
||||
@@ -0,0 +1,438 @@
|
||||
import ctypes
|
||||
import sys
|
||||
import unittest
|
||||
from ctypes import *
|
||||
|
||||
__all__ = [
|
||||
"PAI_CONTIGUOUS",
|
||||
"PAI_FORTRAN",
|
||||
"PAI_ALIGNED",
|
||||
"PAI_NOTSWAPPED",
|
||||
"PAI_WRITEABLE",
|
||||
"PAI_ARR_HAS_DESCR",
|
||||
"ArrayInterface",
|
||||
]
|
||||
|
||||
if sizeof(c_uint) == sizeof(c_void_p):
|
||||
c_size_t = c_uint
|
||||
c_ssize_t = c_int
|
||||
elif sizeof(c_ulong) == sizeof(c_void_p):
|
||||
c_size_t = c_ulong
|
||||
c_ssize_t = c_long
|
||||
elif sizeof(c_ulonglong) == sizeof(c_void_p):
|
||||
c_size_t = c_ulonglong
|
||||
c_ssize_t = c_longlong
|
||||
|
||||
|
||||
SIZEOF_VOID_P = sizeof(c_void_p)
|
||||
if SIZEOF_VOID_P <= sizeof(c_int):
|
||||
Py_intptr_t = c_int
|
||||
elif SIZEOF_VOID_P <= sizeof(c_long):
|
||||
Py_intptr_t = c_long
|
||||
elif "c_longlong" in globals() and SIZEOF_VOID_P <= sizeof(c_longlong):
|
||||
Py_intptr_t = c_longlong
|
||||
else:
|
||||
raise RuntimeError("Unrecognized pointer size %i" % (SIZEOF_VOID_P,))
|
||||
|
||||
|
||||
class PyArrayInterface(Structure):
|
||||
_fields_ = [
|
||||
("two", c_int),
|
||||
("nd", c_int),
|
||||
("typekind", c_char),
|
||||
("itemsize", c_int),
|
||||
("flags", c_int),
|
||||
("shape", POINTER(Py_intptr_t)),
|
||||
("strides", POINTER(Py_intptr_t)),
|
||||
("data", c_void_p),
|
||||
("descr", py_object),
|
||||
]
|
||||
|
||||
|
||||
PAI_Ptr = POINTER(PyArrayInterface)
|
||||
|
||||
try:
|
||||
PyCObject_AsVoidPtr = pythonapi.PyCObject_AsVoidPtr
|
||||
except AttributeError:
|
||||
|
||||
def PyCObject_AsVoidPtr(o):
|
||||
raise TypeError("Not available")
|
||||
|
||||
else:
|
||||
PyCObject_AsVoidPtr.restype = c_void_p
|
||||
PyCObject_AsVoidPtr.argtypes = [py_object]
|
||||
PyCObject_GetDesc = pythonapi.PyCObject_GetDesc
|
||||
PyCObject_GetDesc.restype = c_void_p
|
||||
PyCObject_GetDesc.argtypes = [py_object]
|
||||
|
||||
try:
|
||||
PyCapsule_IsValid = pythonapi.PyCapsule_IsValid
|
||||
except AttributeError:
|
||||
|
||||
def PyCapsule_IsValid(capsule, name):
|
||||
return 0
|
||||
|
||||
else:
|
||||
PyCapsule_IsValid.restype = c_int
|
||||
PyCapsule_IsValid.argtypes = [py_object, c_char_p]
|
||||
PyCapsule_GetPointer = pythonapi.PyCapsule_GetPointer
|
||||
PyCapsule_GetPointer.restype = c_void_p
|
||||
PyCapsule_GetPointer.argtypes = [py_object, c_char_p]
|
||||
PyCapsule_GetContext = pythonapi.PyCapsule_GetContext
|
||||
PyCapsule_GetContext.restype = c_void_p
|
||||
PyCapsule_GetContext.argtypes = [py_object]
|
||||
|
||||
PyCapsule_Destructor = CFUNCTYPE(None, py_object)
|
||||
PyCapsule_New = pythonapi.PyCapsule_New
|
||||
PyCapsule_New.restype = py_object
|
||||
PyCapsule_New.argtypes = [c_void_p, c_char_p, POINTER(PyCapsule_Destructor)]
|
||||
|
||||
|
||||
def capsule_new(p):
|
||||
return PyCapsule_New(addressof(p), None, None)
|
||||
|
||||
|
||||
PAI_CONTIGUOUS = 0x01
|
||||
PAI_FORTRAN = 0x02
|
||||
PAI_ALIGNED = 0x100
|
||||
PAI_NOTSWAPPED = 0x200
|
||||
PAI_WRITEABLE = 0x400
|
||||
PAI_ARR_HAS_DESCR = 0x800
|
||||
|
||||
|
||||
class ArrayInterface:
|
||||
def __init__(self, arr):
|
||||
try:
|
||||
self._cobj = arr.__array_struct__
|
||||
except AttributeError:
|
||||
raise TypeError("The array object lacks an array structure")
|
||||
if not self._cobj:
|
||||
raise TypeError("The array object has a NULL array structure value")
|
||||
try:
|
||||
vp = PyCObject_AsVoidPtr(self._cobj)
|
||||
except TypeError:
|
||||
if PyCapsule_IsValid(self._cobj, None):
|
||||
vp = PyCapsule_GetPointer(self._cobj, None)
|
||||
else:
|
||||
raise TypeError("The array object has an invalid array structure")
|
||||
self.desc = PyCapsule_GetContext(self._cobj)
|
||||
else:
|
||||
self.desc = PyCObject_GetDesc(self._cobj)
|
||||
self._inter = cast(vp, PAI_Ptr)[0]
|
||||
|
||||
def __getattr__(self, name):
|
||||
if name == "typekind":
|
||||
return self._inter.typekind.decode("latin-1")
|
||||
return getattr(self._inter, name)
|
||||
|
||||
def __str__(self):
|
||||
if isinstance(self.desc, tuple):
|
||||
ver = self.desc[0]
|
||||
else:
|
||||
ver = "N/A"
|
||||
return (
|
||||
"nd: %i\n"
|
||||
"typekind: %s\n"
|
||||
"itemsize: %i\n"
|
||||
"flags: %s\n"
|
||||
"shape: %s\n"
|
||||
"strides: %s\n"
|
||||
"ver: %s\n"
|
||||
% (
|
||||
self.nd,
|
||||
self.typekind,
|
||||
self.itemsize,
|
||||
format_flags(self.flags),
|
||||
format_shape(self.nd, self.shape),
|
||||
format_strides(self.nd, self.strides),
|
||||
ver,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def format_flags(flags):
|
||||
names = []
|
||||
for flag, name in [
|
||||
(PAI_CONTIGUOUS, "CONTIGUOUS"),
|
||||
(PAI_FORTRAN, "FORTRAN"),
|
||||
(PAI_ALIGNED, "ALIGNED"),
|
||||
(PAI_NOTSWAPPED, "NOTSWAPPED"),
|
||||
(PAI_WRITEABLE, "WRITEABLE"),
|
||||
(PAI_ARR_HAS_DESCR, "ARR_HAS_DESCR"),
|
||||
]:
|
||||
if flag & flags:
|
||||
names.append(name)
|
||||
return ", ".join(names)
|
||||
|
||||
|
||||
def format_shape(nd, shape):
|
||||
return ", ".join([str(shape[i]) for i in range(nd)])
|
||||
|
||||
|
||||
def format_strides(nd, strides):
|
||||
return ", ".join([str(strides[i]) for i in range(nd)])
|
||||
|
||||
|
||||
class Exporter:
|
||||
def __init__(
|
||||
self, shape, typekind=None, itemsize=None, strides=None, descr=None, flags=None
|
||||
):
|
||||
if typekind is None:
|
||||
typekind = "u"
|
||||
if itemsize is None:
|
||||
itemsize = 1
|
||||
if flags is None:
|
||||
flags = PAI_WRITEABLE | PAI_ALIGNED | PAI_NOTSWAPPED
|
||||
if descr is not None:
|
||||
flags |= PAI_ARR_HAS_DESCR
|
||||
if len(typekind) != 1:
|
||||
raise ValueError("Argument 'typekind' must be length 1 string")
|
||||
nd = len(shape)
|
||||
self.typekind = typekind
|
||||
self.itemsize = itemsize
|
||||
self.nd = nd
|
||||
self.shape = tuple(shape)
|
||||
self._shape = (c_ssize_t * self.nd)(*self.shape)
|
||||
if strides is None:
|
||||
self._strides = (c_ssize_t * self.nd)()
|
||||
self._strides[self.nd - 1] = self.itemsize
|
||||
for i in range(self.nd - 1, 0, -1):
|
||||
self._strides[i - 1] = self.shape[i] * self._strides[i]
|
||||
strides = tuple(self._strides)
|
||||
self.strides = strides
|
||||
elif len(strides) == nd:
|
||||
self.strides = tuple(strides)
|
||||
self._strides = (c_ssize_t * self.nd)(*self.strides)
|
||||
else:
|
||||
raise ValueError("Mismatch in length of strides and shape")
|
||||
self.descr = descr
|
||||
if self.is_contiguous("C"):
|
||||
flags |= PAI_CONTIGUOUS
|
||||
if self.is_contiguous("F"):
|
||||
flags |= PAI_FORTRAN
|
||||
self.flags = flags
|
||||
sz = max(shape[i] * strides[i] for i in range(nd))
|
||||
self._data = (c_ubyte * sz)()
|
||||
self.data = addressof(self._data)
|
||||
self._inter = PyArrayInterface(
|
||||
2,
|
||||
nd,
|
||||
typekind.encode("latin_1"),
|
||||
itemsize,
|
||||
flags,
|
||||
self._shape,
|
||||
self._strides,
|
||||
self.data,
|
||||
descr,
|
||||
)
|
||||
self.len = itemsize
|
||||
for i in range(nd):
|
||||
self.len *= self.shape[i]
|
||||
|
||||
__array_struct__ = property(lambda self: capsule_new(self._inter))
|
||||
|
||||
def is_contiguous(self, fortran):
|
||||
if fortran in "CA":
|
||||
if self.strides[-1] == self.itemsize:
|
||||
for i in range(self.nd - 1, 0, -1):
|
||||
if self.strides[i - 1] != self.shape[i] * self.strides[i]:
|
||||
break
|
||||
else:
|
||||
return True
|
||||
if fortran in "FA":
|
||||
if self.strides[0] == self.itemsize:
|
||||
for i in range(0, self.nd - 1):
|
||||
if self.strides[i + 1] != self.shape[i] * self.strides[i]:
|
||||
break
|
||||
else:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
class Array(Exporter):
|
||||
_ctypes = {
|
||||
("u", 1): c_uint8,
|
||||
("u", 2): c_uint16,
|
||||
("u", 4): c_uint32,
|
||||
("u", 8): c_uint64,
|
||||
("i", 1): c_int8,
|
||||
("i", 2): c_int16,
|
||||
("i", 4): c_int32,
|
||||
("i", 8): c_int64,
|
||||
}
|
||||
|
||||
def __init__(self, *args, **kwds):
|
||||
super().__init__(*args, **kwds)
|
||||
try:
|
||||
if self.flags & PAI_NOTSWAPPED:
|
||||
ct = self._ctypes[self.typekind, self.itemsize]
|
||||
elif c_int.__ctype_le__ is c_int:
|
||||
ct = self._ctypes[self.typekind, self.itemsize].__ctype_be__
|
||||
else:
|
||||
ct = self._ctypes[self.typekind, self.itemsize].__ctype_le__
|
||||
except KeyError:
|
||||
ct = c_uint8 * self.itemsize
|
||||
self._ctype = ct
|
||||
self._ctype_p = POINTER(ct)
|
||||
|
||||
def __getitem__(self, key):
|
||||
return cast(self._addr_at(key), self._ctype_p)[0]
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
cast(self._addr_at(key), self._ctype_p)[0] = value
|
||||
|
||||
def _addr_at(self, key):
|
||||
if not isinstance(key, tuple):
|
||||
key = (key,)
|
||||
if len(key) != self.nd:
|
||||
raise ValueError("wrong number of indexes")
|
||||
for i in range(self.nd):
|
||||
if not (0 <= key[i] < self.shape[i]):
|
||||
raise IndexError(f"index {i} out of range")
|
||||
return self.data + sum(i * s for i, s in zip(key, self.strides))
|
||||
|
||||
|
||||
class ExporterTest(unittest.TestCase):
|
||||
def test_strides(self):
|
||||
self.check_args(0, (10,), "u", (2,), 20, 20, 2)
|
||||
self.check_args(0, (5, 3), "u", (6, 2), 30, 30, 2)
|
||||
self.check_args(0, (7, 3, 5), "u", (30, 10, 2), 210, 210, 2)
|
||||
self.check_args(0, (13, 5, 11, 3), "u", (330, 66, 6, 2), 4290, 4290, 2)
|
||||
self.check_args(3, (7, 3, 5), "i", (2, 14, 42), 210, 210, 2)
|
||||
self.check_args(3, (7, 3, 5), "x", (2, 16, 48), 210, 240, 2)
|
||||
self.check_args(3, (13, 5, 11, 3), "%", (440, 88, 8, 2), 4290, 5720, 2)
|
||||
self.check_args(3, (7, 5), "-", (15, 3), 105, 105, 3)
|
||||
self.check_args(3, (7, 5), "*", (3, 21), 105, 105, 3)
|
||||
self.check_args(3, (7, 5), " ", (3, 24), 105, 120, 3)
|
||||
|
||||
def test_is_contiguous(self):
|
||||
a = Exporter((10,), itemsize=2)
|
||||
self.assertTrue(a.is_contiguous("C"))
|
||||
self.assertTrue(a.is_contiguous("F"))
|
||||
self.assertTrue(a.is_contiguous("A"))
|
||||
a = Exporter((10, 4), itemsize=2)
|
||||
self.assertTrue(a.is_contiguous("C"))
|
||||
self.assertTrue(a.is_contiguous("A"))
|
||||
self.assertFalse(a.is_contiguous("F"))
|
||||
a = Exporter((13, 5, 11, 3), itemsize=2, strides=(330, 66, 6, 2))
|
||||
self.assertTrue(a.is_contiguous("C"))
|
||||
self.assertTrue(a.is_contiguous("A"))
|
||||
self.assertFalse(a.is_contiguous("F"))
|
||||
a = Exporter((10, 4), itemsize=2, strides=(2, 20))
|
||||
self.assertTrue(a.is_contiguous("F"))
|
||||
self.assertTrue(a.is_contiguous("A"))
|
||||
self.assertFalse(a.is_contiguous("C"))
|
||||
a = Exporter((13, 5, 11, 3), itemsize=2, strides=(2, 26, 130, 1430))
|
||||
self.assertTrue(a.is_contiguous("F"))
|
||||
self.assertTrue(a.is_contiguous("A"))
|
||||
self.assertFalse(a.is_contiguous("C"))
|
||||
a = Exporter((2, 11, 6, 4), itemsize=2, strides=(576, 48, 8, 2))
|
||||
self.assertFalse(a.is_contiguous("A"))
|
||||
a = Exporter((2, 11, 6, 4), itemsize=2, strides=(2, 4, 48, 288))
|
||||
self.assertFalse(a.is_contiguous("A"))
|
||||
a = Exporter((3, 2, 2), itemsize=2, strides=(16, 8, 4))
|
||||
self.assertFalse(a.is_contiguous("A"))
|
||||
a = Exporter((3, 2, 2), itemsize=2, strides=(4, 12, 24))
|
||||
self.assertFalse(a.is_contiguous("A"))
|
||||
|
||||
def check_args(
|
||||
self, call_flags, shape, typekind, strides, length, bufsize, itemsize, offset=0
|
||||
):
|
||||
if call_flags & 1:
|
||||
typekind_arg = typekind
|
||||
else:
|
||||
typekind_arg = None
|
||||
if call_flags & 2:
|
||||
strides_arg = strides
|
||||
else:
|
||||
strides_arg = None
|
||||
a = Exporter(shape, itemsize=itemsize, strides=strides_arg)
|
||||
self.assertEqual(sizeof(a._data), bufsize)
|
||||
self.assertEqual(a.data, ctypes.addressof(a._data) + offset)
|
||||
m = ArrayInterface(a)
|
||||
self.assertEqual(m.data, a.data)
|
||||
self.assertEqual(m.itemsize, itemsize)
|
||||
self.assertEqual(tuple(m.shape[0 : m.nd]), shape)
|
||||
self.assertEqual(tuple(m.strides[0 : m.nd]), strides)
|
||||
|
||||
|
||||
class ArrayTest(unittest.TestCase):
|
||||
def __init__(self, *args, **kwds):
|
||||
unittest.TestCase.__init__(self, *args, **kwds)
|
||||
self.a = Array((20, 15), "i", 4)
|
||||
|
||||
def setUp(self):
|
||||
# Every test starts with a zeroed array.
|
||||
memset(self.a.data, 0, sizeof(self.a._data))
|
||||
|
||||
def test__addr_at(self):
|
||||
a = self.a
|
||||
self.assertEqual(a._addr_at((0, 0)), a.data)
|
||||
self.assertEqual(a._addr_at((0, 1)), a.data + 4)
|
||||
self.assertEqual(a._addr_at((1, 0)), a.data + 60)
|
||||
self.assertEqual(a._addr_at((1, 1)), a.data + 64)
|
||||
|
||||
def test_indices(self):
|
||||
a = self.a
|
||||
self.assertEqual(a[0, 0], 0)
|
||||
self.assertEqual(a[19, 0], 0)
|
||||
self.assertEqual(a[0, 14], 0)
|
||||
self.assertEqual(a[19, 14], 0)
|
||||
self.assertEqual(a[5, 8], 0)
|
||||
a[0, 0] = 12
|
||||
a[5, 8] = 99
|
||||
self.assertEqual(a[0, 0], 12)
|
||||
self.assertEqual(a[5, 8], 99)
|
||||
self.assertRaises(IndexError, a.__getitem__, (-1, 0))
|
||||
self.assertRaises(IndexError, a.__getitem__, (0, -1))
|
||||
self.assertRaises(IndexError, a.__getitem__, (20, 0))
|
||||
self.assertRaises(IndexError, a.__getitem__, (0, 15))
|
||||
self.assertRaises(ValueError, a.__getitem__, 0)
|
||||
self.assertRaises(ValueError, a.__getitem__, (0, 0, 0))
|
||||
a = Array((3,), "i", 4)
|
||||
a[1] = 333
|
||||
self.assertEqual(a[1], 333)
|
||||
|
||||
def test_typekind(self):
|
||||
a = Array((1,), "i", 4)
|
||||
self.assertTrue(a._ctype is c_int32)
|
||||
self.assertTrue(a._ctype_p is POINTER(c_int32))
|
||||
a = Array((1,), "u", 4)
|
||||
self.assertTrue(a._ctype is c_uint32)
|
||||
self.assertTrue(a._ctype_p is POINTER(c_uint32))
|
||||
a = Array((1,), "f", 4) # float types unsupported: size system dependent
|
||||
ct = a._ctype
|
||||
self.assertTrue(issubclass(ct, ctypes.Array))
|
||||
self.assertEqual(sizeof(ct), 4)
|
||||
|
||||
def test_itemsize(self):
|
||||
for size in [1, 2, 4, 8]:
|
||||
a = Array((1,), "i", size)
|
||||
ct = a._ctype
|
||||
self.assertTrue(issubclass(ct, ctypes._SimpleCData))
|
||||
self.assertEqual(sizeof(ct), size)
|
||||
|
||||
def test_oddball_itemsize(self):
|
||||
for size in [3, 5, 6, 7, 9]:
|
||||
a = Array((1,), "i", size)
|
||||
ct = a._ctype
|
||||
self.assertTrue(issubclass(ct, ctypes.Array))
|
||||
self.assertEqual(sizeof(ct), size)
|
||||
|
||||
def test_byteswapped(self):
|
||||
a = Array((1,), "u", 4, flags=(PAI_ALIGNED | PAI_WRITEABLE))
|
||||
ct = a._ctype
|
||||
self.assertTrue(ct is not c_uint32)
|
||||
if sys.byteorder == "little":
|
||||
self.assertTrue(ct is c_uint32.__ctype_be__)
|
||||
else:
|
||||
self.assertTrue(ct is c_uint32.__ctype_le__)
|
||||
i = 0xA0B0C0D
|
||||
n = c_uint32(i)
|
||||
a[0] = i
|
||||
self.assertEqual(a[0], i)
|
||||
self.assertEqual(a._data[0:4], cast(addressof(n), POINTER(c_uint8))[3:-1:-1])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,301 @@
|
||||
################################################################################
|
||||
"""
|
||||
|
||||
Modification of http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554
|
||||
|
||||
"""
|
||||
|
||||
#################################### IMPORTS ###################################
|
||||
|
||||
import errno
|
||||
import os
|
||||
import platform
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
|
||||
|
||||
def geterror():
|
||||
return sys.exc_info()[1]
|
||||
|
||||
|
||||
null_byte = "\x00".encode("ascii")
|
||||
|
||||
if platform.system() == "Windows":
|
||||
|
||||
def encode(s):
|
||||
return s.encode("ascii")
|
||||
|
||||
def decode(b):
|
||||
return b.decode("ascii")
|
||||
|
||||
try:
|
||||
import ctypes
|
||||
from ctypes.wintypes import DWORD
|
||||
|
||||
kernel32 = ctypes.windll.kernel32
|
||||
TerminateProcess = ctypes.windll.kernel32.TerminateProcess
|
||||
|
||||
def WriteFile(handle, data, ol=None):
|
||||
c_written = DWORD()
|
||||
success = ctypes.windll.kernel32.WriteFile(
|
||||
handle,
|
||||
ctypes.create_string_buffer(encode(data)),
|
||||
len(data),
|
||||
ctypes.byref(c_written),
|
||||
ol,
|
||||
)
|
||||
return ctypes.windll.kernel32.GetLastError(), c_written.value
|
||||
|
||||
def ReadFile(handle, desired_bytes, ol=None):
|
||||
c_read = DWORD()
|
||||
buffer = ctypes.create_string_buffer(desired_bytes + 1)
|
||||
success = ctypes.windll.kernel32.ReadFile(
|
||||
handle, buffer, desired_bytes, ctypes.byref(c_read), ol
|
||||
)
|
||||
buffer[c_read.value] = null_byte
|
||||
return ctypes.windll.kernel32.GetLastError(), decode(buffer.value)
|
||||
|
||||
def PeekNamedPipe(handle, desired_bytes):
|
||||
c_avail = DWORD()
|
||||
c_message = DWORD()
|
||||
if desired_bytes > 0:
|
||||
c_read = DWORD()
|
||||
buffer = ctypes.create_string_buffer(desired_bytes + 1)
|
||||
success = ctypes.windll.kernel32.PeekNamedPipe(
|
||||
handle,
|
||||
buffer,
|
||||
desired_bytes,
|
||||
ctypes.byref(c_read),
|
||||
ctypes.byref(c_avail),
|
||||
ctypes.byref(c_message),
|
||||
)
|
||||
buffer[c_read.value] = null_byte
|
||||
return decode(buffer.value), c_avail.value, c_message.value
|
||||
else:
|
||||
success = ctypes.windll.kernel32.PeekNamedPipe(
|
||||
handle,
|
||||
None,
|
||||
desired_bytes,
|
||||
None,
|
||||
ctypes.byref(c_avail),
|
||||
ctypes.byref(c_message),
|
||||
)
|
||||
return "", c_avail.value, c_message.value
|
||||
|
||||
except ImportError:
|
||||
from win32api import TerminateProcess
|
||||
from win32file import ReadFile, WriteFile
|
||||
from win32pipe import PeekNamedPipe
|
||||
import msvcrt
|
||||
|
||||
else:
|
||||
import fcntl
|
||||
import select
|
||||
from signal import SIGINT, SIGKILL, SIGTERM
|
||||
|
||||
################################### CONSTANTS ##################################
|
||||
|
||||
PIPE = subprocess.PIPE
|
||||
|
||||
################################################################################
|
||||
|
||||
|
||||
class Popen(subprocess.Popen):
|
||||
def recv(self, maxsize=None):
|
||||
return self._recv("stdout", maxsize)
|
||||
|
||||
def recv_err(self, maxsize=None):
|
||||
return self._recv("stderr", maxsize)
|
||||
|
||||
def send_recv(self, input="", maxsize=None):
|
||||
return self.send(input), self.recv(maxsize), self.recv_err(maxsize)
|
||||
|
||||
def read_async(self, wait=0.1, e=1, tr=5, stderr=0):
|
||||
if tr < 1:
|
||||
tr = 1
|
||||
x = time.time() + wait
|
||||
y = []
|
||||
r = ""
|
||||
pr = self.recv
|
||||
if stderr:
|
||||
pr = self.recv_err
|
||||
while time.time() < x or r:
|
||||
r = pr()
|
||||
if r is None:
|
||||
if e:
|
||||
raise Exception("Other end disconnected!")
|
||||
else:
|
||||
break
|
||||
elif r:
|
||||
y.append(r)
|
||||
else:
|
||||
time.sleep(max((x - time.time()) / tr, 0))
|
||||
return "".join(y)
|
||||
|
||||
def send_all(self, data):
|
||||
while len(data):
|
||||
sent = self.send(data)
|
||||
if sent is None:
|
||||
raise Exception("Other end disconnected!")
|
||||
data = memoryview(data, sent)
|
||||
|
||||
def get_conn_maxsize(self, which, maxsize):
|
||||
if maxsize is None:
|
||||
maxsize = 1024
|
||||
elif maxsize < 1:
|
||||
maxsize = 1
|
||||
return getattr(self, which), maxsize
|
||||
|
||||
def _close(self, which):
|
||||
getattr(self, which).close()
|
||||
setattr(self, which, None)
|
||||
|
||||
if platform.system() == "Windows":
|
||||
|
||||
def kill(self):
|
||||
# Recipes
|
||||
# http://me.in-berlin.de/doc/python/faq/windows.html#how-do-i-emulate-os-kill-in-windows
|
||||
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347462
|
||||
|
||||
"""kill function for Win32"""
|
||||
TerminateProcess(int(self._handle), 0) # returns None
|
||||
|
||||
def send(self, input):
|
||||
if not self.stdin:
|
||||
return None
|
||||
|
||||
try:
|
||||
x = msvcrt.get_osfhandle(self.stdin.fileno())
|
||||
(errCode, written) = WriteFile(x, input)
|
||||
except ValueError:
|
||||
return self._close("stdin")
|
||||
except (subprocess.pywintypes.error, Exception):
|
||||
if geterror()[0] in (109, errno.ESHUTDOWN):
|
||||
return self._close("stdin")
|
||||
raise
|
||||
|
||||
return written
|
||||
|
||||
def _recv(self, which, maxsize):
|
||||
conn, maxsize = self.get_conn_maxsize(which, maxsize)
|
||||
if conn is None:
|
||||
return None
|
||||
|
||||
try:
|
||||
x = msvcrt.get_osfhandle(conn.fileno())
|
||||
(read, nAvail, nMessage) = PeekNamedPipe(x, 0)
|
||||
if maxsize < nAvail:
|
||||
nAvail = maxsize
|
||||
if nAvail > 0:
|
||||
(errCode, read) = ReadFile(x, nAvail, None)
|
||||
except ValueError:
|
||||
return self._close(which)
|
||||
except (subprocess.pywintypes.error, Exception):
|
||||
if geterror()[0] in (109, errno.ESHUTDOWN):
|
||||
return self._close(which)
|
||||
raise
|
||||
|
||||
if self.universal_newlines:
|
||||
# Translate newlines. For Python 3.x assume read is text.
|
||||
# If bytes then another solution is needed.
|
||||
read = read.replace("\r\n", "\n").replace("\r", "\n")
|
||||
return read
|
||||
|
||||
else:
|
||||
|
||||
def kill(self):
|
||||
for i, sig in enumerate([SIGTERM, SIGKILL] * 2):
|
||||
if i % 2 == 0:
|
||||
os.kill(self.pid, sig)
|
||||
time.sleep((i * (i % 2) / 5.0) + 0.01)
|
||||
|
||||
killed_pid, stat = os.waitpid(self.pid, os.WNOHANG)
|
||||
if killed_pid != 0:
|
||||
return
|
||||
|
||||
def send(self, input):
|
||||
if not self.stdin:
|
||||
return None
|
||||
|
||||
if not select.select([], [self.stdin], [], 0)[1]:
|
||||
return 0
|
||||
|
||||
try:
|
||||
written = os.write(self.stdin.fileno(), input)
|
||||
except OSError:
|
||||
if geterror()[0] == errno.EPIPE: # broken pipe
|
||||
return self._close("stdin")
|
||||
raise
|
||||
|
||||
return written
|
||||
|
||||
def _recv(self, which, maxsize):
|
||||
conn, maxsize = self.get_conn_maxsize(which, maxsize)
|
||||
if conn is None:
|
||||
return None
|
||||
|
||||
if not select.select([conn], [], [], 0)[0]:
|
||||
return ""
|
||||
|
||||
r = conn.read(maxsize)
|
||||
if not r:
|
||||
return self._close(which)
|
||||
|
||||
if self.universal_newlines:
|
||||
r = r.replace("\r\n", "\n").replace("\r", "\n")
|
||||
return r
|
||||
|
||||
|
||||
################################################################################
|
||||
|
||||
|
||||
def proc_in_time_or_kill(cmd, time_out, wd=None, env=None):
|
||||
proc = Popen(
|
||||
cmd,
|
||||
cwd=wd,
|
||||
env=env,
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
universal_newlines=1,
|
||||
)
|
||||
|
||||
ret_code = None
|
||||
response = []
|
||||
|
||||
t = time.time()
|
||||
while ret_code is None and ((time.time() - t) < time_out):
|
||||
ret_code = proc.poll()
|
||||
response += [proc.read_async(wait=0.1, e=0)]
|
||||
|
||||
if ret_code is None:
|
||||
ret_code = f'"Process timed out (time_out = {time_out} secs) '
|
||||
try:
|
||||
proc.kill()
|
||||
ret_code += 'and was successfully terminated"'
|
||||
except Exception:
|
||||
ret_code += f'and termination failed (exception: {geterror()})"'
|
||||
|
||||
return ret_code, "".join(response)
|
||||
|
||||
|
||||
################################################################################
|
||||
|
||||
|
||||
class AsyncTest(unittest.TestCase):
|
||||
def test_proc_in_time_or_kill(self):
|
||||
ret_code, response = proc_in_time_or_kill(
|
||||
[sys.executable, "-c", "while True: pass"], time_out=1
|
||||
)
|
||||
|
||||
self.assertIn("rocess timed out", ret_code)
|
||||
self.assertIn("successfully terminated", ret_code)
|
||||
|
||||
|
||||
################################################################################
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,603 @@
|
||||
"""Module pygame.tests.test_utils.array
|
||||
|
||||
Export the Exporter and Importer classes.
|
||||
|
||||
Class Exporter has configurable shape and strides. Exporter objects
|
||||
provide a convenient target for unit tests on Pygame objects and functions that
|
||||
import a new buffer interface.
|
||||
|
||||
Class Importer imports a buffer interface with the given PyBUF_* flags.
|
||||
It returns NULL Py_buffer fields as None. The shape, strides, and suboffsets
|
||||
arrays are returned as tuples of ints. All Py_buffer field properties are
|
||||
read-only. This class is useful in comparing exported buffer interfaces
|
||||
with the actual request. The similar Python builtin memoryview currently
|
||||
does not support configurable PyBUF_* flags.
|
||||
|
||||
This module contains its own unit tests. When Pygame is installed, these tests
|
||||
can be run with the following command line statement:
|
||||
|
||||
python -m pygame.tests.test_utils.array
|
||||
|
||||
"""
|
||||
|
||||
import ctypes
|
||||
import operator
|
||||
import unittest
|
||||
from functools import reduce
|
||||
|
||||
import pygame
|
||||
import pygame.newbuffer
|
||||
from pygame.newbuffer import (
|
||||
PyBUF_ANY_CONTIGUOUS,
|
||||
PyBUF_C_CONTIGUOUS,
|
||||
PyBUF_CONTIG,
|
||||
PyBUF_CONTIG_RO,
|
||||
PyBUF_F_CONTIGUOUS,
|
||||
PyBUF_FORMAT,
|
||||
PyBUF_FULL,
|
||||
PyBUF_FULL_RO,
|
||||
PyBUF_INDIRECT,
|
||||
PyBUF_ND,
|
||||
PyBUF_RECORDS,
|
||||
PyBUF_RECORDS_RO,
|
||||
PyBUF_SIMPLE,
|
||||
PyBUF_STRIDED,
|
||||
PyBUF_STRIDED_RO,
|
||||
PyBUF_STRIDES,
|
||||
PyBUF_WRITABLE,
|
||||
)
|
||||
|
||||
__all__ = ["Exporter", "Importer"]
|
||||
|
||||
try:
|
||||
ctypes.c_ssize_t
|
||||
except AttributeError:
|
||||
void_p_sz = ctypes.sizeof(ctypes.c_void_p)
|
||||
if ctypes.sizeof(ctypes.c_short) == void_p_sz:
|
||||
ctypes.c_ssize_t = ctypes.c_short
|
||||
elif ctypes.sizeof(ctypes.c_int) == void_p_sz:
|
||||
ctypes.c_ssize_t = ctypes.c_int
|
||||
elif ctypes.sizeof(ctypes.c_long) == void_p_sz:
|
||||
ctypes.c_ssize_t = ctypes.c_long
|
||||
elif ctypes.sizeof(ctypes.c_longlong) == void_p_sz:
|
||||
ctypes.c_ssize_t = ctypes.c_longlong
|
||||
else:
|
||||
raise RuntimeError("Cannot set c_ssize_t: sizeof(void *) is %i" % void_p_sz)
|
||||
|
||||
|
||||
def _prop_get(fn):
|
||||
return property(fn)
|
||||
|
||||
|
||||
class Exporter(pygame.newbuffer.BufferMixin):
|
||||
"""An object that exports a multi-dimension new buffer interface
|
||||
|
||||
The only array operation this type supports is to export a buffer.
|
||||
"""
|
||||
|
||||
prefixes = {
|
||||
"@": "",
|
||||
"=": "=",
|
||||
"<": "=",
|
||||
">": "=",
|
||||
"!": "=",
|
||||
"2": "2",
|
||||
"3": "3",
|
||||
"4": "4",
|
||||
"5": "5",
|
||||
"6": "6",
|
||||
"7": "7",
|
||||
"8": "8",
|
||||
"9": "9",
|
||||
}
|
||||
types = {
|
||||
"c": ctypes.c_char,
|
||||
"b": ctypes.c_byte,
|
||||
"B": ctypes.c_ubyte,
|
||||
"=c": ctypes.c_int8,
|
||||
"=b": ctypes.c_int8,
|
||||
"=B": ctypes.c_uint8,
|
||||
"?": ctypes.c_bool,
|
||||
"=?": ctypes.c_int8,
|
||||
"h": ctypes.c_short,
|
||||
"H": ctypes.c_ushort,
|
||||
"=h": ctypes.c_int16,
|
||||
"=H": ctypes.c_uint16,
|
||||
"i": ctypes.c_int,
|
||||
"I": ctypes.c_uint,
|
||||
"=i": ctypes.c_int32,
|
||||
"=I": ctypes.c_uint32,
|
||||
"l": ctypes.c_long,
|
||||
"L": ctypes.c_ulong,
|
||||
"=l": ctypes.c_int32,
|
||||
"=L": ctypes.c_uint32,
|
||||
"q": ctypes.c_longlong,
|
||||
"Q": ctypes.c_ulonglong,
|
||||
"=q": ctypes.c_int64,
|
||||
"=Q": ctypes.c_uint64,
|
||||
"f": ctypes.c_float,
|
||||
"d": ctypes.c_double,
|
||||
"P": ctypes.c_void_p,
|
||||
"x": ctypes.c_ubyte * 1,
|
||||
"2x": ctypes.c_ubyte * 2,
|
||||
"3x": ctypes.c_ubyte * 3,
|
||||
"4x": ctypes.c_ubyte * 4,
|
||||
"5x": ctypes.c_ubyte * 5,
|
||||
"6x": ctypes.c_ubyte * 6,
|
||||
"7x": ctypes.c_ubyte * 7,
|
||||
"8x": ctypes.c_ubyte * 8,
|
||||
"9x": ctypes.c_ubyte * 9,
|
||||
}
|
||||
|
||||
def __init__(self, shape, format=None, strides=None, readonly=None, itemsize=None):
|
||||
if format is None:
|
||||
format = "B"
|
||||
if readonly is None:
|
||||
readonly = False
|
||||
prefix = ""
|
||||
typecode = ""
|
||||
i = 0
|
||||
if i < len(format):
|
||||
try:
|
||||
prefix = self.prefixes[format[i]]
|
||||
i += 1
|
||||
except LookupError:
|
||||
pass
|
||||
if i < len(format) and format[i] == "1":
|
||||
i += 1
|
||||
if i == len(format) - 1:
|
||||
typecode = format[i]
|
||||
if itemsize is None:
|
||||
try:
|
||||
itemsize = ctypes.sizeof(self.types[prefix + typecode])
|
||||
except KeyError:
|
||||
raise ValueError("Unknown item format '" + format + "'")
|
||||
self.readonly = bool(readonly)
|
||||
self.format = format
|
||||
self._format = ctypes.create_string_buffer(format.encode("latin_1"))
|
||||
self.ndim = len(shape)
|
||||
self.itemsize = itemsize
|
||||
self.len = reduce(operator.mul, shape, 1) * self.itemsize
|
||||
self.shape = tuple(shape)
|
||||
self._shape = (ctypes.c_ssize_t * self.ndim)(*self.shape)
|
||||
if strides is None:
|
||||
self._strides = (ctypes.c_ssize_t * self.ndim)()
|
||||
self._strides[self.ndim - 1] = itemsize
|
||||
for i in range(self.ndim - 1, 0, -1):
|
||||
self._strides[i - 1] = self.shape[i] * self._strides[i]
|
||||
self.strides = tuple(self._strides)
|
||||
elif len(strides) == self.ndim:
|
||||
self.strides = tuple(strides)
|
||||
self._strides = (ctypes.c_ssize_t * self.ndim)(*self.strides)
|
||||
else:
|
||||
raise ValueError("Mismatch in length of strides and shape")
|
||||
buflen = max(d * abs(s) for d, s in zip(self.shape, self.strides))
|
||||
self.buflen = buflen
|
||||
self._buf = (ctypes.c_ubyte * buflen)()
|
||||
offset = sum(
|
||||
(d - 1) * abs(s) for d, s in zip(self.shape, self.strides) if s < 0
|
||||
)
|
||||
self.buf = ctypes.addressof(self._buf) + offset
|
||||
|
||||
def buffer_info(self):
|
||||
return (ctypes.addressof(self.buffer), self.shape[0])
|
||||
|
||||
def tobytes(self):
|
||||
return ctypes.cast(self.buffer, ctypes.POINTER(ctypes.c_char))[0 : self._len]
|
||||
|
||||
def __len__(self):
|
||||
return self.shape[0]
|
||||
|
||||
def _get_buffer(self, view, flags):
|
||||
from ctypes import addressof
|
||||
|
||||
if (flags & PyBUF_WRITABLE) == PyBUF_WRITABLE and self.readonly:
|
||||
raise BufferError("buffer is read-only")
|
||||
if (
|
||||
flags & PyBUF_C_CONTIGUOUS
|
||||
) == PyBUF_C_CONTIGUOUS and not self.is_contiguous("C"):
|
||||
raise BufferError("data is not C contiguous")
|
||||
if (
|
||||
flags & PyBUF_F_CONTIGUOUS
|
||||
) == PyBUF_F_CONTIGUOUS and not self.is_contiguous("F"):
|
||||
raise BufferError("data is not F contiguous")
|
||||
if (
|
||||
flags & PyBUF_ANY_CONTIGUOUS
|
||||
) == PyBUF_ANY_CONTIGUOUS and not self.is_contiguous("A"):
|
||||
raise BufferError("data is not contiguous")
|
||||
view.buf = self.buf
|
||||
view.readonly = self.readonly
|
||||
view.len = self.len
|
||||
if flags | PyBUF_WRITABLE == PyBUF_WRITABLE:
|
||||
view.ndim = 0
|
||||
else:
|
||||
view.ndim = self.ndim
|
||||
view.itemsize = self.itemsize
|
||||
if (flags & PyBUF_FORMAT) == PyBUF_FORMAT:
|
||||
view.format = addressof(self._format)
|
||||
else:
|
||||
view.format = None
|
||||
if (flags & PyBUF_ND) == PyBUF_ND:
|
||||
view.shape = addressof(self._shape)
|
||||
elif self.is_contiguous("C"):
|
||||
view.shape = None
|
||||
else:
|
||||
raise BufferError(f"shape required for {self.ndim} dimensional data")
|
||||
if (flags & PyBUF_STRIDES) == PyBUF_STRIDES:
|
||||
view.strides = ctypes.addressof(self._strides)
|
||||
elif view.shape is None or self.is_contiguous("C"):
|
||||
view.strides = None
|
||||
else:
|
||||
raise BufferError("strides required for none C contiguous data")
|
||||
view.suboffsets = None
|
||||
view.internal = None
|
||||
view.obj = self
|
||||
|
||||
def is_contiguous(self, fortran):
|
||||
if fortran in "CA":
|
||||
if self.strides[-1] == self.itemsize:
|
||||
for i in range(self.ndim - 1, 0, -1):
|
||||
if self.strides[i - 1] != self.shape[i] * self.strides[i]:
|
||||
break
|
||||
else:
|
||||
return True
|
||||
if fortran in "FA":
|
||||
if self.strides[0] == self.itemsize:
|
||||
for i in range(0, self.ndim - 1):
|
||||
if self.strides[i + 1] != self.shape[i] * self.strides[i]:
|
||||
break
|
||||
else:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
class Importer:
|
||||
"""An object that imports a new buffer interface
|
||||
|
||||
The fields of the Py_buffer C struct are exposed by identically
|
||||
named Importer read-only properties.
|
||||
"""
|
||||
|
||||
def __init__(self, obj, flags):
|
||||
self._view = pygame.newbuffer.Py_buffer()
|
||||
self._view.get_buffer(obj, flags)
|
||||
|
||||
@property
|
||||
def obj(self):
|
||||
"""return object or None for NULL field"""
|
||||
return self._view.obj
|
||||
|
||||
@property
|
||||
def buf(self):
|
||||
"""return int or None for NULL field"""
|
||||
return self._view.buf
|
||||
|
||||
@property
|
||||
def len(self):
|
||||
"""return int"""
|
||||
return self._view.len
|
||||
|
||||
@property
|
||||
def readonly(self):
|
||||
"""return bool"""
|
||||
return self._view.readonly
|
||||
|
||||
@property
|
||||
def format(self):
|
||||
"""return bytes or None for NULL field"""
|
||||
format_addr = self._view.format
|
||||
if format_addr is None:
|
||||
return None
|
||||
return ctypes.cast(format_addr, ctypes.c_char_p).value.decode("ascii")
|
||||
|
||||
@property
|
||||
def itemsize(self):
|
||||
"""return int"""
|
||||
return self._view.itemsize
|
||||
|
||||
@property
|
||||
def ndim(self):
|
||||
"""return int"""
|
||||
return self._view.ndim
|
||||
|
||||
@property
|
||||
def shape(self):
|
||||
"""return int tuple or None for NULL field"""
|
||||
return self._to_ssize_tuple(self._view.shape)
|
||||
|
||||
@property
|
||||
def strides(self):
|
||||
"""return int tuple or None for NULL field"""
|
||||
return self._to_ssize_tuple(self._view.strides)
|
||||
|
||||
@property
|
||||
def suboffsets(self):
|
||||
"""return int tuple or None for NULL field"""
|
||||
return self._to_ssize_tuple(self._view.suboffsets)
|
||||
|
||||
@property
|
||||
def internal(self):
|
||||
"""return int or None for NULL field"""
|
||||
return self._view.internal
|
||||
|
||||
def _to_ssize_tuple(self, addr):
|
||||
from ctypes import POINTER, c_ssize_t, cast
|
||||
|
||||
if addr is None:
|
||||
return None
|
||||
return tuple(cast(addr, POINTER(c_ssize_t))[0 : self._view.ndim])
|
||||
|
||||
|
||||
class ExporterTest(unittest.TestCase):
|
||||
"""Class Exporter unit tests"""
|
||||
|
||||
def test_formats(self):
|
||||
char_sz = ctypes.sizeof(ctypes.c_char)
|
||||
short_sz = ctypes.sizeof(ctypes.c_short)
|
||||
int_sz = ctypes.sizeof(ctypes.c_int)
|
||||
long_sz = ctypes.sizeof(ctypes.c_long)
|
||||
longlong_sz = ctypes.sizeof(ctypes.c_longlong)
|
||||
float_sz = ctypes.sizeof(ctypes.c_float)
|
||||
double_sz = ctypes.sizeof(ctypes.c_double)
|
||||
voidp_sz = ctypes.sizeof(ctypes.c_void_p)
|
||||
bool_sz = ctypes.sizeof(ctypes.c_bool)
|
||||
|
||||
self.check_args(0, (1,), "B", (1,), 1, 1, 1)
|
||||
self.check_args(1, (1,), "b", (1,), 1, 1, 1)
|
||||
self.check_args(1, (1,), "B", (1,), 1, 1, 1)
|
||||
self.check_args(1, (1,), "c", (char_sz,), char_sz, char_sz, char_sz)
|
||||
self.check_args(1, (1,), "h", (short_sz,), short_sz, short_sz, short_sz)
|
||||
self.check_args(1, (1,), "H", (short_sz,), short_sz, short_sz, short_sz)
|
||||
self.check_args(1, (1,), "i", (int_sz,), int_sz, int_sz, int_sz)
|
||||
self.check_args(1, (1,), "I", (int_sz,), int_sz, int_sz, int_sz)
|
||||
self.check_args(1, (1,), "l", (long_sz,), long_sz, long_sz, long_sz)
|
||||
self.check_args(1, (1,), "L", (long_sz,), long_sz, long_sz, long_sz)
|
||||
self.check_args(
|
||||
1, (1,), "q", (longlong_sz,), longlong_sz, longlong_sz, longlong_sz
|
||||
)
|
||||
self.check_args(
|
||||
1, (1,), "Q", (longlong_sz,), longlong_sz, longlong_sz, longlong_sz
|
||||
)
|
||||
self.check_args(1, (1,), "f", (float_sz,), float_sz, float_sz, float_sz)
|
||||
self.check_args(1, (1,), "d", (double_sz,), double_sz, double_sz, double_sz)
|
||||
self.check_args(1, (1,), "x", (1,), 1, 1, 1)
|
||||
self.check_args(1, (1,), "P", (voidp_sz,), voidp_sz, voidp_sz, voidp_sz)
|
||||
self.check_args(1, (1,), "?", (bool_sz,), bool_sz, bool_sz, bool_sz)
|
||||
self.check_args(1, (1,), "@b", (1,), 1, 1, 1)
|
||||
self.check_args(1, (1,), "@B", (1,), 1, 1, 1)
|
||||
self.check_args(1, (1,), "@c", (char_sz,), char_sz, char_sz, char_sz)
|
||||
self.check_args(1, (1,), "@h", (short_sz,), short_sz, short_sz, short_sz)
|
||||
self.check_args(1, (1,), "@H", (short_sz,), short_sz, short_sz, short_sz)
|
||||
self.check_args(1, (1,), "@i", (int_sz,), int_sz, int_sz, int_sz)
|
||||
self.check_args(1, (1,), "@I", (int_sz,), int_sz, int_sz, int_sz)
|
||||
self.check_args(1, (1,), "@l", (long_sz,), long_sz, long_sz, long_sz)
|
||||
self.check_args(1, (1,), "@L", (long_sz,), long_sz, long_sz, long_sz)
|
||||
self.check_args(
|
||||
1, (1,), "@q", (longlong_sz,), longlong_sz, longlong_sz, longlong_sz
|
||||
)
|
||||
self.check_args(
|
||||
1, (1,), "@Q", (longlong_sz,), longlong_sz, longlong_sz, longlong_sz
|
||||
)
|
||||
self.check_args(1, (1,), "@f", (float_sz,), float_sz, float_sz, float_sz)
|
||||
self.check_args(1, (1,), "@d", (double_sz,), double_sz, double_sz, double_sz)
|
||||
self.check_args(1, (1,), "@?", (bool_sz,), bool_sz, bool_sz, bool_sz)
|
||||
self.check_args(1, (1,), "=b", (1,), 1, 1, 1)
|
||||
self.check_args(1, (1,), "=B", (1,), 1, 1, 1)
|
||||
self.check_args(1, (1,), "=c", (1,), 1, 1, 1)
|
||||
self.check_args(1, (1,), "=h", (2,), 2, 2, 2)
|
||||
self.check_args(1, (1,), "=H", (2,), 2, 2, 2)
|
||||
self.check_args(1, (1,), "=i", (4,), 4, 4, 4)
|
||||
self.check_args(1, (1,), "=I", (4,), 4, 4, 4)
|
||||
self.check_args(1, (1,), "=l", (4,), 4, 4, 4)
|
||||
self.check_args(1, (1,), "=L", (4,), 4, 4, 4)
|
||||
self.check_args(1, (1,), "=q", (8,), 8, 8, 8)
|
||||
self.check_args(1, (1,), "=Q", (8,), 8, 8, 8)
|
||||
self.check_args(1, (1,), "=?", (1,), 1, 1, 1)
|
||||
self.check_args(1, (1,), "<h", (2,), 2, 2, 2)
|
||||
self.check_args(1, (1,), ">h", (2,), 2, 2, 2)
|
||||
self.check_args(1, (1,), "!h", (2,), 2, 2, 2)
|
||||
self.check_args(1, (1,), "<q", (8,), 8, 8, 8)
|
||||
self.check_args(1, (1,), ">q", (8,), 8, 8, 8)
|
||||
self.check_args(1, (1,), "!q", (8,), 8, 8, 8)
|
||||
self.check_args(1, (1,), "1x", (1,), 1, 1, 1)
|
||||
self.check_args(1, (1,), "2x", (2,), 2, 2, 2)
|
||||
self.check_args(1, (1,), "3x", (3,), 3, 3, 3)
|
||||
self.check_args(1, (1,), "4x", (4,), 4, 4, 4)
|
||||
self.check_args(1, (1,), "5x", (5,), 5, 5, 5)
|
||||
self.check_args(1, (1,), "6x", (6,), 6, 6, 6)
|
||||
self.check_args(1, (1,), "7x", (7,), 7, 7, 7)
|
||||
self.check_args(1, (1,), "8x", (8,), 8, 8, 8)
|
||||
self.check_args(1, (1,), "9x", (9,), 9, 9, 9)
|
||||
self.check_args(1, (1,), "1h", (2,), 2, 2, 2)
|
||||
self.check_args(1, (1,), "=1h", (2,), 2, 2, 2)
|
||||
self.assertRaises(ValueError, Exporter, (2, 1), "")
|
||||
self.assertRaises(ValueError, Exporter, (2, 1), "W")
|
||||
self.assertRaises(ValueError, Exporter, (2, 1), "^Q")
|
||||
self.assertRaises(ValueError, Exporter, (2, 1), "=W")
|
||||
self.assertRaises(ValueError, Exporter, (2, 1), "=f")
|
||||
self.assertRaises(ValueError, Exporter, (2, 1), "=d")
|
||||
self.assertRaises(ValueError, Exporter, (2, 1), "<f")
|
||||
self.assertRaises(ValueError, Exporter, (2, 1), "<d")
|
||||
self.assertRaises(ValueError, Exporter, (2, 1), ">f")
|
||||
self.assertRaises(ValueError, Exporter, (2, 1), ">d")
|
||||
self.assertRaises(ValueError, Exporter, (2, 1), "!f")
|
||||
self.assertRaises(ValueError, Exporter, (2, 1), "!d")
|
||||
self.assertRaises(ValueError, Exporter, (2, 1), "0x")
|
||||
self.assertRaises(ValueError, Exporter, (2, 1), "11x")
|
||||
self.assertRaises(ValueError, Exporter, (2, 1), "BB")
|
||||
|
||||
def test_strides(self):
|
||||
self.check_args(1, (10,), "=h", (2,), 20, 20, 2)
|
||||
self.check_args(1, (5, 3), "=h", (6, 2), 30, 30, 2)
|
||||
self.check_args(1, (7, 3, 5), "=h", (30, 10, 2), 210, 210, 2)
|
||||
self.check_args(1, (13, 5, 11, 3), "=h", (330, 66, 6, 2), 4290, 4290, 2)
|
||||
self.check_args(3, (7, 3, 5), "=h", (2, 14, 42), 210, 210, 2)
|
||||
self.check_args(3, (7, 3, 5), "=h", (2, 16, 48), 210, 240, 2)
|
||||
self.check_args(3, (13, 5, 11, 3), "=h", (440, 88, 8, 2), 4290, 5720, 2)
|
||||
self.check_args(3, (7, 5), "3x", (15, 3), 105, 105, 3)
|
||||
self.check_args(3, (7, 5), "3x", (3, 21), 105, 105, 3)
|
||||
self.check_args(3, (7, 5), "3x", (3, 24), 105, 120, 3)
|
||||
|
||||
def test_readonly(self):
|
||||
a = Exporter((2,), "h", readonly=True)
|
||||
self.assertTrue(a.readonly)
|
||||
b = Importer(a, PyBUF_STRIDED_RO)
|
||||
self.assertRaises(BufferError, Importer, a, PyBUF_STRIDED)
|
||||
b = Importer(a, PyBUF_STRIDED_RO)
|
||||
|
||||
def test_is_contiguous(self):
|
||||
a = Exporter((10,), "=h")
|
||||
self.assertTrue(a.is_contiguous("C"))
|
||||
self.assertTrue(a.is_contiguous("F"))
|
||||
self.assertTrue(a.is_contiguous("A"))
|
||||
a = Exporter((10, 4), "=h")
|
||||
self.assertTrue(a.is_contiguous("C"))
|
||||
self.assertTrue(a.is_contiguous("A"))
|
||||
self.assertFalse(a.is_contiguous("F"))
|
||||
a = Exporter((13, 5, 11, 3), "=h", (330, 66, 6, 2))
|
||||
self.assertTrue(a.is_contiguous("C"))
|
||||
self.assertTrue(a.is_contiguous("A"))
|
||||
self.assertFalse(a.is_contiguous("F"))
|
||||
a = Exporter((10, 4), "=h", (2, 20))
|
||||
self.assertTrue(a.is_contiguous("F"))
|
||||
self.assertTrue(a.is_contiguous("A"))
|
||||
self.assertFalse(a.is_contiguous("C"))
|
||||
a = Exporter((13, 5, 11, 3), "=h", (2, 26, 130, 1430))
|
||||
self.assertTrue(a.is_contiguous("F"))
|
||||
self.assertTrue(a.is_contiguous("A"))
|
||||
self.assertFalse(a.is_contiguous("C"))
|
||||
a = Exporter((2, 11, 6, 4), "=h", (576, 48, 8, 2))
|
||||
self.assertFalse(a.is_contiguous("A"))
|
||||
a = Exporter((2, 11, 6, 4), "=h", (2, 4, 48, 288))
|
||||
self.assertFalse(a.is_contiguous("A"))
|
||||
a = Exporter((3, 2, 2), "=h", (16, 8, 4))
|
||||
self.assertFalse(a.is_contiguous("A"))
|
||||
a = Exporter((3, 2, 2), "=h", (4, 12, 24))
|
||||
self.assertFalse(a.is_contiguous("A"))
|
||||
|
||||
def test_PyBUF_flags(self):
|
||||
a = Exporter((10, 2), "d")
|
||||
b = Importer(a, PyBUF_SIMPLE)
|
||||
self.assertTrue(b.obj is a)
|
||||
self.assertTrue(b.format is None)
|
||||
self.assertEqual(b.len, a.len)
|
||||
self.assertEqual(b.itemsize, a.itemsize)
|
||||
self.assertTrue(b.shape is None)
|
||||
self.assertTrue(b.strides is None)
|
||||
self.assertTrue(b.suboffsets is None)
|
||||
self.assertTrue(b.internal is None)
|
||||
self.assertFalse(b.readonly)
|
||||
b = Importer(a, PyBUF_WRITABLE)
|
||||
self.assertTrue(b.obj is a)
|
||||
self.assertTrue(b.format is None)
|
||||
self.assertEqual(b.len, a.len)
|
||||
self.assertEqual(b.itemsize, a.itemsize)
|
||||
self.assertTrue(b.shape is None)
|
||||
self.assertTrue(b.strides is None)
|
||||
self.assertTrue(b.suboffsets is None)
|
||||
self.assertTrue(b.internal is None)
|
||||
self.assertFalse(b.readonly)
|
||||
b = Importer(a, PyBUF_ND)
|
||||
self.assertTrue(b.obj is a)
|
||||
self.assertTrue(b.format is None)
|
||||
self.assertEqual(b.len, a.len)
|
||||
self.assertEqual(b.itemsize, a.itemsize)
|
||||
self.assertEqual(b.shape, a.shape)
|
||||
self.assertTrue(b.strides is None)
|
||||
self.assertTrue(b.suboffsets is None)
|
||||
self.assertTrue(b.internal is None)
|
||||
self.assertFalse(b.readonly)
|
||||
a = Exporter((5, 10), "=h", (24, 2))
|
||||
b = Importer(a, PyBUF_STRIDES)
|
||||
self.assertTrue(b.obj is a)
|
||||
self.assertTrue(b.format is None)
|
||||
self.assertEqual(b.len, a.len)
|
||||
self.assertEqual(b.itemsize, a.itemsize)
|
||||
self.assertEqual(b.shape, a.shape)
|
||||
self.assertEqual(b.strides, a.strides)
|
||||
self.assertTrue(b.suboffsets is None)
|
||||
self.assertTrue(b.internal is None)
|
||||
self.assertFalse(b.readonly)
|
||||
b = Importer(a, PyBUF_FULL)
|
||||
self.assertTrue(b.obj is a)
|
||||
self.assertEqual(b.format, "=h")
|
||||
self.assertEqual(b.len, a.len)
|
||||
self.assertEqual(b.itemsize, a.itemsize)
|
||||
self.assertEqual(b.shape, a.shape)
|
||||
self.assertEqual(b.strides, a.strides)
|
||||
self.assertTrue(b.suboffsets is None)
|
||||
self.assertTrue(b.internal is None)
|
||||
self.assertFalse(b.readonly)
|
||||
self.assertRaises(BufferError, Importer, a, PyBUF_SIMPLE)
|
||||
self.assertRaises(BufferError, Importer, a, PyBUF_WRITABLE)
|
||||
self.assertRaises(BufferError, Importer, a, PyBUF_ND)
|
||||
self.assertRaises(BufferError, Importer, a, PyBUF_C_CONTIGUOUS)
|
||||
self.assertRaises(BufferError, Importer, a, PyBUF_F_CONTIGUOUS)
|
||||
self.assertRaises(BufferError, Importer, a, PyBUF_ANY_CONTIGUOUS)
|
||||
self.assertRaises(BufferError, Importer, a, PyBUF_CONTIG)
|
||||
|
||||
def test_negative_strides(self):
|
||||
self.check_args(3, (3, 5, 4), "B", (20, 4, -1), 60, 60, 1, 3)
|
||||
self.check_args(3, (3, 5, 3), "B", (20, 4, -1), 45, 60, 1, 2)
|
||||
self.check_args(3, (3, 5, 4), "B", (20, -4, 1), 60, 60, 1, 16)
|
||||
self.check_args(3, (3, 5, 4), "B", (-20, -4, -1), 60, 60, 1, 59)
|
||||
self.check_args(3, (3, 5, 3), "B", (-20, -4, -1), 45, 60, 1, 58)
|
||||
|
||||
def test_attributes(self):
|
||||
a = Exporter((13, 5, 11, 3), "=h", (440, 88, 8, 2))
|
||||
self.assertEqual(a.ndim, 4)
|
||||
self.assertEqual(a.itemsize, 2)
|
||||
self.assertFalse(a.readonly)
|
||||
self.assertEqual(a.shape, (13, 5, 11, 3))
|
||||
self.assertEqual(a.format, "=h")
|
||||
self.assertEqual(a.strides, (440, 88, 8, 2))
|
||||
self.assertEqual(a.len, 4290)
|
||||
self.assertEqual(a.buflen, 5720)
|
||||
self.assertEqual(a.buf, ctypes.addressof(a._buf))
|
||||
a = Exporter((8,))
|
||||
self.assertEqual(a.ndim, 1)
|
||||
self.assertEqual(a.itemsize, 1)
|
||||
self.assertFalse(a.readonly)
|
||||
self.assertEqual(a.shape, (8,))
|
||||
self.assertEqual(a.format, "B")
|
||||
self.assertTrue(isinstance(a.strides, tuple))
|
||||
self.assertEqual(a.strides, (1,))
|
||||
self.assertEqual(a.len, 8)
|
||||
self.assertEqual(a.buflen, 8)
|
||||
a = Exporter([13, 5, 11, 3], "=h", [440, 88, 8, 2])
|
||||
self.assertTrue(isinstance(a.shape, tuple))
|
||||
self.assertTrue(isinstance(a.strides, tuple))
|
||||
self.assertEqual(a.shape, (13, 5, 11, 3))
|
||||
self.assertEqual(a.strides, (440, 88, 8, 2))
|
||||
|
||||
def test_itemsize(self):
|
||||
exp = Exporter((4, 5), format="B", itemsize=8)
|
||||
imp = Importer(exp, PyBUF_RECORDS)
|
||||
self.assertEqual(imp.itemsize, 8)
|
||||
self.assertEqual(imp.format, "B")
|
||||
self.assertEqual(imp.strides, (40, 8))
|
||||
exp = Exporter((4, 5), format="weird", itemsize=5)
|
||||
imp = Importer(exp, PyBUF_RECORDS)
|
||||
self.assertEqual(imp.itemsize, 5)
|
||||
self.assertEqual(imp.format, "weird")
|
||||
self.assertEqual(imp.strides, (25, 5))
|
||||
|
||||
def check_args(
|
||||
self, call_flags, shape, format, strides, length, bufsize, itemsize, offset=0
|
||||
):
|
||||
format_arg = format if call_flags & 1 else None
|
||||
strides_arg = strides if call_flags & 2 else None
|
||||
a = Exporter(shape, format_arg, strides_arg)
|
||||
self.assertEqual(a.buflen, bufsize)
|
||||
self.assertEqual(a.buf, ctypes.addressof(a._buf) + offset)
|
||||
m = Importer(a, PyBUF_RECORDS_RO)
|
||||
self.assertEqual(m.buf, a.buf)
|
||||
self.assertEqual(m.len, length)
|
||||
self.assertEqual(m.format, format)
|
||||
self.assertEqual(m.itemsize, itemsize)
|
||||
self.assertEqual(m.shape, shape)
|
||||
self.assertEqual(m.strides, strides)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,343 @@
|
||||
import sys
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise RuntimeError("This module is for import only")
|
||||
test_pkg_name = ".".join(__name__.split(".")[0:-2])
|
||||
is_pygame_pkg = test_pkg_name == "pygame.tests"
|
||||
test_runner_mod = test_pkg_name + ".test_utils.test_runner"
|
||||
|
||||
if is_pygame_pkg:
|
||||
from pygame.tests.test_utils import import_submodule
|
||||
from pygame.tests.test_utils.test_runner import (
|
||||
TEST_RESULTS_START,
|
||||
combine_results,
|
||||
get_test_results,
|
||||
prepare_test_env,
|
||||
run_test,
|
||||
)
|
||||
else:
|
||||
from test.test_utils import import_submodule
|
||||
from test.test_utils.test_runner import (
|
||||
TEST_RESULTS_START,
|
||||
combine_results,
|
||||
get_test_results,
|
||||
prepare_test_env,
|
||||
run_test,
|
||||
)
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import shutil
|
||||
import tempfile
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pprint import pformat
|
||||
|
||||
import pygame
|
||||
|
||||
was_run = False
|
||||
|
||||
|
||||
def run(*args, **kwds):
|
||||
"""Run the Pygame unit test suite and return (total tests run, fails dict)
|
||||
|
||||
Positional arguments (optional):
|
||||
The names of tests to include. If omitted then all tests are run. Test
|
||||
names need not include the trailing '_test'.
|
||||
|
||||
Keyword arguments:
|
||||
incomplete - fail incomplete tests (default False)
|
||||
usesubprocess - run all test suites in the current process
|
||||
(default False, use separate subprocesses)
|
||||
dump - dump failures/errors as dict ready to eval (default False)
|
||||
file - if provided, the name of a file into which to dump failures/errors
|
||||
timings - if provided, the number of times to run each individual test to
|
||||
get an average run time (default is run each test once)
|
||||
exclude - A list of TAG names to exclude from the run. The items may be
|
||||
comma or space separated.
|
||||
show_output - show silenced stderr/stdout on errors (default False)
|
||||
all - dump all results, not just errors (default False)
|
||||
randomize - randomize order of tests (default False)
|
||||
seed - if provided, a seed randomizer integer
|
||||
multi_thread - if provided, the number of THREADS in which to run
|
||||
subprocessed tests
|
||||
time_out - if subprocess is True then the time limit in seconds before
|
||||
killing a test (default 30)
|
||||
fake - if provided, the name of the fake tests package in the
|
||||
run_tests__tests subpackage to run instead of the normal
|
||||
Pygame tests
|
||||
python - the path to a python executable to run subprocessed tests
|
||||
(default sys.executable)
|
||||
interactive - allow tests tagged 'interactive'.
|
||||
|
||||
Return value:
|
||||
A tuple of total number of tests run, dictionary of error information. The
|
||||
dictionary is empty if no errors were recorded.
|
||||
|
||||
By default, individual test modules are run in separate subprocesses. This
|
||||
recreates normal Pygame usage where pygame.init() and pygame.quit() are
|
||||
called only once per program execution, and avoids unfortunate
|
||||
interactions between test modules. Also, a time limit is placed on test
|
||||
execution, so frozen tests are killed when there time allotment expired.
|
||||
Use the single process option if threading is not working properly or if
|
||||
tests are taking too long. It is not guaranteed that all tests will pass
|
||||
in single process mode.
|
||||
|
||||
Tests are run in a randomized order if the randomize argument is True or a
|
||||
seed argument is provided. If no seed integer is provided then the system
|
||||
time is used.
|
||||
|
||||
Individual test modules may have a corresponding *_tags.py module,
|
||||
defining a __tags__ attribute, a list of tag strings used to selectively
|
||||
omit modules from a run. By default, only the 'interactive', 'ignore', and
|
||||
'subprocess_ignore' tags are ignored. 'interactive' is for modules that
|
||||
take user input, like controller_test.py. 'ignore' and 'subprocess_ignore' for
|
||||
disabling modules for foreground and subprocess modes respectively.
|
||||
These are for disabling tests on optional modules or for experimental
|
||||
modules with known problems. These modules can be run from the console as
|
||||
a Python program.
|
||||
|
||||
This function can only be called once per Python session. It is not
|
||||
reentrant.
|
||||
|
||||
"""
|
||||
|
||||
global was_run
|
||||
|
||||
if was_run:
|
||||
raise RuntimeError("run() was already called this session")
|
||||
was_run = True
|
||||
|
||||
options = kwds.copy()
|
||||
option_usesubprocess = options.get("usesubprocess", False)
|
||||
option_dump = options.pop("dump", False)
|
||||
option_file = options.pop("file", None)
|
||||
option_randomize = options.get("randomize", False)
|
||||
option_seed = options.get("seed", None)
|
||||
option_multi_thread = options.pop("multi_thread", 1)
|
||||
option_time_out = options.pop("time_out", 120)
|
||||
option_fake = options.pop("fake", None)
|
||||
option_python = options.pop("python", sys.executable)
|
||||
option_exclude = options.pop("exclude", ())
|
||||
option_interactive = options.pop("interactive", False)
|
||||
|
||||
if not option_interactive and "interactive" not in option_exclude:
|
||||
option_exclude += ("interactive",)
|
||||
if option_usesubprocess and "subprocess_ignore" not in option_exclude:
|
||||
option_exclude += ("subprocess_ignore",)
|
||||
elif "ignore" not in option_exclude:
|
||||
option_exclude += ("ignore",)
|
||||
|
||||
option_exclude += ("python3_ignore",)
|
||||
option_exclude += ("SDL2_ignore",)
|
||||
|
||||
main_dir, test_subdir, fake_test_subdir = prepare_test_env()
|
||||
|
||||
###########################################################################
|
||||
# Compile a list of test modules. If fake, then compile list of fake
|
||||
# xxxx_test.py from run_tests__tests
|
||||
|
||||
TEST_MODULE_RE = re.compile(r"^(.+_test)\.py$")
|
||||
|
||||
test_mods_pkg_name = test_pkg_name
|
||||
|
||||
working_dir_temp = tempfile.mkdtemp()
|
||||
|
||||
if option_fake is not None:
|
||||
test_mods_pkg_name = ".".join(
|
||||
[test_mods_pkg_name, "run_tests__tests", option_fake]
|
||||
)
|
||||
test_subdir = os.path.join(fake_test_subdir, option_fake)
|
||||
working_dir = test_subdir
|
||||
else:
|
||||
working_dir = working_dir_temp
|
||||
|
||||
# Added in because some machines will need os.environ else there will be
|
||||
# false failures in subprocess mode. Same issue as python2.6. Needs some
|
||||
# env vars.
|
||||
|
||||
test_env = os.environ
|
||||
|
||||
fmt1 = "%s.%%s" % test_mods_pkg_name
|
||||
fmt2 = "%s.%%s_test" % test_mods_pkg_name
|
||||
if args:
|
||||
test_modules = [m.endswith("_test") and (fmt1 % m) or (fmt2 % m) for m in args]
|
||||
else:
|
||||
test_modules = []
|
||||
for f in sorted(os.listdir(test_subdir)):
|
||||
for match in TEST_MODULE_RE.findall(f):
|
||||
test_modules.append(fmt1 % (match,))
|
||||
|
||||
###########################################################################
|
||||
# Remove modules to be excluded.
|
||||
|
||||
tmp = test_modules
|
||||
test_modules = []
|
||||
for name in tmp:
|
||||
tag_module_name = f"{name[0:-5]}_tags"
|
||||
try:
|
||||
tag_module = import_submodule(tag_module_name)
|
||||
except ImportError:
|
||||
test_modules.append(name)
|
||||
else:
|
||||
try:
|
||||
tags = tag_module.__tags__
|
||||
except AttributeError:
|
||||
print(f"{tag_module_name} has no tags: ignoring")
|
||||
test_modules.append(name)
|
||||
else:
|
||||
for tag in tags:
|
||||
if tag in option_exclude:
|
||||
print(f"skipping {name} (tag '{tag}')")
|
||||
break
|
||||
else:
|
||||
test_modules.append(name)
|
||||
del tmp, tag_module_name, name
|
||||
|
||||
###########################################################################
|
||||
# Meta results
|
||||
|
||||
results = {}
|
||||
meta_results = {"__meta__": {}}
|
||||
meta = meta_results["__meta__"]
|
||||
|
||||
###########################################################################
|
||||
# Randomization
|
||||
|
||||
if option_randomize or option_seed is not None:
|
||||
if option_seed is None:
|
||||
option_seed = time.time()
|
||||
meta["random_seed"] = option_seed
|
||||
print(f"\nRANDOM SEED USED: {option_seed}\n")
|
||||
random.seed(option_seed)
|
||||
random.shuffle(test_modules)
|
||||
|
||||
###########################################################################
|
||||
# Single process mode
|
||||
|
||||
if not option_usesubprocess:
|
||||
options["exclude"] = option_exclude
|
||||
t = time.time()
|
||||
for module in test_modules:
|
||||
results.update(run_test(module, **options))
|
||||
t = time.time() - t
|
||||
|
||||
###########################################################################
|
||||
# Subprocess mode
|
||||
#
|
||||
|
||||
else:
|
||||
if is_pygame_pkg:
|
||||
from pygame.tests.test_utils.async_sub import proc_in_time_or_kill
|
||||
else:
|
||||
from test.test_utils.async_sub import proc_in_time_or_kill
|
||||
|
||||
pass_on_args = ["--exclude", ",".join(option_exclude)] + [
|
||||
f"--{field}"
|
||||
for field in ("randomize", "incomplete", "unbuffered", "verbosity")
|
||||
if kwds.get(field)
|
||||
]
|
||||
|
||||
def sub_test(module):
|
||||
print(f"loading {module}")
|
||||
|
||||
cmd = [option_python, "-m", test_runner_mod, module] + pass_on_args
|
||||
|
||||
return (
|
||||
module,
|
||||
(cmd, test_env, working_dir),
|
||||
proc_in_time_or_kill(
|
||||
cmd, option_time_out, env=test_env, wd=working_dir
|
||||
),
|
||||
)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=option_multi_thread) as executor:
|
||||
t = time.time()
|
||||
|
||||
for module, cmd, (return_code, raw_return) in executor.map(
|
||||
sub_test, test_modules
|
||||
):
|
||||
test_file = f"{os.path.join(test_subdir, module)}.py"
|
||||
cmd, test_env, working_dir = cmd
|
||||
|
||||
test_results = get_test_results(raw_return)
|
||||
if test_results:
|
||||
results.update(test_results)
|
||||
else:
|
||||
results[module] = {}
|
||||
|
||||
results[module].update(
|
||||
{
|
||||
"return_code": return_code,
|
||||
"raw_return": raw_return,
|
||||
"cmd": cmd,
|
||||
"test_file": test_file,
|
||||
"test_env": test_env,
|
||||
"working_dir": working_dir,
|
||||
"module": module,
|
||||
}
|
||||
)
|
||||
|
||||
t = time.time() - t
|
||||
|
||||
###########################################################################
|
||||
# Output Results
|
||||
#
|
||||
|
||||
untrusty_total, combined = combine_results(results, t)
|
||||
total, n_errors, n_failures = count_results(results)
|
||||
|
||||
meta["total_tests"] = total
|
||||
meta["combined"] = combined
|
||||
meta["total_errors"] = n_errors
|
||||
meta["total_failures"] = n_failures
|
||||
results.update(meta_results)
|
||||
|
||||
if not option_usesubprocess and total != untrusty_total:
|
||||
raise AssertionError(
|
||||
"Something went wrong in the Test Machinery:\n"
|
||||
"total: %d != untrusty_total: %d" % (total, untrusty_total)
|
||||
)
|
||||
|
||||
if not option_dump:
|
||||
print(combined)
|
||||
else:
|
||||
print(TEST_RESULTS_START)
|
||||
print(pformat(results))
|
||||
|
||||
if option_file is not None:
|
||||
results_file = open(option_file, "w")
|
||||
try:
|
||||
results_file.write(pformat(results))
|
||||
finally:
|
||||
results_file.close()
|
||||
|
||||
shutil.rmtree(working_dir_temp)
|
||||
|
||||
return total, n_errors + n_failures
|
||||
|
||||
|
||||
def count_results(results):
|
||||
total = errors = failures = 0
|
||||
for result in results.values():
|
||||
if result.get("return_code", 0):
|
||||
total += 1
|
||||
errors += 1
|
||||
else:
|
||||
total += result["num_tests"]
|
||||
errors += result["num_errors"]
|
||||
failures += result["num_failures"]
|
||||
|
||||
return total, errors, failures
|
||||
|
||||
|
||||
def run_and_exit(*args, **kwargs):
|
||||
"""Run the tests, and if there are failures, exit with a return code of 1.
|
||||
|
||||
This is needed for various buildbots to recognise that the tests have
|
||||
failed.
|
||||
"""
|
||||
total, fails = run(*args, **kwargs)
|
||||
if fails:
|
||||
sys.exit(1)
|
||||
sys.exit(0)
|
||||
@@ -0,0 +1,89 @@
|
||||
import inspect
|
||||
import random
|
||||
import re
|
||||
import unittest
|
||||
|
||||
try:
|
||||
from StringIO import StringIO
|
||||
except ImportError:
|
||||
from io import StringIO
|
||||
|
||||
from . import import_submodule
|
||||
|
||||
|
||||
class PygameTestLoader(unittest.TestLoader):
|
||||
def __init__(
|
||||
self, randomize_tests=False, include_incomplete=False, exclude=("interactive",)
|
||||
):
|
||||
super().__init__()
|
||||
self.randomize_tests = randomize_tests
|
||||
|
||||
if exclude is None:
|
||||
self.exclude = set()
|
||||
else:
|
||||
self.exclude = set(exclude)
|
||||
|
||||
if include_incomplete:
|
||||
self.testMethodPrefix = ("test", "todo_")
|
||||
|
||||
def getTestCaseNames(self, testCaseClass):
|
||||
res = []
|
||||
for name in super().getTestCaseNames(testCaseClass):
|
||||
tags = get_tags(testCaseClass, getattr(testCaseClass, name))
|
||||
if self.exclude.isdisjoint(tags):
|
||||
res.append(name)
|
||||
|
||||
if self.randomize_tests:
|
||||
random.shuffle(res)
|
||||
|
||||
return res
|
||||
|
||||
|
||||
# Exclude by tags:
|
||||
|
||||
TAGS_RE = re.compile(r"\|[tT]ags:(-?[ a-zA-Z,0-9_\n]+)\|", re.M)
|
||||
|
||||
|
||||
class TheTestTags:
|
||||
def __init__(self):
|
||||
self.memoized = {}
|
||||
self.parent_modules = {}
|
||||
|
||||
def get_parent_module(self, class_):
|
||||
if class_ not in self.parent_modules:
|
||||
self.parent_modules[class_] = import_submodule(class_.__module__)
|
||||
return self.parent_modules[class_]
|
||||
|
||||
def __call__(self, parent_class, meth):
|
||||
key = (parent_class, meth.__name__)
|
||||
if key not in self.memoized:
|
||||
parent_module = self.get_parent_module(parent_class)
|
||||
|
||||
module_tags = getattr(parent_module, "__tags__", [])
|
||||
class_tags = getattr(parent_class, "__tags__", [])
|
||||
|
||||
tags = TAGS_RE.search(inspect.getdoc(meth) or "")
|
||||
if tags:
|
||||
test_tags = [t.strip() for t in tags.group(1).split(",")]
|
||||
else:
|
||||
test_tags = []
|
||||
|
||||
combined = set()
|
||||
for tags in (module_tags, class_tags, test_tags):
|
||||
if not tags:
|
||||
continue
|
||||
|
||||
add = {t for t in tags if not t.startswith("-")}
|
||||
remove = {t[1:] for t in tags if t not in add}
|
||||
|
||||
if add:
|
||||
combined.update(add)
|
||||
if remove:
|
||||
combined.difference_update(remove)
|
||||
|
||||
self.memoized[key] = combined
|
||||
|
||||
return self.memoized[key]
|
||||
|
||||
|
||||
get_tags = TheTestTags()
|
||||
@@ -0,0 +1,330 @@
|
||||
import os
|
||||
import sys
|
||||
|
||||
if __name__ == "__main__":
|
||||
pkg_dir = os.path.split(os.path.split(os.path.abspath(__file__))[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 io
|
||||
import optparse
|
||||
import re
|
||||
import unittest
|
||||
from pprint import pformat
|
||||
|
||||
from .test_machinery import PygameTestLoader
|
||||
|
||||
|
||||
def prepare_test_env():
|
||||
test_subdir = os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
|
||||
main_dir = os.path.split(test_subdir)[0]
|
||||
sys.path.insert(0, test_subdir)
|
||||
fake_test_subdir = os.path.join(test_subdir, "run_tests__tests")
|
||||
return main_dir, test_subdir, fake_test_subdir
|
||||
|
||||
|
||||
main_dir, test_subdir, fake_test_subdir = prepare_test_env()
|
||||
|
||||
################################################################################
|
||||
# Set the command line options.
|
||||
#
|
||||
# Options are shared with run_tests.py so make sure not to conflict
|
||||
# in time more will be added here
|
||||
|
||||
TAG_PAT = r"-?[a-zA-Z0-9_]+"
|
||||
TAG_RE = re.compile(TAG_PAT)
|
||||
EXCLUDE_RE = re.compile(rf"({TAG_PAT},?\s*)+$")
|
||||
|
||||
|
||||
def exclude_callback(option, opt, value, parser):
|
||||
if EXCLUDE_RE.match(value) is None:
|
||||
raise optparse.OptionValueError(f"{opt} argument has invalid value")
|
||||
parser.values.exclude = TAG_RE.findall(value)
|
||||
|
||||
|
||||
opt_parser = optparse.OptionParser()
|
||||
|
||||
opt_parser.add_option(
|
||||
"-i", "--incomplete", action="store_true", help="fail incomplete tests"
|
||||
)
|
||||
|
||||
opt_parser.add_option(
|
||||
"-s",
|
||||
"--usesubprocess",
|
||||
action="store_true",
|
||||
help="run everything in a single process (default: use no subprocesses)",
|
||||
)
|
||||
|
||||
opt_parser.add_option(
|
||||
"-e",
|
||||
"--exclude",
|
||||
action="callback",
|
||||
type="string",
|
||||
help="exclude tests containing any of TAGS",
|
||||
callback=exclude_callback,
|
||||
)
|
||||
|
||||
opt_parser.add_option(
|
||||
"-u",
|
||||
"--unbuffered",
|
||||
action="store_true",
|
||||
help="Show stdout/stderr as tests run, rather than storing it and showing on failures",
|
||||
)
|
||||
|
||||
opt_parser.add_option(
|
||||
"-v",
|
||||
"--verbose",
|
||||
dest="verbosity",
|
||||
action="store_const",
|
||||
const=2,
|
||||
help="Verbose output",
|
||||
)
|
||||
opt_parser.add_option(
|
||||
"-q",
|
||||
"--quiet",
|
||||
dest="verbosity",
|
||||
action="store_const",
|
||||
const=0,
|
||||
help="Quiet output",
|
||||
)
|
||||
|
||||
opt_parser.add_option(
|
||||
"-r", "--randomize", action="store_true", help="randomize order of tests"
|
||||
)
|
||||
|
||||
################################################################################
|
||||
# If an xxxx_test.py takes longer than TIME_OUT seconds it will be killed
|
||||
# This is only the default, can be over-ridden on command line
|
||||
|
||||
TIME_OUT = 30
|
||||
|
||||
# DEFAULTS
|
||||
|
||||
################################################################################
|
||||
# Human readable output
|
||||
#
|
||||
|
||||
COMPLETE_FAILURE_TEMPLATE = """
|
||||
======================================================================
|
||||
ERROR: all_tests_for (%(module)s.AllTestCases)
|
||||
----------------------------------------------------------------------
|
||||
Traceback (most recent call last):
|
||||
File "test/%(module)s.py", line 1, in all_tests_for
|
||||
subprocess completely failed with return code of %(return_code)s
|
||||
cmd: %(cmd)s
|
||||
test_env: %(test_env)s
|
||||
working_dir: %(working_dir)s
|
||||
return (first 10 and last 10 lines):
|
||||
%(raw_return)s
|
||||
|
||||
""" # Leave that last empty line else build page regex won't match
|
||||
# Text also needs to be vertically compressed
|
||||
|
||||
|
||||
RAN_TESTS_DIV = (70 * "-") + "\nRan"
|
||||
|
||||
DOTS = re.compile("^([FE.sux]*)$", re.MULTILINE)
|
||||
|
||||
|
||||
def extract_tracebacks(output):
|
||||
"""from test runner output return the tracebacks."""
|
||||
verbose_mode = " ..." in output
|
||||
|
||||
if verbose_mode:
|
||||
if "ERROR" in output or "FAILURE" in output:
|
||||
return "\n\n==".join(output.split("\n\n==")[1:])
|
||||
else:
|
||||
dots = DOTS.search(output).group(1)
|
||||
if "E" in dots or "F" in dots:
|
||||
return output[len(dots) + 1 :].split(RAN_TESTS_DIV)[0]
|
||||
return ""
|
||||
|
||||
|
||||
def output_into_dots(output):
|
||||
"""convert the test runner output into dots."""
|
||||
# verbose_mode = ") ..." in output
|
||||
verbose_mode = " ..." in output
|
||||
|
||||
if verbose_mode:
|
||||
# a map from the verbose output to the dots output.
|
||||
reasons = {
|
||||
"... ERROR": "E",
|
||||
"... unexpected success": "u",
|
||||
"... skipped": "s",
|
||||
"... expected failure": "x",
|
||||
"... ok": ".",
|
||||
"... FAIL": "F",
|
||||
}
|
||||
results = output.split("\n\n==")[0]
|
||||
lines = [l for l in results.split("\n") if l and "..." in l]
|
||||
dotlist = []
|
||||
for l in lines:
|
||||
found = False
|
||||
for reason in reasons:
|
||||
if reason in l:
|
||||
dotlist.append(reasons[reason])
|
||||
found = True
|
||||
break
|
||||
if not found:
|
||||
raise ValueError(f"Not sure what this is. Add to reasons. :{l}")
|
||||
|
||||
return "".join(dotlist)
|
||||
dots = DOTS.search(output).group(1)
|
||||
return dots
|
||||
|
||||
|
||||
def combine_results(all_results, t):
|
||||
"""
|
||||
|
||||
Return pieced together results in a form fit for human consumption. Don't
|
||||
rely on results if piecing together subprocessed results (single process
|
||||
mode is fine). Was originally meant for that purpose but was found to be
|
||||
unreliable. See the dump option for reliable results.
|
||||
|
||||
"""
|
||||
|
||||
all_dots = ""
|
||||
failures = []
|
||||
|
||||
for module, results in sorted(all_results.items()):
|
||||
output, return_code, raw_return = map(
|
||||
results.get, ("output", "return_code", "raw_return")
|
||||
)
|
||||
|
||||
if not output or (return_code and RAN_TESTS_DIV not in output):
|
||||
# would this effect the original dict? TODO
|
||||
output_lines = raw_return.splitlines()
|
||||
if len(output_lines) > 20:
|
||||
results["raw_return"] = "\n".join(
|
||||
output_lines[:10] + ["..."] + output_lines[-10:]
|
||||
)
|
||||
failures.append(COMPLETE_FAILURE_TEMPLATE % results)
|
||||
all_dots += "E"
|
||||
continue
|
||||
|
||||
dots = output_into_dots(output)
|
||||
all_dots += dots
|
||||
tracebacks = extract_tracebacks(output)
|
||||
if tracebacks:
|
||||
failures.append(tracebacks)
|
||||
|
||||
total_fails, total_errors = map(all_dots.count, "FE")
|
||||
total_tests = len(all_dots)
|
||||
|
||||
combined = [all_dots]
|
||||
if failures:
|
||||
combined += ["".join(failures).lstrip("\n")[:-1]]
|
||||
combined += [f"{RAN_TESTS_DIV} {total_tests} tests in {t:.3f}s\n"]
|
||||
|
||||
if failures:
|
||||
infos = ([f"failures={total_fails}"] if total_fails else []) + (
|
||||
[f"errors={total_errors}"] if total_errors else []
|
||||
)
|
||||
combined += [f"FAILED ({', '.join(infos)})\n"]
|
||||
else:
|
||||
combined += ["OK\n"]
|
||||
|
||||
return total_tests, "\n".join(combined)
|
||||
|
||||
|
||||
################################################################################
|
||||
|
||||
TEST_RESULTS_START = "<--!! TEST RESULTS START HERE !!-->"
|
||||
TEST_RESULTS_END = "<--!! TEST RESULTS END HERE !!-->"
|
||||
_test_re_str = f"{TEST_RESULTS_START}\n(.*){TEST_RESULTS_END}"
|
||||
TEST_RESULTS_RE = re.compile(_test_re_str, re.DOTALL | re.M)
|
||||
|
||||
|
||||
def get_test_results(raw_return):
|
||||
if test_results := TEST_RESULTS_RE.search(raw_return):
|
||||
try:
|
||||
return eval(test_results.group(1))
|
||||
except:
|
||||
print(f"BUGGY TEST RESULTS EVAL:\n {test_results.group(1)}")
|
||||
raise
|
||||
|
||||
|
||||
################################################################################
|
||||
|
||||
|
||||
def run_test(
|
||||
module,
|
||||
incomplete=False,
|
||||
usesubprocess=True,
|
||||
randomize=False,
|
||||
exclude=("interactive",),
|
||||
buffer=True,
|
||||
unbuffered=None,
|
||||
verbosity=1,
|
||||
):
|
||||
"""Run a unit test module"""
|
||||
suite = unittest.TestSuite()
|
||||
|
||||
if verbosity is None:
|
||||
verbosity = 1
|
||||
|
||||
if verbosity:
|
||||
print(f"loading {module}")
|
||||
|
||||
loader = PygameTestLoader(
|
||||
randomize_tests=randomize, include_incomplete=incomplete, exclude=exclude
|
||||
)
|
||||
suite.addTest(loader.loadTestsFromName(module))
|
||||
|
||||
output = io.StringIO()
|
||||
runner = unittest.TextTestRunner(stream=output, buffer=buffer, verbosity=verbosity)
|
||||
results = runner.run(suite)
|
||||
|
||||
if verbosity == 2:
|
||||
output.seek(0)
|
||||
print(output.read())
|
||||
output.seek(0)
|
||||
|
||||
# change in way skipped tested counted in Python 3.12.1 only (so far)
|
||||
# This was changed and then reverted in 3.12.2
|
||||
# https://github.com/python/cpython/pull/114994
|
||||
tests_run_and_skipped = results.testsRun
|
||||
if sys.version_info.minor == 12 and sys.version_info.micro == 1:
|
||||
tests_run_and_skipped += len(results.skipped)
|
||||
|
||||
results = {
|
||||
module: {
|
||||
"output": output.getvalue(),
|
||||
"num_tests": tests_run_and_skipped,
|
||||
"num_errors": len(results.errors),
|
||||
"num_failures": len(results.failures),
|
||||
}
|
||||
}
|
||||
|
||||
if usesubprocess:
|
||||
print(TEST_RESULTS_START)
|
||||
print(pformat(results))
|
||||
print(TEST_RESULTS_END)
|
||||
else:
|
||||
return results
|
||||
|
||||
|
||||
################################################################################
|
||||
|
||||
if __name__ == "__main__":
|
||||
options, args = opt_parser.parse_args()
|
||||
if not args:
|
||||
if is_pygame_pkg:
|
||||
run_from = "pygame.tests.go"
|
||||
else:
|
||||
run_from = os.path.join(main_dir, "run_tests.py")
|
||||
sys.exit(f"No test module provided; consider using {run_from} instead")
|
||||
run_test(
|
||||
args[0],
|
||||
incomplete=options.incomplete,
|
||||
usesubprocess=options.usesubprocess,
|
||||
randomize=options.randomize,
|
||||
exclude=options.exclude,
|
||||
buffer=(not options.unbuffered),
|
||||
)
|
||||
|
||||
################################################################################
|
||||
@@ -0,0 +1,511 @@
|
||||
import time
|
||||
import unittest
|
||||
|
||||
import pygame
|
||||
|
||||
Clock = pygame.time.Clock
|
||||
|
||||
|
||||
class ClockTypeTest(unittest.TestCase):
|
||||
__tags__ = ["timing"]
|
||||
|
||||
def test_clock_alias(self):
|
||||
"""Check if pygame.Clock is present and the correct type."""
|
||||
self.assertIs(pygame.Clock, pygame.time.Clock)
|
||||
|
||||
def test_construction(self):
|
||||
"""Ensure a Clock object can be created"""
|
||||
c = Clock()
|
||||
|
||||
self.assertTrue(c, "Clock cannot be constructed")
|
||||
|
||||
def test_get_fps(self):
|
||||
"""test_get_fps tests pygame.time.get_fps()"""
|
||||
# Initialization check, first call should return 0 fps
|
||||
c = Clock()
|
||||
self.assertEqual(c.get_fps(), 0)
|
||||
# Type check get_fps should return float
|
||||
self.assertTrue(type(c.get_fps()) == float)
|
||||
# Allowable margin of error in percentage
|
||||
delta = 0.30
|
||||
# Test fps correctness for 100, 60 and 30 fps
|
||||
self._fps_test(c, 100, delta)
|
||||
self._fps_test(c, 60, delta)
|
||||
self._fps_test(c, 30, delta)
|
||||
|
||||
def _fps_test(self, clock, fps, delta):
|
||||
"""ticks fps times each second, hence get_fps() should return fps"""
|
||||
delay_per_frame = 1.0 / fps
|
||||
for f in range(fps): # For one second tick and sleep
|
||||
clock.tick()
|
||||
time.sleep(delay_per_frame)
|
||||
# We should get around fps (+- fps*delta -- delta % of fps)
|
||||
self.assertAlmostEqual(clock.get_fps(), fps, delta=fps * delta)
|
||||
|
||||
def test_get_rawtime(self):
|
||||
iterations = 10
|
||||
delay = 0.1
|
||||
delay_miliseconds = delay * (10**3) # actual time difference between ticks
|
||||
framerate_limit = 5
|
||||
delta = 50 # allowable error in milliseconds
|
||||
|
||||
# Testing Clock Initialization
|
||||
c = Clock()
|
||||
self.assertEqual(c.get_rawtime(), 0)
|
||||
|
||||
# Testing Raw Time with Frame Delay
|
||||
for f in range(iterations):
|
||||
time.sleep(delay)
|
||||
c.tick(framerate_limit)
|
||||
c1 = c.get_rawtime()
|
||||
self.assertAlmostEqual(delay_miliseconds, c1, delta=delta)
|
||||
|
||||
# Testing get_rawtime() = get_time()
|
||||
for f in range(iterations):
|
||||
time.sleep(delay)
|
||||
c.tick()
|
||||
c1 = c.get_rawtime()
|
||||
c2 = c.get_time()
|
||||
self.assertAlmostEqual(c1, c2, delta=delta)
|
||||
|
||||
def test_get_time(self):
|
||||
# Testing parameters
|
||||
delay = 0.1 # seconds
|
||||
delay_miliseconds = delay * (10**3)
|
||||
iterations = 10
|
||||
delta = 50 # milliseconds
|
||||
|
||||
# Testing Clock Initialization
|
||||
c = Clock()
|
||||
self.assertEqual(c.get_time(), 0)
|
||||
|
||||
# Testing within delay parameter range
|
||||
for i in range(iterations):
|
||||
time.sleep(delay)
|
||||
c.tick()
|
||||
c1 = c.get_time()
|
||||
self.assertAlmostEqual(delay_miliseconds, c1, delta=delta)
|
||||
|
||||
# Comparing get_time() results with the 'time' module
|
||||
for i in range(iterations):
|
||||
t0 = time.time()
|
||||
time.sleep(delay)
|
||||
c.tick()
|
||||
t1 = time.time()
|
||||
c1 = c.get_time() # elapsed time in milliseconds
|
||||
d0 = (t1 - t0) * (
|
||||
10**3
|
||||
) #'time' module elapsed time converted to milliseconds
|
||||
self.assertAlmostEqual(d0, c1, delta=delta)
|
||||
|
||||
def test_tick(self):
|
||||
"""Tests time.Clock.tick()"""
|
||||
"""
|
||||
Loops with a set delay a few times then checks what tick reports to
|
||||
verify its accuracy. Then calls tick with a desired frame-rate and
|
||||
verifies it is not faster than the desired frame-rate nor is it taking
|
||||
a dramatically long time to complete
|
||||
"""
|
||||
|
||||
# Adjust this value to increase the acceptable sleep jitter
|
||||
epsilon = 1.5
|
||||
# Adjust this value to increase the acceptable locked frame-rate jitter
|
||||
epsilon2 = 0.3
|
||||
# adjust this value to increase the acceptable frame-rate margin
|
||||
epsilon3 = 20
|
||||
testing_framerate = 60
|
||||
milliseconds = 5.0
|
||||
|
||||
collection = []
|
||||
c = Clock()
|
||||
|
||||
# verify time.Clock.tick() will measure the time correctly
|
||||
c.tick()
|
||||
for i in range(100):
|
||||
time.sleep(milliseconds / 1000) # convert to seconds
|
||||
collection.append(c.tick())
|
||||
|
||||
# removes the first highest and lowest value
|
||||
for outlier in [min(collection), max(collection)]:
|
||||
if outlier != milliseconds:
|
||||
collection.remove(outlier)
|
||||
|
||||
average_time = float(sum(collection)) / len(collection)
|
||||
|
||||
# assert the deviation from the intended frame-rate is within the
|
||||
# acceptable amount (the delay is not taking a dramatically long time)
|
||||
self.assertAlmostEqual(average_time, milliseconds, delta=epsilon)
|
||||
|
||||
# verify tick will control the frame-rate
|
||||
|
||||
c = Clock()
|
||||
collection = []
|
||||
|
||||
start = time.time()
|
||||
|
||||
for i in range(testing_framerate):
|
||||
collection.append(c.tick(testing_framerate))
|
||||
|
||||
# remove the highest and lowest outliers
|
||||
for outlier in [min(collection), max(collection)]:
|
||||
if outlier != round(1000 / testing_framerate):
|
||||
collection.remove(outlier)
|
||||
|
||||
end = time.time()
|
||||
|
||||
# Since calling tick with a desired fps will prevent the program from
|
||||
# running at greater than the given fps, 100 iterations at 100 fps
|
||||
# should last no less than 1 second
|
||||
self.assertAlmostEqual(end - start, 1, delta=epsilon2)
|
||||
|
||||
average_tick_time = float(sum(collection)) / len(collection)
|
||||
self.assertAlmostEqual(
|
||||
1000 / average_tick_time, testing_framerate, delta=epsilon3
|
||||
)
|
||||
|
||||
def test_tick_busy_loop(self):
|
||||
"""Test tick_busy_loop"""
|
||||
|
||||
c = Clock()
|
||||
|
||||
# Test whether the return value of tick_busy_loop is equal to
|
||||
# (FPS is accurate) or greater than (slower than the set FPS)
|
||||
# with a small margin for error based on differences in how this
|
||||
# test runs in practise - it either sometimes runs slightly fast
|
||||
# or seems to based on a rounding error.
|
||||
second_length = 1000
|
||||
shortfall_tolerance = 1 # (ms) The amount of time a tick is allowed to run short of, to account for underlying rounding errors
|
||||
sample_fps = 40
|
||||
|
||||
self.assertGreaterEqual(
|
||||
c.tick_busy_loop(sample_fps),
|
||||
(second_length / sample_fps) - shortfall_tolerance,
|
||||
)
|
||||
pygame.time.wait(10) # incur delay between ticks that's faster than sample_fps
|
||||
self.assertGreaterEqual(
|
||||
c.tick_busy_loop(sample_fps),
|
||||
(second_length / sample_fps) - shortfall_tolerance,
|
||||
)
|
||||
pygame.time.wait(200) # incur delay between ticks that's slower than sample_fps
|
||||
self.assertGreaterEqual(
|
||||
c.tick_busy_loop(sample_fps),
|
||||
(second_length / sample_fps) - shortfall_tolerance,
|
||||
)
|
||||
|
||||
high_fps = 500
|
||||
self.assertGreaterEqual(
|
||||
c.tick_busy_loop(high_fps), (second_length / high_fps) - shortfall_tolerance
|
||||
)
|
||||
|
||||
low_fps = 1
|
||||
self.assertGreaterEqual(
|
||||
c.tick_busy_loop(low_fps), (second_length / low_fps) - shortfall_tolerance
|
||||
)
|
||||
|
||||
low_non_factor_fps = 35 # 1000/35 makes 28.5714285714
|
||||
frame_length_without_decimal_places = int(
|
||||
second_length / low_non_factor_fps
|
||||
) # Same result as math.floor
|
||||
self.assertGreaterEqual(
|
||||
c.tick_busy_loop(low_non_factor_fps),
|
||||
frame_length_without_decimal_places - shortfall_tolerance,
|
||||
)
|
||||
|
||||
high_non_factor_fps = 750 # 1000/750 makes 1.3333...
|
||||
frame_length_without_decimal_places_2 = int(
|
||||
second_length / high_non_factor_fps
|
||||
) # Same result as math.floor
|
||||
self.assertGreaterEqual(
|
||||
c.tick_busy_loop(high_non_factor_fps),
|
||||
frame_length_without_decimal_places_2 - shortfall_tolerance,
|
||||
)
|
||||
|
||||
zero_fps = 0
|
||||
self.assertEqual(c.tick_busy_loop(zero_fps), 0)
|
||||
|
||||
# Check behaviour of unexpected values
|
||||
|
||||
negative_fps = -1
|
||||
self.assertEqual(c.tick_busy_loop(negative_fps), 0)
|
||||
|
||||
fractional_fps = 32.75
|
||||
frame_length_without_decimal_places_3 = int(second_length / fractional_fps)
|
||||
self.assertGreaterEqual(
|
||||
c.tick_busy_loop(fractional_fps),
|
||||
frame_length_without_decimal_places_3 - shortfall_tolerance,
|
||||
)
|
||||
|
||||
bool_fps = True
|
||||
self.assertGreaterEqual(
|
||||
c.tick_busy_loop(bool_fps), (second_length / bool_fps) - shortfall_tolerance
|
||||
)
|
||||
|
||||
|
||||
class TimeModuleTest(unittest.TestCase):
|
||||
__tags__ = ["timing"]
|
||||
|
||||
def test_multiple_timers(self):
|
||||
"""
|
||||
Test for multiple timers running together, test repeat and dict
|
||||
posting, test per event timing too
|
||||
"""
|
||||
pygame.init()
|
||||
# other timers in background should not affect current timer
|
||||
# test different kinds of timers simultaneously. Test repeat, early
|
||||
# stop with repeat, and stopping timers running on infinite loops.
|
||||
# test dict and no dict posting
|
||||
events_tests_dict = {
|
||||
# each value here is like
|
||||
# (delay time(ms), event dict, set repeat, early repeat stop)
|
||||
pygame.event.custom_type(): (20, {}, 3, None),
|
||||
pygame.event.custom_type(): (13, {1: 2, 3: 1}, 1, None),
|
||||
pygame.event.custom_type(): (30, {"attr1": 10}, 5, 5),
|
||||
pygame.event.custom_type(): (15, {"foo": "bar", "spam": "eggs"}, 10, 8),
|
||||
pygame.event.custom_type(): (16, {}, None, 4),
|
||||
pygame.event.custom_type(): (12, {"test": 42.26}, None, 6),
|
||||
pygame.event.custom_type(): (10, {"foo": "spam", "bar": "eggs"}, None, 8),
|
||||
}
|
||||
|
||||
times = {k: 0.0 for k in events_tests_dict}
|
||||
counts = {k: 0 for k in events_tests_dict}
|
||||
|
||||
# post events, note start times
|
||||
for event, (delay, attrs, repeat, _) in events_tests_dict.items():
|
||||
if repeat is None:
|
||||
pygame.time.set_timer(pygame.event.Event(event, attrs), delay)
|
||||
else:
|
||||
pygame.time.set_timer(pygame.event.Event(event, attrs), delay, repeat)
|
||||
times[event] = time.perf_counter()
|
||||
|
||||
# run for 500ms
|
||||
loop_start = time.perf_counter()
|
||||
while time.perf_counter() < loop_start + 0.5:
|
||||
for event in pygame.event.get():
|
||||
if event.type in events_tests_dict:
|
||||
now_time = time.perf_counter()
|
||||
set_time, set_dict, repeat, stop = events_tests_dict[event.type]
|
||||
# measure time for each event, should almost match expected time
|
||||
self.assertAlmostEqual(
|
||||
(now_time - times[event.type]) * 1000, set_time, delta=4
|
||||
)
|
||||
|
||||
# the dict attribute should be the same reference, if it exists
|
||||
self.assertIs(event.dict, set_dict)
|
||||
|
||||
times[event.type] = now_time
|
||||
counts[event.type] += 1
|
||||
if counts[event.type] == stop:
|
||||
# stop event
|
||||
pygame.time.set_timer(event.type, 0)
|
||||
|
||||
# assert extra events are not created
|
||||
if stop is None:
|
||||
if counts[event.type] > repeat:
|
||||
self.fail("got more events than expected with repeat")
|
||||
else:
|
||||
if counts[event.type] > stop:
|
||||
self.fail("got more events, timer stop did not work")
|
||||
|
||||
# assert events don't come in after the stipulated time
|
||||
time.sleep(0.5)
|
||||
for event in pygame.event.get():
|
||||
self.assertNotIn(event.type, events_tests_dict)
|
||||
|
||||
for event_type, (_, _, repeat, stop) in events_tests_dict.items():
|
||||
# recheck that the counts exactly match, and we don't have lesser
|
||||
# events than expected
|
||||
if stop is not None:
|
||||
self.assertEqual(stop, counts[event_type])
|
||||
else:
|
||||
self.assertEqual(repeat, counts[event_type])
|
||||
|
||||
pygame.quit()
|
||||
|
||||
def test_timer_wrong_args(self):
|
||||
for out_of_range_val in (-1, -10, pygame.NUMEVENTS, pygame.NUMEVENTS + 1):
|
||||
self.assertRaises(ValueError, pygame.time.set_timer, out_of_range_val, 10)
|
||||
self.assertRaises(
|
||||
ValueError, pygame.time.set_timer, event=out_of_range_val, millis=10
|
||||
)
|
||||
|
||||
for incorrect_type in ("string", 4 + 3j, [1, 2, 3], {"a": "b"}):
|
||||
self.assertRaises(TypeError, pygame.time.set_timer, incorrect_type, 15)
|
||||
self.assertRaises(
|
||||
TypeError, pygame.time.set_timer, event=incorrect_type, millis=15
|
||||
)
|
||||
|
||||
def test_timer_common_reference(self):
|
||||
pygame.init()
|
||||
pygame.event.get() # empty queue
|
||||
for event in (
|
||||
pygame.event.Event(pygame.event.custom_type(), attr=(1, 2, 3, 4)),
|
||||
pygame.event.Event(pygame.event.custom_type(), dict={"test": "yes"}),
|
||||
pygame.event.Event(pygame.event.custom_type()),
|
||||
pygame.event.custom_type(),
|
||||
):
|
||||
pygame.time.set_timer(event, 1, loops=2)
|
||||
time.sleep(0.005)
|
||||
events = pygame.event.get(pump=False)
|
||||
self.assertEqual(len(events), 2)
|
||||
|
||||
if isinstance(event, int):
|
||||
for ev in events:
|
||||
self.assertEqual(ev.type, event)
|
||||
self.assertEqual(ev.dict, {})
|
||||
self.assertIsNot(events[0].dict, events[1].dict)
|
||||
else:
|
||||
for ev in events:
|
||||
self.assertEqual(ev.type, event.type)
|
||||
self.assertIs(ev.dict, event.dict)
|
||||
pygame.quit()
|
||||
|
||||
def test_delay(self):
|
||||
"""Tests time.delay() function."""
|
||||
millis = 50 # millisecond to wait on each iteration
|
||||
iterations = 20 # number of iterations
|
||||
delta = 150 # Represents acceptable margin of error for wait in ms
|
||||
# Call checking function
|
||||
self._wait_delay_check(pygame.time.delay, millis, iterations, delta)
|
||||
# After timing behaviour, check argument type exceptions
|
||||
self._type_error_checks(pygame.time.delay)
|
||||
|
||||
def test_get_ticks(self):
|
||||
"""Tests time.get_ticks()"""
|
||||
"""
|
||||
Iterates and delays for arbitrary amount of time for each iteration,
|
||||
check get_ticks to equal correct gap time
|
||||
"""
|
||||
iterations = 20
|
||||
millis = 50
|
||||
delta = 15 # Acceptable margin of error in ms
|
||||
# Assert return type to be int
|
||||
self.assertTrue(type(pygame.time.get_ticks()) == int)
|
||||
for i in range(iterations):
|
||||
curr_ticks = pygame.time.get_ticks() # Save current tick count
|
||||
curr_time = time.time() # Save current time
|
||||
pygame.time.delay(millis) # Delay for millis
|
||||
# Time and Ticks difference from start of the iteration
|
||||
time_diff = round((time.time() - curr_time) * 1000)
|
||||
ticks_diff = pygame.time.get_ticks() - curr_ticks
|
||||
# Assert almost equality of the ticking time and time difference
|
||||
self.assertAlmostEqual(ticks_diff, time_diff, delta=delta)
|
||||
|
||||
def test_set_timer(self):
|
||||
"""Tests time.set_timer()"""
|
||||
"""
|
||||
Tests if a timer will post the correct amount of eventid events in
|
||||
the specified delay. Test is posting event objects work.
|
||||
Also tests if setting milliseconds to 0 stops the timer and if
|
||||
the once argument and repeat arguments work.
|
||||
"""
|
||||
pygame.init()
|
||||
TIMER_EVENT_TYPE = pygame.event.custom_type()
|
||||
timer_event = pygame.event.Event(TIMER_EVENT_TYPE)
|
||||
delta = 50
|
||||
timer_delay = 100
|
||||
test_number = 8 # Number of events to read for the test
|
||||
events = 0 # Events read
|
||||
|
||||
pygame.event.clear()
|
||||
pygame.time.set_timer(TIMER_EVENT_TYPE, timer_delay)
|
||||
|
||||
# Test that 'test_number' events are posted in the right amount of time
|
||||
t1 = pygame.time.get_ticks()
|
||||
max_test_time = t1 + timer_delay * test_number + delta
|
||||
while events < test_number:
|
||||
for event in pygame.event.get():
|
||||
if event == timer_event:
|
||||
events += 1
|
||||
|
||||
# The test takes too much time
|
||||
if pygame.time.get_ticks() > max_test_time:
|
||||
break
|
||||
|
||||
pygame.time.set_timer(TIMER_EVENT_TYPE, 0)
|
||||
t2 = pygame.time.get_ticks()
|
||||
# Is the number ef events and the timing right?
|
||||
self.assertEqual(events, test_number)
|
||||
self.assertAlmostEqual(timer_delay * test_number, t2 - t1, delta=delta)
|
||||
|
||||
# Test that the timer stopped when set with 0ms delay.
|
||||
pygame.time.delay(200)
|
||||
self.assertNotIn(timer_event, pygame.event.get())
|
||||
|
||||
# Test that the old timer for an event is deleted when a new timer is set
|
||||
pygame.time.set_timer(TIMER_EVENT_TYPE, timer_delay)
|
||||
pygame.time.delay(int(timer_delay * 3.5))
|
||||
self.assertEqual(pygame.event.get().count(timer_event), 3)
|
||||
pygame.time.set_timer(TIMER_EVENT_TYPE, timer_delay * 10) # long wait time
|
||||
pygame.time.delay(timer_delay * 5)
|
||||
self.assertNotIn(timer_event, pygame.event.get())
|
||||
pygame.time.set_timer(TIMER_EVENT_TYPE, timer_delay * 3)
|
||||
pygame.time.delay(timer_delay * 7)
|
||||
self.assertEqual(pygame.event.get().count(timer_event), 2)
|
||||
pygame.time.set_timer(TIMER_EVENT_TYPE, timer_delay)
|
||||
pygame.time.delay(int(timer_delay * 5.5))
|
||||
self.assertEqual(pygame.event.get().count(timer_event), 5)
|
||||
|
||||
# Test that the loops=True works
|
||||
pygame.time.set_timer(TIMER_EVENT_TYPE, 10, True)
|
||||
pygame.time.delay(40)
|
||||
self.assertEqual(pygame.event.get().count(timer_event), 1)
|
||||
|
||||
# Test a variety of event objects, test loops argument
|
||||
events_to_test = [
|
||||
pygame.event.Event(TIMER_EVENT_TYPE),
|
||||
pygame.event.Event(
|
||||
TIMER_EVENT_TYPE, foo="9gwz5", baz=12, lol=[124, (34, "")]
|
||||
),
|
||||
pygame.event.Event(pygame.KEYDOWN, key=pygame.K_a, unicode="a"),
|
||||
]
|
||||
repeat = 3
|
||||
millis = 50
|
||||
for e in events_to_test:
|
||||
pygame.time.set_timer(e, millis, loops=repeat)
|
||||
pygame.time.delay(2 * millis * repeat)
|
||||
self.assertEqual(pygame.event.get().count(e), repeat)
|
||||
pygame.quit()
|
||||
|
||||
def test_wait(self):
|
||||
"""Tests time.wait() function."""
|
||||
millis = 100 # millisecond to wait on each iteration
|
||||
iterations = 10 # number of iterations
|
||||
delta = 50 # Represents acceptable margin of error for wait in ms
|
||||
# Call checking function
|
||||
self._wait_delay_check(pygame.time.wait, millis, iterations, delta)
|
||||
# After timing behaviour, check argument type exceptions
|
||||
self._type_error_checks(pygame.time.wait)
|
||||
|
||||
def _wait_delay_check(self, func_to_check, millis, iterations, delta):
|
||||
"""
|
||||
call func_to_check(millis) "iterations" times and check each time if
|
||||
function "waited" for given millisecond (+- delta). At the end, take
|
||||
average time for each call (whole_duration/iterations), which should
|
||||
be equal to millis (+- delta - acceptable margin of error).
|
||||
*Created to avoid code duplication during delay and wait tests
|
||||
"""
|
||||
# take starting time for duration calculation
|
||||
start_time = time.time()
|
||||
for i in range(iterations):
|
||||
wait_time = func_to_check(millis)
|
||||
# Check equality of wait_time and millis with margin of error delta
|
||||
self.assertAlmostEqual(wait_time, millis, delta=delta)
|
||||
stop_time = time.time()
|
||||
# Cycle duration in millisecond
|
||||
duration = round((stop_time - start_time) * 1000)
|
||||
# Duration/Iterations should be (almost) equal to predefined millis
|
||||
self.assertAlmostEqual(duration / iterations, millis, delta=delta)
|
||||
|
||||
def _type_error_checks(self, func_to_check):
|
||||
"""Checks 3 TypeError (float, tuple, string) for the func_to_check"""
|
||||
"""Intended for time.delay and time.wait functions"""
|
||||
# Those methods throw no exceptions on negative integers
|
||||
self.assertRaises(TypeError, func_to_check, 0.1) # check float
|
||||
self.assertRaises(TypeError, pygame.time.delay, (0, 1)) # check tuple
|
||||
self.assertRaises(TypeError, pygame.time.delay, "10") # check string
|
||||
|
||||
|
||||
###############################################################################
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,109 @@
|
||||
import os
|
||||
import unittest
|
||||
|
||||
import pygame
|
||||
from pygame._sdl2 import touch
|
||||
from pygame.tests.test_utils import question
|
||||
|
||||
|
||||
class TouchTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
os.environ["SDL_MOUSE_TOUCH_EVENTS"] = "0"
|
||||
pygame.init()
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
pygame.quit()
|
||||
|
||||
def test_num_devices(self):
|
||||
touch.get_num_devices()
|
||||
|
||||
def test_get_device(self):
|
||||
if touch.get_num_devices() > 0:
|
||||
touch.get_device(0)
|
||||
|
||||
def test_get_device__invalid(self):
|
||||
self.assertRaises(pygame.error, touch.get_device, -1234)
|
||||
self.assertRaises(TypeError, touch.get_device, "test")
|
||||
|
||||
def test_num_fingers(self):
|
||||
if touch.get_num_devices() > 0:
|
||||
if touch.get_device(0) >= 0:
|
||||
# mice acting as touch devices have negative device IDs
|
||||
# they also do not work with get_num_fingers()
|
||||
touch.get_num_fingers(touch.get_device(0))
|
||||
|
||||
def test_num_fingers__invalid(self):
|
||||
self.assertRaises(TypeError, touch.get_num_fingers, "test")
|
||||
self.assertRaises(pygame.error, touch.get_num_fingers, -1234)
|
||||
|
||||
|
||||
class TouchInteractiveTest(unittest.TestCase):
|
||||
__tags__ = ["interactive"]
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
# if we don't have a touch device, enable the mouse to act as a
|
||||
# touch device for the interactive tests.
|
||||
os.environ["SDL_MOUSE_TOUCH_EVENTS"] = "0"
|
||||
pygame.init()
|
||||
if touch.get_num_devices() == 0:
|
||||
pygame.quit()
|
||||
os.environ["SDL_MOUSE_TOUCH_EVENTS"] = "1"
|
||||
pygame.init()
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
pygame.quit()
|
||||
|
||||
def test_get_finger(self):
|
||||
"""ask for touch input and check the dict"""
|
||||
|
||||
os.environ["SDL_VIDEO_WINDOW_POS"] = "50,50"
|
||||
screen = pygame.display.set_mode((1000, 600))
|
||||
screen.fill((255, 255, 255))
|
||||
|
||||
font = pygame.font.Font(None, 32)
|
||||
instructions_str_1 = "Please place some fingers on your touch device"
|
||||
instructions_str_2 = "Close the window when finished, and answer the question"
|
||||
inst_1_render = font.render(instructions_str_1, True, pygame.Color("#000000"))
|
||||
inst_2_render = font.render(instructions_str_2, True, pygame.Color("#000000"))
|
||||
|
||||
running = True
|
||||
while running:
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
running = False
|
||||
|
||||
finger_data_renders = []
|
||||
num_devices = pygame._sdl2.touch.get_num_devices()
|
||||
if num_devices > 0:
|
||||
first_device = pygame._sdl2.touch.get_device(0)
|
||||
if first_device >= 0:
|
||||
num_fingers = pygame._sdl2.touch.get_num_fingers(first_device)
|
||||
else:
|
||||
num_fingers = 1
|
||||
if num_fingers > 0:
|
||||
for finger_index in range(0, num_fingers):
|
||||
data = pygame._sdl2.touch.get_finger(first_device, finger_index)
|
||||
render = font.render(
|
||||
f"finger - {data}", True, pygame.Color("#000000")
|
||||
)
|
||||
|
||||
finger_data_renders.append(render)
|
||||
|
||||
screen.fill((255, 255, 255))
|
||||
screen.blit(inst_1_render, (5, 5))
|
||||
screen.blit(inst_2_render, (5, 40))
|
||||
for index, finger in enumerate(finger_data_renders):
|
||||
screen.blit(finger, (5, 80 + (index * 40)))
|
||||
|
||||
pygame.display.update()
|
||||
|
||||
response = question("Does the finger data seem correct?")
|
||||
self.assertTrue(response)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,26 @@
|
||||
import unittest
|
||||
|
||||
# A basic unit test to test that pygame.typing can import in python code, and
|
||||
# the documented attributes are accessible.
|
||||
# More rigorous testing needs mypy and is therefore implemented in the stubs
|
||||
# directory.
|
||||
TYPING_PUBLIC_ATTRS = [
|
||||
"RectLike",
|
||||
"SequenceLike",
|
||||
"FileLike",
|
||||
"ColorLike",
|
||||
"Point",
|
||||
"IntPoint",
|
||||
]
|
||||
|
||||
|
||||
class TypingTest(unittest.TestCase):
|
||||
def test_typing_has_attrs(self):
|
||||
import pygame.typing
|
||||
|
||||
for i in TYPING_PUBLIC_ATTRS:
|
||||
self.assertTrue(hasattr(pygame.typing, i))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,30 @@
|
||||
import os
|
||||
import unittest
|
||||
from importlib.metadata import version
|
||||
|
||||
import pygame
|
||||
|
||||
pg_header = os.path.join("src_c", "include", "_pygame.h")
|
||||
|
||||
|
||||
class VersionTest(unittest.TestCase):
|
||||
def test_vernum_obj(self):
|
||||
major, minor, patch = map(int, pygame.version.ver.split(".")[:3])
|
||||
self.assertEqual(pygame.version.vernum.major, major)
|
||||
self.assertEqual(pygame.version.vernum[0], major)
|
||||
self.assertEqual(pygame.version.vernum.minor, minor)
|
||||
self.assertEqual(pygame.version.vernum[1], minor)
|
||||
self.assertEqual(pygame.version.vernum.patch, patch)
|
||||
self.assertEqual(pygame.version.vernum[2], patch)
|
||||
|
||||
def test_sdl_version(self):
|
||||
self.assertEqual(len(pygame.version.SDL), 3)
|
||||
self.assertEqual(tuple(pygame.version.SDL), pygame.get_sdl_version())
|
||||
|
||||
def test_installed_version_and_dunder(self):
|
||||
self.assertEqual(pygame.__version__, pygame.version.ver)
|
||||
self.assertEqual(pygame.__version__, version("pygame-ce"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,53 @@
|
||||
import platform
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import pygame
|
||||
from pygame._sdl2 import video
|
||||
|
||||
IS_PYPY = "PyPy" == platform.python_implementation()
|
||||
|
||||
|
||||
class VideoModuleTest(unittest.TestCase):
|
||||
default_caption = "pygame window"
|
||||
|
||||
@unittest.skipIf(
|
||||
not (sys.maxsize > 2**32),
|
||||
"32 bit SDL 2.0.16 has an issue.",
|
||||
)
|
||||
def test_renderer_set_viewport(self):
|
||||
"""works."""
|
||||
window = video.Window(title=self.default_caption, size=(800, 600))
|
||||
renderer = video.Renderer(window=window)
|
||||
renderer.logical_size = (1920, 1080)
|
||||
rect = pygame.Rect(0, 0, 1920, 1080)
|
||||
renderer.set_viewport(rect)
|
||||
self.assertEqual(renderer.get_viewport(), (0, 0, 1920, 1080))
|
||||
|
||||
def test_logical_window_mapping(self):
|
||||
window = video.Window(title=self.default_caption, size=(100, 100))
|
||||
renderer = video.Renderer(window=window)
|
||||
renderer.logical_size = (10, 10)
|
||||
|
||||
self.assertEqual(renderer.coordinates_to_window((10, 10)), (100, 100))
|
||||
self.assertEqual(renderer.coordinates_from_window((100, 100)), (10, 10))
|
||||
with self.assertRaises(TypeError):
|
||||
renderer.coordinates_to_window(42, 42)
|
||||
with self.assertRaises(TypeError):
|
||||
renderer.coordinates_from_window(42, 42)
|
||||
|
||||
@unittest.skipIf(IS_PYPY, "PyPy doesn't have sys.getrefcount")
|
||||
def test_renderer_to_surface_refcount(self):
|
||||
"""Make sure to_surface doesn't leak memory due to reference counting."""
|
||||
window = video.Window(title=self.default_caption, size=(800, 600))
|
||||
renderer = video.Renderer(window=window)
|
||||
surface = pygame.Surface(window.size)
|
||||
|
||||
# directly getting a refcount returns the actual refcount
|
||||
# as opposed to using an intermediate variable where it's 1 more than expected
|
||||
self.assertEqual(sys.getrefcount(renderer.to_surface()), 1)
|
||||
self.assertEqual(sys.getrefcount(renderer.to_surface(surface=surface)), 2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,461 @@
|
||||
import os
|
||||
import platform
|
||||
import unittest
|
||||
|
||||
import pygame
|
||||
from pygame import Window
|
||||
from pygame.version import SDL
|
||||
|
||||
pygame.init()
|
||||
|
||||
|
||||
IS_PYPY = "PyPy" == platform.python_implementation()
|
||||
|
||||
pygame.display.init()
|
||||
is_wayland = pygame.display.get_driver() == "wayland"
|
||||
pygame.display.quit()
|
||||
|
||||
|
||||
class WindowTypeTest(unittest.TestCase):
|
||||
DEFAULT_TITLE = "pygame window"
|
||||
|
||||
def setUp(self):
|
||||
self.win = Window()
|
||||
|
||||
# Used to check the presence and set-ability of boolean attributes without
|
||||
# testing the results of the actions, since the results are not propagated
|
||||
# by the NULL videodriver on CI for some things.
|
||||
def bool_attr_test(self, attr):
|
||||
setattr(self.win, attr, True)
|
||||
setattr(self.win, attr, False)
|
||||
setattr(self.win, attr, "a truthy string")
|
||||
setattr(self.win, attr, "")
|
||||
setattr(self.win, attr, 17)
|
||||
self.assertIsInstance(getattr(self.win, attr), bool)
|
||||
|
||||
def test_grab_mouse_keyboard(self):
|
||||
self.bool_attr_test("grab_mouse")
|
||||
self.bool_attr_test("grab_keyboard")
|
||||
|
||||
self.win.grab_mouse = True
|
||||
self.assertTrue(self.win.grab_mouse)
|
||||
self.win.grab_mouse = False
|
||||
self.assertFalse(self.win.grab_mouse)
|
||||
|
||||
self.win.grab_keyboard = True
|
||||
self.assertTrue(self.win.grab_keyboard)
|
||||
self.win.grab_keyboard = False
|
||||
self.assertFalse(self.win.grab_keyboard)
|
||||
|
||||
def test_mouse_keyboard_grabbed(self):
|
||||
self.assertIsInstance(getattr(self.win, "mouse_grabbed"), bool)
|
||||
self.assertIsInstance(getattr(self.win, "keyboard_grabbed"), bool)
|
||||
self.assertRaises(
|
||||
AttributeError, lambda: setattr(self.win, "mouse_grabbed", False)
|
||||
)
|
||||
self.assertRaises(
|
||||
AttributeError, lambda: setattr(self.win, "keyboard_grabbed", False)
|
||||
)
|
||||
|
||||
def test_title(self):
|
||||
self.assertEqual(self.win.title, self.DEFAULT_TITLE)
|
||||
|
||||
title = "Hello_World你好世界こにじわ"
|
||||
self.win.title = title
|
||||
self.assertEqual(self.win.title, title)
|
||||
|
||||
def test_resizable(self):
|
||||
self.bool_attr_test("resizable")
|
||||
|
||||
@unittest.skipIf(
|
||||
os.environ.get("SDL_VIDEODRIVER") == pygame.NULL_VIDEODRIVER,
|
||||
"requires the SDL_VIDEODRIVER to be a non-null value",
|
||||
)
|
||||
def test_resizable_set(self):
|
||||
self.win.resizable = True
|
||||
self.assertTrue(self.win.resizable)
|
||||
self.win.resizable = False
|
||||
self.assertFalse(self.win.resizable)
|
||||
|
||||
def test_borderless(self):
|
||||
self.bool_attr_test("borderless")
|
||||
|
||||
@unittest.skipIf(
|
||||
os.environ.get("SDL_VIDEODRIVER") == pygame.NULL_VIDEODRIVER,
|
||||
"requires the SDL_VIDEODRIVER to be a non-null value",
|
||||
)
|
||||
def test_borderless_set(self):
|
||||
self.win.borderless = True
|
||||
self.assertTrue(self.win.borderless)
|
||||
self.win.borderless = False
|
||||
self.assertFalse(self.win.borderless)
|
||||
|
||||
def test_always_on_top(self):
|
||||
self.bool_attr_test("always_on_top")
|
||||
|
||||
@unittest.skipIf(
|
||||
os.environ.get("SDL_VIDEODRIVER") == pygame.NULL_VIDEODRIVER,
|
||||
"requires the SDL_VIDEODRIVER to be a non-null value",
|
||||
)
|
||||
@unittest.skipIf(is_wayland, "not supported on wayland")
|
||||
def test_always_on_top_set(self):
|
||||
self.win.always_on_top = True
|
||||
self.assertTrue(self.win.always_on_top)
|
||||
self.win.always_on_top = False
|
||||
self.assertFalse(self.win.always_on_top)
|
||||
|
||||
@unittest.skipIf(
|
||||
os.environ.get("SDL_VIDEODRIVER") == pygame.NULL_VIDEODRIVER,
|
||||
"requires SDL_VIDEODRIVER to be a non-null value",
|
||||
)
|
||||
def test_mouse_rect(self):
|
||||
self.win.mouse_rect = None
|
||||
self.assertIsNone(self.win.mouse_rect)
|
||||
|
||||
TEST_MOUSE_RECT = (10, 10, 123, 456)
|
||||
self.win.mouse_rect = TEST_MOUSE_RECT
|
||||
self.assertIsInstance(self.win.mouse_rect, pygame.Rect)
|
||||
self.assertTupleEqual(tuple(self.win.mouse_rect), TEST_MOUSE_RECT)
|
||||
|
||||
self.assertRaises(
|
||||
TypeError, lambda: setattr(self.win, "mouse_rect", "Incorrect type")
|
||||
)
|
||||
|
||||
# clean the status
|
||||
self.win.mouse_rect = None
|
||||
|
||||
def test_size(self):
|
||||
self.win.size = (1280, 720)
|
||||
self.assertTupleEqual(self.win.size, (1280, 720))
|
||||
|
||||
self.assertRaises(ValueError, lambda: setattr(self.win, "size", (-1, 10)))
|
||||
self.assertRaises(ValueError, lambda: setattr(self.win, "size", (1, -10)))
|
||||
self.assertRaises(ValueError, lambda: setattr(self.win, "size", (-1, -10)))
|
||||
self.assertRaises(ValueError, lambda: setattr(self.win, "size", (0, 0)))
|
||||
|
||||
# test set size when init
|
||||
# On Windows, if SDL <= 2.0.22, this test fails
|
||||
# This bug have been fixed in SDL 2.24.0
|
||||
if SDL > (2, 0, 22):
|
||||
win = Window(size=(12, 34))
|
||||
self.assertTupleEqual((12, 34), win.size)
|
||||
win.destroy()
|
||||
|
||||
self.assertRaises(ValueError, lambda: Window(size=(-1, 0)))
|
||||
|
||||
self.win.size = (640, 480)
|
||||
|
||||
@unittest.skipIf(is_wayland, "not supported on wayland")
|
||||
def test_position(self):
|
||||
new_pos = (self.win.position[0] + 20, self.win.position[1] + 10)
|
||||
self.win.position = new_pos
|
||||
self.assertTupleEqual(self.win.position, new_pos)
|
||||
|
||||
self.win.position = pygame.WINDOWPOS_CENTERED
|
||||
|
||||
# raise TypeError if input is some random number instead of flag
|
||||
self.assertRaises(TypeError, lambda: setattr(self.win, "position", 123))
|
||||
|
||||
# test set position when init
|
||||
win = Window(position=new_pos)
|
||||
self.assertTupleEqual(new_pos, win.position)
|
||||
win.destroy()
|
||||
|
||||
self.assertRaises(TypeError, lambda: Window(position=123))
|
||||
|
||||
def test_maximum_size(self):
|
||||
# Use a new window to prevent being influenced by other tests
|
||||
self.win = Window()
|
||||
|
||||
self.win.maximum_size = (50, 50)
|
||||
self.assertTupleEqual(self.win.maximum_size, (50, 50))
|
||||
|
||||
# size should be limited to the maximum_size
|
||||
self.assertTupleEqual(self.win.size, (50, 50))
|
||||
|
||||
self.win.size = (640, 480)
|
||||
# size should not larger than maximum_size
|
||||
self.assertTupleEqual(self.win.size, (50, 50))
|
||||
|
||||
if SDL.major >= 3:
|
||||
# This part should pass in SDL3
|
||||
self.win.maximum_size = (0, 0) # remove the size limit
|
||||
self.win.size = (640, 480)
|
||||
self.assertTupleEqual(self.win.size, (640, 480))
|
||||
|
||||
self.assertRaises(
|
||||
ValueError, lambda: setattr(self.win, "maximum_size", (-1, -1))
|
||||
)
|
||||
self.assertRaises(
|
||||
TypeError, lambda: setattr(self.win, "maximum_size", "placeholder_str")
|
||||
)
|
||||
|
||||
def test_minimum_size(self):
|
||||
# Use a new window to prevent being influenced by other tests
|
||||
self.win = Window()
|
||||
|
||||
self.win.minimum_size = (700, 700)
|
||||
self.assertTupleEqual(self.win.minimum_size, (700, 700))
|
||||
|
||||
# size should be limited to the minimum_size
|
||||
self.assertTupleEqual(self.win.size, (700, 700))
|
||||
|
||||
self.win.size = (640, 480)
|
||||
# size should not small than minimum_size
|
||||
self.assertTupleEqual(self.win.size, (700, 700))
|
||||
|
||||
if SDL.major >= 3:
|
||||
# This part should pass in SDL3
|
||||
self.win.minimum_size = (0, 0) # remove the size limit
|
||||
self.win.size = (640, 480)
|
||||
self.assertTupleEqual(self.win.size, (640, 480))
|
||||
|
||||
self.assertRaises(
|
||||
ValueError, lambda: setattr(self.win, "minimum_size", (-1, -1))
|
||||
)
|
||||
self.assertRaises(
|
||||
TypeError, lambda: setattr(self.win, "minimum_size", "null_str")
|
||||
)
|
||||
|
||||
def test_min_size_interact_with_max_size(self):
|
||||
# Use a new window to prevent being influenced by other tests
|
||||
self.win = Window()
|
||||
|
||||
self.win.maximum_size = (100, 100)
|
||||
# min size should not larger than max size
|
||||
self.assertRaises(
|
||||
ValueError, lambda: setattr(self.win, "minimum_size", (200, 200))
|
||||
)
|
||||
|
||||
self.win.minimum_size = (90, 90)
|
||||
# max size should not smaller than min size
|
||||
self.assertRaises(
|
||||
ValueError, lambda: setattr(self.win, "maximum_size", (50, 50))
|
||||
)
|
||||
|
||||
# minimum size should be able to equal to maximum size
|
||||
self.win.minimum_size = (60, 60)
|
||||
self.win.maximum_size = (60, 60)
|
||||
self.assertTupleEqual(self.win.maximum_size, (60, 60))
|
||||
self.assertTupleEqual(self.win.minimum_size, (60, 60))
|
||||
|
||||
def test_opacity(self):
|
||||
# Setting is not supported at all with SDL_VIDEODRIVER = pygame.NULL_VIDEODRIVER,
|
||||
# all we can test here is that the attribute exists and is a
|
||||
# float
|
||||
self.assertIsInstance(self.win.opacity, float)
|
||||
|
||||
@unittest.skipIf(
|
||||
os.environ.get("SDL_VIDEODRIVER") == pygame.NULL_VIDEODRIVER,
|
||||
"requires the SDL_VIDEODRIVER to be a non-null value",
|
||||
)
|
||||
@unittest.skipIf(is_wayland, "not supported on wayland")
|
||||
def test_opacity_set(self):
|
||||
self.win.opacity = 0.5
|
||||
self.assertEqual(self.win.opacity, 0.5)
|
||||
self.win.opacity = 0
|
||||
self.assertEqual(self.win.opacity, 0)
|
||||
self.win.opacity = 1
|
||||
self.assertEqual(self.win.opacity, 1)
|
||||
self.win.opacity = -0.1
|
||||
self.assertEqual(self.win.opacity, 0)
|
||||
self.win.opacity = 1.1
|
||||
self.assertEqual(self.win.opacity, 1)
|
||||
|
||||
self.assertRaises(TypeError, lambda: setattr(self.win, "opacity", "null str"))
|
||||
|
||||
def test_init_flags(self):
|
||||
# test no opengl by default
|
||||
win = Window()
|
||||
self.assertFalse(win.opengl)
|
||||
win.destroy()
|
||||
|
||||
# test borderless
|
||||
win = Window(borderless=True)
|
||||
self.assertTrue(win.borderless)
|
||||
win.destroy()
|
||||
|
||||
# test always_on_top
|
||||
win = Window(always_on_top=True)
|
||||
self.assertTrue(win.always_on_top)
|
||||
win.destroy()
|
||||
|
||||
# test resizable
|
||||
win = Window(resizable=True)
|
||||
self.assertTrue(win.resizable)
|
||||
win.destroy()
|
||||
|
||||
# test utility
|
||||
win = Window(utility=True)
|
||||
self.assertTrue(win.utility)
|
||||
win.destroy()
|
||||
|
||||
# should raise a TypeError if keyword is random
|
||||
self.assertRaises(TypeError, lambda: Window(aaa=True))
|
||||
self.assertRaises(TypeError, lambda: Window(aaa=False))
|
||||
|
||||
def test_set_icon(self):
|
||||
self.assertRaises(TypeError, lambda: self.win.set_icon(1234))
|
||||
|
||||
test_icon = pygame.Surface((32, 32))
|
||||
test_icon.fill((255, 0, 0))
|
||||
|
||||
return_value = self.win.set_icon(test_icon)
|
||||
self.assertIsNone(return_value)
|
||||
|
||||
def test_window_object_repr(self):
|
||||
win = Window("awa")
|
||||
self.assertEqual(repr(win), f"<Window(title='{win.title}', id={win.id})>")
|
||||
|
||||
win.destroy()
|
||||
self.assertEqual(repr(win), "<Window(Destroyed)>")
|
||||
|
||||
pygame.display.set_mode((640, 480))
|
||||
win = Window.from_display_module()
|
||||
self.assertEqual(repr(win), "<Window(From Display)>")
|
||||
|
||||
pygame.display.quit()
|
||||
pygame.init()
|
||||
|
||||
def test_from_display_module(self):
|
||||
surf = pygame.display.set_mode((640, 480))
|
||||
|
||||
win1 = Window.from_display_module()
|
||||
win2 = Window.from_display_module()
|
||||
|
||||
self.assertIs(win1, win2)
|
||||
self.assertIs(win1.get_surface(), surf)
|
||||
|
||||
pygame.display.quit()
|
||||
pygame.init()
|
||||
|
||||
@unittest.skipIf(IS_PYPY, "for some reason this test is flaky on pypy")
|
||||
def test_window_surface(self):
|
||||
win = Window(size=(640, 480))
|
||||
surf = win.get_surface()
|
||||
|
||||
self.assertIsInstance(surf, pygame.Surface)
|
||||
|
||||
# test auto resize
|
||||
self.assertTupleEqual(win.size, surf.get_size())
|
||||
win.size = (100, 100)
|
||||
self.assertTupleEqual(win.size, surf.get_size())
|
||||
win.size = (1280, 720)
|
||||
self.assertTupleEqual(win.size, surf.get_size())
|
||||
|
||||
# window surface should be invalid after the window is destroyed
|
||||
win.destroy()
|
||||
self.assertRaises(pygame.error, lambda: surf.fill((0, 0, 0)))
|
||||
|
||||
@unittest.skipIf(IS_PYPY, "for some reason this test is flaky on pypy")
|
||||
def test_window_surface_with_display_module(self):
|
||||
# get_surface() should raise an error if the set_mode() is not called.
|
||||
pygame.display.set_mode((640, 480))
|
||||
win1 = Window.from_display_module()
|
||||
pygame.display.quit()
|
||||
pygame.init()
|
||||
self.assertRaises(pygame.error, lambda: win1.get_surface())
|
||||
|
||||
# the surface returned by get_surface() should be
|
||||
# the surface returned by set_mode()
|
||||
surf1 = pygame.display.set_mode((640, 480))
|
||||
win2 = Window.from_display_module()
|
||||
surf2 = win2.get_surface()
|
||||
self.assertIs(surf1, surf2)
|
||||
|
||||
def test_window_flip(self):
|
||||
win = Window(size=(640, 480))
|
||||
surf = win.get_surface()
|
||||
surf.fill((255, 0, 0))
|
||||
|
||||
self.assertRaises(TypeError, lambda: win.flip("an argument"))
|
||||
self.assertIs(win.flip(), None)
|
||||
win.destroy()
|
||||
|
||||
# creates a new window with no surface associated
|
||||
win = Window(size=(640, 480))
|
||||
self.assertRaisesRegex(
|
||||
pygame.error,
|
||||
"the Window has no surface associated with it, did you forget to call Window.get_surface()",
|
||||
win.flip,
|
||||
)
|
||||
win.destroy()
|
||||
|
||||
@unittest.skipIf(
|
||||
os.environ.get("SDL_VIDEODRIVER") == pygame.NULL_VIDEODRIVER,
|
||||
"OpenGL requires a non-null SDL_VIDEODRIVER",
|
||||
)
|
||||
def test_window_opengl(self):
|
||||
win1 = Window(opengl=True)
|
||||
self.assertTrue(win1.opengl)
|
||||
win1.flip()
|
||||
win1.destroy()
|
||||
|
||||
win2 = Window(opengl=False)
|
||||
self.assertFalse(win2.opengl)
|
||||
win2.get_surface()
|
||||
win2.flip()
|
||||
win2.destroy()
|
||||
|
||||
pygame.display.set_mode((640, 480), pygame.OPENGL)
|
||||
win = Window.from_display_module()
|
||||
self.assertTrue(win.opengl)
|
||||
pygame.display.quit()
|
||||
pygame.init()
|
||||
|
||||
@unittest.skipIf(IS_PYPY, "for some reason this test is flaky on pypy")
|
||||
def test_window_subclassable(self):
|
||||
class WindowSubclass(Window):
|
||||
def __init__(self, title="Different title", size=(640, 480), **flags):
|
||||
super().__init__(title, size, pygame.WINDOWPOS_CENTERED, **flags)
|
||||
self.attribute = 10
|
||||
|
||||
window = WindowSubclass()
|
||||
self.assertTrue(issubclass(WindowSubclass, Window))
|
||||
self.assertIsInstance(window, WindowSubclass)
|
||||
self.assertEqual(window.title, "Different title")
|
||||
self.assertEqual(window.attribute, 10)
|
||||
window.destroy()
|
||||
|
||||
pygame.display.set_mode((200, 200))
|
||||
window = WindowSubclass.from_display_module()
|
||||
self.assertIsInstance(window, WindowSubclass)
|
||||
self.assertEqual(window.size, (200, 200))
|
||||
|
||||
def test_window_flash(self):
|
||||
window = pygame.Window()
|
||||
|
||||
with self.assertRaises(TypeError):
|
||||
window.flash("string")
|
||||
window.flash(2.2)
|
||||
window.flash([0])
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
window.flash(-1)
|
||||
window.flash(3)
|
||||
|
||||
for operation in [
|
||||
pygame.FLASH_CANCEL,
|
||||
pygame.FLASH_BRIEFLY,
|
||||
pygame.FLASH_UNTIL_FOCUSED,
|
||||
]:
|
||||
try:
|
||||
result = window.flash(operation)
|
||||
self.assertIsNone(result)
|
||||
except pygame.error:
|
||||
pass
|
||||
|
||||
def test_window_focused(self):
|
||||
window = pygame.Window()
|
||||
self.assertIsInstance(window.focused, bool)
|
||||
|
||||
def test_handle(self):
|
||||
window = pygame.Window()
|
||||
self.assertIsInstance(window.handle, int)
|
||||
|
||||
def tearDown(self):
|
||||
self.win.destroy()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user