This commit is contained in:
wittmannzl103469 committed 2026-11-05 15:08:42 +01:00
1 parent de41a02749
commit 9af09cebd3
764 files changed
+54218 -78859

No files matched your search

@@ -12,7 +12,7 @@ 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.
useful if the test, such as cdrom_test, is interactive.
For Pygame development the test suite can be run from a Pygame distribution
root directory using run_tests.py. Alternately, test/__main__.py can be run
@@ -103,7 +103,7 @@ 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.
# args will be the test module list, passed as positional argumemts.
options, args = opt_parser.parse_args()
kwds = {}
@@ -1,7 +1,8 @@
import platform
import sys
import unittest
import platform
IS_PYPY = "PyPy" == platform.python_implementation()
try:
@@ -10,6 +11,7 @@ except NameError:
pass
import pygame
quit_count = 0
@@ -113,8 +115,7 @@ class BaseModuleTest(unittest.TestCase):
# verified by first checking the weak reference both before and
# after the regular reference held by o is removed.
import gc
import weakref
import weakref, gc
class NoDictError(RuntimeError):
pass
@@ -192,7 +193,8 @@ class BaseModuleTest(unittest.TestCase):
o = Exporter(shape, typechar, itemsize)
self.assertEqual(getrefcount(o.__array_struct__), 1)
from pygame.tests.test_utils import buftools
if pygame.HAVE_NEWBUF:
from pygame.tests.test_utils import buftools
def NEWBUF_assertSame(self, proxy, exp):
buftools = self.buftools
@@ -207,6 +209,7 @@ class BaseModuleTest(unittest.TestCase):
self.assertEqual(imp.strides, exp.strides)
self.assertTrue(imp.suboffsets is None)
@unittest.skipIf(not pygame.HAVE_NEWBUF, "newbuf not implemented")
@unittest.skipIf(IS_PYPY, "pypy no likey")
def test_newbuf(self):
from pygame.bufferproxy import BufferProxy
@@ -247,11 +250,11 @@ class BaseModuleTest(unittest.TestCase):
v = BufferProxy(o)
self.NEWBUF_assertSame(v, o)
@unittest.skipIf(not pygame.HAVE_NEWBUF, "newbuf not implemented")
def test_bad_format(self):
from ctypes import addressof, create_string_buffer
from pygame.bufferproxy import BufferProxy
from pygame.newbuffer import BufferMixin
from ctypes import create_string_buffer, addressof
buftools = self.buftools
Exporter = buftools.Exporter
@@ -277,6 +280,7 @@ class BaseModuleTest(unittest.TestCase):
b = BufferProxy(exp)
self.assertRaises(ValueError, Importer, b, PyBUF_FORMAT)
@unittest.skipIf(not pygame.HAVE_NEWBUF, "newbuf not implemented")
@unittest.skipIf(IS_PYPY, "fails on pypy")
def test_PgDict_AsBuffer_PyBUF_flags(self):
from pygame.bufferproxy import BufferProxy
@@ -378,11 +382,10 @@ class BaseModuleTest(unittest.TestCase):
self.assertEqual(b.buf, 1000000)
self.assertRaises(BufferError, Importer, a, buftools.PyBUF_FULL)
@unittest.skipIf(IS_PYPY, "newbuf with ctypes")
@unittest.skipIf(IS_PYPY or (not pygame.HAVE_NEWBUF), "newbuf with ctypes")
def test_PgObject_AsBuffer_PyBUF_flags(self):
import ctypes
from pygame.bufferproxy import BufferProxy
import ctypes
is_lil_endian = pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN
fsys, frev = ("<", ">") if is_lil_endian else (">", "<")
@@ -507,6 +510,7 @@ class BaseModuleTest(unittest.TestCase):
# Scrap is optional.
pass
# pygame.cdrom
# pygame.joystick
def init_assertions(self):
@@ -3,6 +3,8 @@ import unittest
import pygame
from pygame.locals import *
from time import time
class BlitTest(unittest.TestCase):
def test_SRCALPHA(self):
@@ -71,7 +73,21 @@ class BlitTest(unittest.TestCase):
s.blit(d, (0, 0), None, BLEND_SUB)
self.assertEqual(s.get_at((0, 0))[0], 0)
class BlitsTest(unittest.TestCase):
"""Tests for pygame.Surface.blits"""
def setUp(self):
self.NUM_SURFS = 255
self.PRINT_TIMING = 0
self.dst = pygame.Surface((self.NUM_SURFS * 10, 10), SRCALPHA, 32)
self.dst.fill((230, 230, 230))
self.blit_list = self.make_blit_list(self.NUM_SURFS)
def make_blit_list(self, num_surfs):
"""Generate a list of tuples representing surfaces and destinations
for blitting"""
blit_list = []
for i in range(num_surfs):
dest = (i * 10, 0)
@@ -81,172 +97,95 @@ class BlitTest(unittest.TestCase):
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 custom_blits(self, blit_list):
"""Custom blits method that manually iterates over the blit_list and blits
each surface onto the destination."""
def blits(blit_list):
for surface, dest in blit_list:
dst.blit(surface, dest)
for surface, dest in blit_list:
self.dst.blit(surface, dest)
from time import time
def test_custom_blits_performance(self):
"""Checks time performance of the custom blits method"""
t0 = time()
results = blits(blit_list)
results = self.custom_blits(self.blit_list)
t1 = time()
if PRINT_TIMING:
if self.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)
def test_blits_performance(self):
"""Checks time performance of blits"""
t0 = time()
results = dst.blits(blit_list, doreturn=0)
results = self.dst.blits(self.blit_list)
t1 = time()
if PRINT_TIMING:
if self.PRINT_TIMING:
print(f"Surface.blits: {t1 - t0}")
# Measure time performance of blits with doreturn=0
t0 = time()
results = self.dst.blits(self.blit_list, doreturn=0)
t1 = time()
if self.PRINT_TIMING:
print(f"Surface.blits doreturn=0: {t1 - t0}")
self.assertEqual(results, None)
# Measure time performance of blits using a generator
t0 = time()
results = dst.blits(((surf, dest) for surf, dest in blit_list))
results = self.dst.blits(((surf, dest) for surf, dest in self.blit_list))
t1 = time()
if PRINT_TIMING:
if self.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 test_blits_correctness(self):
"""Checks the correctness of the colors on the destination
after blitting and tests that the length of the results list
matches the number of surfaces blitted."""
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):
results = self.dst.blits(self.blit_list)
for i in range(self.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(self.dst.get_at((i * 10, 0)), color)
self.assertEqual(self.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)
self.assertEqual(len(results), self.NUM_SURFS)
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_blits_doreturn(self):
"""Tests that when doreturn=0, it returns None"""
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())
results = self.dst.blits(self.blit_list, doreturn=0)
self.assertEqual(results, None)
def test_blits_not_sequence(self):
"""Tests that calling blits with an invalid non-sequence None argument
raises a ValueError."""
dst = pygame.Surface((100, 10), SRCALPHA, 32)
self.assertRaises(ValueError, dst.blits, None)
with self.assertRaises(ValueError):
dst.blits(None)
def test_blits_wrong_length(self):
"""Tests that calling blits with an invalid sequence containing a single surface
(without a destination) raises a ValueError."""
dst = pygame.Surface((100, 10), SRCALPHA, 32)
self.assertRaises(
ValueError, dst.blits, [pygame.Surface((10, 10), SRCALPHA, 32)]
)
with self.assertRaises(ValueError):
dst.blits([pygame.Surface((10, 10), SRCALPHA, 32)])
def test_blits_bad_surf_args(self):
"""Tests that calling blits with a sequence containing an invalid tuple of
None arguments raises a TypeError."""
dst = pygame.Surface((100, 10), SRCALPHA, 32)
self.assertRaises(TypeError, dst.blits, [(None, None)])
with self.assertRaises(TypeError):
dst.blits([(None, None)])
def test_blits_bad_dest(self):
"""Tests that calling blits with a sequence containing an invalid tuple with a
destination of None raises a TypeError."""
dst = pygame.Surface((100, 10), SRCALPHA, 32)
self.assertRaises(
TypeError, dst.blits, [(pygame.Surface((10, 10), SRCALPHA, 32), None)]
)
with self.assertRaises(TypeError):
dst.blits([(pygame.Surface((10, 10), SRCALPHA, 32), None)])
if __name__ == "__main__":
@@ -1,12 +1,13 @@
import ctypes
import gc
import re
import unittest
import weakref
import gc
import ctypes
import unittest
import pygame
from pygame.bufferproxy import BufferProxy
try:
BufferError
except NameError:
@@ -254,6 +255,7 @@ class BufferProxyTest(unittest.TestCase):
self.assertEqual(r[:2], "*<")
self.assertEqual(r[-2:], ">*")
@unittest.skipIf(not pygame.HAVE_NEWBUF, "newbuf not implemented")
def NEWBUF_test_newbuf(self):
from ctypes import string_at
@@ -307,7 +309,7 @@ class BufferProxyTest(unittest.TestCase):
"shape": (10,),
"strides": (1,),
"data": (9, True),
} # 9? Will not read the data anyway.
} # 9? Will not reading the data anyway.
b = BufferProxy(d)
imp = Importer(b, buftools.PyBUF_SIMPLE)
self.assertTrue(imp.obj is b)
@@ -331,7 +333,7 @@ class BufferProxyTest(unittest.TestCase):
self.OLDBUF_test_oldbuf_arg()
def OLDBUF_test_oldbuf_arg(self):
from pygame.bufferproxy import get_read_buffer, get_segcount, get_write_buffer
from pygame.bufferproxy import get_segcount, get_read_buffer, get_write_buffer
content = b"\x01\x00\x00\x02" * 12
memory = ctypes.create_string_buffer(content)
@@ -457,7 +459,7 @@ class BufferProxyLegacyTest(unittest.TestCase):
# 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
from ctypes import c_byte, sizeof, addressof, string_at, memset
nullbyte = b"\x00"
Buf = c_byte * 10
@@ -1,5 +1,35 @@
import unittest
import os
import pygame
import pygame.camera
class CameraModuleTest(unittest.TestCase):
pass
def setUp(self):
pygame.init()
pygame.camera.init()
@unittest.skipIf(
os.environ.get("SDL_VIDEODRIVER") in ["dummy", "android"],
"requires the SDL_VIDEODRIVER to be non dummy",
)
def test_camera(self):
cameras = pygame.camera.list_cameras()
if len(cameras) == 0:
self.skipTest("No cameras found")
cam = pygame.camera.Camera(cameras[0], (640, 480))
cam.start()
image = cam.get_image()
self.assertIsNotNone(image, "Could not capture image")
cam.stop()
def tearDown(self):
pygame.camera.quit()
pygame.quit()
if __name__ == "__main__":
unittest.main()
@@ -500,7 +500,8 @@ class ColorTypeTest(unittest.TestCase):
def test_repr(self):
c = pygame.Color(68, 38, 26, 69)
self.assertEqual(repr(c), "Color(68, 38, 26, 69)")
t = "(68, 38, 26, 69)"
self.assertEqual(repr(c), t)
def test_add(self):
c1 = pygame.Color(0)
@@ -527,7 +528,7 @@ class ColorTypeTest(unittest.TestCase):
self.assertEqual(c3.b, 164)
self.assertEqual(c3.a, 255)
# pygame-ce issue #301: Is type checking done for Python 3.x?
# Issue #286: Is type checking done for Python 3.x?
self.assertRaises(TypeError, operator.add, c1, None)
self.assertRaises(TypeError, operator.add, None, c1)
@@ -556,7 +557,7 @@ class ColorTypeTest(unittest.TestCase):
self.assertEqual(c3.b, 91)
self.assertEqual(c3.a, 0)
# pygame-ce issue #301: Is type checking done for Python 3.x?
# Issue #286: Is type checking done for Python 3.x?
self.assertRaises(TypeError, operator.sub, c1, None)
self.assertRaises(TypeError, operator.sub, None, c1)
@@ -585,7 +586,7 @@ class ColorTypeTest(unittest.TestCase):
self.assertEqual(c3.b, 9)
self.assertEqual(c3.a, 255)
# pygame-ce issue #301: Is type checking done for Python 3.x?
# Issue #286: Is type checking done for Python 3.x?
self.assertRaises(TypeError, operator.mul, c1, None)
self.assertRaises(TypeError, operator.mul, None, c1)
@@ -614,7 +615,7 @@ class ColorTypeTest(unittest.TestCase):
self.assertEqual(c3.b, 2)
self.assertEqual(c3.a, 0)
# pygame-ce issue #301: Is type checking done for Python 3.x?
# Issue #286: Is type checking done for Python 3.x?
self.assertRaises(TypeError, operator.floordiv, c1, None)
self.assertRaises(TypeError, operator.floordiv, None, c1)
@@ -646,7 +647,7 @@ class ColorTypeTest(unittest.TestCase):
self.assertEqual(c3.b, 7)
self.assertEqual(c3.a, 15)
# pygame-ce issue #301: Is type checking done for Python 3.x?
# Issue #286: Is type checking done for Python 3.x?
self.assertRaises(TypeError, operator.mod, c1, None)
self.assertRaises(TypeError, operator.mod, None, c1)
@@ -773,135 +774,6 @@ class ColorTypeTest(unittest.TestCase):
self.assertEqual(c.a, 146)
self.assertEqual(int(c), int(0x33727592))
def test_bytes(self):
c = pygame.Color(0x00012345)
self.assertEqual(c.r, 0x00)
self.assertEqual(c.g, 0x01)
self.assertEqual(c.b, 0x23)
self.assertEqual(c.a, 0x45)
as_bytes = bytes(c)
self.assertEqual(as_bytes, bytes([0x00, 0x01, 0x23, 0x45]))
self.assertEqual(len(as_bytes), 4)
def test_from_cmy(self):
cmy = pygame.Color.from_cmy(0.5, 0.5, 0.5)
cmy_tuple = pygame.Color.from_cmy((0.5, 0.5, 0.5))
cmy_instance = pygame.Color(0, 0, 0, 0).from_cmy(0.5, 0.5, 0.5)
expected_cmy = (127, 127, 127)
self.assertEqual(expected_cmy, cmy)
self.assertEqual(expected_cmy, cmy_tuple)
self.assertEqual(expected_cmy, cmy_instance)
self.assertRaises(
ValueError, lambda: pygame.Color.from_cmy(0.5, 0.5, 0.5, "lel", "foo")
)
self.assertRaises(
ValueError, lambda: pygame.Color.from_cmy((0.5, 0.5, 0.5, 0.5))
)
def test_from_hsva(self):
hsva = pygame.Color.from_hsva(0, 100, 100, 100)
hsva_tuple = pygame.Color.from_hsva((0, 100, 100, 100))
hsva_instance = pygame.Color(0, 0, 0, 0).from_hsva(0, 100, 100, 100)
expected_hsva = (255, 0, 0)
self.assertEqual(expected_hsva, hsva)
self.assertEqual(expected_hsva, hsva_tuple)
self.assertEqual(expected_hsva, hsva_instance)
self.assertRaises(
ValueError, lambda: pygame.Color.from_hsva(0, 100, 100, 100, "lel", "foo")
)
self.assertRaises(
ValueError, lambda: pygame.Color.from_hsva((0, 100, 100, 100, "lel"))
)
def test_from_hsla(self):
hsla = pygame.Color.from_hsla(0, 100, 100, 100)
hsla_tuple = pygame.Color.from_hsla((0, 100, 100, 100))
hsla_instance = pygame.Color(0, 0, 0, 0).from_hsla(0, 100, 100, 100)
expected_hsla = (255, 255, 255)
self.assertEqual(expected_hsla, hsla)
self.assertEqual(expected_hsla, hsla_tuple)
self.assertEqual(expected_hsla, hsla_instance)
self.assertRaises(
ValueError, lambda: pygame.Color.from_hsla(0, 100, 100, 100, "lel")
)
self.assertRaises(
ValueError, lambda: pygame.Color.from_hsla((0, 100, 100, 100, "lel", "foo"))
)
def test_from_i1i2i3(self):
i1i2i3 = pygame.Color.from_i1i2i3(0, 0, 0)
i1i2i3_tuple = pygame.Color.from_i1i2i3((0, 0, 0))
i1i2i3_instance = pygame.Color(0, 0, 0, 0).from_i1i2i3(0, 0, 0)
expected_i1i2i3 = (0, 0, 0)
self.assertEqual(expected_i1i2i3, i1i2i3)
self.assertEqual(expected_i1i2i3, i1i2i3_tuple)
self.assertEqual(expected_i1i2i3, i1i2i3_instance)
self.assertRaises(
ValueError, lambda: pygame.Color.from_i1i2i3(0, 0, 0, "lel", "foo")
)
self.assertRaises(ValueError, lambda: pygame.Color.from_i1i2i3((0, 0, 0, 0)))
def test_from_normalized(self):
normal = pygame.Color.from_normalized(1, 1, 1, 1)
normal_tuple = pygame.Color.from_normalized((1, 1, 1, 1))
normal_instance = pygame.Color(0, 0, 0, 0).from_normalized(1, 1, 1, 1)
expected_normal = (255, 255, 255, 255)
self.assertEqual(expected_normal, normal)
self.assertEqual(expected_normal, normal_tuple)
self.assertEqual(expected_normal, normal_instance)
self.assertRaises(
ValueError, lambda: pygame.Color.from_normalized(1, 1, 1, 1, "lel")
)
def test_from_hex(self):
color1 = pygame.Color.from_hex("#FFFFFF") # White
color2 = pygame.Color.from_hex("#000000") # Black
color3 = pygame.Color.from_hex("#AAFF00") # Random
color4 = pygame.Color.from_hex("#FF000080") # Red (50% opacity)
color_instance1 = pygame.Color(0, 0, 0, 0).from_hex("#FFFFFF")
color_instance2 = pygame.Color(63, 12, 83).from_hex("#000000")
color_instance3 = pygame.Color(52, 31, 8, 255).from_hex("#AAFF00")
color_instance4 = pygame.Color("#E4A010").from_hex("#FF000080")
expected_color1 = (255, 255, 255, 255)
expected_color2 = (0, 0, 0, 255)
expected_color3 = (170, 255, 0, 255)
expected_color4 = (255, 0, 0, 128)
self.assertEqual(color1, expected_color1)
self.assertEqual(color2, expected_color2)
self.assertEqual(color3, expected_color3)
self.assertEqual(color4, expected_color4)
self.assertEqual(color_instance1, expected_color1)
self.assertEqual(color_instance2, expected_color2)
self.assertEqual(color_instance3, expected_color3)
self.assertEqual(color_instance4, expected_color4)
self.assertRaises(ValueError, lambda: pygame.Color.from_hex("#FFFFFG"))
self.assertRaises(ValueError, lambda: pygame.Color.from_hex("#FFFFFFF"))
self.assertRaises(ValueError, lambda: pygame.Color.from_hex("not-a-color"))
self.assertRaises(
TypeError, lambda: pygame.Color.from_hex("not-a-color", "lel")
)
def test_normalize(self):
c = pygame.Color(204, 38, 194, 55)
self.assertEqual(c.r, 204)
@@ -996,46 +868,7 @@ class ColorTypeTest(unittest.TestCase):
self.assertTrue(-0.5 <= i2 <= 0.5)
self.assertTrue(-0.5 <= i3 <= 0.5)
def test_normalize__all_elements_within_limits(self):
for c in rgba_combos_Color_generator():
r, g, b, a = c.normalized
self.assertTrue(0 <= r <= 1)
self.assertTrue(0 <= g <= 1)
self.assertTrue(0 <= b <= 1)
self.assertTrue(0 <= a <= 1)
def test_hex_property(self):
color = pygame.Color(255, 0, 255, 0)
hex = color.hex
self.assertEqual(hex, "#ff00ff00")
for c in rgba_combos_Color_generator():
col_hex = c.hex
self.assertIsInstance(col_hex, str)
self.assertEqual(len(col_hex), 9)
self.assertEqual(col_hex[0], "#")
for char in col_hex:
self.assertIn(char, "#0123456789abcdef")
self.assertEqual(c, pygame.Color(col_hex))
with self.assertRaises(TypeError):
color.hex = 0xFFFFFFFF
with self.assertRaises(AttributeError):
del color.hex
for value in ["FFFFFFFF", "#FFzzFF00", "0x FFFFFF", "#FF"]:
for v in [value, value.lower()]:
with self.assertRaises(ValueError):
color.hex = v
for value in ["#FFFFFFFF", "#FFFFFF", "0xFFFFFFFF", "0xFFFFFF"]:
for v in [value, value.lower()]:
color.hex = v
self.assertEqual(
(color.r, color.g, color.b, color.a), (255, 255, 255, 255)
)
def test_issue_284(self):
def test_issue_269(self):
"""PyColor OverflowError on HSVA with hue value of 360
>>> c = pygame.Color(0)
@@ -1089,12 +922,6 @@ class ColorTypeTest(unittest.TestCase):
def test_i1i2i3__sanity_testing_converted_should_not_raise(self):
self.colorspaces_converted_should_not_raise("i1i2i3")
def test_normalized__sanity_testing_converted_should_not_raise(self):
self.colorspaces_converted_should_not_raise("normalized")
def test_hex__sanity_testing_converted_should_not_raise(self):
self.colorspaces_converted_should_not_raise("hex")
################################################################################
def colorspaces_converted_should_equate_bar_rounding(self, prop):
@@ -1127,20 +954,6 @@ class ColorTypeTest(unittest.TestCase):
def test_i1i2i3__sanity_testing_converted_should_equate_bar_rounding(self):
self.colorspaces_converted_should_equate_bar_rounding("i1i2i3")
def test_normalized__sanity_testing_converted_should_equate_bar_rounding(self):
self.colorspaces_converted_should_equate_bar_rounding("normalized")
def test_hex__sanity_testing_converted_should_equate_bar_rounding(self):
self.colorspaces_converted_should_equate_bar_rounding("hex")
def test_colorspaces_deprecated_large_sequence(self):
c = pygame.Color("black")
for space in ("hsla", "hsva", "i1i2i3", "cmy", "normalized"):
with self.assertRaises(ValueError):
setattr(
c, space, (0, 0, 0, 0, "HAHAHAHAHAHA, don't ignore 5th member :)")
)
################################################################################
def test_correct_gamma__verified_against_python_implementation(self):
@@ -1178,9 +991,8 @@ class ColorTypeTest(unittest.TestCase):
@unittest.skipIf(IS_PYPY, "PyPy has no ctypes")
def test_arraystruct(self):
import ctypes as ct
import pygame.tests.test_utils.arrinter as ai
import ctypes as ct
c_byte_p = ct.POINTER(ct.c_byte)
c = pygame.Color(5, 7, 13, 23)
@@ -1199,10 +1011,10 @@ class ColorTypeTest(unittest.TestCase):
for j in range(i):
self.assertEqual(data[j], c[j])
@unittest.skipIf(not pygame.HAVE_NEWBUF, "newbuf not implemented")
def test_newbuf(self):
from ctypes import POINTER, c_uint8, cast
from pygame.tests.test_utils import buftools
from ctypes import cast, POINTER, c_uint8
class ColorImporter(buftools.Importer):
def __init__(self, color, flags):
@@ -1360,51 +1172,6 @@ class ColorTypeTest(unittest.TestCase):
self.assertRaises(ValueError, lambda: color0.lerp((0, 0, 0, 256), 0.5))
self.assertRaises(TypeError, lambda: color0.lerp(0.2, 0.5))
def test_swizzle_get(self):
c = pygame.color.Color(10, 20, 30, 40)
self.assertEqual(c.rg, (10, 20))
self.assertEqual(c.rb, (10, 30))
self.assertEqual(c.rr, (10, 10))
self.assertEqual(c.rgb, (10, 20, 30))
self.assertEqual(c.bgr, (30, 20, 10))
self.assertEqual(c.rrr, (10, 10, 10))
self.assertEqual(c.rrg, (10, 10, 20))
self.assertEqual(c.rrb, (10, 10, 30))
self.assertEqual(c.ggg, (20, 20, 20))
self.assertEqual(c.ggb, (20, 20, 30))
self.assertEqual(c.ggr, (20, 20, 10))
self.assertEqual(c.bbb, (30, 30, 30))
self.assertEqual(c.bbg, (30, 30, 20))
self.assertEqual(c.bbr, (30, 30, 10))
c.rgba = c.abgr
self.assertEqual(c.rgba, (40, 30, 20, 10))
c.rgba = c.rgga
self.assertEqual(c.rgba, (40, 30, 30, 10))
c.rg = c.gg
self.assertEqual(c.rgba, (30, 30, 30, 10))
with self.assertRaises(AttributeError):
c.rr = (10, 10)
c.bb = (10, 10)
c.gg = (10, 10)
c.aa = (10, 10)
c.aaa = (10, 10, 100)
c.rgb = (256, 256, 256)
def test_swizzle_return_types(self):
c = pygame.color.Color(10, 20, 30, 40)
self.assertEqual(type(c.rgb), tuple)
self.assertEqual(type(c.rgba), pygame.color.Color)
self.assertEqual(type(c.bgra), pygame.color.Color)
self.assertEqual(type(c.bg), tuple)
self.assertEqual(type(c.gr), tuple)
self.assertEqual(type(c.rr), tuple)
self.assertEqual(type(c.rrggbb), tuple)
def test_premul_alpha(self):
# setup
Color = pygame.color.Color
@@ -1421,7 +1188,7 @@ class ColorTypeTest(unittest.TestCase):
# type checking
self.assertTrue(isinstance(color0.premul_alpha(), Color))
# handcrafted value testing
# hand crafted value testing
self.assertEqual(alpha0.premul_alpha(), Color(0, 0, 0, 0))
self.assertEqual(alpha49.premul_alpha(), Color(49, 0, 0, 49))
self.assertEqual(alpha67.premul_alpha(), Color(0, 67, 0, 67))
@@ -1,7 +1,7 @@
import unittest
import pygame.constants
# K_* and KSCAN_* common names.
K_AND_KSCAN_COMMON_NAMES = (
"UNKNOWN",
@@ -138,7 +138,7 @@ K_AND_KSCAN_COMMON_OVERLAPS = (
def create_overlap_set(constant_names):
"""Helper function to find overlapping constant values/names.
Returns a set of frozensets:
Returns a set of fronzensets:
set(frozenset(names of overlapping constants), ...)
"""
# Create an overlap dict.
@@ -1,5 +1,4 @@
import unittest
import pygame
import pygame._sdl2.controller as controller
from pygame.tests.test_utils import prompt, question
@@ -34,6 +33,15 @@ class ControllerModuleTest(unittest.TestCase):
def test_get_init(self):
self.assertTrue(controller.get_init())
def test_get_eventstate(self):
controller.set_eventstate(True)
self.assertTrue(controller.get_eventstate())
controller.set_eventstate(False)
self.assertFalse(controller.get_eventstate())
controller.set_eventstate(True)
def test_get_count(self):
self.assertGreaterEqual(controller.get_count(), 0)
@@ -44,12 +52,15 @@ class ControllerModuleTest(unittest.TestCase):
self.assertIsInstance(c, controller.Controller)
c.quit()
else:
with self.assertRaises(pygame.error):
with self.assertRaises(pygame._sdl2.sdl2.error):
c = controller.Controller(i)
with self.assertRaises(TypeError):
controller.is_controller("Test")
def test_name_forindex(self):
self.assertIsNone(controller.name_forindex(-1))
class ControllerTypeTest(unittest.TestCase):
def setUp(self):
@@ -64,19 +75,22 @@ class ControllerTypeTest(unittest.TestCase):
return controller.Controller(i)
def test_construction(self):
if c := self._get_first_controller():
c = self._get_first_controller()
if c:
self.assertIsInstance(c, controller.Controller)
else:
self.skipTest("No controller connected")
def test__auto_init(self):
if c := self._get_first_controller():
c = self._get_first_controller()
if c:
self.assertTrue(c.get_init())
else:
self.skipTest("No controller connected")
def test_get_init(self):
if c := self._get_first_controller():
c = self._get_first_controller()
if c:
self.assertTrue(c.get_init())
c.quit()
self.assertFalse(c.get_init())
@@ -95,14 +109,16 @@ class ControllerTypeTest(unittest.TestCase):
self.assertIsInstance(c, controller.Controller)
def test_as_joystick(self):
if c := self._get_first_controller():
c = self._get_first_controller()
if c:
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():
c = self._get_first_controller()
if c:
mapping = c.get_mapping()
self.assertIsInstance(mapping, dict)
self.assertIsNotNone(mapping["a"])
@@ -110,7 +126,8 @@ class ControllerTypeTest(unittest.TestCase):
self.skipTest("No controller connected")
def test_set_mapping(self):
if c := self._get_first_controller():
c = self._get_first_controller()
if c:
mapping = c.get_mapping()
mapping["a"] = "b3"
mapping["y"] = "b0"
@@ -162,6 +179,75 @@ class ControllerInteractiveTest(unittest.TestCase):
self.assertTrue(ans)
def test_set_eventstate_on_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
screen.fill((255, 255, 255))
screen.blit(
font.render("Press button 'x' (on ps4) or 'a' (on xbox).", True, (0, 0, 0)),
(0, 0),
)
pygame.display.update()
controller.set_eventstate(True)
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.CONTROLLERBUTTONDOWN:
running = False
pygame.display.quit()
pygame.font.quit()
def test_set_eventstate_off_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
screen.fill((255, 255, 255))
screen.blit(
font.render("Press button 'x' (on ps4) or 'a' (on xbox).", True, (0, 0, 0)),
(0, 0),
)
pygame.display.update()
controller.set_eventstate(False)
while running:
for event in pygame.event.get(pygame.QUIT):
if event:
running = False
if c.get_button(pygame.CONTROLLER_BUTTON_A):
if pygame.event.peek(pygame.CONTROLLERBUTTONDOWN):
pygame.display.quit()
pygame.font.quit()
self.fail()
else:
running = False
pygame.display.quit()
pygame.font.quit()
def test_get_button_interactive(self):
c = self._get_first_controller()
if not c:
@@ -1,17 +0,0 @@
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()
@@ -1,7 +1,6 @@
import unittest
import pygame
from pygame.tests.test_utils import fixture_path
import pygame
class CursorsModuleTest(unittest.TestCase):
@@ -53,154 +52,151 @@ class CursorsModuleTest(unittest.TestCase):
# 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,
),
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)
@@ -222,7 +218,7 @@ class CursorsModuleTest(unittest.TestCase):
# __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.
# 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
@@ -1,24 +0,0 @@
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")
@@ -1,16 +1,13 @@
import unittest
import os
import sys
import time
import unittest
import pygame
import pygame.transform
from pygame import display
import pygame, pygame.transform
from pygame.tests.test_utils import question
pygame.display.init()
is_wayland = pygame.display.get_driver() == "wayland"
pygame.display.quit()
from pygame import display
class DisplayModuleTest(unittest.TestCase):
@@ -72,10 +69,9 @@ class DisplayModuleTest(unittest.TestCase):
self.assertEqual(pygame.display.get_active(), False)
@unittest.skipIf(
os.environ.get("SDL_VIDEODRIVER") == pygame.NULL_VIDEODRIVER,
"requires the SDL_VIDEODRIVER to be a non-null value",
os.environ.get("SDL_VIDEODRIVER") == "dummy",
"requires the SDL_VIDEODRIVER to be a non dummy value",
)
@unittest.skipIf(is_wayland, "broken on wayland")
def test_get_active_iconify(self):
"""Test the get_active function after an iconify"""
@@ -105,6 +101,14 @@ class DisplayModuleTest(unittest.TestCase):
self.assertEqual(display.get_caption()[0], TEST_CAPTION)
self.assertEqual(display.get_caption()[1], TEST_CAPTION)
def test_set_caption_kwargs(self):
TEST_CAPTION = "test"
screen = display.set_mode((100, 100))
self.assertIsNone(display.set_caption(title=TEST_CAPTION))
self.assertEqual(display.get_caption()[0], TEST_CAPTION)
self.assertEqual(display.get_caption()[1], TEST_CAPTION)
def test_caption_unicode(self):
TEST_CAPTION = "台"
display.set_caption(TEST_CAPTION)
@@ -119,7 +123,7 @@ class DisplayModuleTest(unittest.TestCase):
"dga",
"directx",
"directfb",
pygame.NULL_VIDEODRIVER,
"dummy",
"emscripten",
"fbcon",
"ggi",
@@ -154,31 +158,22 @@ class DisplayModuleTest(unittest.TestCase):
# display.init() already called in setUp()
self.assertTrue(display.get_init())
# This test can be uncommented when issues #991 and #993 are resolved.
@unittest.skipIf(True, "SDL2 issues")
def test_get_surface(self):
"""Ensures get_surface gets the current display surface.
We can't guarantee small screen sizes get respected, so the
sizes of the surfaces returned from set_mode must be compared
to the size of the surface from get_surface.
"""
"""Ensures get_surface gets the current display surface."""
lengths = (1, 5, 100)
correct_depth = pygame.display.Info().bitsize
for expected_size in ((w, h) for w in lengths for h in lengths):
for set_depth in (8, 16, 24, 32):
if set_depth == correct_depth:
expected_surface = display.set_mode(expected_size, 0, set_depth)
else:
with self.assertWarns(DeprecationWarning):
expected_surface = pygame.display.set_mode(
expected_size, 0, set_depth
)
for expected_depth in (8, 16, 24, 32):
expected_surface = display.set_mode(expected_size, 0, expected_depth)
surface = pygame.display.get_surface()
self.assertEqual(surface, expected_surface)
self.assertIsInstance(surface, pygame.Surface)
self.assertEqual(surface.get_size(), expected_surface.get_size())
self.assertEqual(surface.get_bitsize(), correct_depth)
self.assertEqual(surface.get_size(), expected_size)
self.assertEqual(surface.get_bitsize(), expected_depth)
def test_get_surface__mode_not_set(self):
"""Ensures get_surface handles the display mode not being set."""
@@ -224,9 +219,9 @@ class DisplayModuleTest(unittest.TestCase):
@unittest.skipIf(
(
"skipping for all because some failures on rasppi and maybe other platforms"
or os.environ.get("SDL_VIDEODRIVER") == pygame.NULL_VIDEODRIVER
or os.environ.get("SDL_VIDEODRIVER") == "dummy"
),
"OpenGL requires a non-null SDL_VIDEODRIVER",
'OpenGL requires a non-"dummy" SDL_VIDEODRIVER',
)
def test_gl_get_attribute(self):
screen = display.set_mode((0, 0), pygame.OPENGL)
@@ -348,9 +343,159 @@ class DisplayModuleTest(unittest.TestCase):
@unittest.skipIf(
(
"skipping for all because some failures on rasppi and maybe other platforms"
or os.environ.get("SDL_VIDEODRIVER") == pygame.NULL_VIDEODRIVER
or os.environ.get("SDL_VIDEODRIVER") == "dummy"
),
"OpenGL requires a non-null SDL_VIDEODRIVER",
'OpenGL requires a non-"dummy" SDL_VIDEODRIVER',
)
def test_gl_get_attribute_kwargs(self):
screen = display.set_mode((0, 0), pygame.OPENGL)
# We create a list where we store the original values of the
# flags before setting them with a different value.
original_values = []
original_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_ALPHA_SIZE)
)
original_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_DEPTH_SIZE)
)
original_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_STENCIL_SIZE)
)
original_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_ACCUM_RED_SIZE)
)
original_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_ACCUM_GREEN_SIZE)
)
original_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_ACCUM_BLUE_SIZE)
)
original_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_ACCUM_ALPHA_SIZE)
)
original_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_MULTISAMPLEBUFFERS)
)
original_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_MULTISAMPLESAMPLES)
)
original_values.append(pygame.display.gl_get_attribute(flag=pygame.GL_STEREO))
original_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_ACCELERATED_VISUAL)
)
original_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_CONTEXT_MAJOR_VERSION)
)
original_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_CONTEXT_MINOR_VERSION)
)
original_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_CONTEXT_FLAGS)
)
original_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_CONTEXT_PROFILE_MASK)
)
original_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_SHARE_WITH_CURRENT_CONTEXT)
)
original_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_FRAMEBUFFER_SRGB_CAPABLE)
)
# Setting the flags with values supposedly different from the original values
# assign SDL1-supported values with gl_set_attribute
pygame.display.gl_set_attribute(flag=pygame.GL_ALPHA_SIZE, value=8)
pygame.display.gl_set_attribute(flag=pygame.GL_DEPTH_SIZE, value=24)
pygame.display.gl_set_attribute(flag=pygame.GL_STENCIL_SIZE, value=8)
pygame.display.gl_set_attribute(flag=pygame.GL_ACCUM_RED_SIZE, value=16)
pygame.display.gl_set_attribute(flag=pygame.GL_ACCUM_GREEN_SIZE, value=16)
pygame.display.gl_set_attribute(flag=pygame.GL_ACCUM_BLUE_SIZE, value=16)
pygame.display.gl_set_attribute(flag=pygame.GL_ACCUM_ALPHA_SIZE, value=16)
pygame.display.gl_set_attribute(flag=pygame.GL_MULTISAMPLEBUFFERS, value=1)
pygame.display.gl_set_attribute(flag=pygame.GL_MULTISAMPLESAMPLES, value=1)
pygame.display.gl_set_attribute(flag=pygame.GL_STEREO, value=0)
pygame.display.gl_set_attribute(flag=pygame.GL_ACCELERATED_VISUAL, value=0)
pygame.display.gl_set_attribute(flag=pygame.GL_CONTEXT_MAJOR_VERSION, value=1)
pygame.display.gl_set_attribute(flag=pygame.GL_CONTEXT_MINOR_VERSION, value=1)
pygame.display.gl_set_attribute(flag=pygame.GL_CONTEXT_FLAGS, value=0)
pygame.display.gl_set_attribute(flag=pygame.GL_CONTEXT_PROFILE_MASK, value=0)
pygame.display.gl_set_attribute(
flag=pygame.GL_SHARE_WITH_CURRENT_CONTEXT, value=0
)
pygame.display.gl_set_attribute(
flag=pygame.GL_FRAMEBUFFER_SRGB_CAPABLE, value=0
)
# We create a list where we store the values that we set each flag to
set_values = [8, 24, 8, 16, 16, 16, 16, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0]
# We create a list where we store the values after getting them
get_values = []
get_values.append(pygame.display.gl_get_attribute(flag=pygame.GL_ALPHA_SIZE))
get_values.append(pygame.display.gl_get_attribute(flag=pygame.GL_DEPTH_SIZE))
get_values.append(pygame.display.gl_get_attribute(flag=pygame.GL_STENCIL_SIZE))
get_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_ACCUM_RED_SIZE)
)
get_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_ACCUM_GREEN_SIZE)
)
get_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_ACCUM_BLUE_SIZE)
)
get_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_ACCUM_ALPHA_SIZE)
)
get_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_MULTISAMPLEBUFFERS)
)
get_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_MULTISAMPLESAMPLES)
)
get_values.append(pygame.display.gl_get_attribute(flag=pygame.GL_STEREO))
get_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_ACCELERATED_VISUAL)
)
get_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_CONTEXT_MAJOR_VERSION)
)
get_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_CONTEXT_MINOR_VERSION)
)
get_values.append(pygame.display.gl_get_attribute(flag=pygame.GL_CONTEXT_FLAGS))
get_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_CONTEXT_PROFILE_MASK)
)
get_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_SHARE_WITH_CURRENT_CONTEXT)
)
get_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_FRAMEBUFFER_SRGB_CAPABLE)
)
# We check to see if the values that we get correspond to the values that we set
# them to or to the original values.
for i in range(len(original_values)):
self.assertTrue(
(get_values[i] == original_values[i])
or (get_values[i] == set_values[i])
)
# test using non-flag argument
with self.assertRaises(TypeError):
pygame.display.gl_get_attribute("DUMMY")
@unittest.skipIf(
(
"skipping for all because some failures on rasppi and maybe other platforms"
or os.environ.get("SDL_VIDEODRIVER") == "dummy"
),
'OpenGL requires a non-"dummy" SDL_VIDEODRIVER',
)
def test_gl_set_attribute(self):
# __doc__ (as of 2008-08-02) for pygame.display.gl_set_attribute:
@@ -413,10 +558,102 @@ class DisplayModuleTest(unittest.TestCase):
pygame.display.gl_get_attribute("DUMMY")
@unittest.skipIf(
os.environ.get("SDL_VIDEODRIVER") in [pygame.NULL_VIDEODRIVER, "android"],
(
"skipping for all because some failures on rasppi and maybe other platforms"
or os.environ.get("SDL_VIDEODRIVER") == "dummy"
),
'OpenGL requires a non-"dummy" SDL_VIDEODRIVER',
)
def test_gl_set_attribute_kwargs(self):
# __doc__ (as of 2008-08-02) for pygame.display.gl_set_attribute:
# pygame.display.gl_set_attribute(flag, value): return None
# request an opengl display attribute for the display mode
#
# When calling pygame.display.set_mode() with the pygame.OPENGL flag,
# Pygame automatically handles setting the OpenGL attributes like
# color and doublebuffering. OpenGL offers several other attributes
# you may want control over. Pass one of these attributes as the flag,
# and its appropriate value. This must be called before
# pygame.display.set_mode()
#
# The OPENGL flags are;
# GL_ALPHA_SIZE, GL_DEPTH_SIZE, GL_STENCIL_SIZE, GL_ACCUM_RED_SIZE,
# GL_ACCUM_GREEN_SIZE, GL_ACCUM_BLUE_SIZE, GL_ACCUM_ALPHA_SIZE,
# GL_MULTISAMPLEBUFFERS, GL_MULTISAMPLESAMPLES, GL_STEREO
screen = display.set_mode((0, 0), pygame.OPENGL)
# We create a list where we store the values that we set each flag to
set_values = [8, 24, 8, 16, 16, 16, 16, 1, 1, 0]
# Setting the flags with values supposedly different from the original values
# assign SDL1-supported values with gl_set_attribute
pygame.display.gl_set_attribute(flag=pygame.GL_ALPHA_SIZE, value=set_values[0])
pygame.display.gl_set_attribute(flag=pygame.GL_DEPTH_SIZE, value=set_values[1])
pygame.display.gl_set_attribute(
flag=pygame.GL_STENCIL_SIZE, value=set_values[2]
)
pygame.display.gl_set_attribute(
flag=pygame.GL_ACCUM_RED_SIZE, value=set_values[3]
)
pygame.display.gl_set_attribute(
flag=pygame.GL_ACCUM_GREEN_SIZE, value=set_values[4]
)
pygame.display.gl_set_attribute(
flag=pygame.GL_ACCUM_BLUE_SIZE, value=set_values[5]
)
pygame.display.gl_set_attribute(
flag=pygame.GL_ACCUM_ALPHA_SIZE, value=set_values[6]
)
pygame.display.gl_set_attribute(
flag=pygame.GL_MULTISAMPLEBUFFERS, value=set_values[7]
)
pygame.display.gl_set_attribute(
flag=pygame.GL_MULTISAMPLESAMPLES, value=set_values[8]
)
pygame.display.gl_set_attribute(flag=pygame.GL_STEREO, value=set_values[9])
# We create a list where we store the values after getting them
get_values = []
get_values.append(pygame.display.gl_get_attribute(flag=pygame.GL_ALPHA_SIZE))
get_values.append(pygame.display.gl_get_attribute(flag=pygame.GL_DEPTH_SIZE))
get_values.append(pygame.display.gl_get_attribute(flag=pygame.GL_STENCIL_SIZE))
get_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_ACCUM_RED_SIZE)
)
get_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_ACCUM_GREEN_SIZE)
)
get_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_ACCUM_BLUE_SIZE)
)
get_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_ACCUM_ALPHA_SIZE)
)
get_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_MULTISAMPLEBUFFERS)
)
get_values.append(
pygame.display.gl_get_attribute(flag=pygame.GL_MULTISAMPLESAMPLES)
)
get_values.append(pygame.display.gl_get_attribute(flag=pygame.GL_STEREO))
# We check to see if the values that we get correspond to the values that we set
# them to or to the original values.
for i in range(len(set_values)):
self.assertTrue(get_values[i] == set_values[i])
# test using non-flag argument
with self.assertRaises(TypeError):
pygame.display.gl_get_attribute("DUMMY")
@unittest.skipIf(
os.environ.get("SDL_VIDEODRIVER") in ["dummy", "android"],
"iconify is only supported on some video drivers/platforms",
)
@unittest.skipIf(is_wayland, "broken on wayland")
def test_iconify(self):
pygame.display.set_mode((640, 480))
@@ -518,14 +755,8 @@ class DisplayModuleTest(unittest.TestCase):
self.assertFalse(display.get_init())
@unittest.skipIf(
os.environ.get("SDL_VIDEODRIVER") == pygame.NULL_VIDEODRIVER,
"Needs a non-null videodriver",
os.environ.get("SDL_VIDEODRIVER") == "dummy", "Needs a not dummy videodriver"
)
@unittest.skipIf(
pygame.version.SDL >= (2, 32, 50),
"set_gamma is removed in SDL3, does not work in sdl2-compat either",
)
@unittest.skipIf(is_wayland, "not supported on wayland")
def test_set_gamma(self):
pygame.display.set_mode((1, 1))
@@ -537,14 +768,8 @@ class DisplayModuleTest(unittest.TestCase):
self.assertEqual(pygame.display.set_gamma(gamma), True)
@unittest.skipIf(
os.environ.get("SDL_VIDEODRIVER") == pygame.NULL_VIDEODRIVER,
"Needs a non-null videodriver",
os.environ.get("SDL_VIDEODRIVER") == "dummy", "Needs a not dummy videodriver"
)
@unittest.skipIf(
pygame.version.SDL >= (2, 32, 50),
"set_gamma is removed in SDL3, does not work in sdl2-compat either",
)
@unittest.skipIf(is_wayland, "not supported on wayland")
def test_set_gamma__tuple(self):
pygame.display.set_mode((1, 1))
@@ -554,8 +779,8 @@ class DisplayModuleTest(unittest.TestCase):
self.assertEqual(pygame.display.set_gamma(r, g, b), True)
@unittest.skipIf(
pygame.version.SDL >= (2, 32, 50),
"set_gamma_ramp is removed in SDL3, does not work in sdl2-compat either",
not hasattr(pygame.display, "set_gamma_ramp"),
"Not all systems and hardware support gamma ramps",
)
def test_set_gamma_ramp(self):
# __doc__ (as of 2008-08-02) for pygame.display.set_gamma_ramp:
@@ -608,7 +833,7 @@ class DisplayModuleTest(unittest.TestCase):
def test_set_mode_unscaled(self):
"""Ensures a window created with SCALED can become smaller."""
# see https://github.com/pygame-community/pygame-ce/issues/1194
# see https://github.com/pygame/pygame/issues/2327
screen = pygame.display.set_mode((300, 300), pygame.SCALED)
self.assertEqual(screen.get_size(), (300, 300))
@@ -653,11 +878,41 @@ class DisplayModuleTest(unittest.TestCase):
palette = [1, 2, 3]
pygame.display.set_palette(palette)
skip_list = [pygame.NULL_VIDEODRIVER, "android"]
skip_list = ["dummy", "android"]
@unittest.skipIf(True, "set_palette() not supported in SDL2")
def test_set_palette_kwargs(self):
with self.assertRaises(pygame.error):
palette = [1, 2, 3]
pygame.display.set_palette(palette=palette)
pygame.display.set_mode((1024, 768), 0, 8)
palette = []
self.assertIsNone(pygame.display.set_palette(palette=palette))
with self.assertRaises(ValueError):
palette = 12
pygame.display.set_palette(palette=palette)
with self.assertRaises(TypeError):
palette = [[1, 2], [1, 2]]
pygame.display.set_palette(palette=palette)
with self.assertRaises(TypeError):
palette = [[0, 0, 0, 0, 0]] + [[x, x, x, x, x] for x in range(1, 255)]
pygame.display.set_palette(palette=palette)
with self.assertRaises(TypeError):
palette = "qwerty"
pygame.display.set_palette(palette=palette)
with self.assertRaises(TypeError):
palette = [[123, 123, 123] * 10000]
pygame.display.set_palette(palette=palette)
with self.assertRaises(TypeError):
palette = [1, 2, 3]
pygame.display.set_palette(palette=palette)
skip_list = ["dummy", "android"]
@unittest.skipIf(
os.environ.get("SDL_VIDEODRIVER") in skip_list,
"requires the SDL_VIDEODRIVER to be non-null",
"requires the SDL_VIDEODRIVER to be non dummy",
)
def test_toggle_fullscreen(self):
"""Test for toggle fullscreen"""
@@ -698,14 +953,6 @@ class DisplayModuleTest(unittest.TestCase):
(test_surf.get_width(), test_surf.get_height()), width_height
)
@unittest.skipIf(is_wayland, "not supported on wayland")
def test_get_set_window_position(self):
pygame.display.set_mode((500, 500))
pygame.display.set_window_position((420, 360))
position = pygame.display.get_window_position()
self.assertEqual(position[0], 420)
self.assertEqual(position[1], 360)
class DisplayUpdateTest(unittest.TestCase):
def question(self, qstr):
@@ -734,9 +981,6 @@ class DisplayUpdateTest(unittest.TestCase):
r3 = pygame.Rect(-10, 0, -100, -100)
pygame.display.update(r3)
# random point in rect
self.assertEqual(self.screen.get_at((50, 50)), (0, 255, 0))
self.question("Is the screen green in (0, 0, 100, 100)?")
def test_update_sequence(self):
@@ -751,47 +995,6 @@ class DisplayUpdateTest(unittest.TestCase):
pygame.display.update(rects)
pygame.event.pump() # so mac updates
# random points in rect
for random_point in ((50, 50), (150, 50), (250, 50), (350, 350)):
self.assertEqual(self.screen.get_at(random_point), (0, 255, 0))
self.question(f"Is the screen green in {rects}?")
def test_update_dict_values(self):
"""only updates the part of the display given by the rects."""
self.screen.fill("green")
rects = {
"foo": pygame.Rect(0, 0, 100, 100),
"foobar": pygame.Rect(100, 0, 100, 100),
"hello": pygame.Rect(200, 0, 100, 100),
"hi": pygame.Rect(300, 300, 100, 100),
}
pygame.display.update(rects.values())
pygame.event.pump() # so mac updates
# random points in rect
for random_point in ((50, 50), (150, 50), (250, 50), (350, 350)):
self.assertEqual(self.screen.get_at(random_point), (0, 255, 0))
self.question(f"Is the screen green in {' '.join(map(str, rects.values()))}?")
def test_update_generator(self):
"""only updates the part of the display given by the rects."""
self.screen.fill("green")
rects = [
pygame.Rect(0, 0, 100, 100),
pygame.Rect(100, 0, 100, 100),
pygame.Rect(200, 0, 100, 100),
pygame.Rect(300, 300, 100, 100),
]
# make a generator from list, pass list with rect duplicates
pygame.display.update(i for i in (rects * 5))
pygame.event.pump() # so mac updates
# random points in rect
for random_point in ((50, 50), (150, 50), (250, 50), (350, 350)):
self.assertEqual(self.screen.get_at(random_point), (0, 255, 0))
self.question(f"Is the screen green in {rects}?")
def test_update_none_skipped(self):
@@ -807,10 +1010,6 @@ class DisplayUpdateTest(unittest.TestCase):
pygame.display.update(rects)
pygame.event.pump() # so mac updates
# random points in rect
for random_point in ((50, 50), (150, 50), (250, 50), (350, 350)):
self.assertEqual(self.screen.get_at(random_point), (0, 255, 0))
self.question(f"Is the screen green in {rects}?")
def test_update_none(self):
@@ -818,19 +1017,14 @@ class DisplayUpdateTest(unittest.TestCase):
self.screen.fill("green")
pygame.display.update(None)
pygame.event.pump() # so mac updates
self.question(f"Is the screen black and NOT green?")
self.question("Is the screen black and NOT green?")
def test_update_no_args(self):
"""does NOT update the display."""
self.screen.fill("green")
pygame.display.update()
pygame.event.pump() # so mac updates
# random points in rect
for random_point in ((50, 50), (150, 50), (250, 50), (350, 350)):
self.assertEqual(self.screen.get_at(random_point), (0, 255, 0))
self.question(f"Is the WHOLE screen green?")
self.question("Is the WHOLE screen green?")
def test_update_args(self):
"""updates the display using the args as a rect."""
@@ -839,9 +1033,6 @@ class DisplayUpdateTest(unittest.TestCase):
pygame.event.pump() # so mac updates
self.question("Is the screen green in (100, 100, 100, 100)?")
# random points in rect
self.assertEqual(self.screen.get_at((150, 150)), (0, 255, 0))
def test_update_incorrect_args(self):
"""raises a ValueError when inputs are wrong."""
@@ -889,10 +1080,6 @@ class DisplayInteractiveTest(unittest.TestCase):
self.assertTrue(response)
pygame.display.quit()
@unittest.skipIf(
pygame.version.SDL >= (2, 32, 50),
"set_gamma_ramp is removed in SDL3, does not work in sdl2-compat either",
)
def test_set_gamma_ramp(self):
os.environ["SDL_VIDEO_WINDOW_POS"] = "100,250"
pygame.display.quit()
@@ -919,7 +1106,7 @@ class DisplayInteractiveTest(unittest.TestCase):
pygame.display.quit()
class FullscreenToggleTestsInteractive(unittest.TestCase):
class FullscreenToggleTests(unittest.TestCase):
__tags__ = ["interactive"]
screen = None
@@ -985,8 +1172,8 @@ class FullscreenToggleTestsInteractive(unittest.TestCase):
@unittest.skipIf(
os.environ.get("SDL_VIDEODRIVER") == pygame.NULL_VIDEODRIVER,
"OpenGL requires a non-null SDL_VIDEODRIVER",
os.environ.get("SDL_VIDEODRIVER") == "dummy",
'OpenGL requires a non-"dummy" SDL_VIDEODRIVER',
)
class DisplayOpenGLTest(unittest.TestCase):
def test_screen_size_opengl(self):
@@ -1000,7 +1187,7 @@ class DisplayOpenGLTest(unittest.TestCase):
class X11CrashTest(unittest.TestCase):
def test_x11_set_mode_crash_gh1654(self):
# Test for https://github.com/pygame-community/pygame-ce/issues/924
# Test for https://github.com/pygame/pygame/issues/1654
# If unfixed, this will trip a segmentation fault
pygame.display.init()
pygame.display.quit()
@@ -1008,105 +1195,5 @@ class X11CrashTest(unittest.TestCase):
self.assertEqual((640, 480), screen.get_size())
class MessageBoxTest(unittest.TestCase):
def test_messagebox_args(self):
mb = pygame.display.message_box
self.assertRaises(IndexError, lambda: mb("", escape_button=1))
self.assertRaises(IndexError, lambda: mb("", escape_button=-2))
self.assertRaises(IndexError, lambda: mb("", return_button=1))
self.assertRaises(IndexError, lambda: mb("", return_button=-2))
self.assertRaises(
IndexError,
lambda: mb("", buttons=("A", "B", "C"), return_button=3),
)
self.assertRaises(
IndexError,
lambda: mb("", buttons=("A", "B", "C"), return_button=-4),
)
self.assertRaises(
IndexError,
lambda: mb("", buttons=("A", "B", "C"), escape_button=3),
)
self.assertRaises(
IndexError,
lambda: mb("", buttons=("A", "B", "C"), escape_button=-4),
)
self.assertRaises(ValueError, lambda: mb("", message_type="random_str"))
self.assertRaises(TypeError, lambda: mb("", buttons=()))
self.assertRaises(TypeError, lambda: mb("", parent_window=123456))
class MessageBoxInteractiveTest(unittest.TestCase):
__tags__ = ["interactive"]
def test_message_box_type(self):
result = pygame.display.message_box(
"Test",
"Is this an error message box?",
message_type="error",
buttons=("Yes", "No"),
)
self.assertEqual(result, 0)
result = pygame.display.message_box(
"Test",
"Is this an info message box?",
message_type="info",
buttons=("Yes", "No"),
)
self.assertEqual(result, 0)
result = pygame.display.message_box(
"Test",
"Is this a warn message box?",
message_type="warn",
buttons=("Yes", "No"),
)
self.assertEqual(result, 0)
def test_message_box_buttons(self):
result = pygame.display.message_box("Hit the 'OK' button")
self.assertEqual(result, 0)
result = pygame.display.message_box(
"Hit the 'Hello' button",
buttons=("Nope", "Nope", "Nope", "Hello", "Nope", "Nope"),
)
self.assertEqual(result, 3)
result = pygame.display.message_box(
"Press Enter on your keyboard",
buttons=("O", "O", "O", "O", "O", "O"),
return_button=4,
)
self.assertEqual(result, 4)
result = pygame.display.message_box(
"Press Enter on your keyboard",
buttons=("O", "O", "O", "O", "O", "O"),
return_button=-3,
)
self.assertEqual(result, 3)
result = pygame.display.message_box(
"Press Esc on your keyboard",
buttons=("O", "O", "O", "O", "O", "O"),
escape_button=2,
)
self.assertEqual(result, 2)
result = pygame.display.message_box(
"Test",
"You saw 'Yes' on the left and 'No' on the right. Is this correct?",
buttons=("Yes", "No"),
)
self.assertEqual(result, 0)
def test_message_box_parent_window_none(self):
pygame.display.message_box(
"Test", "Just close this messagebox", parent_window=None
)
if __name__ == "__main__":
unittest.main()
@@ -6,11 +6,11 @@ import unittest
class DocsIncludedTest(unittest.TestCase):
def test_doc_import_works(self):
from pygame.docs import PKG_DIR, has_local_docs
from pygame.docs.__main__ import has_local_docs, open_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
from pygame.docs.__main__ import has_local_docs
self.assertTrue(has_local_docs())
File diff suppressed because it is too large. Load diff
@@ -1,14 +1,10 @@
import collections
import os
import time
import unittest
import os
import pygame
pygame.display.init()
is_wayland = pygame.display.get_driver() == "wayland"
pygame.display.quit()
EVENT_TYPES = (
# pygame.NOEVENT,
# pygame.ACTIVEEVENT,
@@ -86,10 +82,6 @@ NAMES_AND_EVENTS = (
class EventTypeTest(unittest.TestCase):
def test_Event_alias(self):
"""Check if pygame.Event is present and the correct type."""
self.assertIs(pygame.Event, pygame.event.Event)
def test_Event(self):
"""Ensure an Event object can be created."""
e = pygame.event.Event(pygame.USEREVENT, some_attr=1, other_attr="1")
@@ -98,7 +90,7 @@ class EventTypeTest(unittest.TestCase):
self.assertEqual(e.other_attr, "1")
# Event now uses tp_dictoffset and tp_members:
# https://github.com/pygame-community/pygame-ce/issues/77
# https://github.com/pygame/pygame/issues/62
self.assertEqual(e.type, pygame.USEREVENT)
self.assertIs(e.dict, e.__dict__)
@@ -151,60 +143,26 @@ class EventTypeTest(unittest.TestCase):
c = pygame.event.Event(EVENT_TYPES[1], a=1)
d = pygame.event.Event(EVENT_TYPES[0], a=2)
self.assertTrue(a == a)
self.assertFalse(a != a)
self.assertTrue(a == b)
self.assertFalse(a != b)
self.assertTrue(a != c)
self.assertFalse(a == c)
self.assertTrue(a != d)
self.assertFalse(a == d)
# Comparing event a
self.assertEqual(a, a) # Event is equal to itself
self.assertEqual(a, b) # Same type and attributes
self.assertNotEqual(a, c) # Different type but same attributes
self.assertNotEqual(a, d) # Same type but different attributes
def test_event_args(self):
"""Test event creation with args"""
NESTED_DICT = {"haha": True, "no": 92138023, "test": ("y", "e", "s")}
EXPECTED_ATTRIBUTES = {
"foo": "bar",
"ratio": 100,
"favourite_numbers": [3, 26, 42],
"nested_dict": NESTED_DICT,
"complex": 3 + 4j,
}
for event in (
pygame.event.Event(1, EXPECTED_ATTRIBUTES), # pass as dict
pygame.event.Event(1, **EXPECTED_ATTRIBUTES), # pass as kwargs
pygame.event.Event( # test passing both dict and kwargs
1,
{"nested_dict": NESTED_DICT, "complex": 3 + 4j},
foo="bar",
ratio=100,
favourite_numbers=[3, 26, 42],
),
):
self.assertDictEqual(event.dict, EXPECTED_ATTRIBUTES)
# Comparing event b
self.assertEqual(b, a) # Same type and attributes
self.assertNotEqual(b, c) # Different type but same attributes
self.assertNotEqual(b, d) # Same type but different attributes
for out_of_range_val in (-1, -10, pygame.NUMEVENTS, pygame.NUMEVENTS + 1):
self.assertRaises(ValueError, pygame.event.Event, out_of_range_val)
# Comparing event c
self.assertNotEqual(c, a) # Different type but same attributes
self.assertNotEqual(c, b) # Different type but same attributes
self.assertNotEqual(c, d) # Different type and different attributes
for incorrect_type in ("string", 4 + 3j, [1, 2, 3], {"a": "b"}):
self.assertRaises(TypeError, pygame.event.Event, incorrect_type)
def test_event_common_dict_changes(self):
d = {}
events = [pygame.Event(pygame.event.custom_type(), d) for _ in range(2)]
self.assertNotEqual(events[0], events[1])
d["hi"] = "hello"
events[0].hello = "hi"
events[1].dict["amongus"] = "sus"
self.assertEqual(d, {"hi": "hello", "hello": "hi", "amongus": "sus"})
for ev in events:
self.assertIs(d, ev.dict)
self.assertEqual(ev.dict, {"hi": "hello", "hello": "hi", "amongus": "sus"})
self.assertEqual(ev.hi, "hello")
self.assertEqual(ev.hello, "hi")
self.assertEqual(ev.amongus, "sus")
# Comparing event d
self.assertNotEqual(d, a) # Same type but different attributes
self.assertNotEqual(d, b) # Same type but different attributes
self.assertNotEqual(d, c) # Different type and different attributes
race_condition_notification = """
@@ -253,32 +211,16 @@ class EventModuleArgsTest(unittest.TestCase):
self.assertRaises(ValueError, pygame.event.clear, 0x0010FFFFF)
self.assertRaises(TypeError, pygame.event.get, ["a", "b", "c"])
def test_peek_no_arg(self):
pygame.event.clear()
# do a strict "is" check and not just a simple truthy-test to check that
# we have a boolean instance.
self.assertIs(pygame.event.peek(), False)
self.assertIs(pygame.event.peek(None), False)
# peek should return True if there's any event on the queue
pygame.event.post(pygame.event.Event(pygame.USEREVENT))
self.assertIs(pygame.event.peek(), True)
self.assertIs(pygame.event.peek(None), True)
def test_peek(self):
self.assertIsInstance(pygame.event.peek(), bool)
self.assertIsInstance(pygame.event.peek(None), bool)
self.assertIsInstance(pygame.event.peek(None, True), bool)
pygame.event.peek()
pygame.event.peek(None)
pygame.event.peek(None, True)
self.assertIsInstance(pygame.event.peek(pump=False), bool)
self.assertIsInstance(pygame.event.peek(pump=True), bool)
self.assertIsInstance(pygame.event.peek(eventtype=None), bool)
self.assertIsInstance(
pygame.event.peek(eventtype=[pygame.KEYUP, pygame.KEYDOWN]), bool
)
self.assertIsInstance(
pygame.event.peek(eventtype=pygame.USEREVENT, pump=False), bool
)
pygame.event.peek(pump=False)
pygame.event.peek(pump=True)
pygame.event.peek(eventtype=None)
pygame.event.peek(eventtype=[pygame.KEYUP, pygame.KEYDOWN])
pygame.event.peek(eventtype=pygame.USEREVENT, pump=False)
class Foo:
pass
@@ -492,19 +434,6 @@ class EventModuleTest(unittest.TestCase):
self.assertEqual(e.a, "a" * 1024)
self.assertEqual(e.test, list(range(100)))
def test_post_same_reference(self):
"""
Test that event.post posts an event with a common reference to a dict.
"""
for event in (
pygame.event.Event(pygame.event.custom_type(), attr=(1, 2, 3, 4)),
pygame.event.Event(pygame.event.custom_type()),
):
pygame.event.post(event)
e = pygame.event.poll()
self.assertEqual(e.type, event.type)
self.assertIs(e.dict, event.dict)
def test_post_blocked(self):
"""
Test blocked events are not posted. Also test whether post()
@@ -721,6 +650,13 @@ class EventModuleTest(unittest.TestCase):
pygame.event.event_name(event), unexpected_name, f"0x{event:X}"
)
def test_event_name__kwargs(self):
"""Ensure event_name() returns the correct event name when kwargs used."""
for expected_name, event in NAMES_AND_EVENTS:
self.assertEqual(
pygame.event.event_name(type=event), expected_name, f"0x{event:X}"
)
def test_peek(self):
"""Ensure queued events can be peeked at."""
event_types = [pygame.KEYDOWN, pygame.KEYUP, pygame.MOUSEMOTION]
@@ -839,11 +775,12 @@ class EventModuleTest(unittest.TestCase):
"""Ensure pump() functions properly."""
pygame.event.pump()
@unittest.skipIf(
os.environ.get("SDL_VIDEODRIVER") == pygame.NULL_VIDEODRIVER,
"requires the SDL_VIDEODRIVER to be a non-null value",
)
@unittest.skipIf(is_wayland, "broken on wayland")
# @unittest.skipIf(
# os.environ.get("SDL_VIDEODRIVER") == "dummy",
# 'requires the SDL_VIDEODRIVER to be a non "dummy" value',
# )
# Fails on SDL 2.0.18
@unittest.skip("flaky test, and broken on 2.0.18 windows")
def test_set_grab__and_get_symmetric(self):
"""Ensure event grabbing can be enabled and disabled.
@@ -908,11 +845,12 @@ class EventModuleTest(unittest.TestCase):
self.assertTrue(blocked)
@unittest.skipIf(
os.environ.get("SDL_VIDEODRIVER") == pygame.NULL_VIDEODRIVER,
"requires the SDL_VIDEODRIVER to be a non-null value",
)
@unittest.skipIf(is_wayland, "broken on wayland")
# @unittest.skipIf(
# os.environ.get("SDL_VIDEODRIVER") == "dummy",
# 'requires the SDL_VIDEODRIVER to be a non "dummy" value',
# )
# Fails on SDL 2.0.18
@unittest.skip("flaky test, and broken on 2.0.18 windows")
def test_get_grab(self):
"""Ensure get_grab() works as expected"""
surf = pygame.display.set_mode((10, 10))
@@ -921,6 +859,22 @@ class EventModuleTest(unittest.TestCase):
pygame.event.set_grab(i % 2)
self.assertEqual(pygame.event.get_grab(), i % 2)
@unittest.skipIf(
os.environ.get("SDL_VIDEODRIVER") == "dummy",
"requires the SDL_VIDEODRIVER to be a non dummy value",
)
@unittest.skipIf(pygame.get_sdl_version() < (2, 0, 16), "Needs at least SDL 2.0.16")
def test_set_keyboard_grab_and_get_keyboard_grab(self):
"""Ensure set_keyboard_grab() and get_keyboard_grab() work as expected"""
surf = pygame.display.set_mode((10, 10))
pygame.event.set_keyboard_grab(True)
self.assertTrue(pygame.event.get_keyboard_grab())
pygame.event.set_keyboard_grab(False)
self.assertFalse(pygame.event.get_keyboard_grab())
def test_poll(self):
"""Ensure poll() works as expected"""
pygame.event.clear()
@@ -1,238 +0,0 @@
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
@@ -1,15 +1,14 @@
# -*- coding: utf-8 -*-
import io
import sys
import os
import unittest
import pathlib
import platform
import sys
import unittest
from tempfile import TemporaryDirectory
import pygame
from pygame import font as pygame_font # So font can be replaced with ftfont
FONTDIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "fonts")
@@ -118,10 +117,7 @@ class FontModuleTest(unittest.TestCase):
for font in fonts:
path = pygame_font.match_font(font)
self.assertFalse(path is None)
self.assertTrue(
os.path.isabs(path) and os.path.isfile(path),
msg=f"path '{path}': exists: {os.path.exists(path)} is abs path:{os.path.isabs(path)} and is file:{os.path.isfile(path)} is link: {os.path.islink(path)} is mount: {os.path.ismount(path)} is dir: {os.path.isdir(path)}",
)
self.assertTrue(os.path.isabs(path) and os.path.isfile(path))
def test_match_font_name(self):
"""That match_font accepts names of various types"""
@@ -181,7 +177,7 @@ class FontModuleTest(unittest.TestCase):
any(pygame_font.match_font(font, italic=True) for font in fonts)
)
def test_issue_553(self):
def test_issue_742(self):
"""that the font background does not crash."""
surf = pygame.Surface((320, 240))
font = pygame_font.Font(None, 24)
@@ -190,7 +186,7 @@ class FontModuleTest(unittest.TestCase):
image.set_alpha(255)
surf.blit(image, (0, 0))
# not pygame-ce issue 553, but be sure to test that background color is
# not issue 742, but be sure to test that background color is
# correctly issued on this mode
self.assertEqual(surf.get_at((0, 0)), pygame.Color(0, 0, 0))
@@ -248,34 +244,9 @@ class FontTest(unittest.TestCase):
self.assertEqual(tuple(screen.get_at((0, 0)))[:3], (255, 255, 255))
self.assertEqual(tuple(screen.get_at(font_rect.topleft))[:3], (255, 255, 255))
# ftfont and font render with different arguments
if pygame_font.__name__ == "pygame.font":
font_surface = f.render(
text=" bar",
antialias=True,
color=(0, 0, 0),
bgcolor=(255, 255, 255),
wraplength=0,
)
else:
font_surface = f.render(
text=" bar",
antialias=True,
color=(0, 0, 0),
bgcolor=(255, 255, 255),
)
screen.fill((10, 10, 10))
font_rect = font_surface.get_rect()
font_rect.topleft = rect.topleft
self.assertTrue(font_surface)
screen.blit(font_surface, font_rect, font_rect)
pygame.display.update()
self.assertEqual(tuple(screen.get_at((0, 0)))[:3], (255, 255, 255))
self.assertEqual(tuple(screen.get_at(font_rect.topleft))[:3], (255, 255, 255))
# If we don't have a real display, don't do this test.
# Transparent background doesn't seem to work without a read video card.
if os.environ.get("SDL_VIDEODRIVER") != pygame.NULL_VIDEODRIVER:
if os.environ.get("SDL_VIDEODRIVER") != "dummy":
screen.fill((10, 10, 10))
font_surface = f.render(" bar", True, (0, 0, 0), None)
font_rect = font_surface.get_rect()
@@ -296,42 +267,6 @@ class FontTest(unittest.TestCase):
self.assertEqual(tuple(screen.get_at((0, 0)))[:3], (10, 10, 10))
self.assertEqual(tuple(screen.get_at(font_rect.topleft))[:3], (10, 10, 10))
def test_render_multiline(self):
if pygame_font.__name__ == "pygame.ftfont":
return
f = pygame_font.Font(None, 20)
one_line = f.render("hello", True, "black", "white", 200)
two_lines = f.render("hello\nworld", True, "black", "white", 200)
self.assertGreater(two_lines.get_height(), one_line.get_height())
one_line = f.render("hello", True, "black", None, 200)
two_lines = f.render("hello\nworld", True, "black", None, 200)
self.assertGreater(two_lines.get_height(), one_line.get_height())
one_line = f.render("hello", False, "black", None, 200)
two_lines = f.render("hello\nworld", False, "black", None, 200)
self.assertGreater(two_lines.get_height(), one_line.get_height())
@unittest.skipIf(
pygame.font.get_sdl_ttf_version() < (2, 22, 0), "bug fixed in SDL_ttf 2.22.0"
)
def test_render_multiple_newlines(self):
if pygame_font.__name__ == "pygame.ftfont":
return
f = pygame_font.Font(None, 20)
one_newline = f.render("\n", True, "black", "white")
two_newlines = f.render("\n\n", True, "black", "white")
three_newlines = f.render("\n\n\n", True, "black", "white")
self.assertTrue(
one_newline.get_height()
< two_newlines.get_height()
< three_newlines.get_height()
)
self.assertEqual(one_newline.get_height() * 2, two_newlines.get_height())
self.assertEqual(one_newline.get_height() * 3, three_newlines.get_height())
@unittest.skipIf(IS_PYPY, "pypy skip known failure") # TODO
class FontTypeTest(unittest.TestCase):
@@ -344,10 +279,6 @@ class FontTypeTest(unittest.TestCase):
def test_default_parameters(self):
f = pygame_font.Font()
def test_font_alias(self):
"""Check if pygame.Font is present and the correct type."""
self.assertIs(pygame.Font, pygame.font.Font)
def test_get_ascent(self):
# Checking ascent would need a custom test font to do properly.
f = pygame_font.Font(None, 20)
@@ -371,7 +302,7 @@ class FontTypeTest(unittest.TestCase):
self.assertTrue(isinstance(height, int))
self.assertTrue(height > 0)
s = f.render("X", False, (255, 255, 255))
self.assertAlmostEqual(s.get_height(), height, delta=3)
self.assertTrue(s.get_size()[1] == height)
def test_get_linesize(self):
# Checking linesize would need a custom test font to do properly.
@@ -381,35 +312,6 @@ class FontTypeTest(unittest.TestCase):
self.assertTrue(isinstance(linesize, int))
self.assertTrue(linesize > 0)
@unittest.skipIf(
pygame.font.get_sdl_ttf_version() < (2, 24, 0),
"supported in SDL_ttf 2.24.0 onwards",
)
def test_set_linesize(self):
if pygame_font.__name__ == "pygame.ftfont":
return # not a pygame.ftfont thing
f = pygame_font.Font(None, 20)
linesize = f.get_linesize()
# check increasing linesize
f.set_linesize(linesize + 1)
self.assertEqual(f.get_linesize(), linesize + 1)
# check random linesize
expected_linesizes = [30, 1, 22, 34, 5, 10, 0]
for expected_size in expected_linesizes:
f.set_linesize(expected_size)
self.assertEqual(f.get_linesize(), expected_size)
# check invalid linesize
with self.assertRaises(ValueError):
f.set_linesize(-1)
with self.assertRaises(OverflowError):
f.set_linesize(2**100)
with self.assertRaises(TypeError):
f.set_linesize(12.0)
def test_metrics(self):
# Ensure bytes decoding works correctly. Can only compare results
# with unicode for now.
@@ -422,7 +324,7 @@ class FontTypeTest(unittest.TestCase):
self.assertIsNotNone(um[0])
self.assertEqual(um, bm)
u = "\u212a"
u = "\u212A"
b = u.encode("UTF-16")[2:] # Keep byte order consistent. [2:] skips BOM
bm = f.metrics(b)
@@ -441,10 +343,7 @@ class FontTypeTest(unittest.TestCase):
bm = f.metrics(u)
self.assertEqual(len(bm), 1)
if pygame_font.__name__ != "pygame.ftfont":
self.assertIsNotNone(bm[0])
else:
self.assertIsNone(bm[0])
self.assertIsNone(bm[0])
return # unfinished
# The documentation is useless here. How large a list?
@@ -492,7 +391,7 @@ class FontTypeTest(unittest.TestCase):
su = f.render(".", False, [0, 0, 0], [255, 255, 255])
sb = f.render(b".", False, [0, 0, 0], [255, 255, 255])
self.assertTrue(equal_images(su, sb))
u = "\u212a"
u = "\u212A"
b = u.encode("UTF-16")[2:] # Keep byte order consistent. [2:] skips BOM
sb = f.render(b, False, [0, 0, 0], [255, 255, 255])
try: # FIXME why do we do this try/except ?
@@ -512,7 +411,7 @@ class FontTypeTest(unittest.TestCase):
# If the font module is SDL_ttf < 2.0.15 based, then it only supports UCS-2
# it will raise an exception for an out-of-range UCS-4 code point.
if hasattr(pygame_font, "UCS4"):
ucs_2 = "\uffee"
ucs_2 = "\uFFEE"
s = f.render(ucs_2, False, [0, 0, 0], [255, 255, 255])
ucs_4 = "\U00010000"
s = f.render(ucs_4, False, [0, 0, 0], [255, 255, 255])
@@ -542,12 +441,13 @@ class FontTypeTest(unittest.TestCase):
self.assertFalse(f.get_underline())
def test_set_strikethrough(self):
f = pygame_font.Font(None, 20)
self.assertFalse(f.get_strikethrough())
f.set_strikethrough(True)
self.assertTrue(f.get_strikethrough())
f.set_strikethrough(False)
self.assertFalse(f.get_strikethrough())
if pygame_font.__name__ != "pygame.ftfont":
f = pygame_font.Font(None, 20)
self.assertFalse(f.get_strikethrough())
f.set_strikethrough(True)
self.assertTrue(f.get_strikethrough())
f.set_strikethrough(False)
self.assertFalse(f.get_strikethrough())
def test_bold_attr(self):
f = pygame_font.Font(None, 20)
@@ -574,31 +474,13 @@ class FontTypeTest(unittest.TestCase):
self.assertFalse(f.underline)
def test_set_strikethrough_property(self):
f = pygame_font.Font(None, 20)
self.assertFalse(f.strikethrough)
f.strikethrough = True
self.assertTrue(f.strikethrough)
f.strikethrough = False
self.assertFalse(f.strikethrough)
def test_set_align_property(self):
if pygame_font.__name__ == "pygame.ftfont":
return
f = pygame_font.Font(None, 20)
if pygame.font.get_sdl_ttf_version() < (2, 20, 0):
with self.assertRaises(pygame.error):
f.align = pygame.FONT_CENTER
return
self.assertEqual(f.align, pygame.FONT_LEFT)
f.align = pygame.FONT_CENTER
self.assertEqual(f.align, pygame.FONT_CENTER)
f.align = pygame.FONT_RIGHT
self.assertEqual(f.align, pygame.FONT_RIGHT)
f.align = pygame.FONT_LEFT
self.assertEqual(f.align, pygame.FONT_LEFT)
if pygame_font.__name__ != "pygame.ftfont":
f = pygame_font.Font(None, 20)
self.assertFalse(f.strikethrough)
f.strikethrough = True
self.assertTrue(f.strikethrough)
f.strikethrough = False
self.assertFalse(f.strikethrough)
def test_size(self):
f = pygame_font.Font(None, 20)
@@ -610,116 +492,16 @@ class FontTypeTest(unittest.TestCase):
self.assertIsInstance(w, int)
self.assertIsInstance(h, int)
# test width and height match, with a tolerance for 1 pixel errors
self.assertTrue(w - 1 <= s.get_width() <= w + 1)
self.assertTrue(h - 1 <= s.get_height() <= h + 1)
self.assertEqual(s.get_size(), size)
self.assertEqual(f.size(btext), size)
text = "\u212a"
text = "\u212A"
btext = text.encode("UTF-16")[2:] # Keep the byte order consistent.
bsize = f.size(btext)
size = f.size(text)
self.assertNotEqual(size, bsize)
def test_point_size_property(self):
if pygame_font.__name__ == "pygame.ftfont":
return # not a pygame.ftfont feature
pygame_font.init()
font_path = os.path.join(
os.path.split(pygame.__file__)[0], pygame_font.get_default_font()
)
f = pygame_font.Font(pathlib.Path(font_path), 25)
self.assertEqual(25, f.point_size)
f.point_size = 10
self.assertEqual(10, f.point_size)
f.point_size += 23
self.assertEqual(33, f.point_size)
f.point_size -= 2
self.assertEqual(31, f.point_size)
def test_neg():
f.point_size = -500
def test_incorrect_type():
f.point_size = "15"
self.assertRaises(ValueError, test_neg)
self.assertRaises(TypeError, test_incorrect_type)
def test_point_size_method(self):
if pygame_font.__name__ == "pygame.ftfont":
return # not a pygame.ftfont feature
pygame_font.init()
font_path = os.path.join(
os.path.split(pygame.__file__)[0], pygame_font.get_default_font()
)
f = pygame_font.Font(pathlib.Path(font_path), 25)
self.assertEqual(25, f.get_point_size())
f = pygame_font.Font(None, 25)
f.set_point_size(10)
self.assertEqual(10, f.get_point_size())
self.assertRaises(ValueError, f.set_point_size, -500)
self.assertRaises(TypeError, f.set_point_size, "15")
def test_outline_property(self):
if pygame_font.__name__ == "pygame.ftfont":
return # not a pygame.ftfont feature
pygame_font.init()
font_path = os.path.join(
os.path.split(pygame.__file__)[0], pygame_font.get_default_font()
)
f = pygame_font.Font(pathlib.Path(font_path), 25)
# Default outline should be an integer >= 0 (typically 0)
self.assertIsInstance(f.outline, int)
self.assertGreaterEqual(f.outline, 0)
orig = f.outline
f.outline = orig + 1
self.assertEqual(orig + 1, f.outline)
f.outline += 2
self.assertEqual(orig + 3, f.outline)
f.outline -= 1
self.assertEqual(orig + 2, f.outline)
def test_neg():
f.outline = -1
def test_incorrect_type():
f.outline = "2"
self.assertRaises(ValueError, test_neg)
self.assertRaises(TypeError, test_incorrect_type)
def test_font_name(self):
f = pygame_font.Font(None, 20)
self.assertEqual(f.name, "FreeSans")
def test_set_name():
f.name = "Say my name."
self.assertRaises(AttributeError, test_set_name)
def test_font_style_name(self):
f = pygame_font.Font(None, 20)
self.assertNotEqual(f.style_name, "")
self.assertNotEqual(f.style_name, None)
self.assertIsInstance(f.style_name, str)
def test_font_style_name_is_readonly(self):
f = pygame_font.Font(None, 20)
def _set_style_name():
f.style_name = "Say my other name."
self.assertRaises(AttributeError, _set_style_name)
def test_font_file_not_found(self):
# A per BUG reported by Bo Jangeborg on pygame-user mailing list,
# http://www.mail-archive.com/pygame-users@seul.org/msg11675.html
@@ -774,12 +556,6 @@ class FontTypeTest(unittest.TestCase):
with open(font_path, "rb") as f:
font = pygame_font.Font(f)
def test_load_from_invalid_sized_file_obj(self):
pygame.font.init()
f = io.StringIO()
with self.assertRaises(ValueError):
font = pygame.font.Font(f)
def test_load_default_font_filename(self):
# In font_init, a special case is when the filename argument is
# identical to the default font file name.
@@ -793,12 +569,19 @@ class FontTypeTest(unittest.TestCase):
def _load_unicode(self, path):
import shutil
with TemporaryDirectory() as tmpdir:
fdir = str(FONTDIR)
temp = os.path.join(tmpdir, path)
pgfont = os.path.join(fdir, "test_sans.ttf")
shutil.copy(pgfont, temp)
fdir = str(FONTDIR)
temp = os.path.join(fdir, path)
pgfont = os.path.join(fdir, "test_sans.ttf")
shutil.copy(pgfont, temp)
try:
with open(temp, "rb") as f:
pass
except FileNotFoundError:
raise unittest.SkipTest("the path cannot be opened")
try:
pygame_font.Font(temp, 20)
finally:
os.remove(temp)
def test_load_from_file_unicode_0(self):
"""ASCII string as a unicode object"""
@@ -820,7 +603,7 @@ class FontTypeTest(unittest.TestCase):
bfont_path = font_path.encode(filesystem_encoding, filesystem_errors)
f = pygame_font.Font(bfont_path, 20)
def test_issue_1587(self):
def test_issue_3144(self):
fpath = os.path.join(FONTDIR, "PlayfairDisplaySemibold.ttf")
# issue in SDL_ttf 2.0.18 DLL on Windows
@@ -851,224 +634,9 @@ class FontTypeTest(unittest.TestCase):
else:
self.assertRaises(pygame.error, font.set_script, "Deva")
def test_font_set_direction(self):
if pygame_font.__name__ == "pygame.ftfont":
return # not a pygame.ftfont thing
font = pygame_font.Font(None, 16)
ttf_version = pygame.font.get_sdl_ttf_version()
if ttf_version >= (2, 20, 0):
self.assertRaises(TypeError, pygame.font.Font.set_direction)
self.assertRaises(TypeError, pygame.font.Font.set_direction, font)
self.assertRaises(TypeError, pygame.font.Font.set_direction, "font")
self.assertRaises(TypeError, font.set_direction, [1, 1])
self.assertRaises(TypeError, font.set_direction, "string1", "string2")
self.assertRaises(ValueError, font.set_direction, -1)
self.assertRaises(ValueError, font.set_direction, 4)
font.set_direction(pygame.DIRECTION_RTL)
else:
self.assertRaises(pygame.error, font.set_direction, pygame.DIRECTION_RTL)
def test_font_method_should_raise_exception_after_quit(self):
# arrange
if pygame_font.__name__ == "pygame.ftfont":
surf = pygame.Surface((1, 1))
methods = [
("get_sized_height", ()),
("get_sized_ascender", ()),
("get_sized_glyph_height", ()),
("get_rect", ("any text",)),
("get_metrics", ("any text",)),
("get_sizes", ()),
("render", ("any text", True, "white")),
(
"render_to",
(
surf,
(10, 11),
"text",
),
), # surf
("render_raw", ("any text",)),
(
"render_raw_to",
(
surf.get_view("2"),
None,
),
),
("get_ascent", ()),
("get_bold", ()),
("get_descent", ()),
("get_height", ()),
("get_italic", ()),
("get_linesize", ()),
("get_sized_descender", ()),
("get_underline", ()),
("metrics", ("any text",)),
("set_bold", (True,)),
("set_italic", (True,)),
("set_underline", (True,)),
("size", ("any Text",)),
]
skip_methods = {"get_strikethrough", "set_strikethrough"}
else:
methods = [
("get_height", ()),
("get_descent", ()),
("get_ascent", ()),
("get_linesize", ()),
("get_bold", ()),
("set_bold", (True,)),
("get_italic", ()),
("set_italic", (True,)),
("get_underline", ()),
("set_underline", (True,)),
("get_strikethrough", ()),
("set_strikethrough", (True,)),
("metrics", ("any text",)),
("render", ("hello", True, "white")),
("size", ("any text",)),
("set_script", ("is it other text",)),
("set_direction", ("is it text",)),
("get_point_size", ()),
("set_point_size", (34,)),
]
skip_methods = set()
version = pygame.font.get_sdl_ttf_version()
if version >= (2, 24, 0):
methods.append(("set_linesize", (2,)))
else:
skip_methods.add("set_linesize")
if version < (2, 20, 0):
skip_methods.add("align")
font = pygame_font.Font(None, 10)
actual_names = []
for n in sorted(dir(font)):
if n in skip_methods:
continue
if n.startswith("_"):
continue
if not callable(getattr(font, n)):
continue
actual_names.append(n)
expected_names = [n for n, a in sorted(methods)]
self.assertEqual(
len(expected_names),
len(actual_names),
msg=f"ensure all methods are checked \n{expected_names} \n!= \n{actual_names}",
)
for name, args in methods:
# import sys
# print("###", name,file=sys.__stdout__,flush=True)
with self.subTest(name=name):
# arrange
font = pygame_font.Font(None, 16)
pygame_font.quit()
pygame_font.init()
# act / assert
self.assertRaises(pygame.error, getattr(font, name), *args)
def test_font_property_should_raise_exception_after_quit(self):
if pygame_font.__name__ == "pygame.ftfont":
properties = [
("style", 10.5),
("height", None),
("ascender", None),
("descender", None),
("name", None),
("style_name", None),
("path", None),
("scalable", None),
("fixed_width", None),
("fixed_sizes", None),
("antialiased", 45),
("kerning", 46),
("vertical", 47),
("pad", 48),
("oblique", 1),
("strong", 1),
("underline", 1),
("wide", 1),
("strength", 49),
("underline_adjustment", 50),
("ucs4", 1),
("use_bitmap_strikes", 1),
("rotation", 33),
("fgcolor", (1, 1, 1)),
("bgcolor", (2, 2, 2)),
("origin", None),
("bold", True),
("italic", True),
("resolution", None),
]
skip_properties = {"strikethrough"}
else:
properties = [
("name", None),
("style_name", None),
("bold", True),
("italic", True),
("underline", True),
("strikethrough", True),
("outline", 1),
("point_size", 1),
]
skip_properties = set()
version = pygame.font.get_sdl_ttf_version()
if version >= (2, 20, 0):
properties.append(("align", 1))
else:
skip_properties.add("align")
font = pygame_font.Font(None, 10)
actual_names = []
for n in sorted(dir(font)):
if n in skip_properties:
continue
if n.startswith("_"):
continue
if callable(getattr(font, n)):
continue
actual_names.append(n)
expected_names = [n for n, a in sorted(properties)]
self.assertEqual(
len(expected_names),
len(actual_names),
msg=f"ensure all properties are checked \n{expected_names} \n!= \n{actual_names}",
)
for name, arg in properties:
# import sys
# print(">>>", name,file=sys.__stdout__,flush=True)
with self.subTest(name=name + " get"):
# arrange
font = pygame_font.Font(None, 16)
pygame_font.quit()
pygame_font.init()
# act / assert
self.assertRaises(pygame.error, getattr, font, name) # read
if arg is not None:
with self.subTest(name=name + " write"):
# act / assert
self.assertRaises(pygame.error, setattr, font, name, arg) # write
@unittest.skipIf(IS_PYPY, "pypy skip known failure") # TODO
class VisualTestsInteractive(unittest.TestCase):
class VisualTests(unittest.TestCase):
__tags__ = ["interactive"]
screen = None
@@ -1094,7 +662,6 @@ class VisualTestsInteractive(unittest.TestCase):
underline=False,
strikethrough=False,
antialiase=False,
outline=0,
):
if self.aborted:
return False
@@ -1105,7 +672,7 @@ class VisualTestsInteractive(unittest.TestCase):
screen = self.screen
screen.fill((255, 255, 255))
pygame.display.flip()
if not (bold or italic or underline or strikethrough or antialiase or outline):
if not (bold or italic or underline or strikethrough or antialiase):
text = "normal"
else:
modes = []
@@ -1119,22 +686,20 @@ class VisualTestsInteractive(unittest.TestCase):
modes.append("strikethrough")
if antialiase:
modes.append("antialiased")
if outline:
modes.append("outlined")
text = f"{'-'.join(modes)} (y/n):"
f.set_bold(bold)
f.set_italic(italic)
f.set_underline(underline)
f.set_strikethrough(strikethrough)
f.outline = outline
if pygame_font.__name__ != "pygame.ftfont":
f.set_strikethrough(strikethrough)
s = f.render(text, antialiase, (0, 0, 0))
screen.blit(s, (offset, y))
y += s.get_size()[1] + spacing
f.set_bold(False)
f.set_italic(False)
f.set_underline(False)
f.set_strikethrough(False)
f.outline = 0
if pygame_font.__name__ != "pygame.ftfont":
f.set_strikethrough(False)
s = f.render("(some comparison text)", False, (0, 0, 0))
screen.blit(s, (offset, y))
pygame.display.flip()
@@ -1162,7 +727,8 @@ class VisualTestsInteractive(unittest.TestCase):
self.assertTrue(self.query(underline=True))
def test_strikethrough(self):
self.assertTrue(self.query(strikethrough=True))
if pygame_font.__name__ != "pygame.ftfont":
self.assertTrue(self.query(strikethrough=True))
def test_antialiase(self):
self.assertTrue(self.query(antialiase=True))
@@ -1174,10 +740,8 @@ class VisualTestsInteractive(unittest.TestCase):
self.assertTrue(self.query(italic=True, underline=True))
def test_bold_strikethrough(self):
self.assertTrue(self.query(bold=True, strikethrough=True))
def test_outline(self):
self.assertTrue(self.query(outline=1))
if pygame_font.__name__ != "pygame.ftfont":
self.assertTrue(self.query(bold=True, strikethrough=True))
if __name__ == "__main__":
@@ -1,12 +1,14 @@
import ctypes
import gc
import io
import os
if os.environ.get("SDL_VIDEODRIVER") == "dummy":
__tags__ = ("ignore", "subprocess_ignore")
import unittest
import ctypes
import weakref
import gc
import pathlib
import platform
import sys
import unittest
import weakref
IS_PYPY = "PyPy" == platform.python_implementation()
@@ -17,7 +19,12 @@ except NameError:
pass
import pygame
import pygame.freetype as ft
try:
import pygame.freetype as ft
except ImportError:
ft = None
FONTDIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "fonts")
@@ -57,7 +64,7 @@ class FreeTypeFontTest(unittest.TestCase):
def setUpClass(cls):
ft.init()
# Set up the test fonts.
# Setup the test fonts.
# Inconsolata is an open-source font designed by Raph Levien.
# Licensed under the Open Font License.
@@ -126,7 +133,7 @@ class FreeTypeFontTest(unittest.TestCase):
FileNotFoundError, f.__init__, os.path.join(FONTDIR, "nonexistent.ttf")
)
# Test attribute preservation during reinitialization
# Test attribute preservation during reinitalization
f = ft.Font(self._sans_path, size=24, ucs4=True)
self.assertEqual(f.name, "Liberation Sans")
self.assertTrue(f.scalable)
@@ -154,11 +161,6 @@ class FreeTypeFontTest(unittest.TestCase):
f.__init__(self._bmp_8_75dpi_path, size=12)
self.assertEqual(f.size, 12.0)
def test_load_from_invalid_sized_file_obj(self):
f = io.StringIO()
with self.assertRaises(ValueError):
font = f = ft.Font(f, size=24)
@unittest.skipIf(IS_PYPY, "PyPy doesn't use refcounting")
def test_freetype_Font_dealloc(self):
import sys
@@ -200,7 +202,7 @@ class FreeTypeFontTest(unittest.TestCase):
Note: This does not test what changes occur to a rendered font by
having kerning enabled.
Related to pygame-ce issue #371.
Related to issue #367.
"""
surface = pygame.Surface((10, 10), 0, 32)
TEST_TEXT = "Freetype Font"
@@ -508,11 +510,11 @@ class FreeTypeFontTest(unittest.TestCase):
# one code point or two.
ufont = self._TEST_FONTS["mono"]
rect_utf32 = ufont.get_rect("\U00013079", size=24)
rect_utf16 = ufont.get_rect("\ud80c\udc79", size=24)
rect_utf16 = ufont.get_rect("\uD80C\uDC79", size=24)
self.assertEqual(rect_utf16, rect_utf32)
ufont.ucs4 = True
try:
rect_utf16 = ufont.get_rect("\ud80c\udc79", size=24)
rect_utf16 = ufont.get_rect("\uD80C\uDC79", size=24)
finally:
ufont.ucs4 = False
self.assertNotEqual(rect_utf16, rect_utf32)
@@ -545,9 +547,8 @@ class FreeTypeFontTest(unittest.TestCase):
f = self._TEST_FONTS["fixed"]
self.assertEqual(f.name, "Inconsolata")
with self.assertRaises(AttributeError):
null_font = ft.Font.__new__(ft.Font)
null_font.name
nf = nullfont()
self.assertEqual(nf.name, repr(nf))
def test_freetype_Font_size(self):
f = ft.Font(None, size=12)
@@ -775,29 +776,29 @@ class FreeTypeFontTest(unittest.TestCase):
ucs4 = font2.ucs4
try:
font2.ucs4 = False
rend1 = font2.render("\ud80c\udc79", color, size=24)
rend1 = font2.render("\uD80C\uDC79", color, size=24)
rend2 = font2.render("\U00013079", color, size=24)
self.assertEqual(rend1[1], rend2[1])
font2.ucs4 = True
rend1 = font2.render("\ud80c\udc79", color, size=24)
rend1 = font2.render("\uD80C\uDC79", color, size=24)
self.assertNotEqual(rend1[1], rend2[1])
finally:
font2.ucs4 = ucs4
# malformed surrogate pairs
self.assertRaises(UnicodeEncodeError, font.render, "\ud80c", color, size=24)
self.assertRaises(UnicodeEncodeError, font.render, "\udca7", color, size=24)
self.assertRaises(UnicodeEncodeError, font.render, "\uD80C", color, size=24)
self.assertRaises(UnicodeEncodeError, font.render, "\uDCA7", color, size=24)
self.assertRaises(
UnicodeEncodeError, font.render, "\ud7ff\udca7", color, size=24
UnicodeEncodeError, font.render, "\uD7FF\uDCA7", color, size=24
)
self.assertRaises(
UnicodeEncodeError, font.render, "\udc00\udca7", color, size=24
UnicodeEncodeError, font.render, "\uDC00\uDCA7", color, size=24
)
self.assertRaises(
UnicodeEncodeError, font.render, "\ud80c\udbff", color, size=24
UnicodeEncodeError, font.render, "\uD80C\uDBFF", color, size=24
)
self.assertRaises(
UnicodeEncodeError, font.render, "\ud80c\ue000", color, size=24
UnicodeEncodeError, font.render, "\uD80C\uE000", color, size=24
)
# raises exception when uninitialized
@@ -921,17 +922,15 @@ class FreeTypeFontTest(unittest.TestCase):
self.assertEqual(
surf.get_at(bottomleft),
fill_color,
"Position: {}. Depth: {}. fg_color: {}.".format(
bottomleft, surf.get_bitsize(), fg_color
),
"Position: {}. Depth: {}."
" fg_color: {}.".format(bottomleft, surf.get_bitsize(), fg_color),
)
bottomright = rrect.width - 1, rrect.height - 1
self.assertEqual(
surf.get_at(bottomright),
r_fg_color,
"Position: {}. Depth: {}. fg_color: {}.".format(
bottomright, surf.get_bitsize(), fg_color
),
"Position: {}. Depth: {}."
" fg_color: {}.".format(bottomright, surf.get_bitsize(), fg_color),
)
for i, surf in enumerate(surfaces):
surf.fill(fill_color)
@@ -1012,7 +1011,7 @@ class FreeTypeFontTest(unittest.TestCase):
font = self._TEST_FONTS["sans"]
text = "abc"
# No frills anti aliased render to int1 (__render_glyph_INT)
# No frills antialiased render to int1 (__render_glyph_INT)
srect = font.get_rect(text, size=24)
surf = pygame.Surface(srect.size, 0, 8)
rrect = font.render_raw_to(surf.get_view("2"), text, size=24)
@@ -1053,7 +1052,7 @@ class FreeTypeFontTest(unittest.TestCase):
finally:
font.antialiased = True
# Anti aliased render to ints sized greater than 1 byte
# Antialiased render to ints sized greater than 1 byte
# (__render_glyph_INT)
srect = font.get_rect(text, size=24)
@@ -1244,6 +1243,7 @@ class FreeTypeFontTest(unittest.TestCase):
self.assertRaises(AttributeError, setattr, f, "bgcolor", None)
@unittest.skipIf(not pygame.HAVE_NEWBUF, "newbuf not implemented")
@unittest.skipIf(IS_PYPY, "pypy no likey")
def test_newbuf(self):
from pygame.tests.test_utils import buftools
@@ -1353,10 +1353,7 @@ class FreeTypeFontTest(unittest.TestCase):
def test_freetype_Font_path(self):
self.assertEqual(self._TEST_FONTS["sans"].path, self._sans_path)
with self.assertRaises(AttributeError):
nullfont = ft.Font.__new__(ft.Font)
nullfont.path
self.assertRaises(AttributeError, getattr, nullfont(), "path")
# This Font cache test is conditional on freetype being built by a debug
# version of Python or with the C macro PGFT_DEBUG_CACHE defined.
@@ -1484,10 +1481,10 @@ class FreeTypeFontTest(unittest.TestCase):
self.assertIsNone(metrics[0])
self.assertIsInstance(metrics[1], tuple)
def test_issue_257(self):
"""pygame-ce issue #257: get_rect() uses 0 as default style"""
def test_issue_242(self):
"""Issue #242: get_rect() uses 0 as default style"""
# pygame-ce issue #257: freetype.Font.get_rect() ignores style defaults when
# Issue #242: freetype.Font.get_rect() ignores style defaults when
# the style argument is not given
#
# The text boundary rectangle returned by freetype.Font.get_rect()
@@ -1544,10 +1541,10 @@ class FreeTypeFontTest(unittest.TestCase):
finally:
font.underline = prev_style
def test_issue_252(self):
"""pygame-ce issue #252: Memory overrun when rendered with underlining"""
def test_issue_237(self):
"""Issue #237: Memory overrun when rendered with underlining"""
# pygame-ce issue #252: Memory overrun when text without descenders is rendered
# Issue #237: Memory overrun when text without descenders is rendered
# with underlining
#
# The bug crashes the Python interpreter. The bug is caught with C
@@ -1567,10 +1564,10 @@ class FreeTypeFontTest(unittest.TestCase):
font.underline_adjustment = adj
s, r = font.render("Amazon", size=19)
def test_issue_258(self):
"""pygame-ce issue #258: trailing space ignored in boundary calculation"""
def test_issue_243(self):
"""Issue Y: trailing space ignored in boundary calculation"""
# pygame-ce issue #258: For a string with trailing spaces, freetype ignores the
# Issue #243: For a string with trailing spaces, freetype ignores the
# last space in boundary calculations
#
font = self._TEST_FONTS["fixed"]
@@ -1598,20 +1595,13 @@ class FreeTypeFontTest(unittest.TestCase):
n = len(refs)
self.assertTrue(n > 0)
# for pypy we perform garbage collection twice.
# for pypy we garbage collection twice.
for i in range(2):
gc.collect()
for i in range(n):
self.assertIsNone(refs[i](), "ref %d not collected" % i)
font2 = ft.Font(self._fixed_path)
ref = weakref.ref(font2)
del font2
for i in range(2):
gc.collect()
self.assertIsNone(ref(), "ref not collected")
try:
from sys import getrefcount
except ImportError:
@@ -1619,16 +1609,16 @@ class FreeTypeFontTest(unittest.TestCase):
else:
array = arrinter.Array(rect.size, "u", 1)
o = font.render_raw(text)
self.assertIn(getrefcount(o), (1, 2))
self.assertEqual(getrefcount(o), 2)
self.assertEqual(getrefcount(o[0]), 2)
self.assertEqual(getrefcount(o[1]), 2)
self.assertEqual(getrefcount(font.render_raw_to(array, text)), 1)
o = font.get_metrics("AB")
self.assertIn(getrefcount(o), (1, 2))
self.assertEqual(getrefcount(o), 2)
for i in range(len(o)):
self.assertEqual(getrefcount(o[i]), 2, "refcount fail for item %d" % i)
o = font.get_sizes()
self.assertIn(getrefcount(o), (1, 2))
self.assertEqual(getrefcount(o), 2)
for i in range(len(o)):
self.assertEqual(getrefcount(o[i]), 2, "refcount fail for item %d" % i)
@@ -1636,7 +1626,7 @@ class FreeTypeFontTest(unittest.TestCase):
"""Font.render_to() on a closed display surface"""
# The Font.render_to() method checks that PySurfaceObject.surf is NULL
# and raise an exception if it is. This fixes a bug in Pygame revision
# and raise a exception if it is. This fixes a bug in Pygame revision
# 0600ea4f1cfb and earlier where Pygame segfaults instead.
null_surface = pygame.Surface.__new__(pygame.Surface)
f = self._TEST_FONTS["sans"]
@@ -1703,7 +1693,7 @@ class FreeTypeFontTest(unittest.TestCase):
self.assertEqual(font_name_2, font_name)
# Check mixed list of bytes and string.
names = [fonts_b[i] if i % 2 else str_font for i, str_font in enumerate(fonts)]
names = [fonts[0], fonts_b[1], fonts[2], fonts_b[3]]
font_name_2 = ft.SysFont(names, size).name
self.assertEqual(font_name_2, font_name)
@@ -1774,10 +1764,6 @@ class FreeTypeTest(unittest.TestCase):
# Test if get_init() gets the init state.
self.assertTrue(ft.get_init())
def test_was_init_deprecated(self):
with self.assertWarns(DeprecationWarning):
self.assertTrue(ft.was_init())
def test_cache_size(self):
DEFAULT_CACHE_SIZE = 64
self.assertEqual(ft.get_cache_size(), DEFAULT_CACHE_SIZE)
@@ -1,11 +1,10 @@
import os
import sys
import os
import unittest
from pygame.tests import font_test
import pygame.ftfont
from . import font_test
font_test.pygame_font = pygame.ftfont
for name in dir(font_test):
File diff suppressed because it is too large. Load diff
@@ -1,5 +1,4 @@
import unittest
import pygame
import pygame.gfxdraw
from pygame.locals import *
@@ -601,7 +600,7 @@ class GfxdrawDefaultTest(unittest.TestCase):
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.
Related to issue #622.
"""
bg_color = pygame.Color("white")
line_color = pygame.Color("black")
@@ -734,7 +733,7 @@ class GfxdrawDefaultTest(unittest.TestCase):
aapolygon() and the other using multiple line() calls. They should
produce the same final drawing.
Related to pygame-ce issue #506.
Related to issue #622.
"""
bg_color = pygame.Color("white")
line_color = pygame.Color("black")
@@ -872,46 +871,6 @@ class GfxdrawDefaultTest(unittest.TestCase):
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()
@@ -1,14 +1,14 @@
import os
import unittest
from pygame.tests import test_utils
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",
os.environ.get("SDL_VIDEODRIVER") == "dummy",
'OpenGL requires a non-"dummy" SDL_VIDEODRIVER',
)
class GL_ImageSave(unittest.TestCase):
def test_image_save_works_with_opengl_surfaces(self):
File diff suppressed because it is too large. Load diff
@@ -2,12 +2,10 @@ 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
import pygame, pygame.image, pygame.pkgdata
imageext = sys.modules["pygame.imageext"]
@@ -54,26 +52,41 @@ class ImageextModuleTest(unittest.TestCase):
"""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)
orig = example_path("data/alien1.png")
temp = os.path.join(example_path("data"), "你好.png")
shutil.copy(orig, temp)
try:
im = imageext.load_extended(temp)
finally:
os.remove(temp)
def _unicode_save(self, temp_file):
im = pygame.Surface((10, 10), 0, 32)
try:
with open(temp_file, "w") as f:
pass
os.remove(temp_file)
except OSError:
raise unittest.SkipTest("the path cannot be opened")
self.assertFalse(os.path.exists(temp_file))
imageext.save_extended(im, temp_file)
self.assertGreater(os.path.getsize(temp_file), 10)
try:
imageext.save_extended(im, temp_file)
self.assertGreater(os.path.getsize(temp_file), 10)
finally:
try:
os.remove(temp_file)
except OSError:
pass
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"))
self._unicode_save("temp_file.png")
def test_save_unicode_path_1(self):
with TemporaryDirectory() as tmpdir:
self._unicode_save(os.path.join(tmpdir, "你好.png"))
self._unicode_save("你好.png")
if __name__ == "__main__":
@@ -1,8 +1,8 @@
import unittest
from pygame.tests.test_utils import question, prompt
import pygame
import pygame._sdl2.controller
from pygame.tests.test_utils import prompt, question
class JoystickTypeTest(unittest.TestCase):
@@ -31,10 +31,6 @@ class JoystickTypeTest(unittest.TestCase):
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):
@@ -122,7 +118,7 @@ class JoystickModuleTest(unittest.TestCase):
try:
count = pygame.joystick.get_count()
self.assertGreaterEqual(
count, 0, ("joystick.get_count() must return a value >= 0")
count, 0, ("joystick.get_count() must " "return a value >= 0")
)
finally:
pygame.joystick.quit()
@@ -1,5 +1,4 @@
import os
import platform
import time
import unittest
@@ -8,7 +7,6 @@ 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 = {
@@ -170,7 +168,6 @@ KEY_NAME_COMPAT = {
class KeyModuleTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
pygame.quit()
pygame.init()
@classmethod
@@ -189,10 +186,9 @@ class KeyModuleTest(unittest.TestCase):
"""does it import?"""
import pygame.key
@unittest.skipIf(
not ("Windows" in platform.system() or "Darwin" in platform.system()),
"Not windows or macOS - we skip.",
)
# fixme: test_get_focused failing systematically in some linux
# fixme: test_get_focused failing on SDL 2.0.18 on Windows
@unittest.skip("flaky test, and broken on 2.0.18 windows")
def test_get_focused(self):
# This test fails in SDL2 in some linux
# This test was skipped in SDL1.
@@ -200,14 +196,14 @@ class KeyModuleTest(unittest.TestCase):
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:
if os.environ.get("SDL_VIDEODRIVER") != "dummy":
# 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
# Pump event queue to get window focus on macos
pygame.event.pump()
focused = pygame.key.get_focused()
self.assertIsInstance(focused, int)
@@ -238,21 +234,13 @@ class KeyModuleTest(unittest.TestCase):
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_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):
@@ -270,7 +258,7 @@ class KeyModuleTest(unittest.TestCase):
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
# can work together and handle each others outputs
# test positional args
self.assertEqual(pygame.key.name(const_val), expected_str_name)
@@ -288,8 +276,7 @@ class KeyModuleTest(unittest.TestCase):
# 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.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)
@@ -1,14 +1,15 @@
from collections import OrderedDict
import copy
import platform
import random
import sys
import unittest
from collections import OrderedDict
import sys
import pygame
from pygame.locals import *
from pygame.math import Vector2
IS_PYPY = "PyPy" == platform.python_implementation()
@@ -24,7 +25,8 @@ def random_mask(size=(100, 100)):
def maskFromSurface(surface, threshold=127):
mask = pygame.Mask(surface.get_size())
if key := surface.get_colorkey():
key = surface.get_colorkey()
if key:
for y in range(surface.get_height()):
for x in range(surface.get_width()):
if surface.get_at((x + 0.1, y + 0.1)) != key:
@@ -197,7 +199,7 @@ class MaskTypeTest(unittest.TestCase):
"""Ensures masks are created correctly using the fill keyword
over a range of sizes.
Test masks of different sizes, including:
Tests masks of different sizes, including:
-masks 31 to 33 bits wide (32 bit boundaries)
-masks 63 to 65 bits wide (64 bit boundaries)
"""
@@ -707,7 +709,7 @@ class MaskTypeTest(unittest.TestCase):
def test_overlap__bit_boundaries(self):
"""Ensures overlap handles masks of different sizes correctly.
Test masks of different sizes, including:
Tests masks of different sizes, including:
-masks 31 to 33 bits wide (32 bit boundaries)
-masks 63 to 65 bits wide (64 bit boundaries)
"""
@@ -855,7 +857,7 @@ class MaskTypeTest(unittest.TestCase):
def test_overlap_area__bit_boundaries(self):
"""Ensures overlap_area handles masks of different sizes correctly.
Test masks of different sizes, including:
Tests masks of different sizes, including:
-masks 31 to 33 bits wide (32 bit boundaries)
-masks 63 to 65 bits wide (64 bit boundaries)
"""
@@ -1077,7 +1079,7 @@ class MaskTypeTest(unittest.TestCase):
def test_overlap_mask__bit_boundaries(self):
"""Ensures overlap_mask handles masks of different sizes correctly.
Test masks of different sizes, including:
Tests masks of different sizes, including:
-masks 31 to 33 bits wide (32 bit boundaries)
-masks 63 to 65 bits wide (64 bit boundaries)
"""
@@ -1169,7 +1171,7 @@ class MaskTypeTest(unittest.TestCase):
def test_fill__bit_boundaries(self):
"""Ensures masks of different sizes are filled correctly.
Test masks of different sizes, including:
Tests masks of different sizes, including:
-masks 31 to 33 bits wide (32 bit boundaries)
-masks 63 to 65 bits wide (64 bit boundaries)
"""
@@ -1198,7 +1200,7 @@ class MaskTypeTest(unittest.TestCase):
def test_clear__bit_boundaries(self):
"""Ensures masks of different sizes are cleared correctly.
Test masks of different sizes, including:
Tests masks of different sizes, including:
-masks 31 to 33 bits wide (32 bit boundaries)
-masks 63 to 65 bits wide (64 bit boundaries)
"""
@@ -1273,7 +1275,7 @@ class MaskTypeTest(unittest.TestCase):
def test_invert__bit_boundaries(self):
"""Ensures masks of different sizes are inverted correctly.
Test masks of different sizes, including:
Tests masks of different sizes, including:
-masks 31 to 33 bits wide (32 bit boundaries)
-masks 63 to 65 bits wide (64 bit boundaries)
"""
@@ -1467,7 +1469,7 @@ class MaskTypeTest(unittest.TestCase):
def test_draw__bit_boundaries(self):
"""Ensures draw handles masks of different sizes correctly.
Test masks of different sizes, including:
Tests masks of different sizes, including:
-masks 31 to 33 bits wide (32 bit boundaries)
-masks 63 to 65 bits wide (64 bit boundaries)
"""
@@ -1661,7 +1663,7 @@ class MaskTypeTest(unittest.TestCase):
def test_erase__bit_boundaries(self):
"""Ensures erase handles masks of different sizes correctly.
Test masks of different sizes, including:
Tests masks of different sizes, including:
-masks 31 to 33 bits wide (32 bit boundaries)
-masks 63 to 65 bits wide (64 bit boundaries)
"""
@@ -1740,7 +1742,7 @@ class MaskTypeTest(unittest.TestCase):
def test_count__bit_boundaries(self):
"""Ensures the set bits of different sized masks are counted correctly.
Test masks of different sizes, including:
Tests masks of different sizes, including:
-masks 31 to 33 bits wide (32 bit boundaries)
-masks 63 to 65 bits wide (64 bit boundaries)
"""
@@ -1919,9 +1921,17 @@ class MaskTypeTest(unittest.TestCase):
self.assertEqual(centroid, expected_centroid)
def todo_test_angle(self):
def test_angle(self):
"""Ensure a mask's orientation angle is correctly calculated."""
self.fail()
expected_angle = -45.0
expected_size = (100, 100)
surface = pygame.Surface(expected_size)
mask = pygame.mask.from_surface(surface)
angle = mask.angle() # Returns the orientation of the pixels
self.assertIsInstance(angle, float)
self.assertEqual(angle, expected_angle)
def test_angle__empty_mask(self):
"""Ensure an empty mask's angle is correctly calculated."""
@@ -2569,7 +2579,7 @@ class MaskTypeTest(unittest.TestCase):
@unittest.skipIf(IS_PYPY, "Segfaults on pypy")
def test_to_surface(self):
"""Ensures empty and full masks can be drawn onto surfaces."""
expected_ref_count = (2, 3)
expected_ref_count = 3
size = (33, 65)
surface = pygame.Surface(size, SRCALPHA, 32)
surface_color = pygame.Color("red")
@@ -2583,13 +2593,13 @@ class MaskTypeTest(unittest.TestCase):
self.assertIs(to_surface, surface)
if not IS_PYPY:
self.assertIn(sys.getrefcount(to_surface), expected_ref_count)
self.assertEqual(sys.getrefcount(to_surface), expected_ref_count)
self.assertEqual(to_surface.get_size(), size)
assertSurfaceFilled(self, to_surface, expected_color)
def test_to_surface__create_surface(self):
"""Ensures empty and full masks can be drawn onto a created surface."""
expected_ref_count = (1, 2)
expected_ref_count = 2
expected_flag = SRCALPHA
expected_depth = 32
size = (33, 65)
@@ -2606,7 +2616,7 @@ class MaskTypeTest(unittest.TestCase):
self.assertIsInstance(to_surface, pygame.Surface)
if not IS_PYPY:
self.assertIn(sys.getrefcount(to_surface), expected_ref_count)
self.assertEqual(sys.getrefcount(to_surface), expected_ref_count)
self.assertTrue(to_surface.get_flags() & expected_flag)
self.assertEqual(to_surface.get_bitsize(), expected_depth)
self.assertEqual(to_surface.get_size(), size)
@@ -2614,7 +2624,7 @@ class MaskTypeTest(unittest.TestCase):
def test_to_surface__surface_param(self):
"""Ensures to_surface accepts a surface arg/kwarg."""
expected_ref_count = (3, 4)
expected_ref_count = 4
expected_color = pygame.Color("white")
surface_color = pygame.Color("red")
size = (5, 3)
@@ -2632,13 +2642,13 @@ class MaskTypeTest(unittest.TestCase):
self.assertIs(to_surface, surface)
if not IS_PYPY:
self.assertIn(sys.getrefcount(to_surface), expected_ref_count)
self.assertEqual(sys.getrefcount(to_surface), expected_ref_count)
self.assertEqual(to_surface.get_size(), size)
assertSurfaceFilled(self, to_surface, expected_color)
def test_to_surface__setsurface_param(self):
"""Ensures to_surface accepts a setsurface arg/kwarg."""
expected_ref_count = (1, 2)
expected_ref_count = 2
expected_flag = SRCALPHA
expected_depth = 32
expected_color = pygame.Color("red")
@@ -2657,7 +2667,7 @@ class MaskTypeTest(unittest.TestCase):
self.assertIsInstance(to_surface, pygame.Surface)
if not IS_PYPY:
self.assertIn(sys.getrefcount(to_surface), expected_ref_count)
self.assertEqual(sys.getrefcount(to_surface), expected_ref_count)
self.assertTrue(to_surface.get_flags() & expected_flag)
self.assertEqual(to_surface.get_bitsize(), expected_depth)
self.assertEqual(to_surface.get_size(), size)
@@ -2665,7 +2675,7 @@ class MaskTypeTest(unittest.TestCase):
def test_to_surface__unsetsurface_param(self):
"""Ensures to_surface accepts a unsetsurface arg/kwarg."""
expected_ref_count = (1, 2)
expected_ref_count = 2
expected_flag = SRCALPHA
expected_depth = 32
expected_color = pygame.Color("red")
@@ -2683,7 +2693,7 @@ class MaskTypeTest(unittest.TestCase):
self.assertIsInstance(to_surface, pygame.Surface)
if not IS_PYPY:
self.assertIn(sys.getrefcount(to_surface), expected_ref_count)
self.assertEqual(sys.getrefcount(to_surface), expected_ref_count)
self.assertTrue(to_surface.get_flags() & expected_flag)
self.assertEqual(to_surface.get_bitsize(), expected_depth)
self.assertEqual(to_surface.get_size(), size)
@@ -2691,7 +2701,7 @@ class MaskTypeTest(unittest.TestCase):
def test_to_surface__setcolor_param(self):
"""Ensures to_surface accepts a setcolor arg/kwarg."""
expected_ref_count = (1, 2)
expected_ref_count = 2
expected_flag = SRCALPHA
expected_depth = 32
expected_color = pygame.Color("red")
@@ -2707,7 +2717,7 @@ class MaskTypeTest(unittest.TestCase):
self.assertIsInstance(to_surface, pygame.Surface)
if not IS_PYPY:
self.assertIn(sys.getrefcount(to_surface), expected_ref_count)
self.assertEqual(sys.getrefcount(to_surface), expected_ref_count)
self.assertTrue(to_surface.get_flags() & expected_flag)
self.assertEqual(to_surface.get_bitsize(), expected_depth)
self.assertEqual(to_surface.get_size(), size)
@@ -2727,8 +2737,8 @@ class MaskTypeTest(unittest.TestCase):
assertSurfaceFilled(self, to_surface, expected_color)
def test_to_surface__unsetcolor_param(self):
"""Ensures to_surface accepts an unsetcolor arg/kwarg."""
expected_ref_count = (1, 2)
"""Ensures to_surface accepts a unsetcolor arg/kwarg."""
expected_ref_count = 2
expected_flag = SRCALPHA
expected_depth = 32
expected_color = pygame.Color("red")
@@ -2746,7 +2756,7 @@ class MaskTypeTest(unittest.TestCase):
self.assertIsInstance(to_surface, pygame.Surface)
if not IS_PYPY:
self.assertIn(sys.getrefcount(to_surface), expected_ref_count)
self.assertEqual(sys.getrefcount(to_surface), expected_ref_count)
self.assertTrue(to_surface.get_flags() & expected_flag)
self.assertEqual(to_surface.get_bitsize(), expected_depth)
self.assertEqual(to_surface.get_size(), size)
@@ -2767,7 +2777,7 @@ class MaskTypeTest(unittest.TestCase):
def test_to_surface__dest_param(self):
"""Ensures to_surface accepts a dest arg/kwarg."""
expected_ref_count = (1, 2)
expected_ref_count = 2
expected_flag = SRCALPHA
expected_depth = 32
default_surface_color = (0, 0, 0, 0)
@@ -2791,7 +2801,7 @@ class MaskTypeTest(unittest.TestCase):
self.assertIsInstance(to_surface, pygame.Surface)
if not IS_PYPY:
self.assertIn(sys.getrefcount(to_surface), expected_ref_count)
self.assertEqual(sys.getrefcount(to_surface), expected_ref_count)
self.assertTrue(to_surface.get_flags() & expected_flag)
self.assertEqual(to_surface.get_bitsize(), expected_depth)
self.assertEqual(to_surface.get_size(), size)
@@ -2820,9 +2830,10 @@ class MaskTypeTest(unittest.TestCase):
assertSurfaceFilled(self, to_surface, expected_color, mask_rect)
assertSurfaceFilledIgnoreArea(self, to_surface, surface_color, mask_rect)
@unittest.expectedFailure
def test_to_surface__area_param(self):
"""Ensures to_surface accepts an area arg/kwarg."""
expected_ref_count = (1, 2)
expected_ref_count = 2
expected_flag = SRCALPHA
expected_depth = 32
default_surface_color = (0, 0, 0, 0)
@@ -2845,294 +2856,12 @@ class MaskTypeTest(unittest.TestCase):
self.assertIsInstance(to_surface, pygame.Surface)
if not IS_PYPY:
self.assertIn(sys.getrefcount(to_surface), expected_ref_count)
self.assertEqual(sys.getrefcount(to_surface), expected_ref_count)
self.assertTrue(to_surface.get_flags() & expected_flag)
self.assertEqual(to_surface.get_bitsize(), expected_depth)
self.assertEqual(to_surface.get_size(), size)
assertSurfaceFilled(self, to_surface, expected_color)
def test_to_surface__area_output(self):
dst = pygame.Surface((2, 2))
mask = pygame.mask.Mask((2, 2), fill=True)
white = (255, 255, 255, 255)
black = (0, 0, 0, 255)
# make sure the surface is black, this is to make sure the test surface and mask are different colors
self.assertEqual(dst.get_at((0, 0)), black)
# make sure the mask is set and the default color after conversion is white
self.assertEqual(mask.to_surface().get_at((0, 0)), white)
test_areas_plus_destinations_and_expected_pattern = [
[{"dest": (0, 0), "area": None}, [[white, white], [white, white]]],
[{"dest": (0, 0), "area": (0, 0, 1, 1)}, [[white, black], [black, black]]],
[{"dest": (0, 0), "area": (0, 0, 2, 2)}, [[white, white], [white, white]]],
[{"dest": (1, 0), "area": (0, 0, 1, 2)}, [[black, white], [black, white]]],
[{"dest": (0, 0), "area": (0, 0, 0, 0)}, [[black, black], [black, black]]],
[{"dest": (1, 0), "area": (-1, 0, 1, 1)}, [[black, black], [black, black]]],
[{"dest": (0, 0), "area": (-1, 0, 2, 1)}, [[white, black], [black, black]]],
[
{"dest": (1, 1), "area": (-2, -2, 1, 1)},
[[black, black], [black, black]],
],
[
{"dest": (0, 1), "area": (0, 0, 50, 50)},
[[black, black], [white, white]],
],
[
{"dest": (-1, 0), "area": (-1, 0, 2, 2)},
[[black, black], [black, black]],
],
[
{"dest": (0, -1), "area": (-1, 0, 3, 2)},
[[white, white], [black, black]],
],
[{"dest": (0, 0), "area": (2, 2, 2, 2)}, [[black, black], [black, black]]],
[
{"dest": (-5, -5), "area": (-5, -5, 6, 6)},
[[black, black], [black, black]],
],
[
{"dest": (-5, -5), "area": (-5, -5, 1, 1)},
[[black, black], [black, black]],
],
]
for kwargs, pattern in test_areas_plus_destinations_and_expected_pattern:
surface = dst.copy()
mask.to_surface(surface=surface, **kwargs)
for y, row in enumerate(pattern):
for x, value in enumerate(row):
self.assertEqual(surface.get_at((x, y)), value)
def create_surface_from_array(
self, size: tuple[int, int], array: list[list[pygame.Color]], *args, **kwargs
) -> pygame.Surface:
assert (len(array), len(array[0])) == size
surface = pygame.Surface(size, *args, **kwargs)
for y, row in enumerate(array):
for x, color in enumerate(row):
surface.set_at((x, y), color)
return surface
def assert_surface_matches_array(
self, surface: pygame.Surface, array: list[list[pygame.Color]]
) -> None:
assert (len(array), len(array[0])) == surface.get_size()
for y, row in enumerate(array):
for x, color in enumerate(row):
with self.subTest(x=x, y=y, color=color):
self.assertEqual(color, surface.get_at((x, y)))
def test_to_surface__area_with_setsurface_create_new(self):
c_1 = pygame.Color("red")
c_2 = pygame.Color("green")
size = (4, 4)
mask = pygame.Mask(size, fill=True)
set_surface = self.create_surface_from_array(
size=size,
array=[
[c_1, c_1, c_2, c_2],
[c_1, c_1, c_2, c_2],
[c_1, c_1, c_1, c_1],
[c_1, c_1, c_1, c_1],
],
flags=SRCALPHA,
)
area = pygame.Rect(0, 0, 2, 2)
expected_pixels = [
[c_1, c_1],
[c_1, c_1],
]
surface = mask.to_surface(area=area, setsurface=set_surface)
self.assert_surface_matches_array(surface, expected_pixels)
area = pygame.Rect(1, 1, 2, 2)
expected_pixels = [
[c_1, c_2],
[c_1, c_1],
]
surface = mask.to_surface(area=area, setsurface=set_surface)
self.assert_surface_matches_array(surface, expected_pixels)
area = pygame.Rect(2, 1, 2, 2)
expected_pixels = [
[c_2, c_2],
[c_1, c_1],
]
surface = mask.to_surface(area=area, setsurface=set_surface)
self.assert_surface_matches_array(surface, expected_pixels)
def test_to_surface__area_with_unsetsurface_create_new(self):
c_1 = pygame.Color("red")
c_2 = pygame.Color("green")
size = (4, 4)
mask = pygame.Mask(size, fill=False)
unset_surface = self.create_surface_from_array(
size=size,
array=[
[c_1, c_1, c_2, c_2],
[c_1, c_1, c_2, c_2],
[c_1, c_1, c_1, c_1],
[c_1, c_1, c_1, c_1],
],
flags=SRCALPHA,
)
area = pygame.Rect(0, 0, 2, 2)
expected_pixels = [
[c_1, c_1],
[c_1, c_1],
]
surface = mask.to_surface(area=area, unsetsurface=unset_surface)
self.assert_surface_matches_array(surface, expected_pixels)
area = pygame.Rect(1, 1, 2, 2)
expected_pixels = [
[c_1, c_2],
[c_1, c_1],
]
surface = mask.to_surface(area=area, unsetsurface=unset_surface)
self.assert_surface_matches_array(surface, expected_pixels)
area = pygame.Rect(2, 1, 2, 2)
expected_pixels = [
[c_2, c_2],
[c_1, c_1],
]
surface = mask.to_surface(area=area, unsetsurface=unset_surface)
self.assert_surface_matches_array(surface, expected_pixels)
def test_to_surface__area_with_setsurface_to_destination(self):
c_1 = pygame.Color("red")
c_2 = pygame.Color("green")
c_3 = pygame.Color("blue")
size = (4, 4)
mask = pygame.Mask(size, fill=True)
set_surface = self.create_surface_from_array(
size=size,
array=[
[c_1, c_1, c_2, c_2],
[c_1, c_1, c_2, c_2],
[c_1, c_1, c_1, c_1],
[c_1, c_1, c_1, c_1],
],
)
area = pygame.Rect(0, 0, 2, 2)
expected_pixels = [
[c_1, c_1, c_3, c_3],
[c_1, c_1, c_3, c_3],
[c_3, c_3, c_3, c_3],
[c_3, c_3, c_3, c_3],
]
surface = pygame.Surface(size)
surface.fill(c_3)
surface = mask.to_surface(surface=surface, area=area, setsurface=set_surface)
self.assert_surface_matches_array(surface, expected_pixels)
area = pygame.Rect(1, 1, 2, 2)
dest = (2, 0)
expected_pixels = [
[c_3, c_3, c_1, c_2],
[c_3, c_3, c_1, c_1],
[c_3, c_3, c_3, c_3],
[c_3, c_3, c_3, c_3],
]
surface = pygame.Surface(size)
surface.fill(c_3)
surface = mask.to_surface(
surface=surface, dest=dest, area=area, setsurface=set_surface
)
self.assert_surface_matches_array(surface, expected_pixels)
area = pygame.Rect(2, 1, 2, 2)
dest = (1, 1)
expected_pixels = [
[c_3, c_3, c_3, c_3],
[c_3, c_2, c_2, c_3],
[c_3, c_1, c_1, c_3],
[c_3, c_3, c_3, c_3],
]
surface = pygame.Surface(size)
surface.fill(c_3)
surface = mask.to_surface(
surface=surface, dest=dest, area=area, setsurface=set_surface
)
self.assert_surface_matches_array(surface, expected_pixels)
def test_to_surface__area_with_unsetsurface_to_destination(self):
c_1 = pygame.Color("red")
c_2 = pygame.Color("green")
c_3 = pygame.Color("blue")
size = (4, 4)
mask = pygame.Mask(size, fill=False)
unset_surface = self.create_surface_from_array(
size=size,
array=[
[c_1, c_1, c_2, c_2],
[c_1, c_1, c_2, c_2],
[c_1, c_1, c_1, c_1],
[c_1, c_1, c_1, c_1],
],
)
area = pygame.Rect(0, 0, 2, 2)
expected_pixels = [
[c_1, c_1, c_3, c_3],
[c_1, c_1, c_3, c_3],
[c_3, c_3, c_3, c_3],
[c_3, c_3, c_3, c_3],
]
surface = pygame.Surface(size)
surface.fill(c_3)
surface = mask.to_surface(
surface=surface, area=area, unsetsurface=unset_surface
)
self.assert_surface_matches_array(surface, expected_pixels)
area = pygame.Rect(1, 1, 2, 2)
dest = (2, 0)
expected_pixels = [
[c_3, c_3, c_1, c_2],
[c_3, c_3, c_1, c_1],
[c_3, c_3, c_3, c_3],
[c_3, c_3, c_3, c_3],
]
surface = pygame.Surface(size)
surface.fill(c_3)
surface = mask.to_surface(
surface=surface, dest=dest, area=area, unsetsurface=unset_surface
)
self.assert_surface_matches_array(surface, expected_pixels)
area = pygame.Rect(2, 1, 2, 2)
dest = (1, 1)
expected_pixels = [
[c_3, c_3, c_3, c_3],
[c_3, c_2, c_2, c_3],
[c_3, c_1, c_1, c_3],
[c_3, c_3, c_3, c_3],
]
surface = pygame.Surface(size)
surface.fill(c_3)
surface = mask.to_surface(
surface=surface, dest=dest, area=area, unsetsurface=unset_surface
)
self.assert_surface_matches_array(surface, expected_pixels)
def test_to_surface__area_default(self):
"""Ensures the default area is correct."""
expected_color = pygame.Color("white")
@@ -3492,6 +3221,7 @@ class MaskTypeTest(unittest.TestCase):
assertSurfaceFilled(self, to_surface, expected_color)
@unittest.expectedFailure
def test_to_surface__valid_area_formats(self):
"""Ensures to_surface handles valid area formats correctly."""
size = (3, 5)
@@ -3524,6 +3254,7 @@ class MaskTypeTest(unittest.TestCase):
assertSurfaceFilled(self, to_surface, expected_color, area_rect)
assertSurfaceFilledIgnoreArea(self, to_surface, surface_color, area_rect)
@unittest.expectedFailure
def test_to_surface__invalid_area_formats(self):
"""Ensures to_surface handles invalid area formats correctly."""
mask = pygame.mask.Mask((3, 5))
@@ -3539,9 +3270,10 @@ class MaskTypeTest(unittest.TestCase):
)
for area in invalid_areas:
with self.assertRaisesRegex(TypeError, "invalid rectstyle argument"):
mask.to_surface(area=area)
with self.assertRaisesRegex(TypeError, "invalid area argument"):
unused_to_surface = mask.to_surface(area=area)
@unittest.expectedFailure
def test_to_surface__negative_sized_area_rect(self):
"""Ensures to_surface correctly handles negative sized area rects."""
size = (3, 5)
@@ -3566,6 +3298,7 @@ class MaskTypeTest(unittest.TestCase):
assertSurfaceFilled(self, to_surface, expected_color, area)
assertSurfaceFilledIgnoreArea(self, to_surface, surface_color, area)
@unittest.expectedFailure
def test_to_surface__zero_sized_area_rect(self):
"""Ensures to_surface correctly handles zero sized area rects."""
size = (3, 5)
@@ -3591,10 +3324,10 @@ class MaskTypeTest(unittest.TestCase):
"""Ensures to_surface works with a default surface value
and combinations of other parameters.
This tests many parameter combinations with full and empty
This tests many different parameter combinations with full and empty
masks.
"""
expected_ref_count = (1, 2)
expected_ref_count = 2
expected_flag = SRCALPHA
expected_depth = 32
size = (5, 3)
@@ -3661,7 +3394,7 @@ class MaskTypeTest(unittest.TestCase):
self.assertIsInstance(to_surface, pygame.Surface)
if not IS_PYPY:
self.assertIn(
self.assertEqual(
sys.getrefcount(to_surface), expected_ref_count
)
self.assertTrue(to_surface.get_flags() & expected_flag)
@@ -3675,10 +3408,10 @@ class MaskTypeTest(unittest.TestCase):
"""Ensures to_surface works with a surface value
and combinations of other parameters.
This tests many parameter combinations with full and empty
This tests many different parameter combinations with full and empty
masks.
"""
expected_ref_count = (3, 4)
expected_ref_count = 4
expected_flag = SRCALPHA
expected_depth = 32
size = (5, 3)
@@ -3748,7 +3481,7 @@ class MaskTypeTest(unittest.TestCase):
self.assertIs(to_surface, surface)
if not IS_PYPY:
self.assertIn(
self.assertEqual(
sys.getrefcount(to_surface), expected_ref_count
)
self.assertTrue(to_surface.get_flags() & expected_flag)
@@ -3759,7 +3492,7 @@ class MaskTypeTest(unittest.TestCase):
assertSurfaceFilled(self, to_surface, expected_color)
def test_to_surface__set_and_unset_bits(self):
"""Ensures that to_surface works correctly with set/unset bits
"""Ensures that to_surface works correctly with with set/unset bits
when using the defaults for setcolor and unsetcolor.
"""
default_setcolor = pygame.Color("white")
@@ -3796,7 +3529,7 @@ class MaskTypeTest(unittest.TestCase):
to_surface.unlock()
def test_to_surface__set_and_unset_bits_with_setsurface_unsetsurface(self):
"""Ensures that to_surface works correctly with set/unset bits
"""Ensures that to_surface works correctly with with set/unset bits
when using setsurface and unsetsurface.
"""
width, height = size = (10, 20)
@@ -4778,12 +4511,12 @@ class MaskTypeTest(unittest.TestCase):
default_setcolor = pygame.Color("white")
default_unsetcolor = pygame.Color("black")
directions = [
[(s, 0) for s in range(-SIDE, SIDE + 1)], # left to right
[(0, s) for s in range(-SIDE, SIDE + 1)], # top to bottom
[(s, s) for s in range(-SIDE, SIDE + 1)], # topleft to bottomright diag
[(-s, s) for s in range(-SIDE, SIDE + 1)], # topright to bottomleft diag
]
directions = (
((s, 0) for s in range(-SIDE, SIDE + 1)), # left to right
((0, s) for s in range(-SIDE, SIDE + 1)), # top to bottom
((s, s) for s in range(-SIDE, SIDE + 1)), # topleft to bottomright diag
((-s, s) for s in range(-SIDE, SIDE + 1)), # topright to bottomleft diag
)
for fill in (True, False):
mask = pygame.mask.Mask((SIDE, SIDE), fill=fill)
@@ -4802,6 +4535,8 @@ class MaskTypeTest(unittest.TestCase):
self, to_surface, surface_color, overlap_rect
)
@unittest.expectedFailure
@unittest.skipIf(IS_PYPY, "Segfaults on pypy")
def test_to_surface__area_locations(self):
"""Ensures area rects can be different locations on/off the mask."""
SIDE = 7
@@ -4811,12 +4546,12 @@ class MaskTypeTest(unittest.TestCase):
default_setcolor = pygame.Color("white")
default_unsetcolor = pygame.Color("black")
directions = [
[(s, 0) for s in range(-SIDE, SIDE + 1)], # left to right
[(0, s) for s in range(-SIDE, SIDE + 1)], # top to bottom
[(s, s) for s in range(-SIDE, SIDE + 1)], # topleft to bottomright diag
[(-s, s) for s in range(-SIDE, SIDE + 1)], # topright to bottomleft diag
]
directions = (
((s, 0) for s in range(-SIDE, SIDE + 1)), # left to right
((0, s) for s in range(-SIDE, SIDE + 1)), # top to bottom
((s, s) for s in range(-SIDE, SIDE + 1)), # topleft to bottomright diag
((-s, s) for s in range(-SIDE, SIDE + 1)), # topright to bottomleft diag
)
for fill in (True, False):
mask = pygame.mask.Mask((SIDE, SIDE), fill=fill)
@@ -4838,6 +4573,7 @@ class MaskTypeTest(unittest.TestCase):
self, to_surface, surface_color, overlap_rect
)
@unittest.expectedFailure
def test_to_surface__dest_and_area_locations(self):
"""Ensures dest/area values can be different locations on/off the
surface/mask.
@@ -4851,16 +4587,16 @@ class MaskTypeTest(unittest.TestCase):
default_setcolor = pygame.Color("white")
default_unsetcolor = pygame.Color("black")
dest_directions = [
[(s, 0) for s in range(-SIDE, SIDE + 1)], # left to right
[(0, s) for s in range(-SIDE, SIDE + 1)], # top to bottom
[(s, s) for s in range(-SIDE, SIDE + 1)], # topleft to bottomright diag
[(-s, s) for s in range(-SIDE, SIDE + 1)], # topright to bottomleft diag
]
dest_directions = (
((s, 0) for s in range(-SIDE, SIDE + 1)), # left to right
((0, s) for s in range(-SIDE, SIDE + 1)), # top to bottom
((s, s) for s in range(-SIDE, SIDE + 1)), # topleft to bottomright diag
((-s, s) for s in range(-SIDE, SIDE + 1)), # topright to bottomleft diag
)
# Using only the topleft to bottomright diagonal to test the area (to
# reduce the number of loop iterations).
area_positions = dest_directions[2]
area_positions = list(dest_directions[2])
for fill in (True, False):
mask = pygame.mask.Mask((SIDE, SIDE), fill=fill)
@@ -4891,6 +4627,7 @@ class MaskTypeTest(unittest.TestCase):
self, to_surface, surface_color, dest_overlap_rect
)
@unittest.expectedFailure
def test_to_surface__area_sizes(self):
"""Ensures area rects can be different sizes."""
SIDE = 7
@@ -5350,6 +5087,8 @@ class MaskTypeTest(unittest.TestCase):
self, to_surface, surface_color, mask_rect
)
@unittest.expectedFailure
@unittest.skipIf(IS_PYPY, "Segfaults on pypy")
def test_to_surface__area_on_mask(self):
"""Ensures area values on the mask work correctly
when using the defaults for setcolor and unsetcolor.
@@ -5382,6 +5121,7 @@ class MaskTypeTest(unittest.TestCase):
self, to_surface, surface_color, overlap_rect
)
@unittest.expectedFailure
def test_to_surface__area_on_mask_with_setsurface_unsetsurface(self):
"""Ensures area values on the mask work correctly
when using setsurface and unsetsurface.
@@ -5438,6 +5178,8 @@ class MaskTypeTest(unittest.TestCase):
self, to_surface, surface_color, overlap_rect
)
@unittest.expectedFailure
@unittest.skipIf(IS_PYPY, "Segfaults on pypy")
def test_to_surface__area_off_mask(self):
"""Ensures area values off the mask work correctly
when using the defaults for setcolor and unsetcolor.
@@ -5473,6 +5215,8 @@ class MaskTypeTest(unittest.TestCase):
self, to_surface, surface_color, overlap_rect
)
@unittest.expectedFailure
@unittest.skipIf(IS_PYPY, "Segfaults on pypy")
def test_to_surface__area_off_mask_with_setsurface_unsetsurface(self):
"""Ensures area values off the mask work correctly
when using setsurface and unsetsurface.
@@ -5529,7 +5273,7 @@ class MaskTypeTest(unittest.TestCase):
def test_to_surface__surface_with_zero_size(self):
"""Ensures zero sized surfaces are handled correctly."""
expected_ref_count = (2, 3)
expected_ref_count = 3
size = (0, 0)
surface = pygame.Surface(size)
mask = pygame.mask.Mask((3, 4), fill=True)
@@ -5538,12 +5282,12 @@ class MaskTypeTest(unittest.TestCase):
self.assertIs(to_surface, surface)
if not IS_PYPY:
self.assertIn(sys.getrefcount(to_surface), expected_ref_count)
self.assertEqual(sys.getrefcount(to_surface), expected_ref_count)
self.assertEqual(to_surface.get_size(), size)
def test_to_surface__setsurface_with_zero_size(self):
"""Ensures zero sized setsurfaces are handled correctly."""
expected_ref_count = (1, 2)
expected_ref_count = 2
expected_flag = SRCALPHA
expected_depth = 32
expected_color = pygame.Color("white") # Default setcolor.
@@ -5555,7 +5299,7 @@ class MaskTypeTest(unittest.TestCase):
self.assertIsInstance(to_surface, pygame.Surface)
if not IS_PYPY:
self.assertIn(sys.getrefcount(to_surface), expected_ref_count)
self.assertEqual(sys.getrefcount(to_surface), expected_ref_count)
self.assertTrue(to_surface.get_flags() & expected_flag)
self.assertEqual(to_surface.get_bitsize(), expected_depth)
self.assertEqual(to_surface.get_size(), mask_size)
@@ -5563,7 +5307,7 @@ class MaskTypeTest(unittest.TestCase):
def test_to_surface__unsetsurface_with_zero_size(self):
"""Ensures zero sized unsetsurfaces are handled correctly."""
expected_ref_count = (1, 2)
expected_ref_count = 2
expected_flag = SRCALPHA
expected_depth = 32
expected_color = pygame.Color("black") # Default unsetcolor.
@@ -5575,7 +5319,7 @@ class MaskTypeTest(unittest.TestCase):
self.assertIsInstance(to_surface, pygame.Surface)
if not IS_PYPY:
self.assertIn(sys.getrefcount(to_surface), expected_ref_count)
self.assertEqual(sys.getrefcount(to_surface), expected_ref_count)
self.assertTrue(to_surface.get_flags() & expected_flag)
self.assertEqual(to_surface.get_bitsize(), expected_depth)
self.assertEqual(to_surface.get_size(), mask_size)
@@ -6329,7 +6073,7 @@ class MaskModuleTest(unittest.TestCase):
This test checks the masks created by the from_surface function using
16 and 32 bit surfaces. Each alpha value (0-255) is tested against
several threshold values.
several different threshold values.
Note: On 16 bit surface the requested alpha value can differ from what
is actually set. This test uses the value read from the surface.
"""
@@ -6348,7 +6092,7 @@ class MaskModuleTest(unittest.TestCase):
if depth < 32:
# On surfaces with depths < 32 the requested alpha can be
# different from what gets set. Use the value read from the
# different than what gets set. Use the value read from the
# surface.
alpha = surface.get_at((0, 0))[3]
@@ -6443,7 +6187,7 @@ class MaskModuleTest(unittest.TestCase):
# special handling.
for threshold in range(threshold_count):
# On surfaces with depths < 32 the requested alpha can be different
# from what gets set. Use the value read from the surface.
# than what gets set. Use the value read from the surface.
alpha = surface.get_at((threshold, 0))[3]
if alpha not in alpha_thresholds:
@@ -6512,7 +6256,7 @@ class MaskModuleTest(unittest.TestCase):
for colorkey in colorkeys:
surface.set_colorkey(colorkey)
# With some depths (i.e. 8 and 16) the actual colorkey can be
# different from what was requested via the set.
# different than what was requested via the set.
surface.fill(surface.get_colorkey())
mask = pygame.mask.from_surface(surface)
@@ -6590,19 +6334,21 @@ class MaskModuleTest(unittest.TestCase):
def test_from_threshold(self):
"""Does mask.from_threshold() work correctly?"""
bpp = [16, 24, 32]
a = [16, 24, 32]
for i in bpp:
for i in a:
surf = pygame.surface.Surface((70, 70), 0, i)
surf.fill((100, 50, 200), (20, 20, 20, 20))
mask = pygame.mask.from_threshold(
surf, (100, 50, 200, 255), (10, 10, 10, 255)
)
rects = mask.get_bounding_rects()
self.assertEqual(mask.count(), 400)
self.assertEqual(mask.get_bounding_rects(), [pygame.Rect((20, 20, 20, 20))])
for i in bpp:
for i in a:
surf = pygame.surface.Surface((70, 70), 0, i)
surf2 = pygame.surface.Surface((70, 70), 0, i)
surf.fill((100, 100, 100))
@@ -6619,10 +6365,6 @@ class MaskModuleTest(unittest.TestCase):
self.assertEqual(mask.count(), 100)
self.assertEqual(mask.get_bounding_rects(), [pygame.Rect((40, 40, 10, 10))])
for color in [(20, 20, 20), 10, "green", pygame.Color("blue")]:
surf = pygame.surface.Surface((10, 10))
pygame.mask.from_threshold(surf, color, color)
def test_zero_size_from_surface(self):
"""Ensures from_surface can create masks from zero sized surfaces."""
for size in ((100, 0), (0, 100), (0, 0)):
@@ -6,17 +6,32 @@ from collections.abc import Collection, Sequence
import pygame.math
from pygame.math import Vector2, Vector3
try:
import numpy
except ModuleNotFoundError:
numpy = None
IS_PYPY = "PyPy" == platform.python_implementation()
class MathModuleTest(unittest.TestCase):
"""Math module tests."""
def test_lerp(self):
result = pygame.math.lerp(10, 100, 0.5) # 55.0
self.assertAlmostEqual(result, 55.0)
result = pygame.math.lerp(10, 100, 0.0) # 10
self.assertAlmostEqual(result, 10.0)
result = pygame.math.lerp(10, 100, 1.0) # 100
self.assertAlmostEqual(result, 100.0)
# Not enough args
self.assertRaises(TypeError, pygame.math.lerp, 1)
# Wrong arg type
self.assertRaises(TypeError, pygame.math.lerp, "str", "str", "str")
# Percent outside range [0, 1]
self.assertRaises(ValueError, pygame.math.lerp, 10, 100, 1.1)
self.assertRaises(ValueError, pygame.math.lerp, 10, 100, -0.5)
def test_clamp(self):
"""Test clamp function."""
@@ -57,154 +72,9 @@ class MathModuleTest(unittest.TestCase):
# Error tests
# Not enough args
self.assertRaises(TypeError, pygame.math.clamp, 10)
# Non-numeric args
# Non numeric args
self.assertRaises(TypeError, pygame.math.clamp, "hello", "py", "thon")
def test_lerp(self):
a = 0.0
b = 10.0
self.assertEqual(pygame.math.lerp(a, b, 0.5), 5.0)
a = 0.0
b = 10.0
self.assertEqual(pygame.math.lerp(a, b, 0.1), 1.0)
a = -10.0
b = 10.0
self.assertEqual(pygame.math.lerp(a, b, 0.5), 0.0)
a = -10.0
b = 10.0
self.assertEqual(pygame.math.lerp(a, b, 1.5), 10.0)
a = -10.0
b = 10.0
self.assertEqual(pygame.math.lerp(a, b, 1.5, False), 20.0)
with self.assertRaises(TypeError):
a = Vector2(0, 0)
b = Vector2(10.0, 10.0)
pygame.math.lerp(a, b, 0.5)
with self.assertRaises(TypeError):
a = 1
b = 2
pygame.math.lerp(a, b, Vector2(0, 0))
def test_invlerp(self):
a = 0.0
b = 10.0
self.assertEqual(pygame.math.invlerp(a, b, 5.0), 0.5)
a = 0.0
b = 10.0
self.assertEqual(pygame.math.invlerp(a, b, 0.1), 0.01)
a = -10.0
b = 10.0
self.assertEqual(pygame.math.invlerp(a, b, 0.5), 0.525)
a = -10.0
b = 10.0
self.assertEqual(pygame.math.invlerp(a, b, 1.5), 0.575)
a = 0.0
b = 100.0
self.assertEqual(pygame.math.invlerp(a, b, 0.25), 0.0025)
with self.assertRaises(TypeError):
a = Vector2(0, 0)
b = Vector2(10.0, 10.0)
pygame.math.invlerp(a, b, 0.5)
with self.assertRaises(TypeError):
a = 1
b = 2
pygame.math.invlerp(a, b, Vector2(0, 0))
with self.assertRaises(ValueError):
a = 5
b = 5
pygame.math.invlerp(a, b, 5)
with self.assertRaises(TypeError):
a = 12**300
b = 11**30
pygame.math.invlerp(a, b, 1)
def test_remap(self):
a = 0.0
b = 10.0
c = 0.0
d = 100.0
self.assertEqual(pygame.math.remap(a, b, c, d, 1.0), 10.0)
a = 0.0
b = 10.0
c = 0.0
d = 100.0
self.assertEqual(pygame.math.remap(a, b, c, d, -1.0), -10.0)
a = -10.0
b = 10.0
c = -20.0
d = 20.0
self.assertEqual(pygame.math.remap(a, b, c, d, 0.0), 0.0)
a = -10.0
b = 10.0
c = 10.0
d = 110.0
self.assertEqual(pygame.math.remap(a, b, c, d, -8.0), 20.0)
with self.assertRaises(TypeError):
a = Vector2(0, 0)
b = "fish"
c = "durk"
d = Vector2(100, 100)
pygame.math.remap(a, b, c, d, 10)
with self.assertRaises(TypeError):
a = 1
b = 2
c = 10
d = 20
pygame.math.remap(a, b, c, d, Vector2(0, 0))
with self.assertRaises(ValueError):
a = 5
b = 5
c = 0
d = 100
pygame.math.remap(a, b, c, d, 10)
with self.assertRaises(TypeError):
a = 12**300
b = 11**30
c = 20
d = 30
pygame.math.remap(a, b, c, d, 100 * 50)
with self.assertRaises(TypeError):
a = 12j
b = 11j
c = 10j
d = 9j
pygame.math.remap(a, b, c, d, 50j)
def test_smoothstep(self):
a = 0.0
b = 10.0
self.assertEqual(pygame.math.smoothstep(a, b, 0.5), 5.0)
a = 0.0
b = 10.0
self.assertEqual(pygame.math.smoothstep(a, b, 0.1), 0.28)
a = -10.0
b = 10.0
self.assertEqual(pygame.math.smoothstep(a, b, 0.5), 0.0)
class Vector2TypeTest(unittest.TestCase):
def setUp(self):
@@ -260,48 +130,6 @@ class Vector2TypeTest(unittest.TestCase):
self.assertEqual(v.x, 1.2)
self.assertEqual(v.y, 3.4)
def testConstructionNumericSequence(self):
class NumericSequence:
# PyFloat_AsDouble will use this to convert to a float
# so this is testing the implementation a bit
def __float__(self):
raise TypeError("Cannot convert to float")
def __getitem__(self, index):
return [1, 0][index]
def __len__(self):
return 2
v = Vector2(NumericSequence())
self.assertEqual(v.x, 1.0)
self.assertEqual(v.y, 0.0)
def testConstructionNumericNonFloat(self):
class NumericNonFloat:
# PyFloat_AsDouble will use this to convert to a float
# so this is testing the implementation a bit
def __float__(self):
raise TypeError("Cannot convert to float")
with self.assertRaises(TypeError):
Vector2(NumericNonFloat())
with self.assertRaises(TypeError):
Vector2(NumericNonFloat(), NumericNonFloat())
with self.assertRaises(TypeError):
Vector2(1.0, NumericNonFloat())
@unittest.skipIf(numpy is None, "numpy not available")
def testConstructionNumpyArray(self):
assert numpy is not None
arr = numpy.array([1.2, 3.4])
v = Vector2(arr)
self.assertEqual(v.x, 1.2)
self.assertEqual(v.y, 3.4)
def testAttributeAccess(self):
tmp = self.v1.x
self.assertEqual(tmp, self.v1.x)
@@ -702,8 +530,8 @@ class Vector2TypeTest(unittest.TestCase):
def testRepr(self):
v = Vector2(1.2, 3.4)
self.assertEqual(repr(v), "Vector2(1.2, 3.4)")
self.assertEqual(v, Vector2(repr(v)))
self.assertEqual(v.__repr__(), "<Vector2(1.2, 3.4)>")
self.assertEqual(v, Vector2(v.__repr__()))
def testIter(self):
it = self.v1.__iter__()
@@ -742,7 +570,7 @@ class Vector2TypeTest(unittest.TestCase):
v2 = v1.rotate(0)
self.assertEqual(v1.x, v2.x)
self.assertEqual(v1.y, v2.y)
# pygame-ce issue 229
# issue 214
self.assertEqual(Vector2(0, 1).rotate(359.99999999), Vector2(0, 1))
def test_rotate_rad(self):
@@ -1140,31 +968,15 @@ class Vector2TypeTest(unittest.TestCase):
self.assertEqual(v1.lerp(v2, 0.5), (5, 5))
self.assertRaises(ValueError, lambda: v1.lerp(v2, 2.5))
v1 = Vector2(0, 0)
v2 = Vector2(10, 10)
self.assertEqual(v1.lerp(v2, 0.1), (1, 1))
v1 = Vector2(-10, -5)
v2 = Vector2(10, 10)
self.assertEqual(v1.lerp(v2, 0.5), (0, 2.5))
def test_smoothstep(self):
v1 = Vector2(0, 0)
v2 = Vector2(10, 10)
self.assertEqual(v1.smoothstep(v2, 0.5), (5, 5))
v1 = Vector2(0, 0)
v2 = Vector2(10, 10)
self.assertEqual(v1.smoothstep(v2, 0.1), (0.28, 0.28))
v1 = Vector2(-10, -5)
v2 = Vector2(10, 10)
self.assertEqual(v1.smoothstep(v2, 0.5), (0, 2.5))
def test_polar(self):
v = Vector2()
v.from_polar(self.v1.as_polar())
self.assertEqual(self.v1, v)
self.assertEqual(self.v1, Vector2.from_polar(self.v1.as_polar()))
self.assertEqual(self.e1.as_polar(), (1, 0))
self.assertEqual(self.e2.as_polar(), (1, 90))
self.assertEqual((2 * self.e2).as_polar(), (2, 90))
@@ -1174,22 +986,33 @@ class Vector2TypeTest(unittest.TestCase):
self.assertRaises(TypeError, lambda: v.from_polar((1, 2, 3)))
self.assertRaises(TypeError, lambda: v.from_polar((1,)))
self.assertRaises(TypeError, lambda: v.from_polar(1, 2))
self.assertRaises(TypeError, lambda: Vector2.from_polar((None, None)))
self.assertRaises(TypeError, lambda: Vector2.from_polar("ab"))
self.assertRaises(TypeError, lambda: Vector2.from_polar((None, 1)))
self.assertRaises(TypeError, lambda: Vector2.from_polar((1, 2, 3)))
self.assertRaises(TypeError, lambda: Vector2.from_polar((1,)))
self.assertRaises(TypeError, lambda: Vector2.from_polar(1, 2))
v.from_polar((0.5, 90))
self.assertEqual(v, 0.5 * self.e2)
self.assertEqual(Vector2.from_polar((0.5, 90)), 0.5 * self.e2)
self.assertEqual(Vector2.from_polar((0.5, 90)), v)
v.from_polar((1, 0))
self.assertEqual(v, self.e1)
self.assertEqual(Vector2.from_polar((1, 0)), self.e1)
self.assertEqual(Vector2.from_polar((1, 0)), v)
def test_subclass_operation(self):
class Vector(pygame.math.Vector2):
pass
vec = Vector()
vec_a = Vector(2, 0)
vec_b = Vector(0, 1)
vec_a + vec_b
result_add = vec_a + vec_b
self.assertEqual(result_add, Vector(2, 1))
vec_a *= 2
self.assertEqual(vec_a, Vector(4, 0))
def test_project_v2_onto_x_axis(self):
"""Project onto x-axis, e.g. get the component pointing in the x-axis direction."""
@@ -1319,11 +1142,6 @@ class Vector2TypeTest(unittest.TestCase):
self.assertEqual(v1, v2)
self.assertEqual(v1, Vector2(1, 2))
v2 = Vector2()
self.assertEqual(v2.clamp_magnitude(1), Vector2())
v2.clamp_magnitude_ip(2)
self.assertEqual(v2.magnitude(), 0)
def test_clamp_mag_v2_edge_cases(self):
v1 = Vector2(1, 2)
v2 = v1.clamp_magnitude(6, 6)
@@ -1357,10 +1175,10 @@ class Vector2TypeTest(unittest.TestCase):
self.assertRaises(ValueError, v1.clamp_magnitude, *invalid_args)
self.assertRaises(ValueError, v1.clamp_magnitude_ip, *invalid_args)
# 0 vector with a min_length > 0
# 0 vector
v2 = Vector2()
self.assertRaises(ValueError, v2.clamp_magnitude, 1, 2)
self.assertRaises(ValueError, v2.clamp_magnitude_ip, 2, 3)
self.assertRaises(ValueError, v2.clamp_magnitude, 3)
self.assertRaises(ValueError, v2.clamp_magnitude_ip, 4)
def test_subclassing_v2(self):
"""Check if Vector2 is subclassable"""
@@ -1394,120 +1212,6 @@ class Vector2TypeTest(unittest.TestCase):
self.assertEqual(type(other / 3), TestVector)
self.assertEqual(type(other.elementwise() ** 3), TestVector)
def test_del_x(self):
"""Verify that the correct error message gets spit out when trying to delete x"""
with self.assertRaises(TypeError) as ctx:
del Vector2().x
exception = ctx.exception
self.assertEqual(str(exception), "Cannot delete the x attribute")
def test_del_y(self):
"""Verify that the correct error message gets spit out when trying to delete y"""
with self.assertRaises(TypeError) as ctx:
del Vector2().y
exception = ctx.exception
self.assertEqual(str(exception), "Cannot delete the y attribute")
def test_angle_rad_property(self):
v0 = Vector2(1, 0)
self.assertEqual(v0.angle_rad, 0.0)
v1 = Vector2(0, 1)
self.assertEqual(v1.angle_rad, math.pi / 2)
v2 = Vector2(-1, 0)
self.assertEqual(v2.angle_rad, math.pi)
v3 = Vector2(0, -1)
self.assertEqual(v3.angle_rad, -math.pi / 2)
v4 = Vector2(1, 1)
self.assertEqual(v4.angle_rad, math.pi / 4)
v5 = Vector2(-1, 1)
self.assertEqual(v5.angle_rad, 3 * math.pi / 4)
v6 = Vector2(-1, -1)
self.assertEqual(v6.angle_rad, -3 * math.pi / 4)
v7 = Vector2(1, -1)
self.assertEqual(v7.angle_rad, -math.pi / 4)
v8 = Vector2(float('inf'), float('inf'))
self.assertEqual(v8.angle_rad, math.pi / 4)
v9 = Vector2(float('-inf'), float('inf'))
self.assertEqual(v9.angle_rad, 3 * math.pi / 4)
v10 = Vector2(float('-inf'), float('-inf'))
self.assertEqual(v10.angle_rad, -3 * math.pi / 4)
v11 = Vector2(float('inf'), float('-inf'))
self.assertEqual(v11.angle_rad, -math.pi / 4)
v12 = Vector2(0, 0)
self.assertEqual(v12.angle_rad, 0.0)
v13 = Vector2(float('nan'), 1)
self.assertTrue(math.isnan(v13.angle_rad))
v14 = Vector2(1, float('nan'))
self.assertTrue(math.isnan(v14.angle_rad))
v15 = Vector2(float('nan'), float('nan'))
self.assertTrue(math.isnan(v15.angle_rad))
def test_angle_property(self):
v0 = pygame.math.Vector2(1, 0)
self.assertEqual(v0.angle, 0.0)
v1 = pygame.math.Vector2(0, 1)
self.assertEqual(v1.angle, 90.0)
v2 = pygame.math.Vector2(-1, 0)
self.assertEqual(v2.angle, 180.0)
v3 = pygame.math.Vector2(0, -1)
self.assertEqual(v3.angle, -90.0)
v4 = pygame.math.Vector2(1, 1)
self.assertEqual(v4.angle, 45.0)
v5 = pygame.math.Vector2(-1, 1)
self.assertEqual(v5.angle, 135.0)
v6 = pygame.math.Vector2(-1, -1)
self.assertEqual(v6.angle, -135.0)
v7 = pygame.math.Vector2(1, -1)
self.assertEqual(v7.angle, -45.0)
v8 = pygame.math.Vector2(float('inf'), float('inf'))
self.assertEqual(v8.angle, 45.0)
v9 = pygame.math.Vector2(float('-inf'), float('inf'))
self.assertEqual(v9.angle, 135.0)
v10 = pygame.math.Vector2(float('-inf'), float('-inf'))
self.assertEqual(v10.angle, -135.0)
v11 = pygame.math.Vector2(float('inf'), float('-inf'))
self.assertEqual(v11.angle, -45.0)
v12 = pygame.math.Vector2(0, 0)
self.assertEqual(v12.angle, 0.0)
v13 = pygame.math.Vector2(float('nan'), 1)
self.assertTrue(math.isnan(v13.angle))
v14 = pygame.math.Vector2(1, float('nan'))
self.assertTrue(math.isnan(v14.angle))
v15 = pygame.math.Vector2(float('nan'), float('nan'))
self.assertTrue(math.isnan(v15.angle))
class Vector3TypeTest(unittest.TestCase):
def setUp(self):
@@ -1576,53 +1280,6 @@ class Vector3TypeTest(unittest.TestCase):
self.assertRaises(ValueError, Vector3, 1, 2)
self.assertRaises(ValueError, Vector3, x=1, y=2)
def testConstructionNumericSequence(self):
class NumericSequence:
# PyFloat_AsDouble will use this to convert to a float
# so this is testing the implementation a bit
def __float__(self):
raise TypeError("Cannot convert to float")
def __getitem__(self, index):
return [1, 0, 5][index]
def __len__(self):
return 3
v = Vector3(NumericSequence())
self.assertEqual(v.x, 1.0)
self.assertEqual(v.y, 0.0)
self.assertEqual(v.z, 5.0)
def testConstructionNumericNonFloat(self):
class NumericNonFloat:
# PyFloat_AsDouble will use this to convert to a float
# so this is testing the implementation a bit
def __float__(self):
raise TypeError("Cannot convert to float")
with self.assertRaises(TypeError):
Vector3(NumericNonFloat())
with self.assertRaises(TypeError):
Vector3(NumericNonFloat(), NumericNonFloat(), NumericNonFloat())
with self.assertRaises(TypeError):
Vector3(1.0, NumericNonFloat(), 5.0)
with self.assertRaises(TypeError):
Vector3(1.0, 0.0, NumericNonFloat())
@unittest.skipIf(numpy is None, "numpy not available")
def testConstructionNumpyArray(self):
assert numpy is not None
arr = numpy.array([1.2, 3.4, 5.6], dtype=float)
v = Vector3(arr)
self.assertEqual(v.x, 1.2)
self.assertEqual(v.y, 3.4)
self.assertEqual(v.z, 5.6)
def testAttributeAccess(self):
tmp = self.v1.x
self.assertEqual(tmp, self.v1.x)
@@ -1871,8 +1528,8 @@ class Vector3TypeTest(unittest.TestCase):
def testRepr(self):
v = Vector3(1.2, 3.4, -9.6)
self.assertEqual(repr(v), "Vector3(1.2, 3.4, -9.6)")
self.assertEqual(v, Vector3(repr(v)))
self.assertEqual(v.__repr__(), "<Vector3(1.2, 3.4, -9.6)>")
self.assertEqual(v, Vector3(v.__repr__()))
def testIter(self):
it = self.v1.__iter__()
@@ -2039,7 +1696,7 @@ class Vector3TypeTest(unittest.TestCase):
self.assertEqual(v1.x, v2.x)
self.assertEqual(v1.y, v2.y)
self.assertEqual(v1.z, v2.z)
# pygame-ce issue 229
# issue 214
self.assertEqual(
Vector3(0, 1, 0).rotate(359.9999999, Vector3(0, 0, 1)), Vector3(0, 1, 0)
)
@@ -2180,23 +1837,6 @@ class Vector3TypeTest(unittest.TestCase):
vec.rotate_y_rad_ip(math.pi / 2)
self.assertEqual(vec, (0, 0, -1))
def test_rotate_y_ip_rad(self):
import warnings
vec = Vector3(1, 0, 0)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always", DeprecationWarning)
# This previously (and incorrectly) rotated around the X axis
vec.rotate_y_ip_rad(math.pi / 2)
self.assertEqual(len(w), 1)
self.assertTrue(issubclass(w[-1].category, DeprecationWarning))
self.assertIn("vector3_rotate_y_rad_ip", str(w[-1].message))
# Verify it now correctly rotates around the Y axis
self.assertEqual(vec, (0, 0, -1))
def test_rotate_z(self):
v1 = Vector3(1, 0, 0)
v2 = v1.rotate_z(90)
@@ -2246,23 +1886,6 @@ class Vector3TypeTest(unittest.TestCase):
vec.rotate_z_rad_ip(math.pi / 2)
self.assertEqual(vec, (0, 1, 0))
def test_rotate_z_ip_rad(self):
import warnings
vec = Vector3(1, 0, 0)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always", DeprecationWarning)
# This previously (and incorrectly) rotated around the X axis
vec.rotate_z_ip_rad(math.pi / 2)
self.assertEqual(len(w), 1)
self.assertTrue(issubclass(w[-1].category, DeprecationWarning))
self.assertIn("vector3_rotate_z_rad_ip", str(w[-1].message))
# Verify it now correctly rotates around the Z axis
self.assertEqual(vec, (0, 1, 0))
def test_normalize(self):
v = self.v1.normalize()
# length is 1
@@ -2927,31 +2550,15 @@ class Vector3TypeTest(unittest.TestCase):
self.assertEqual(v1.lerp(v2, 0.5), (5, 5, 5))
self.assertRaises(ValueError, lambda: v1.lerp(v2, 2.5))
v1 = Vector3(0, 0, 0)
v2 = Vector3(10, 10, 10)
self.assertEqual(v1.lerp(v2, 0.1), (1, 1, 1))
v1 = Vector3(-10, -5, -20)
v2 = Vector3(10, 10, -20)
self.assertEqual(v1.lerp(v2, 0.5), (0, 2.5, -20))
def test_smoothstep(self):
v1 = Vector3(0, 0, 0)
v2 = Vector3(10, 10, 10)
self.assertEqual(v1.smoothstep(v2, 0.5), (5, 5, 5))
v1 = Vector3(0, 0, 0)
v2 = Vector3(10, 10, 10)
self.assertEqual(v1.smoothstep(v2, 0.1), (0.28, 0.28, 0.28))
v1 = Vector3(-10, -5, -20)
v2 = Vector3(10, 10, -20)
self.assertEqual(v1.smoothstep(v2, 0.5), (0, 2.5, -20))
def test_spherical(self):
v = Vector3()
v.from_spherical(self.v1.as_spherical())
self.assertEqual(self.v1, v)
self.assertEqual(self.v1, Vector3.from_spherical(self.v1.as_spherical()))
self.assertEqual(self.e1.as_spherical(), (1, 90, 0))
self.assertEqual(self.e2.as_spherical(), (1, 90, 90))
self.assertEqual(self.e3.as_spherical(), (1, 0, 0))
@@ -2962,8 +2569,16 @@ class Vector3TypeTest(unittest.TestCase):
self.assertRaises(TypeError, lambda: v.from_spherical((1, 2, 3, 4)))
self.assertRaises(TypeError, lambda: v.from_spherical((1, 2)))
self.assertRaises(TypeError, lambda: v.from_spherical(1, 2, 3))
self.assertRaises(TypeError, lambda: Vector3.from_spherical((None, None, None)))
self.assertRaises(TypeError, lambda: Vector3.from_spherical("abc"))
self.assertRaises(TypeError, lambda: Vector3.from_spherical((None, 1, 2)))
self.assertRaises(TypeError, lambda: Vector3.from_spherical((1, 2, 3, 4)))
self.assertRaises(TypeError, lambda: Vector3.from_spherical((1, 2)))
self.assertRaises(TypeError, lambda: Vector3.from_spherical(1, 2, 3))
v.from_spherical((0.5, 90, 90))
self.assertEqual(v, 0.5 * self.e2)
self.assertEqual(Vector3.from_spherical((0.5, 90, 90)), 0.5 * self.e2)
self.assertEqual(Vector3.from_spherical((0.5, 90, 90)), v)
def test_inplace_operators(self):
v = Vector3(1, 1, 1)
@@ -3174,11 +2789,6 @@ class Vector3TypeTest(unittest.TestCase):
self.assertEqual(v1, v2)
self.assertEqual(v1, Vector3(1, 2, 3))
v2 = Vector3()
self.assertEqual(v2.clamp_magnitude(1), Vector3())
v2.clamp_magnitude_ip(2)
self.assertEqual(v2.magnitude(), 0)
def test_clamp_mag_v3_edge_cases(self):
v1 = Vector3(1, 2, 1)
v2 = v1.clamp_magnitude(6, 6)
@@ -3214,8 +2824,8 @@ class Vector3TypeTest(unittest.TestCase):
# 0 vector
v2 = Vector3()
self.assertRaises(ValueError, v2.clamp_magnitude, 1, 2)
self.assertRaises(ValueError, v2.clamp_magnitude_ip, 2, 3)
self.assertRaises(ValueError, v2.clamp_magnitude, 3)
self.assertRaises(ValueError, v2.clamp_magnitude_ip, 4)
def test_subclassing_v3(self):
"""Check if Vector3 is subclassable"""
@@ -3314,30 +2924,6 @@ class Vector3TypeTest(unittest.TestCase):
self.assertRaises(TypeError, origin.move_towards, "c", 3)
self.assertRaises(TypeError, origin.move_towards_ip, "d", 3)
def test_del_x(self):
"""Verify that the correct error message gets spit out when trying to delete x"""
with self.assertRaises(TypeError) as ctx:
del Vector3().x
exception = ctx.exception
self.assertEqual(str(exception), "Cannot delete the x attribute")
def test_del_y(self):
"""Verify that the correct error message gets spit out when trying to delete y"""
with self.assertRaises(TypeError) as ctx:
del Vector3().y
exception = ctx.exception
self.assertEqual(str(exception), "Cannot delete the y attribute")
def test_del_z(self):
"""Verify that the correct error message gets spit out when trying to delete z"""
with self.assertRaises(TypeError) as ctx:
del Vector3().z
exception = ctx.exception
self.assertEqual(str(exception), "Cannot delete the z attribute")
if __name__ == "__main__":
unittest.main()
@@ -1,5 +1,6 @@
import unittest
import pygame
@@ -209,7 +210,7 @@ class MidiOutputTest(unittest.TestCase):
out.pitch_bend(-10001, 1)
self.assertEqual(
str(cm.exception),
"Pitch bend value must be between -8192 and +8191, not -10001.",
"Pitch bend value must be between " "-8192 and +8191, not -10001.",
)
with self.assertRaises(ValueError) as cm:
out.pitch_bend(10665, 2)
@@ -438,7 +439,7 @@ class MidiModuleNonInteractiveTest(unittest.TestCase):
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
from pygame.midi import frequency_to_midi, midi_to_frequency, midi_to_ansi_note
self.assertEqual(frequency_to_midi(27.5), 21)
self.assertEqual(frequency_to_midi(36.7), 26)
@@ -1,12 +1,11 @@
import os
import platform
import sys
import time
import platform
import unittest
from tempfile import TemporaryDirectory
import time
import pygame
from pygame.tests.test_utils import example_path
import pygame
class MixerMusicModuleTest(unittest.TestCase):
@@ -27,47 +26,20 @@ class MixerMusicModuleTest(unittest.TestCase):
def test_load_mp3(self):
"|tags:music|"
self.music_load("house_lo.mp3")
self.music_load("mp3")
def test_load_ogg(self):
"|tags:music|"
self.music_load("house_lo.ogg")
self.music_load("ogg")
def test_load_wav(self):
"|tags:music|"
self.music_load("house_lo.wav")
self.music_load("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):
def music_load(self, format):
data_fname = example_path("data")
path = os.path.join(data_fname, filename)
path = os.path.join(data_fname, f"house_lo.{format}")
if os.sep == "\\":
path = path.replace("\\", "\\\\")
umusfn = str(path)
@@ -78,28 +50,10 @@ class MixerMusicModuleTest(unittest.TestCase):
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")
formats = ["ogg", "wav"]
data_fname = example_path("data")
for file in filenames:
path = os.path.join(data_fname, file)
for f in formats:
path = os.path.join(data_fname, f"house_lo.{f}")
if os.sep == "\\":
path = path.replace("\\", "\\\\")
bmusfn = path.encode()
@@ -109,59 +63,46 @@ class MixerMusicModuleTest(unittest.TestCase):
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")
formats = ["wav", "ogg"]
data_fname = example_path("data")
for file in filenames:
path = os.path.join(data_fname, file)
for f in formats:
path = os.path.join(data_fname, f"house_lo.{f}")
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)
pygame.mixer.music.load(musf, f)
with open(bmusfn, "rb") as musf:
pygame.mixer.music.queue(musf, format)
pygame.mixer.music.queue(musf, f)
with open(bmusfn, "rb") as musf:
pygame.mixer.music.load(musf, namehint=format)
pygame.mixer.music.load(musf, namehint=f)
with open(bmusfn, "rb") as musf:
pygame.mixer.music.queue(musf, namehint=format)
pygame.mixer.music.queue(musf, namehint=f)
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)
temp_file = os.path.join(ep, "你好.wav")
org_file = os.path.join(ep, "house_lo.wav")
try:
with open(temp_file, "w") as f:
pass
os.remove(temp_file)
except OSError:
raise unittest.SkipTest("the path cannot be opened")
shutil.copy(org_file, temp_file)
try:
pygame.mixer.music.load(temp_file)
pygame.mixer.music.load(org_file) # unload
finally:
os.remove(temp_file)
def test_unload(self):
import shutil
@@ -202,53 +143,6 @@ class MixerMusicModuleTest(unittest.TestCase):
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"))
@@ -280,7 +174,7 @@ class MixerMusicModuleTest(unittest.TestCase):
def test_queue__invalid_filename(self):
"""Ensures queue() correctly handles invalid filenames."""
with self.assertRaises(FileNotFoundError):
with self.assertRaises(pygame.error):
pygame.mixer.music.queue("")
def test_music_pause__unpause(self):
@@ -301,48 +195,46 @@ class MixerMusicModuleTest(unittest.TestCase):
pygame.mixer.music.unpause()
after_unpause = pygame.mixer.music.get_pos()
self.assertAlmostEqual(before_unpause, after_unpause, delta=2)
self.assertEqual(before_unpause, after_unpause)
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):
def test_stop(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.stop:
# Stops the music playback if it is currently playing.
filename = example_path(os.path.join("data", "house_lo.mp3"))
pygame.mixer.music.load(filename)
pygame.mixer.music.play()
self.fail()
pygame.mixer.music.stop()
self.assertEqual(pygame.mixer.music.get_busy(), False)
def todo_test_rewind(self):
def test_rewind(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.rewind:
# Resets playback of the current music to the beginning.
filename = example_path(os.path.join("data", "house_lo.mp3"))
pygame.mixer.music.load(filename)
pygame.mixer.music.play()
self.fail()
# The music be played for some time
time.sleep(3)
# Then it is rewinded
pygame.mixer.music.rewind()
# Since the sound is 7s long, if it is busy after 6s it means it has been restarted
time.sleep(6.9)
self.assertTrue(pygame.mixer.music.get_busy())
pygame.mixer.music.stop()
# Testing that if the music is paused, rewind works but keep the music paused
pygame.mixer.music.play()
time.sleep(2)
pygame.mixer.music.pause()
pygame.mixer.music.rewind()
self.assertFalse(pygame.mixer.music.get_busy())
time.sleep(1)
pygame.mixer.music.unpause()
time.sleep(6.9)
self.assertTrue(pygame.mixer.music.get_busy())
def todo_test_get_pos(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.get_pos:
@@ -355,15 +247,14 @@ class MixerMusicModuleTest(unittest.TestCase):
self.fail()
def todo_test_fadeout(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.fadeout:
# def test_fadeout(self):
# filename = example_path(os.path.join("data", "house_lo.mp3"))
# pygame.mixer.music.load(filename)
# pygame.mixer.music.play()
# 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()
# pygame.mixer.music.fadeout(50)
# time.sleep(0.3)
# self.assertEqual(pygame.mixer.music.get_busy(), False)
@unittest.skipIf(
os.environ.get("SDL_AUDIODRIVER") == "disk",
@@ -392,7 +283,7 @@ class MixerMusicModuleTest(unittest.TestCase):
self.assertEqual(time_to_finish, 1)
running = False
def todo_test_play(self):
def 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
@@ -409,10 +300,15 @@ class MixerMusicModuleTest(unittest.TestCase):
# MOD music it is the pattern order number. Passing a startpos will
# raise a NotImplementedError if it cannot set the start position
#
filename = example_path(os.path.join("data", "house_lo.mp3"))
pygame.mixer.music.load(filename)
pygame.mixer.music.play()
self.fail()
self.assertTrue(pygame.mixer.music.get_busy())
def todo_test_load(self):
pygame.mixer.music.stop()
def 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
@@ -423,39 +319,44 @@ class MixerMusicModuleTest(unittest.TestCase):
# like the other pygame loading functions.
#
self.fail()
filename = example_path(os.path.join("data", "house_lo.mp3"))
pygame.mixer.music.load(filename)
self.assertFalse(pygame.mixer.music.get_busy())
pygame.mixer.music.play()
self.assertTrue(pygame.mixer.music.get_busy())
def todo_test_get_volume(self):
filename = example_path(os.path.join("data", "house_lo.wav"))
pygame.mixer.music.load(filename)
self.assertFalse(pygame.mixer.music.get_busy())
def 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.
#
filename = example_path(os.path.join("data", "house_lo.mp3"))
pygame.mixer.music.load(filename)
pygame.mixer.music.play()
self.fail()
vol = pygame.mixer.music.get_volume()
self.assertGreaterEqual(vol, 0)
self.assertLessEqual(vol, 1)
def todo_test_set_endevent(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.set_endevent:
pygame.mixer.music.stop()
# 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):
def 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()
self.music_load("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 test_get_busy(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.get_busy:
@@ -464,38 +365,50 @@ class MixerMusicModuleTest(unittest.TestCase):
# music is idle this returns False.
#
self.music_load("house_lo.ogg")
self.music_load("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):
def 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()
filename = example_path(os.path.join("data", "house_lo.mp3"))
pygame.mixer.music.load(filename)
pygame.mixer.music.play()
self.assertTrue(pygame.mixer.music.get_busy())
time.sleep(0.1)
pygame.mixer.music.pause()
self.assertFalse(pygame.mixer.music.get_busy())
before = pygame.mixer.music.get_pos()
pygame.mixer.music.unpause()
after = pygame.mixer.music.get_pos()
self.assertTrue(pygame.mixer.music.get_busy())
# It could rarely be that it is +/- 1 different
# But mostly, after should equal before.
self.assertTrue(before - 1 <= after <= before + 1)
def todo_test_set_volume(self):
pygame.mixer.music.stop()
def 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.
#
filename = example_path(os.path.join("data", "house_lo.mp3"))
pygame.mixer.music.load(filename)
pygame.mixer.music.play()
self.fail()
pygame.mixer.music.set_volume(0.5)
vol = pygame.mixer.music.get_volume()
self.assertEqual(vol, 0.5)
pygame.mixer.music.stop()
def todo_test_set_pos(self):
# __doc__ (as of 2010-24-05) for pygame.mixer_music.set_pos:
@@ -510,9 +423,9 @@ class MixerMusicModuleTest(unittest.TestCase):
self.fail()
def test_init(self):
"""pygame-ce issue #622. unload music whenever mixer.quit() is called"""
import shutil
"""issue #955. unload music whenever mixer.quit() is called"""
import tempfile
import shutil
testfile = example_path(os.path.join("data", "house_lo.wav"))
tempcopy = os.path.join(tempfile.gettempdir(), "tempfile.wav")
@@ -527,5 +440,54 @@ class MixerMusicModuleTest(unittest.TestCase):
os.remove(tempcopy)
# class MixerMusicEndEventTest(unittest.TestCase):
# def setUp(self):
# pygame.display.init()
# pygame.display.set_mode((40, 40))
# if pygame.mixer.get_init() is None:
# pygame.mixer.init()
# def tearDown(self):
# pygame.display.quit()
# pygame.mixer.quit()
# def 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.
# #
# filename = example_path(os.path.join("data", "car_door.wav"))
# pygame.mixer.music.load(filename)
# pygame.mixer.music.play()
# no_event = pygame.mixer_music.get_endevent()
# self.assertEqual(pygame.NOEVENT, no_event)
# event_type = pygame.USEREVENT
# pygame.mixer_music.set_endevent(event_type)
# end_event = pygame.mixer_music.get_endevent()
# self.assertEqual(event_type, end_event)
# def 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.
# #
# filename = example_path(os.path.join("data", "house_lo.wav"))
# pygame.mixer.music.load(filename)
# pygame.mixer.music.play()
# event_type = pygame.USEREVENT
# pygame.mixer_music.set_endevent(event_type)
# end_event = pygame.mixer_music.get_endevent()
# self.assertEqual(event_type, end_event)
if __name__ == "__main__":
unittest.main()
File diff suppressed because it is too large. Load diff
@@ -1,10 +1,10 @@
import unittest
import os
import platform
import unittest
import warnings
import pygame
DARWIN = "Darwin" in platform.platform()
@@ -27,10 +27,10 @@ class MouseModuleInteractiveTest(MouseTests):
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.
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.
# The window needs to be focused for the mouse.set_pos to work on macos.
return
clock = pygame.time.Clock()
@@ -56,7 +56,7 @@ class MouseModuleInteractiveTest(MouseTests):
class MouseModuleTest(MouseTests):
@unittest.skipIf(
os.environ.get("SDL_VIDEODRIVER", "") == pygame.NULL_VIDEODRIVER,
os.environ.get("SDL_VIDEODRIVER", "") == "dummy",
"Cursors not supported on headless test machines",
)
def test_get_cursor(self):
@@ -96,7 +96,7 @@ class MouseModuleTest(MouseTests):
pygame.mouse.get_cursor()
@unittest.skipIf(
os.environ.get("SDL_VIDEODRIVER", "") == pygame.NULL_VIDEODRIVER,
os.environ.get("SDL_VIDEODRIVER", "") == "dummy",
"mouse.set_system_cursor only available in SDL2",
)
def test_set_system_cursor(self):
@@ -138,7 +138,7 @@ class MouseModuleTest(MouseTests):
)
@unittest.skipIf(
os.environ.get("SDL_VIDEODRIVER", "") == pygame.NULL_VIDEODRIVER,
os.environ.get("SDL_VIDEODRIVER", "") == "dummy",
"Cursors not supported on headless test machines",
)
def test_set_cursor(self):
@@ -285,36 +285,9 @@ class MouseModuleTest(MouseTests):
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
@@ -326,16 +299,6 @@ class MouseModuleTest(MouseTests):
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"), []):
@@ -378,41 +341,6 @@ class MouseModuleTest(MouseTests):
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)
################################################################################
@@ -15,6 +15,7 @@ except NameError:
import pygame
IS_PYPY = "PyPy" == platform.python_implementation()
@@ -307,7 +308,7 @@ class PixelArrayTypeTest(unittest.TestCase, TestMixin):
self.assertFalse(sf.get_locked())
def test_as_class(self):
# Check general new-style class features.
# Check general new-style class freatures.
sf = pygame.Surface((2, 3), 0, 32)
ar = pygame.PixelArray(sf)
self.assertRaises(AttributeError, getattr, ar, "nonnative")
@@ -669,7 +670,7 @@ class PixelArrayTypeTest(unittest.TestCase, TestMixin):
self.assertEqual(refcnts_after, refcnts_before)
def test_subscript(self):
# By default, we do not need to work with any special __***__
# By default we do not need to work with any special __***__
# methods as map subscripts are the first looked up by the
# object system.
for bpp in (8, 16, 24, 32):
@@ -1019,6 +1020,7 @@ class PixelArrayTypeTest(unittest.TestCase, TestMixin):
self.assertEqual(iterations, 5)
def test_replace(self):
# print("replace start")
for bpp in (8, 16, 24, 32):
sf = pygame.Surface((10, 10), 0, bpp)
sf.fill((255, 0, 0))
@@ -1039,8 +1041,10 @@ class PixelArrayTypeTest(unittest.TestCase, TestMixin):
self.assertEqual(ar[3][6], oval)
self.assertEqual(ar[8][9], oval)
self.assertEqual(ar[9][9], oval)
# print("replace end")
def test_extract(self):
# print("extract start")
for bpp in (8, 16, 24, 32):
sf = pygame.Surface((10, 10), 0, bpp)
sf.fill((0, 0, 255))
@@ -1066,6 +1070,7 @@ class PixelArrayTypeTest(unittest.TestCase, TestMixin):
self.assertEqual(newar[3][6], white)
self.assertEqual(newar[8][9], black)
self.assertEqual(newar[9][9], black)
# print("extract end")
def test_2dslice_assignment(self):
w = 2 * 5 * 8
@@ -1229,7 +1234,7 @@ class PixelArrayTypeTest(unittest.TestCase, TestMixin):
def test_transpose(self):
# PixelArray.transpose(): swap axis on a 2D array, add a length
# 1 x-axis to a 1D array.
# 1 x axis to a 1D array.
sf = pygame.Surface((3, 7), 0, 32)
ar = pygame.PixelArray(sf)
w, h = ar.shape
@@ -1304,113 +1309,6 @@ class PixelArrayTypeTest(unittest.TestCase, TestMixin):
pixel = sf.get_at_mapped((0, 0))
self.assertEqual(repr(ar), type(ar).__name__ + "([\n [42, 42, 42]]\n)")
def test_zero_size_surface(self):
"""Should not be able to create PixelArray on a surface with a width or height of 0
Regression test for pygame-ce issue 2275 (https://github.com/pygame-community/pygame-ce/issues/2275)
"""
weird_surface = pygame.Surface((5, 0))
self.assertRaises(ValueError, lambda: pygame.PixelArray(weird_surface))
weird_surface = pygame.Surface((0, 5))
self.assertRaises(ValueError, lambda: pygame.PixelArray(weird_surface))
def test_assign_seq_to_single(self):
"""
Regression test for https://github.com/pygame-community/pygame-ce/issues/2740
This usage should ValueError and not segfault (as list is to be interpreted as
pixel sequence, and not color)
"""
test = pygame.PixelArray(pygame.Surface([800, 800]))
with self.assertRaises(ValueError):
test[400][400] = [255, 255, 0]
with self.assertRaises(ValueError):
test[400, 400] = [255, 255, 0]
def test_set_pixel_24bit_formats(self):
"""Pixel assignment must write the correct channels on both RGB24 and BGR24.
On little-endian systems, RGB24 has Rmask=0xFF (R at byte 0) while the
default pygame.Surface(..., 24) produces BGR24 (Rmask=0xFF0000, R at
byte 2). The old _array_assign_index code assumed the mapped color was
always 0x00RRGGBB, which silently worked for BGR24 but swapped R and B
for RGB24.
"""
color = (200, 100, 50)
masks_and_names = [
((0xFF, 0xFF00, 0xFF0000, 0), "RGB24"),
((0xFF0000, 0xFF00, 0xFF, 0), "BGR24"),
]
for masks, name in masks_and_names:
with self.subTest(format=name):
sf = pygame.Surface((4, 4), depth=24, masks=masks)
sf.fill((0, 0, 0))
ar = pygame.PixelArray(sf)
ar[1][2] = color
del ar
self.assertEqual(sf.get_at((1, 2))[:3], color)
def test_set_slice_24bit_formats(self):
"""Slice assignment with a single color must write correctly on RGB24 and BGR24."""
color = (200, 100, 50)
masks_and_names = [
((0xFF, 0xFF00, 0xFF0000, 0), "RGB24"),
((0xFF0000, 0xFF00, 0xFF, 0), "BGR24"),
]
for masks, name in masks_and_names:
with self.subTest(format=name):
sf = pygame.Surface((4, 4), depth=24, masks=masks)
sf.fill((0, 0, 0))
ar = pygame.PixelArray(sf)
ar[0:2] = color
del ar
self.assertEqual(sf.get_at((0, 0))[:3], color)
self.assertEqual(sf.get_at((1, 3))[:3], color)
self.assertEqual(sf.get_at((2, 0))[:3], (0, 0, 0))
def test_set_sequence_24bit_formats(self):
"""Slice assignment with a color list must write correctly on RGB24 and BGR24."""
color_a = (200, 100, 50)
color_b = (10, 20, 30)
masks_and_names = [
((0xFF, 0xFF00, 0xFF0000, 0), "RGB24"),
((0xFF0000, 0xFF00, 0xFF, 0), "BGR24"),
]
for masks, name in masks_and_names:
with self.subTest(format=name):
sf = pygame.Surface((4, 4), depth=24, masks=masks)
sf.fill((0, 0, 0))
ar = pygame.PixelArray(sf)
ar[0:2] = [color_a, color_b]
del ar
self.assertEqual(sf.get_at((0, 0))[:3], color_a)
self.assertEqual(sf.get_at((1, 0))[:3], color_b)
def test_replace_24bit_formats(self):
"""PixelArray.replace must match and write the correct channels on RGB24 and BGR24."""
old_color = (200, 100, 50)
new_color = (10, 20, 30)
masks_and_names = [
((0xFF, 0xFF00, 0xFF0000, 0), "RGB24"),
((0xFF0000, 0xFF00, 0xFF, 0), "BGR24"),
]
for masks, name in masks_and_names:
with self.subTest(format=name):
sf = pygame.Surface((4, 4), depth=24, masks=masks)
sf.fill(old_color)
ar = pygame.PixelArray(sf)
ar.replace(old_color, new_color)
del ar
self.assertEqual(sf.get_at((0, 0))[:3], new_color)
self.assertEqual(sf.get_at((3, 3))[:3], new_color)
# distance-based variant
sf.fill(old_color)
ar = pygame.PixelArray(sf)
ar.replace(old_color, new_color, distance=0.1)
del ar
self.assertEqual(sf.get_at((0, 0))[:3], new_color)
@unittest.skipIf(IS_PYPY, "pypy having issues")
class PixelArrayArrayInterfaceTest(unittest.TestCase, TestMixin):
@@ -1542,9 +1440,11 @@ class PixelArrayArrayInterfaceTest(unittest.TestCase, TestMixin):
self.assert_surfaces_equal(sf3, sf2)
@unittest.skipIf(not pygame.HAVE_NEWBUF, "newbuf not implemented")
@unittest.skipIf(IS_PYPY, "pypy having issues")
class PixelArrayNewBufferTest(unittest.TestCase, TestMixin):
from pygame.tests.test_utils import buftools
if pygame.HAVE_NEWBUF:
from pygame.tests.test_utils import buftools
bitsize_to_format = {8: "B", 16: "=H", 24: "3x", 32: "=I"}
@@ -7,7 +7,7 @@ except NameError:
pass
import pygame
from pygame.locals import *
from pygame.pixelcopy import array_to_surface, make_surface, map_array, surface_to_array
from pygame.pixelcopy import surface_to_array, map_array, array_to_surface, make_surface
IS_PYPY = "PyPy" == platform.python_implementation()
@@ -377,7 +377,7 @@ class PixelCopyTestWithArrayNumpy(unittest.TestCase):
def test_surface_to_array_2d(self):
try:
from numpy import dtype, empty
from numpy import empty, dtype
except ImportError:
return
@@ -458,7 +458,7 @@ class PixelCopyTestWithArrayNumpy(unittest.TestCase):
def test_surface_to_array_3d(self):
try:
from numpy import dtype, empty
from numpy import empty, dtype
except ImportError:
return
@@ -534,7 +534,7 @@ class PixelCopyTestWithArrayNumpy(unittest.TestCase):
def test_map_array(self):
try:
from numpy import all as np_all, array, int32, uint8, zeros
from numpy import array, zeros, uint8, int32, all as alltrue
except ImportError:
return
@@ -545,7 +545,7 @@ class PixelCopyTestWithArrayNumpy(unittest.TestCase):
target = zeros((5, 7), int32)
map_array(target, color, surf)
self.assertTrue(np_all(target == surf.map_rgb(color)))
self.assertTrue(alltrue(target == surf.map_rgb(color)))
# array column stripes
stripe = array([[2, 5, 7], [11, 19, 23], [37, 53, 101]], uint8)
@@ -553,7 +553,7 @@ class PixelCopyTestWithArrayNumpy(unittest.TestCase):
map_array(target, stripe, surf)
target_stripe = array([surf.map_rgb(c) for c in stripe], int32)
self.assertTrue(np_all(target == target_stripe))
self.assertTrue(alltrue(target == target_stripe))
# array row stripes
stripe = array(
@@ -563,7 +563,7 @@ class PixelCopyTestWithArrayNumpy(unittest.TestCase):
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))
self.assertTrue(alltrue(target == target_stripe))
# mismatched shape
w = 4
@@ -593,41 +593,43 @@ class PixelCopyTestWithArrayNumpy(unittest.TestCase):
del numpy
@unittest.skipIf(not pygame.HAVE_NEWBUF, "newbuf not implemented")
@unittest.skipIf(IS_PYPY, "pypy having illegal instruction on mac")
class PixelCopyTestWithArrayNewBuf(unittest.TestCase):
from pygame.tests.test_utils import buftools
if pygame.HAVE_NEWBUF:
from pygame.tests.test_utils import buftools
class Array2D(buftools.Exporter):
def __init__(self, initializer):
from ctypes import POINTER, c_uint32, cast
class Array2D(buftools.Exporter):
def __init__(self, initializer):
from ctypes import cast, POINTER, c_uint32
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
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]
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
class Array3D(buftools.Exporter):
def __init__(self, initializer):
from ctypes import cast, POINTER, c_uint8
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
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]
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)
File diff suppressed because it is too large. Load diff
@@ -1,490 +0,0 @@
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)))
@@ -1,14 +1,12 @@
import pathlib
import platform
import sys
import unittest
from pygame import encode_file_path, encode_string
IS_PYPY = "PyPy" == platform.python_implementation()
from pygame import encode_string, encode_file_path
class RWopsEncodeStringTest(unittest.TestCase):
global getrefcount
def test_obj_None(self):
encoded_string = encode_string(None)
@@ -21,13 +19,13 @@ class RWopsEncodeStringTest(unittest.TestCase):
self.assertIsInstance(encoded_string, bytes)
def test_obj_bytes(self):
b = b"encyclop\xe6dia"
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"
u = "\u00DEe Olde Komp\u00FCter Shoppe"
b = u.encode("utf-8")
self.assertEqual(encode_string(u, "utf-8"), b)
@@ -35,7 +33,7 @@ class RWopsEncodeStringTest(unittest.TestCase):
self.assertRaises(SyntaxError, encode_string)
def test_errors(self):
u = "abc\u0109defg\u011dh\u0125ij\u0135klmnoprs\u015dtu\u016dvz"
u = "abc\u0109defg\u011Dh\u0125ij\u0135klmnoprs\u015Dtu\u016Dvz"
b = u.encode("ascii", "ignore")
self.assertEqual(encode_string(u, "ascii", "ignore"), b)
@@ -46,7 +44,7 @@ class RWopsEncodeStringTest(unittest.TestCase):
self.assertIsNone(encoded_string)
def test_check_defaults(self):
u = "a\u01f7b"
u = "a\u01F7b"
b = u.encode("unicode_escape", "backslashreplace")
encoded_string = encode_string(u)
@@ -70,19 +68,26 @@ class RWopsEncodeStringTest(unittest.TestCase):
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))
try:
from sys import getrefcount as _g
getrefcount = _g # This nonsense is for Python 3.x
except ImportError:
pass
else:
def test_refcount(self):
bpath = b" This is a string that is not cached."[1:]
upath = bpath.decode("ascii")
before = getrefcount(bpath)
bpath = encode_string(bpath)
self.assertEqual(getrefcount(bpath), before)
bpath = encode_string(upath)
self.assertEqual(getrefcount(bpath), before)
def test_smp(self):
utf_8 = b"a\xf0\x93\x82\xa7b"
u = "a\U000130a7b"
utf_8 = b"a\xF0\x93\x82\xA7b"
u = "a\U000130A7b"
b = encode_string(u, "utf-8", "strict", AssertionError)
self.assertEqual(b, utf_8)
@@ -1,14 +1,13 @@
import os
import platform
import sys
if os.environ.get("SDL_VIDEODRIVER") == "dummy":
__tags__ = ("ignore", "subprocess_ignore")
import unittest
from pygame.tests.test_utils import trunk_relative_path
import pygame
from pygame import scrap
from pygame.tests.test_utils import trunk_relative_path
if os.environ.get("SDL_VIDEODRIVER") == pygame.NULL_VIDEODRIVER:
__tags__ = ("ignore", "subprocess_ignore")
class ScrapModuleTest(unittest.TestCase):
@@ -52,10 +51,6 @@ class ScrapModuleTest(unittest.TestCase):
"""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.
@@ -100,22 +95,15 @@ class ScrapModuleTest(unittest.TestCase):
self.assertEqual(scrap.get(pygame.SCRAP_TEXT), b"Another String")
@unittest.skipIf(
platform.system() != "Windows",
"scrap features are broken on non windows platforms",
)
@unittest.skipIf("pygame.image" not in sys.modules, "requires pygame.image module")
def test_put__bmp_image(self):
"""Ensures put can place a BMP image into the clipboard."""
sf = pygame.image.load(trunk_relative_path("examples/data/asprite.bmp"))
expected_bytes = pygame.image.tobytes(sf, "RGBA")
scrap.put(pygame.SCRAP_BMP, expected_bytes)
expected_string = pygame.image.tostring(sf, "RGBA")
scrap.put(pygame.SCRAP_BMP, expected_string)
self.assertEqual(scrap.get(pygame.SCRAP_BMP), expected_bytes)
self.assertEqual(scrap.get(pygame.SCRAP_BMP), expected_string)
@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.
@@ -127,19 +115,6 @@ class ScrapModuleTest(unittest.TestCase):
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
@@ -217,5 +192,110 @@ class ScrapModuleClipboardNotOwnedTest(unittest.TestCase):
self.assertTrue(lost)
class X11InteractiveTest(unittest.TestCase):
__tags__ = ["ignore", "subprocess_ignore"]
try:
pygame.display.init()
except Exception:
pass
else:
if pygame.display.get_driver() == "x11":
__tags__ = ["interactive"]
pygame.display.quit()
def test_issue_208(self):
"""PATCH: pygame.scrap on X11, fix copying into PRIMARY selection
Copying into theX11 PRIMARY selection (mouse copy/paste) would not
work due to a confusion between content type and clipboard type.
"""
from pygame import display, event, freetype
from pygame.locals import SCRAP_SELECTION, SCRAP_TEXT
from pygame.locals import KEYDOWN, K_y, QUIT
success = False
freetype.init()
font = freetype.Font(None, 24)
display.init()
display.set_caption("Interactive X11 Paste Test")
screen = display.set_mode((600, 200))
screen.fill(pygame.Color("white"))
text = "Scrap put() succeeded."
msg = (
"Some text has been placed into the X11 clipboard."
" Please click the center mouse button in an open"
" text window to retrieve it."
'\n\nDid you get "{}"? (y/n)'
).format(text)
word_wrap(screen, msg, font, 6)
display.flip()
event.pump()
scrap.init()
scrap.set_mode(SCRAP_SELECTION)
scrap.put(SCRAP_TEXT, text.encode("UTF-8"))
while True:
e = event.wait()
if e.type == QUIT:
break
if e.type == KEYDOWN:
success = e.key == K_y
break
pygame.display.quit()
self.assertTrue(success)
def word_wrap(surf, text, font, margin=0, color=(0, 0, 0)):
font.origin = True
surf_width, surf_height = surf.get_size()
width = surf_width - 2 * margin
height = surf_height - 2 * margin
line_spacing = int(1.25 * font.get_sized_height())
x, y = margin, margin + line_spacing
space = font.get_rect(" ")
for word in iwords(text):
if word == "\n":
x, y = margin, y + line_spacing
else:
bounds = font.get_rect(word)
if x + bounds.width + bounds.x >= width:
x, y = margin, y + line_spacing
if x + bounds.width + bounds.x >= width:
raise ValueError("word too wide for the surface")
if y + bounds.height - bounds.y >= height:
raise ValueError("text to long for the surface")
font.render_to(surf, (x, y), None, color)
x += bounds.width + space.width
return x, y
def iwords(text):
# r"\n|[^ ]+"
#
head = 0
tail = head
end = len(text)
while head < end:
if text[head] == " ":
head += 1
tail = head + 1
elif text[head] == "\n":
head += 1
yield "\n"
tail = head + 1
elif tail == end:
yield text[head:]
head = end
elif text[tail] == "\n":
yield text[head:tail]
head = tail
elif text[tail] == " ":
yield text[head:tail]
head = tail
else:
tail += 1
if __name__ == "__main__":
unittest.main()
@@ -3,6 +3,7 @@ __tags__ = ["array"]
exclude = False
try:
import pygame.mixer
import numpy
except ImportError:
exclude = True
@@ -1,8 +1,9 @@
import unittest
from numpy import int8, int16, uint8, uint16, float32, array, all as alltrue
import pygame
import pygame.sndarray
from numpy import all as np_all, array, float32, int8, int16, uint8, uint16
class SndarrayTest(unittest.TestCase):
@@ -27,7 +28,7 @@ class SndarrayTest(unittest.TestCase):
arr = pygame.sndarray.array(snd)
self._assert_compatible(arr, size)
self.assertTrue(
np_all(arr == srcarr),
alltrue(arr == srcarr),
"size: %i\n%s\n%s" % (size, arr, test_data),
)
finally:
@@ -40,7 +41,7 @@ class SndarrayTest(unittest.TestCase):
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(-8, 2, [[0, -0x80], [-0x64, 0x64], [0x25, -0x50], [-1, 0]])
check_array(-16, 1, [0, 0x7FFF, -0x7FFF, -1])
check_array(-16, 2, [[0, -0x7FFF], [-0x7FFF, 0], [0x7FFF, 0], [0, 0x7FFF]])
@@ -70,20 +71,20 @@ class SndarrayTest(unittest.TestCase):
snd = pygame.sndarray.make_sound(srcarr)
arr = pygame.sndarray.samples(snd)
self.assertTrue(
np_all(arr == srcarr),
alltrue(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(8, 2, [[0, 0x80], [0x2D, 0x41], [0x64, 0xA1], [125, 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(-8, 2, [[0, -0x80], [-0x64, 0x64], [0x25, -0x50], [-1, 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]])
@@ -109,7 +110,7 @@ class SndarrayTest(unittest.TestCase):
samples[...] = test_data
arr = pygame.sndarray.array(snd)
self.assertTrue(
np_all(samples == arr),
alltrue(samples == arr),
"size: %i\n%s\n%s" % (size, arr, test_data),
)
finally:
@@ -122,7 +123,7 @@ class SndarrayTest(unittest.TestCase):
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(-8, 2, [[0, -0x80], [-0x64, 0x64], [0x25, -0x50], [-1, 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]])
@@ -1,25 +1,17 @@
#################################### IMPORTS ###################################
import types
import typing
import unittest
import pygame
from pygame import sprite
################################# MODULE LEVEL #################################
class SpriteModuleTest(unittest.TestCase):
def test_deprecation__sprite_submodule(self):
# Test that using the old cython sprite module raises
# a deprecation warning.
with self.assertWarns(DeprecationWarning):
import pygame._sprite
pygame.init()
test_group = pygame.sprite.Group()
pass
######################### SPRITECOLLIDE FUNCTIONS TEST #########################
@@ -527,7 +519,7 @@ class AbstractGroupTypeTest(unittest.TestCase):
self.bg = pygame.Surface((20, 20))
self.scr = pygame.Surface((20, 20))
self.scr.fill(pygame.Color("gray"))
self.scr.fill(pygame.Color("grey"))
def test_has(self):
"See if AbstractGroup.has() works as expected."
@@ -661,16 +653,6 @@ class AbstractGroupTypeTest(unittest.TestCase):
self.assertEqual(test_sprite.sink, [1, 2, 3])
self.assertEqual(test_sprite.sink_kwargs, {"foo": 4, "bar": 5})
def test_type_subscript(self):
try:
group_generic_alias = sprite.Group[sprite.Sprite]
except TypeError as e:
self.fail(e)
self.assertIsInstance(group_generic_alias, types.GenericAlias)
self.assertIs(typing.get_origin(group_generic_alias), sprite.Group)
self.assertEqual(typing.get_args(group_generic_alias), (sprite.Sprite,))
################################################################################
@@ -1129,7 +1111,7 @@ class LayeredDirtyTypeTest__DirtySprite(LayeredGroupBase, unittest.TestCase):
# use_source_rect - allows non-dirty sprites to be tested
# with (True) and without (False) a source_rect
#
# This test was written to reproduce the behavior seen in pygame-ce issue # 605.
# This test was written to reproduce the behavior seen in issue #898.
# A non-dirty sprite (using source_rect) was being redrawn incorrectly
# after a dirty sprite intersected with it.
#
@@ -1225,7 +1207,7 @@ class LayeredDirtyTypeTest__DirtySprite(LayeredGroupBase, unittest.TestCase):
"""Ensure non-dirty sprites using source_rects are correctly redrawn
when dirty sprites intersect with them.
Related to pygame-ce issue #605.
Related to issue #898.
"""
self._nondirty_intersections_redrawn(True)
@@ -1261,6 +1243,7 @@ class SpriteBase:
self.assertFalse(g in self.sprite.groups())
def test_update(self):
# What does this and the next test actually test?
class test_sprite(pygame.sprite.Sprite):
sink = []
@@ -1351,6 +1334,7 @@ class SpriteTypeTest(SpriteBase, unittest.TestCase):
sprite.Group,
sprite.LayeredUpdates,
sprite.RenderUpdates,
sprite.OrderedUpdates,
]
@@ -1361,20 +1345,42 @@ class DirtySpriteTypeTest(SpriteBase, unittest.TestCase):
sprite.Group,
sprite.LayeredUpdates,
sprite.RenderUpdates,
sprite.OrderedUpdates,
sprite.LayeredDirty,
]
class WeakSpriteTypeTest(SpriteTypeTest):
Sprite = sprite.WeakSprite
def test_weak_group_ref(self):
"""
We create a list of groups, add them to the sprite.
When we then delete the groups, the sprite should be "dead"
"""
import gc
groups = [Group() for Group in self.Groups]
self.sprite.add(groups)
del groups
gc.collect()
self.assertFalse(self.sprite.alive())
class DirtyWeakSpriteTypeTest(DirtySpriteTypeTest, WeakSpriteTypeTest):
Sprite = sprite.WeakDirtySprite
############################## BUG TESTS #######################################
class SingleGroupBugsTest(unittest.TestCase):
def test_memoryleak_bug(self):
# For memory leak bug posted to mailing list by Tobias Steinrücken on 16/11/10.
# For memoryleak bug posted to mailing list by Tobias Steinrücken on 16/11/10.
# Fixed in revision 2953.
import gc
import weakref
import gc
class MySprite(sprite.Sprite):
def __init__(self, *args, **kwargs):
File diff suppressed because it is too large. Load diff
@@ -6,6 +6,11 @@ try:
import numpy
except ImportError:
exclude = True
else:
try:
import pygame.pixelcopy
except ImportError:
exclude = True
if exclude:
__tags__.extend(("ignore", "subprocess_ignore"))
@@ -1,23 +1,25 @@
import platform
import unittest
import platform
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,
float32,
float64,
all as alltrue,
rint,
arange,
)
import pygame
from pygame.locals import *
import pygame.surfarray
IS_PYPY = "PyPy" == platform.python_implementation()
@@ -111,10 +113,10 @@ class SurfarrayModuleTest(unittest.TestCase):
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])
arr[:5, :6] = surf.map_rgb(palette[1]) & 0xFFFFFFFF
arr[5:, :6] = surf.map_rgb(palette[2]) & 0xFFFFFFFF
arr[:5, 6:] = surf.map_rgb(palette[3]) & 0xFFFFFFFF
arr[5:, 6:] = surf.map_rgb(palette[4]) & 0xFFFFFFFF
def _fill_array3d(self, arr):
palette = self.test_palette
@@ -233,7 +235,7 @@ class SurfarrayModuleTest(unittest.TestCase):
),
)
else:
self.assertTrue(np_all(arr == 255))
self.assertTrue(alltrue(arr == 255))
# No per-pixel alpha when blanket alpha is None.
for surf in targets:
@@ -241,7 +243,7 @@ class SurfarrayModuleTest(unittest.TestCase):
surf.set_alpha(None)
arr = pygame.surfarray.array_alpha(surf)
self.assertTrue(
np_all(arr == 255),
alltrue(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()),
@@ -255,12 +257,12 @@ class SurfarrayModuleTest(unittest.TestCase):
arr = pygame.surfarray.array_alpha(surf)
if surf.get_masks()[3]:
self.assertFalse(
np_all(arr == 255),
alltrue(arr == 255),
"bitsize: %i, flags: %i" % (surf.get_bitsize(), surf.get_flags()),
)
else:
self.assertTrue(
np_all(arr == 255),
alltrue(arr == 255),
"bitsize: %i, flags: %i" % (surf.get_bitsize(), surf.get_flags()),
)
surf.set_alpha(blanket_alpha)
@@ -288,7 +290,7 @@ class SurfarrayModuleTest(unittest.TestCase):
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))
self.assertTrue(alltrue(arr == 255))
for i in range(1, len(palette)):
surf.set_colorkey(p[i])
@@ -469,34 +471,39 @@ class SurfarrayModuleTest(unittest.TestCase):
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])))
# Issue #81: round from float to int
try:
rint
except NameError:
pass
else:
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()
array_type = pygame.surfarray.get_arraytype()
self.assertEqual(array_type, "numpy", f"unknown array type {array_type}")
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)
arraytypes = pygame.surfarray.get_arraytypes()
self.assertIn("numpy", arraytypes)
for atype in arraytypes:
self.assertEqual(atype, "numpy", f"unknown array type {atype}")
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
@@ -513,17 +520,24 @@ class SurfarrayModuleTest(unittest.TestCase):
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])))
# Issue #81: round from float to int
try:
rint
except NameError:
pass
else:
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)
@@ -560,11 +574,6 @@ class SurfarrayModuleTest(unittest.TestCase):
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),
@@ -710,23 +719,24 @@ class SurfarrayModuleTest(unittest.TestCase):
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")
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)
for atype in pygame.surfarray.get_arraytypes():
pygame.surfarray.use_arraytype(atype)
ar = pygame.surfarray.pixels2d(sf)
self.assertTrue(sf.get_locked())
ar = pygame.surfarray.pixels2d(sf)
self.assertTrue(sf.get_locked())
sf.unlock()
self.assertTrue(sf.get_locked())
sf.unlock()
self.assertTrue(sf.get_locked())
del ar
self.assertFalse(sf.get_locked())
self.assertEqual(sf.get_locks(), ())
del ar
self.assertFalse(sf.get_locked())
self.assertEqual(sf.get_locks(), ())
if __name__ == "__main__":
@@ -1,6 +1,6 @@
import platform
import sys
import unittest
import sys
import platform
import pygame
@@ -1,5 +1,5 @@
import platform
import unittest
import platform
class SysfontModuleTest(unittest.TestCase):
@@ -29,31 +29,6 @@ class SysfontModuleTest(unittest.TestCase):
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.",
@@ -69,25 +44,6 @@ class SysfontModuleTest(unittest.TestCase):
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
)
###############################################################################
@@ -1,123 +0,0 @@
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()
@@ -1,8 +1,10 @@
import os
import pygame
import sys
import tempfile
import time
import pygame
is_pygame_pkg = __name__.startswith("pygame.tests.")
###############################################################################
@@ -21,8 +23,11 @@ def geterror():
###############################################################################
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]
trunk_dir = os.path.split(os.path.split(this_dir)[0])[0]
if is_pygame_pkg:
test_module = "tests"
else:
test_module = "test"
def trunk_relative_path(relative):
@@ -30,7 +35,7 @@ def trunk_relative_path(relative):
def fixture_path(path):
return os.path.join(this_dir_parent, "fixtures", path)
return trunk_relative_path(os.path.join(test_module, "fixtures", path))
def example_path(path):
@@ -70,6 +75,22 @@ def rgba_between(value, minimum=0, maximum=255):
return value
def combinations(seqs):
"""
Recipe 496807 from ActiveState Python CookBook
Non recursive technique for getting all possible combinations of a sequence
of sequences.
"""
r = [[]]
for x in seqs:
r = [i + [y] for y in x for i in r]
return r
def gradient(width, height):
"""
@@ -1,7 +1,7 @@
import ctypes
import sys
import unittest
import ctypes
from ctypes import *
import unittest
__all__ = [
"PAI_CONTIGUOUS",
@@ -7,14 +7,14 @@ 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 errno
import time
import sys
import unittest
import tempfile
def geterror():
@@ -86,15 +86,15 @@ if platform.system() == "Windows":
return "", c_avail.value, c_message.value
except ImportError:
from win32api import TerminateProcess
from win32file import ReadFile, WriteFile
from win32pipe import PeekNamedPipe
from win32api import TerminateProcess
import msvcrt
else:
import fcntl
from signal import SIGINT, SIGTERM, SIGKILL
import select
from signal import SIGINT, SIGKILL, SIGTERM
import fcntl
################################### CONSTANTS ##################################
@@ -3,14 +3,14 @@
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.
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
with the actual request. The simular Python builtin memoryview currently
does not support configurable PyBUF_* flags.
This module contains its own unit tests. When Pygame is installed, these tests
@@ -20,33 +20,37 @@ python -m pygame.tests.test_utils.array
"""
import ctypes
import operator
import unittest
from functools import reduce
import pygame
if not pygame.HAVE_NEWBUF:
emsg = "This Pygame build does not support the new buffer protocol"
raise ImportError(emsg)
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_FORMAT,
PyBUF_ND,
PyBUF_WRITABLE,
PyBUF_STRIDES,
PyBUF_C_CONTIGUOUS,
PyBUF_F_CONTIGUOUS,
PyBUF_ANY_CONTIGUOUS,
PyBUF_INDIRECT,
PyBUF_STRIDED,
PyBUF_STRIDED_RO,
PyBUF_STRIDES,
PyBUF_WRITABLE,
PyBUF_RECORDS,
PyBUF_RECORDS_RO,
PyBUF_FULL,
PyBUF_FULL_RO,
PyBUF_CONTIG,
PyBUF_CONTIG_RO,
)
import unittest
import ctypes
import operator
from functools import reduce
__all__ = ["Exporter", "Importer"]
try:
@@ -321,7 +325,7 @@ class Importer:
return self._view.internal
def _to_ssize_tuple(self, addr):
from ctypes import POINTER, c_ssize_t, cast
from ctypes import cast, POINTER, c_ssize_t
if addr is None:
return None
@@ -44,7 +44,7 @@
# 2006-06-17 Nicko: Reworked into a class, faster interlacing.
# 2006-06-17 Johann: Very simple prototype PNG decoder.
# 2006-06-17 Nicko: Test suite with various image generators.
# 2006-06-17 Nicko: Alpha-channel, gray-scale, 16-bit/plane support.
# 2006-06-17 Nicko: Alpha-channel, grey-scale, 16-bit/plane support.
# 2006-06-15 Johann: Scanline iterator interface for large input files.
# 2006-06-09 Johann: Very simple prototype PNG encoder.
@@ -61,8 +61,8 @@ Pure Python PNG Reader/Writer
This Python module implements support for PNG images (see PNG
specification at http://www.w3.org/TR/2003/REC-PNG-20031110/ ). It reads
and writes PNG files with all allowable bit depths (1/2/4/8/16/24/32/48/64
bits per pixel) and color combinations: grayscale (1/2/4/8/16 bit); RGB,
RGBA, LA (grayscale with alpha) with 8/16 bits per channel; color mapped
bits per pixel) and colour combinations: greyscale (1/2/4/8/16 bit); RGB,
RGBA, LA (greyscale with alpha) with 8/16 bits per channel; colour mapped
images (1/2/4/8 bit). Adam7 interlacing is supported for reading and
writing. A number of optional chunks can be specified (when writing)
and understood (when reading): ``tRNS``, ``bKGD``, ``gAMA``.
@@ -81,15 +81,15 @@ A note on spelling and terminology
----------------------------------
Generally British English spelling is used in the documentation. So
that's "grayscale" and "color". This not only matches the author's
that's "greyscale" and "colour". This not only matches the author's
native language, it's also used by the PNG specification.
The major color models supported by PNG (and hence by PyPNG) are:
grayscale, RGB, grayscale--alpha, RGB--alpha. These are sometimes
The major colour models supported by PNG (and hence by PyPNG) are:
greyscale, RGB, greyscale--alpha, RGB--alpha. These are sometimes
referred to using the abbreviations: L, RGB, LA, RGBA. In this case
each letter abbreviates a single channel: *L* is for Luminance or Luma or
Lightness which is the channel used in grayscale images; *R*, *G*, *B* stand
for Red, Green, Blue, the components of a color image; *A* stands for
Lightness which is the channel used in greyscale images; *R*, *G*, *B* stand
for Red, Green, Blue, the components of a colour image; *A* stands for
Alpha, the opacity channel (used for transparency effects, but higher
values are more opaque, so it makes sense to call it opacity).
@@ -125,7 +125,7 @@ Flat row flat pixel::
[R,G,B, R,G,B, R,G,B,
R,G,B, R,G,B, R,G,B]
The entire image is one single giant sequence of color values.
The entire image is one single giant sequence of colour values.
Generally an array will be used (to save space), not a list.
Boxed row boxed pixel::
@@ -138,7 +138,7 @@ tuple. A serious memory burn in Python.
In all cases the top row comes first, and for each row the pixels are
ordered from left-to-right. Within a pixel the values appear in the
order, R-G-B-A (or L-A for grayscale--alpha).
order, R-G-B-A (or L-A for greyscale--alpha).
There is a fourth format, mentioned because it is used internally,
is close to what lies inside a PNG file itself, and has some support
@@ -167,8 +167,8 @@ import math
import operator
import struct
import sys
import warnings
import zlib
import warnings
from array import array
from functools import reduce
@@ -220,7 +220,7 @@ except:
def interleave_planes(ipixels, apixels, ipsize, apsize):
"""
Interleave (color) planes, e.g. RGB + A = RGBA.
Interleave (colour) planes, e.g. RGB + A = RGBA.
Return an array of pixels consisting of the `ipsize` elements of data
from each pixel in `ipixels` followed by the `apsize` elements of data
@@ -307,7 +307,7 @@ class Writer:
width=None,
height=None,
size=None,
grayscale=False,
greyscale=False,
alpha=False,
bitdepth=8,
palette=None,
@@ -331,18 +331,18 @@ class Writer:
Image size in pixels, as two separate arguments.
size
Image size (w,h) in pixels, as single argument.
grayscale
Input data is grayscale, not RGB.
greyscale
Input data is greyscale, not RGB.
alpha
Input data has alpha channel (RGBA or LA).
bitdepth
Bit depth: from 1 to 16.
palette
Create a palette for a color mapped image (color type 3).
Create a palette for a colour mapped image (colour type 3).
transparent
Specify a transparent color (create a ``tRNS`` chunk).
Specify a transparent colour (create a ``tRNS`` chunk).
background
Specify a default background color (create a ``bKGD`` chunk).
Specify a default background colour (create a ``bKGD`` chunk).
gamma
Specify a gamma value (create a ``gAMA`` chunk).
compression
@@ -357,8 +357,8 @@ class Writer:
argument. If `size` is used it should be a pair (*width*,
*height*).
`grayscale` and `alpha` are booleans that specify whether
an image is grayscale (or color), and whether it has an
`greyscale` and `alpha` are booleans that specify whether
an image is greyscale (or colour), and whether it has an
alpha channel (or not).
`bitdepth` specifies the bit depth of the source pixel values.
@@ -371,27 +371,27 @@ class Writer:
precision of the source image. In this case the supplied pixel
values will be rescaled to fit the range of the selected bit depth.
The details of which bit depth / color model combinations the
The details of which bit depth / colour model combinations the
PNG file format supports directly, are somewhat arcane
(refer to the PNG specification for full details). Briefly:
"small" bit depths (1,2,4) are only allowed with grayscale and
color mapped images; color mapped images cannot have bit depth
"small" bit depths (1,2,4) are only allowed with greyscale and
colour mapped images; colour mapped images cannot have bit depth
16.
For color mapped images (in other words, when the `palette`
For colour mapped images (in other words, when the `palette`
argument is specified) the `bitdepth` argument must match one of
the valid PNG bit depths: 1, 2, 4, or 8. (It is valid to have a
PNG image with a palette and an ``sBIT`` chunk, but the meaning
is slightly different; it would be awkward to press the
`bitdepth` argument into service for this.)
The `palette` option, when specified, causes a color mapped image
to be created: the PNG color type is set to 3; grayscale
The `palette` option, when specified, causes a colour mapped image
to be created: the PNG colour type is set to 3; greyscale
must not be set; alpha must not be set; transparent must
not be set; the bit depth must be 1,2,4, or 8. When a color
not be set; the bit depth must be 1,2,4, or 8. When a colour
mapped image is created, the pixel values are palette indexes
and the `bitdepth` argument specifies the size of these indexes
(not the size of the color values in the palette).
(not the size of the colour values in the palette).
The palette argument value should be a sequence of 3- or
4-tuples. 3-tuples specify RGB palette entries; 4-tuples
@@ -406,7 +406,7 @@ class Writer:
If specified, the `transparent` and `background` parameters must
be a tuple with three integer values for red, green, blue, or
a simple integer (or singleton tuple) for a grayscale image.
a simple integer (or singleton tuple) for a greyscale image.
If specified, the `gamma` parameter must be a positive number
(generally, a float). A ``gAMA`` chunk will be created. Note that
@@ -440,7 +440,7 @@ class Writer:
"""
# At the moment the `planes` argument is ignored;
# its purpose is to act as a placeholder argument so that
# its purpose is to act as a dummy so that
# ``Writer(x, y, **info)`` works, where `info` is a dictionary
# returned by Reader.read and friends.
# Ditto for `colormap`.
@@ -455,22 +455,22 @@ class Writer:
return False
def check_color(c, which):
"""Checks that a color argument for transparent or
background options is the right form. Also, "corrects" bare
"""Checks that a colour argument for transparent or
background options is the right form. Also "corrects" bare
integers to 1-tuples.
"""
if c is None:
return c
if grayscale:
if greyscale:
try:
l = len(c)
except TypeError:
c = (c,)
if len(c) != 1:
raise ValueError(f"{which} for grayscale must be 1-tuple")
raise ValueError(f"{which} for greyscale must be 1-tuple")
if not isinteger(c[0]):
raise ValueError(f"{which} color for grayscale must be integer")
raise ValueError(f"{which} colour for greyscale must be integer")
else:
if not (
len(c) == 3
@@ -478,7 +478,7 @@ class Writer:
and isinteger(c[1])
and isinteger(c[2])
):
raise ValueError(f"{which} color must be a triple of integers")
raise ValueError(f"{which} colour must be a triple of integers")
return c
if size:
@@ -506,7 +506,7 @@ class Writer:
raise ValueError("width and height cannot exceed 2**32-1")
if alpha and transparent is not None:
raise ValueError("transparent color not allowed with alpha channel")
raise ValueError("transparent colour not allowed with alpha channel")
if bytes_per_sample is not None:
warnings.warn(
@@ -529,18 +529,18 @@ class Writer:
raise ValueError("transparent and palette not compatible")
if alpha:
raise ValueError("alpha and palette not compatible")
if grayscale:
raise ValueError("grayscale and palette not compatible")
if greyscale:
raise ValueError("greyscale and palette not compatible")
else:
# No palette, check for sBIT chunk generation.
if alpha or not grayscale:
if alpha or not greyscale:
if bitdepth not in (8, 16):
targetbitdepth = (8, 16)[bitdepth > 8]
self.rescale = (bitdepth, targetbitdepth)
bitdepth = targetbitdepth
del targetbitdepth
else:
assert grayscale
assert greyscale
assert not alpha
if bitdepth not in (1, 2, 4, 8, 16):
if bitdepth > 8:
@@ -554,15 +554,15 @@ class Writer:
bitdepth = targetbitdepth
del targetbitdepth
if bitdepth < 8 and (alpha or not grayscale and not palette):
raise ValueError("bitdepth < 8 only permitted with grayscale or palette")
if bitdepth < 8 and (alpha or not greyscale and not palette):
raise ValueError("bitdepth < 8 only permitted with greyscale or palette")
if bitdepth > 8 and palette:
raise ValueError("bit depth must be 8 or less for images with palette")
transparent = check_color(transparent, "transparent")
background = check_color(background, "background")
# It's important that the true boolean values (grayscale, alpha,
# It's important that the true boolean values (greyscale, alpha,
# colormap, interlace) are converted to bool because Iverson's
# convention is relied upon later on.
self.width = width
@@ -570,7 +570,7 @@ class Writer:
self.transparent = transparent
self.background = background
self.gamma = gamma
self.grayscale = bool(grayscale)
self.greyscale = bool(greyscale)
self.alpha = bool(alpha)
self.colormap = bool(palette)
self.bitdepth = int(bitdepth)
@@ -579,10 +579,10 @@ class Writer:
self.interlace = bool(interlace)
self.palette = check_palette(palette)
self.color_type = 4 * self.alpha + 2 * (not grayscale) + 1 * self.colormap
self.color_type = 4 * self.alpha + 2 * (not greyscale) + 1 * self.colormap
assert self.color_type in (0, 2, 3, 4, 6)
self.color_planes = (3, 1)[self.grayscale or self.colormap]
self.color_planes = (3, 1)[self.greyscale or self.colormap]
self.planes = self.color_planes + self.alpha
# :todo: fix for bitdepth < 8
self.psize = (self.bitdepth / 8) * self.planes
@@ -701,14 +701,14 @@ class Writer:
# http://www.w3.org/TR/PNG/#11tRNS
if self.transparent is not None:
if self.grayscale:
if self.greyscale:
write_chunk(outfile, "tRNS", struct.pack("!1H", *self.transparent))
else:
write_chunk(outfile, "tRNS", struct.pack("!3H", *self.transparent))
# http://www.w3.org/TR/PNG/#11bKGD
if self.background is not None:
if self.grayscale:
if self.greyscale:
write_chunk(outfile, "bKGD", struct.pack("!1H", *self.background))
else:
write_chunk(outfile, "bKGD", struct.pack("!3H", *self.background))
@@ -757,7 +757,7 @@ class Writer:
oldextend((int(round(factor * x)) for x in sl))
# Build the first row, testing mostly to see if we need to
# change the extend function to cope with NumPy integer types
# changed the extend function to cope with NumPy integer types
# (they cause our ordinary definition of extend to fail, so we
# wrap it). See
# http://code.google.com/p/pypng/issues/detail?id=44
@@ -799,7 +799,7 @@ class Writer:
# print(len(data), len(compressed), file= >> sys.stderr)
write_chunk(outfile, "IDAT", compressed)
# Because of our very witty definition of ``extend``,
# above, we must re-use the same ``data`` object. Hence,
# above, we must reuse the same ``data`` object. Hence
# we use ``del`` to empty this one, rather than create a
# fresh one (which would be my natural FP instinct).
del data[:]
@@ -832,7 +832,7 @@ class Writer:
which should be in boxed row packed format. Each row should be
a sequence of packed bytes.
Technically, this method does work for interlaced images, but it
Technically, this method does work for interlaced images but it
is best avoided. For interlaced images, the rows should be
presented in the order that they appear in the file.
@@ -1057,9 +1057,9 @@ def filter_scanline(type, line, fo, prev=None):
ai += 1
if not prev:
# We're on the first line. Some of the filters can be reduced
# We're on the first line. Some of the filters can be reduced
# to simpler cases which makes handling the line "off the top"
# of the image simpler. "up" becomes "none"; "paeth" becomes
# of the image simpler. "up" becomes "none"; "paeth" becomes
# "left" (non-trivial, but true). "average" needs to be handled
# specially.
if type == 2: # "up"
@@ -1089,31 +1089,31 @@ def from_array(a, mode=None, info={}):
.. note :
The use of the term *3-dimensional* is for marketing purposes
only. It doesn't actually work. Please bear with us. Meanwhile,
only. It doesn't actually work. Please bear with us. Meanwhile
enjoy the complimentary snacks (on request) and please use a
2-dimensional array.
Unless they are specified using the *info* parameter, the PNG's
height and width are taken from the array size. For a 3 dimensional
array the first axis is the height; the second axis is the width;
and the third axis is the channel number. Thus, an RGB image that is
and the third axis is the channel number. Thus an RGB image that is
16 pixels high and 8 wide will use an array that is 16x8x3. For 2
dimensional arrays the first axis is the height, but the second axis
is ``width*channels``, so an RGB image that is 16 pixels high and 8
wide will use a 2-dimensional array that is 16x24 (each row will be
8*3==24 sample values).
*mode* is a string that specifies the image color format in a
*mode* is a string that specifies the image colour format in a
PIL-style mode. It can be:
``'L'``
grayscale (1 channel)
greyscale (1 channel)
``'LA'``
grayscale with alpha (2 channel)
greyscale with alpha (2 channel)
``'RGB'``
color image (3 channel)
colour image (3 channel)
``'RGBA'``
color image with alpha (4 channel)
colour image with alpha (4 channel)
The mode string can also specify the bit depth (overriding how this
function normally derives the bit depth, see below). Appending
@@ -1160,7 +1160,7 @@ def from_array(a, mode=None, info={}):
Generally anything specified in the
*info* dictionary will override any implicit choices that this
function would otherwise make, but must match any explicit ones.
For example, if the *info* dictionary has a ``grayscale`` key then
For example, if the *info* dictionary has a ``greyscale`` key then
this must be true when mode is ``'L'`` or ``'LA'`` and false when
mode is ``'RGB'`` or ``'RGBA'``.
"""
@@ -1212,11 +1212,11 @@ def from_array(a, mode=None, info={}):
except:
raise Error("len(a) does not work, supply info['height'] instead.")
info["height"] = l
# Color format.
if "grayscale" in info:
if bool(info["grayscale"]) != ("L" in mode):
raise Error("info['grayscale'] should match mode.")
info["grayscale"] = "L" in mode
# Colour format.
if "greyscale" in info:
if bool(info["greyscale"]) != ("L" in mode):
raise Error("info['greyscale'] should match mode.")
info["greyscale"] = "L" in mode
if "alpha" in info:
if bool(info["alpha"]) != ("A" in mode):
raise Error("info['alpha'] should match mode.")
@@ -1271,7 +1271,7 @@ def from_array(a, mode=None, info={}):
bitdepth = 8 * dtype.itemsize
info["bitdepth"] = bitdepth
for thing in "width height bitdepth grayscale alpha".split():
for thing in "width height bitdepth greyscale alpha".split():
assert thing in info
return Image(a, info)
@@ -1491,12 +1491,12 @@ class Reader:
)
# Filter unit. The stride from one pixel to the corresponding
# byte from the previous scanline. Normally this is the pixel
# byte from the previous previous. Normally this is the pixel
# size in bytes, but when this is smaller than 1, the previous
# byte is used instead.
fu = max(1, self.psize)
# For the first line of a pass, synthesize a fake previous
# For the first line of a pass, synthesize a dummy previous
# line. An alternative approach would be to observe that on the
# first line 'up' is the same as 'null', 'paeth' is the same
# as 'sub', with only 'average' requiring any special case.
@@ -1773,16 +1773,16 @@ class Reader:
if self.bitdepth not in (1, 2, 4, 8, 16):
raise Error("invalid bit depth %d" % self.bitdepth)
if self.color_type not in (0, 2, 3, 4, 6):
raise Error("invalid color type %d" % self.color_type)
raise Error("invalid colour type %d" % self.color_type)
# Check indexed (palettized) images have 8 or fewer bits
# per pixel; check only indexed or grayscale images have
# per pixel; check only indexed or greyscale images have
# fewer than 8 bits per pixel.
if (self.color_type & 1 and self.bitdepth > 8) or (
self.bitdepth < 8 and self.color_type not in (0, 3)
):
raise FormatError(
"Illegal combination of bit depth (%d)"
" and color type (%d)."
" and colour type (%d)."
" See http://www.w3.org/TR/2003/REC-PNG-20031110/#table111 ."
% (self.bitdepth, self.color_type)
)
@@ -1804,13 +1804,13 @@ class Reader:
# Derived values
# http://www.w3.org/TR/PNG/#6Colour-values
colormap = bool(self.color_type & 1)
grayscale = not (self.color_type & 2)
greyscale = not (self.color_type & 2)
alpha = bool(self.color_type & 4)
color_planes = (3, 1)[grayscale or colormap]
color_planes = (3, 1)[greyscale or colormap]
planes = color_planes + alpha
self.colormap = colormap
self.grayscale = grayscale
self.greyscale = greyscale
self.alpha = alpha
self.color_planes = color_planes
self.planes = planes
@@ -1861,7 +1861,7 @@ class Reader:
else:
if self.alpha:
raise FormatError(
"tRNS chunk is not valid with color type %d." % self.color_type
"tRNS chunk is not valid with colour type %d." % self.color_type
)
try:
self.transparent = struct.unpack("!%dH" % self.color_planes, data)
@@ -1942,7 +1942,7 @@ class Reader:
else:
pixels = self.iterboxed(self.iterstraight(raw))
meta = {}
for attr in "grayscale alpha planes bitdepth interlace".split():
for attr in "greyscale alpha planes bitdepth interlace".split():
meta[attr] = getattr(self, attr)
meta["size"] = (self.width, self.height)
for attr in "gamma transparent background".split():
@@ -1975,7 +1975,7 @@ class Reader:
chunks should have already been processed (for example, by
calling the :meth:`preamble` method). All the tuples are the
same size: 3-tuples if there is no ``tRNS`` chunk, 4-tuples when
there is a ``tRNS`` chunk. Assumes that the image is color type
there is a ``tRNS`` chunk. Assumes that the image is colour type
3 and therefore a ``PLTE`` chunk is required.
If the `alpha` argument is ``'force'`` then an alpha channel is
@@ -1983,7 +1983,7 @@ class Reader:
"""
if not self.plte:
raise FormatError("Required PLTE chunk is missing in color type 3 image.")
raise FormatError("Required PLTE chunk is missing in colour type 3 image.")
plte = group(array("B", self.plte), 3)
if self.trns or alpha == "force":
trns = array("B", self.trns or "")
@@ -1995,11 +1995,11 @@ class Reader:
"""Returns the image data as a direct representation of an
``x * y * planes`` array. This method is intended to remove the
need for callers to deal with palettes and transparency
themselves. Images with a palette (color type 3)
themselves. Images with a palette (colour type 3)
are converted to RGB or RGBA; images with transparency (a
``tRNS`` chunk) are converted to LA or RGBA as appropriate.
When returned in this format the pixel values represent the
color value directly without needing to refer to palettes or
colour value directly without needing to refer to palettes or
transparency information.
Like the :meth:`read` method this method returns a 4-tuple:
@@ -2018,7 +2018,7 @@ class Reader:
The *meta* dictionary that is returned reflects the `direct`
format and not the original source image. For example, an RGB
source image with a ``tRNS`` chunk to represent a transparent
color, will have ``planes=3`` and ``alpha=False`` for the
colour, will have ``planes=3`` and ``alpha=False`` for the
source image, but the *meta* dictionary returned by this method
will have ``planes=4`` and ``alpha=True`` because an alpha
channel is synthesized and added.
@@ -2163,8 +2163,8 @@ class Reader:
return self._as_rescale(self.asRGBA, 8)
def asRGB(self):
"""Return image as RGB pixels. RGB color images are passed
through unchanged; grayscales are expanded into RGB
"""Return image as RGB pixels. RGB colour images are passed
through unchanged; greyscales are expanded into RGB
triplets (there is a small speed overhead for doing this).
An alpha channel in the source image will raise an
@@ -2173,15 +2173,15 @@ class Reader:
The return values are as for the :meth:`read` method
except that the *metadata* reflect the returned pixels, not the
source image. In particular, for this method
``metadata['grayscale']`` will be ``False``.
``metadata['greyscale']`` will be ``False``.
"""
width, height, pixels, meta = self.asDirect()
if meta["alpha"]:
raise Error("will not convert image with alpha channel to RGB")
if not meta["grayscale"]:
if not meta["greyscale"]:
return width, height, pixels, meta
meta["grayscale"] = False
meta["greyscale"] = False
typecode = "BH"[meta["bitdepth"] > 8]
def iterrgb():
@@ -2194,17 +2194,17 @@ class Reader:
return width, height, iterrgb(), meta
def asRGBA(self):
"""Return image as RGBA pixels. Grayscales are expanded into
"""Return image as RGBA pixels. Greyscales are expanded into
RGB triplets; an alpha channel is synthesized if necessary.
The return values are as for the :meth:`read` method
except that the *metadata* reflect the returned pixels, not the
source image. In particular, for this method
``metadata['grayscale']`` will be ``False``, and
``metadata['greyscale']`` will be ``False``, and
``metadata['alpha']`` will be ``True``.
"""
width, height, pixels, meta = self.asDirect()
if meta["alpha"] and not meta["grayscale"]:
if meta["alpha"] and not meta["greyscale"]:
return width, height, pixels, meta
typecode = "BH"[meta["bitdepth"] > 8]
maxval = 2 ** meta["bitdepth"] - 1
@@ -2212,7 +2212,7 @@ class Reader:
def newarray():
return array(typecode, [0]) * 4 * width
if meta["alpha"] and meta["grayscale"]:
if meta["alpha"] and meta["greyscale"]:
# LA to RGBA
def convert():
for row in pixels:
@@ -2225,7 +2225,7 @@ class Reader:
a[3::4] = row[1::2]
yield a
elif meta["grayscale"]:
elif meta["greyscale"]:
# L to RGBA
def convert():
for row in pixels:
@@ -2236,7 +2236,7 @@ class Reader:
yield a
else:
assert not meta["alpha"] and not meta["grayscale"]
assert not meta["alpha"] and not meta["greyscale"]
# RGB to RGBA
def convert():
@@ -2248,7 +2248,7 @@ class Reader:
yield a
meta["alpha"] = True
meta["grayscale"] = False
meta["greyscale"] = False
return width, height, convert(), meta
@@ -2364,7 +2364,7 @@ class Test(unittest.TestCase):
mask = (1 << n) - 1
# Use small chunk_limit so that multiple chunk writing is
# tested. Making it a test for Issue 20.
w = Writer(15, 17, grayscale=True, bitdepth=n, chunk_limit=99)
w = Writer(15, 17, greyscale=True, bitdepth=n, chunk_limit=99)
f = BytesIO()
w.write_array(f, array("B", map(mask.__and__, range(1, 256))))
r = Reader(bytes=f.getvalue())
@@ -2383,7 +2383,7 @@ class Test(unittest.TestCase):
def testL2(self):
"Also tests asRGB8."
w = Writer(1, 4, grayscale=True, bitdepth=2)
w = Writer(1, 4, greyscale=True, bitdepth=2)
f = BytesIO()
w.write_array(f, array("B", range(4)))
r = Reader(bytes=f.getvalue())
@@ -2409,7 +2409,7 @@ class Test(unittest.TestCase):
self.assertEqual(list(pixels), map(list, [a, b, b, c]))
def testPtrns(self):
"Test color type 3 and tRNS chunk (and 4-bit palette)."
"Test colour type 3 and tRNS chunk (and 4-bit palette)."
a = (50, 99, 50, 50)
b = (200, 120, 120, 80)
c = (255, 255, 255)
@@ -2430,8 +2430,8 @@ class Test(unittest.TestCase):
self.assertEqual(map(list, pixels), map(list, flat))
def testRGBtoRGBA(self):
"asRGBA8() on color type 2 source."
# Test for pygame-ce issue 41
"asRGBA8() on colour type 2 source." ""
# Test for Issue 26
r = Reader(bytes=_pngsuite["basn2c08"])
x, y, pixels, meta = r.asRGBA8()
# Test the pixels at row 9 columns 0 and 1.
@@ -2439,20 +2439,20 @@ class Test(unittest.TestCase):
self.assertEqual(row9[0:8], [0xFF, 0xDF, 0xFF, 0xFF, 0xFF, 0xDE, 0xFF, 0xFF])
def testLtoRGBA(self):
"asRGBA() on gray source."
# Test for pygame-ce issue 75
"asRGBA() on grey source." ""
# Test for Issue 60
r = Reader(bytes=_pngsuite["basi0g08"])
x, y, pixels, meta = r.asRGBA()
row9 = list(list(pixels)[9])
self.assertEqual(row9[0:8], [222, 222, 222, 255, 221, 221, 221, 255])
def testCtrns(self):
"Test color type 2 and tRNS chunk."
# Test for pygame-ce issue 40
"Test colour type 2 and tRNS chunk."
# Test for Issue 25
r = Reader(bytes=_pngsuite["tbrn2c08"])
x, y, pixels, meta = r.asRGBA8()
# I just happen to know that the first pixel is transparent.
# In particular, it should be #7f7f7f00
# In particular it should be #7f7f7f00
row0 = list(pixels)[0]
self.assertEqual(tuple(row0[0:4]), (0x7F, 0x7F, 0x7F, 0x00))
@@ -2486,7 +2486,7 @@ class Test(unittest.TestCase):
# we have written is to read it back again.
for name, bytes in _pngsuite.items():
# Only certain color types supported for this test.
# Only certain colour types supported for this test.
if name[3:5] not in ["n0", "n2", "n4", "n6"]:
continue
it = Reader(bytes=bytes)
@@ -2497,7 +2497,7 @@ class Test(unittest.TestCase):
x=x,
y=y,
bitdepth=it.bitdepth,
grayscale=it.grayscale,
greyscale=it.greyscale,
alpha=it.alpha,
transparent=it.transparent,
interlace=False,
@@ -2511,7 +2511,7 @@ class Test(unittest.TestCase):
x=x,
y=y,
bitdepth=it.bitdepth,
grayscale=it.grayscale,
greyscale=it.greyscale,
alpha=it.alpha,
transparent=it.transparent,
interlace=True,
@@ -2534,7 +2534,7 @@ class Test(unittest.TestCase):
testWithIO(s, o, do)
r = Reader(bytes=o.getvalue())
x, y, pixels, meta = r.read()
self.assertTrue(r.grayscale)
self.assertTrue(r.greyscale)
self.assertEqual(r.bitdepth, 2)
def testPAMin(self):
@@ -2561,19 +2561,19 @@ class Test(unittest.TestCase):
r = Reader(bytes=o.getvalue())
x, y, pixels, meta = r.read()
self.assertTrue(r.alpha)
self.assertTrue(not r.grayscale)
self.assertTrue(not r.greyscale)
self.assertEqual(list(itertools.chain(*pixels)), flat)
def testLA4(self):
"""Create an LA image with bitdepth 4."""
bytes = topngbytes(
"la4.png", [[5, 12]], 1, 1, grayscale=True, alpha=True, bitdepth=4
"la4.png", [[5, 12]], 1, 1, greyscale=True, alpha=True, bitdepth=4
)
sbit = Reader(bytes=bytes).chunk("sBIT")[1]
self.assertEqual(sbit, strtobytes("\x04\x04"))
def testPNMsbit(self):
"""Test that PNM files can generate an sBIT chunk."""
"""Test that PNM files can generates sBIT chunk."""
def do():
return _main(["testPNMsbit"])
@@ -2591,7 +2591,7 @@ class Test(unittest.TestCase):
self.assertEqual(sbit, strtobytes("\x01\x01\x01"))
def testLtrns0(self):
"""Create grayscale image with tRNS chunk."""
"""Create greyscale image with tRNS chunk."""
return self.helperLtrns(0)
def testLtrns1(self):
@@ -2602,12 +2602,12 @@ class Test(unittest.TestCase):
"""Helper used by :meth:`testLtrns*`."""
pixels = zip([0x00, 0x38, 0x4C, 0x54, 0x5C, 0x40, 0x38, 0x00])
o = BytesIO()
w = Writer(8, 8, grayscale=True, bitdepth=1, transparent=transparent)
w = Writer(8, 8, greyscale=True, bitdepth=1, transparent=transparent)
w.write_packed(o, pixels)
r = Reader(bytes=o.getvalue())
x, y, pixels, meta = r.asDirect()
self.assertTrue(meta["alpha"])
self.assertTrue(meta["grayscale"])
self.assertTrue(meta["greyscale"])
self.assertEqual(meta["bitdepth"], 1)
def testWinfo(self):
@@ -2621,9 +2621,9 @@ class Test(unittest.TestCase):
def testPackedIter(self):
"""Test iterator for row when using write_packed.
Indicative for pygame-ce issue 62.
Indicative for Issue 47.
"""
w = Writer(16, 2, grayscale=True, alpha=False, bitdepth=1)
w = Writer(16, 2, greyscale=True, alpha=False, bitdepth=1)
o = BytesIO()
w.write_packed(
o, [itertools.chain([0x0A], [0xAA]), itertools.chain([0x0F], [0xFF])]
@@ -2763,7 +2763,7 @@ class Test(unittest.TestCase):
rows = [map(numpy.uint16, range(0, 0x10000, 0x5555))]
b = topngbytes(
"numpyuint16.png", rows, 4, 1, grayscale=True, alpha=False, bitdepth=16
"numpyuint16.png", rows, 4, 1, greyscale=True, alpha=False, bitdepth=16
)
def testNumpyuint8(self):
@@ -2777,7 +2777,7 @@ class Test(unittest.TestCase):
rows = [map(numpy.uint8, range(0, 0x100, 0x55))]
b = topngbytes(
"numpyuint8.png", rows, 4, 1, grayscale=True, alpha=False, bitdepth=8
"numpyuint8.png", rows, 4, 1, greyscale=True, alpha=False, bitdepth=8
)
def testNumpybool(self):
@@ -2791,7 +2791,7 @@ class Test(unittest.TestCase):
rows = [map(numpy.bool, [0, 1])]
b = topngbytes(
"numpybool.png", rows, 2, 1, grayscale=True, alpha=False, bitdepth=1
"numpybool.png", rows, 2, 1, greyscale=True, alpha=False, bitdepth=1
)
def testNumpyarray(self):
@@ -2812,8 +2812,8 @@ class Test(unittest.TestCase):
def _dehex(s):
"""Liberally convert from hex string to binary string."""
import binascii
import re
import binascii
# Remove all non-hexadecimal digits
s = re.sub(r"[^a-fA-F\d]", "", s)
@@ -3539,7 +3539,7 @@ def test_suite(options, args):
assert w == h
# LAn for n < 8 is a special case for which we need to rescale
# the data.
if meta["grayscale"] and meta["alpha"] and meta["bitdepth"] < 8:
if meta["greyscale"] and meta["alpha"] and meta["bitdepth"] < 8:
factor = 255 // (2 ** meta["bitdepth"] - 1)
def rescale(data):
@@ -3556,7 +3556,7 @@ def test_suite(options, args):
if options.test_size:
size = options.test_size
options.bitdepth = options.test_depth
options.grayscale = bool(options.test_black)
options.greyscale = bool(options.test_black)
kwargs = {}
if options.test_red:
@@ -3567,10 +3567,10 @@ def test_suite(options, args):
kwargs["blue"] = options.test_blue
if options.test_alpha:
kwargs["alpha"] = options.test_alpha
if options.grayscale:
if options.greyscale:
if options.test_red or options.test_green or options.test_blue:
raise ValueError(
"cannot specify colors (R, G, B) when grayscale image (black channel, K) is specified"
"cannot specify colours (R, G, B) when greyscale image (black channel, K) is specified"
)
kwargs["red"] = options.test_black
kwargs["green"] = None
@@ -3580,7 +3580,7 @@ def test_suite(options, args):
pixels = test_rgba(size, options.bitdepth, **kwargs)
else:
size, pixels, meta = pngsuite_image(args[0])
for k in ["bitdepth", "alpha", "grayscale"]:
for k in ["bitdepth", "alpha", "greyscale"]:
setattr(options, k, meta[k])
writer = Writer(
@@ -3590,7 +3590,7 @@ def test_suite(options, args):
transparent=options.transparent,
background=options.background,
gamma=options.gamma,
grayscale=options.grayscale,
greyscale=options.greyscale,
alpha=options.alpha,
compression=options.compression,
interlace=options.interlace,
@@ -3764,8 +3764,8 @@ def write_pnm(file, width, height, pixels, meta):
def color_triple(color):
"""
Convert a command line color value to a RGB triple of integers.
FIXME: Somewhere we need support for grayscale backgrounds etc.
Convert a command line colour value to a RGB triple of integers.
FIXME: Somewhere we need support for greyscale backgrounds etc.
"""
if color.startswith("#") and len(color) == 4:
return (int(color[1], 16), int(color[2], 16), int(color[3], 16))
@@ -3781,8 +3781,8 @@ def _main(argv):
"""
# Parse command line arguments
import re
from optparse import OptionParser
import re
version = "%prog " + re.sub(r"( ?\$|URL: |Rev:)", "", __version__)
parser = OptionParser(version=version)
@@ -3807,7 +3807,7 @@ def _main(argv):
action="store",
type="string",
metavar="color",
help="mark the specified color (#RRGGBB) as transparent",
help="mark the specified colour (#RRGGBB) as transparent",
)
parser.add_option(
"-b",
@@ -3815,7 +3815,7 @@ def _main(argv):
action="store",
type="string",
metavar="color",
help="save the specified background color",
help="save the specified background colour",
)
parser.add_option(
"-a",
@@ -3893,7 +3893,7 @@ def _main(argv):
action="store",
type="string",
metavar="pattern",
help="test pattern for grayscale image",
help="test pattern for greyscale image",
)
parser.add_option(
"-d",
@@ -3953,12 +3953,12 @@ def _main(argv):
infile, ("P5", "P6", "P7")
)
# When it comes to the variety of input formats, we do something
# rather rude. Observe that L, LA, RGB, RGBA are the 4 color
# rather rude. Observe that L, LA, RGB, RGBA are the 4 colour
# types supported by PNG and that they correspond to 1, 2, 3, 4
# channels respectively. So we use the number of channels in
# the source image to determine which one we have. We do not
# care about TUPLTYPE.
grayscale = depth <= 2
greyscale = depth <= 2
pamalpha = depth in (2, 4)
supported = (2**x - 1 for x in range(1, 17))
try:
@@ -3971,7 +3971,7 @@ def _main(argv):
writer = Writer(
width,
height,
grayscale=grayscale,
greyscale=greyscale,
bitdepth=bitdepth,
interlace=options.interlace,
transparent=options.transparent,
@@ -9,32 +9,32 @@ 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,
combine_results,
get_test_results,
TEST_RESULTS_START,
)
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,
combine_results,
get_test_results,
TEST_RESULTS_START,
)
import pygame
import pygame.threads
import os
import random
import re
import shutil
import tempfile
import time
from concurrent.futures import ThreadPoolExecutor
import random
from pprint import pformat
import pygame
was_run = False
@@ -74,7 +74,7 @@ def run(*args, **kwds):
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
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
@@ -89,10 +89,10 @@ def run(*args, **kwds):
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
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.
take user input, like cdrom_test.py. 'ignore' and 'subprocess_ignore' for
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.
@@ -233,7 +233,7 @@ def run(*args, **kwds):
from test.test_utils.async_sub import proc_in_time_or_kill
pass_on_args = ["--exclude", ",".join(option_exclude)] + [
f"--{field}"
"--" + field
for field in ("randomize", "incomplete", "unbuffered", "verbosity")
if kwds.get(field)
]
@@ -251,34 +251,41 @@ def run(*args, **kwds):
),
)
with ThreadPoolExecutor(max_workers=option_multi_thread) as executor:
t = time.time()
if option_multi_thread > 1:
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,
}
def tmap(f, args):
return pygame.threads.tmap(
f, args, stop_on_error=False, num_workers=option_multi_thread
)
t = time.time() - t
else:
tmap = map
t = time.time()
for module, cmd, (return_code, raw_return) in tmap(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
@@ -44,7 +44,7 @@ class PygameTestLoader(unittest.TestLoader):
TAGS_RE = re.compile(r"\|[tT]ags:(-?[ a-zA-Z,0-9_\n]+)\|", re.M)
class TheTestTags:
class TestTags:
def __init__(self):
self.memoized = {}
self.parent_modules = {}
@@ -86,4 +86,4 @@ class TheTestTags:
return self.memoized[key]
get_tags = TheTestTags()
get_tags = TestTags()
@@ -1,5 +1,5 @@
import os
import sys
import os
if __name__ == "__main__":
pkg_dir = os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
@@ -30,9 +30,9 @@ def prepare_test_env():
main_dir, test_subdir, fake_test_subdir = prepare_test_env()
################################################################################
# Set the command line options.
# Set the command line options
#
# Options are shared with run_tests.py so make sure not to conflict
# 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_]+"
@@ -56,7 +56,7 @@ opt_parser.add_option(
"-s",
"--usesubprocess",
action="store_true",
help="run everything in a single process (default: use no subprocesses)",
help="run everything in a single process " " (default: use no subprocesses)",
)
opt_parser.add_option(
@@ -240,7 +240,8 @@ 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):
test_results = TEST_RESULTS_RE.search(raw_return)
if test_results:
try:
return eval(test_results.group(1))
except:
@@ -284,17 +285,10 @@ def run_test(
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_tests": results.testsRun,
"num_errors": len(results.errors),
"num_failures": len(results.failures),
}
@@ -1,7 +1,8 @@
import time
import os
import platform
import unittest
import pygame
import time
Clock = pygame.time.Clock
@@ -9,10 +10,6 @@ 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()
@@ -68,6 +65,10 @@ class ClockTypeTest(unittest.TestCase):
c2 = c.get_time()
self.assertAlmostEqual(c1, c2, delta=delta)
@unittest.skipIf(platform.machine() == "s390x", "Fails on s390x")
@unittest.skipIf(
os.environ.get("CI", None), "CI can have variable time slices, slow."
)
def test_get_time(self):
# Testing parameters
delay = 0.1 # seconds
@@ -98,6 +99,10 @@ class ClockTypeTest(unittest.TestCase):
) #'time' module elapsed time converted to milliseconds
self.assertAlmostEqual(d0, c1, delta=delta)
@unittest.skipIf(platform.machine() == "s390x", "Fails on s390x")
@unittest.skipIf(
os.environ.get("CI", None), "CI can have variable time slices, slow."
)
def test_tick(self):
"""Tests time.Clock.tick()"""
"""
@@ -108,7 +113,8 @@ class ClockTypeTest(unittest.TestCase):
"""
# Adjust this value to increase the acceptable sleep jitter
epsilon = 1.5
epsilon = 5 # 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
@@ -244,121 +250,10 @@ class ClockTypeTest(unittest.TestCase):
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()
@unittest.skipIf(platform.machine() == "s390x", "Fails on s390x")
@unittest.skipIf(
os.environ.get("CI", None), "CI can have variable time slices, slow."
)
def test_delay(self):
"""Tests time.delay() function."""
millis = 50 # millisecond to wait on each iteration
@@ -390,6 +285,10 @@ class TimeModuleTest(unittest.TestCase):
# Assert almost equality of the ticking time and time difference
self.assertAlmostEqual(ticks_diff, time_diff, delta=delta)
@unittest.skipIf(platform.machine() == "s390x", "Fails on s390x")
@unittest.skipIf(
os.environ.get("CI", None), "CI can have variable time slices, slow."
)
def test_set_timer(self):
"""Tests time.set_timer()"""
"""
@@ -477,7 +376,7 @@ class TimeModuleTest(unittest.TestCase):
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
@@ -1,38 +1,36 @@
import os
import unittest
import os
import pygame
from pygame._sdl2 import touch
from pygame.tests.test_utils import question
has_touchdevice = touch.get_num_devices() > 0
class TouchTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
os.environ["SDL_MOUSE_TOUCH_EVENTS"] = "0"
pygame.init()
pygame.display.init()
@classmethod
def tearDownClass(cls):
pygame.quit()
pygame.display.quit()
def test_num_devices(self):
touch.get_num_devices()
@unittest.skipIf(not has_touchdevice, "no touch devices found")
def test_get_device(self):
if touch.get_num_devices() > 0:
touch.get_device(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")
@unittest.skipIf(not has_touchdevice, "no touch devices found")
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))
touch.get_num_fingers(touch.get_device(0))
def test_num_fingers__invalid(self):
self.assertRaises(TypeError, touch.get_num_fingers, "test")
@@ -42,31 +40,22 @@ class TouchTest(unittest.TestCase):
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()
@unittest.skipIf(not has_touchdevice, "no touch devices found")
def test_get_finger(self):
"""ask for touch input and check the dict"""
pygame.display.init()
pygame.font.init()
os.environ["SDL_VIDEO_WINDOW_POS"] = "50,50"
screen = pygame.display.set_mode((1000, 600))
screen = pygame.display.set_mode((800, 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"
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"))
@@ -80,10 +69,7 @@ class TouchInteractiveTest(unittest.TestCase):
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
num_fingers = pygame._sdl2.touch.get_num_fingers(first_device)
if num_fingers > 0:
for finger_index in range(0, num_fingers):
data = pygame._sdl2.touch.get_finger(first_device, finger_index)
@@ -104,6 +90,8 @@ class TouchInteractiveTest(unittest.TestCase):
response = question("Does the finger data seem correct?")
self.assertTrue(response)
pygame.display.quit()
if __name__ == "__main__":
unittest.main()
@@ -1,25 +1,13 @@
import itertools
import unittest
import os
import platform
import unittest
from pygame.tests import test_utils
from pygame.tests.test_utils import example_path
import pygame
import pygame.transform
from pygame.locals import *
from pygame.tests import test_utils
from pygame.tests.test_utils import example_path
def surfaces_have_same_pixels(surf1, surf2):
if surf1.get_size() != surf2.get_size():
return False
for row in range(surf1.get_height()):
for col in range(surf1.get_width()):
if surf1.get_at((col, row)) != surf2.get_at((col, row)):
return False
return True
def show_image(s, images=[]):
@@ -60,7 +48,7 @@ def threshold(
diff_color=(0, 0, 0),
change_return=True,
):
"""given the color it makes return_surf only have areas with the given color."""
"""given the color it makes return_surf only have areas with the given colour."""
width, height = surf.get_width(), surf.get_height()
@@ -93,84 +81,6 @@ def threshold(
return similar
def rgb_to_hsl(rgb):
r, g, b = rgb
r, g, b = r / 255.0, g / 255.0, b / 255.0
max_color = max(r, g, b)
min_color = min(r, g, b)
l = (max_color + min_color) / 2
if max_color == min_color:
s = h = 0
else:
if l < 0.5:
s = (max_color - min_color) / (max_color + min_color)
else:
s = (max_color - min_color) / (2.0 - max_color - min_color)
if r == max_color:
h = (g - b) / (max_color - min_color)
elif g == max_color:
h = 2.0 + (b - r) / (max_color - min_color)
else:
h = 4.0 + (r - g) / (max_color - min_color)
h /= 6.0
h %= 1
return h, s, l
def hsl_to_rgb(hsl):
h, s, l = hsl
if s == 0:
r = g = b = l
else:
def hue_to_rgb(p, q, t):
if t < 0:
t += 1
if t > 1:
t -= 1
if t < 1 / 6:
return p + (q - p) * 6 * t
if t < 1 / 2:
return q
if t < 2 / 3:
return p + (q - p) * (2 / 3 - t) * 6
return p
q = l * (1 + s) if l < 0.5 else l + s - l * s
p = 2 * l - q
r = hue_to_rgb(p, q, h + 1 / 3)
g = hue_to_rgb(p, q, h)
b = hue_to_rgb(p, q, h - 1 / 3)
return int(r * 255), int(g * 255), int(b * 255)
def modify_hsl(h, s, l, dh, ds, dl):
if dh:
h += dh
if h > 1:
h -= 1
elif h < 0:
h += 1
if ds:
s *= 1 + ds
if s > 1:
s = 1
elif s < 0:
s = 0
if dl:
if dl > 0:
l = l * (1 - dl) + dl
else:
l = l * (1 + dl)
if l > 1:
l = 1
elif l < 0:
l = 0
return h, s, l
class TransformModuleTest(unittest.TestCase):
def test_scale__alpha(self):
"""see if set_alpha information is kept."""
@@ -186,48 +96,10 @@ class TransformModuleTest(unittest.TestCase):
self.assertEqual(s.get_alpha(), s3.get_alpha())
self.assertEqual(s.get_alpha(), s2.get_alpha())
def test_scale__palette(self):
"""see if palette information from source is kept.
Test for newsurf_fromsurf regression reported in
https://github.com/pygame-community/pygame-ce/issues/3463"""
s = pygame.Surface((32, 32), depth=8)
s.fill("red", [0, 0, 32, 16])
s.fill("purple", [0, 16, 32, 16])
self.assertTrue(len(s.get_palette()) > 0)
s2 = pygame.transform.scale(s, (64, 64))
self.assertEqual(s.get_palette()[0], s2.get_palette()[0])
self.assertEqual(s.get_at_mapped((0, 0)), s2.get_at_mapped((0, 0)))
self.assertEqual(s.get_at_mapped((0, 17)), s2.get_at_mapped((0, 35)))
# Also test with a custom palette to make sure the output doesn't just
# have a default palette.
s = pygame.Surface((32, 32), depth=8)
s.set_palette(
[
pygame.Color("red"),
pygame.Color("purple"),
pygame.Color("gold"),
pygame.Color("blue"),
pygame.Color("lightgreen"),
]
)
s.fill("red", [0, 0, 32, 16])
s.fill("purple", [0, 16, 32, 16])
self.assertTrue(len(s.get_palette()) > 0)
s2 = pygame.transform.scale(s, (64, 64))
self.assertEqual(s.get_palette()[0], s2.get_palette()[0])
self.assertEqual(s.get_palette(), s2.get_palette())
self.assertEqual(s.get_at_mapped((0, 0)), s2.get_at_mapped((0, 0)))
self.assertEqual(s.get_at_mapped((0, 17)), s2.get_at_mapped((0, 35)))
def test_scale__destination(self):
"""see if the destination surface can be passed in to use."""
s = pygame.Surface((32, 32), depth=32)
s = pygame.Surface((32, 32))
s2 = pygame.transform.scale(s, (64, 64))
s3 = s2.copy()
@@ -248,18 +120,6 @@ class TransformModuleTest(unittest.TestCase):
# the wrong size surface is past in. Should raise an error.
self.assertRaises(ValueError, pygame.transform.smoothscale, s, (33, 64), s3)
alpha_surf = pygame.Surface((64, 64), pygame.SRCALPHA)
pygame.transform.scale(alpha_surf, (32, 32), s)
alpha_surf_weird = pygame.Surface(
(64, 64), pygame.SRCALPHA, 32, (0xFF000000, 0xFF0000, 0xFF00, 0xFF)
)
assert alpha_surf_weird.get_shifts() != alpha_surf.get_shifts()
self.assertRaises(
ValueError, pygame.transform.scale, alpha_surf_weird, (32, 32), s
)
def test_scale__vector2(self):
s = pygame.Surface((32, 32))
s2 = pygame.transform.scale(s, pygame.Vector2(64, 64))
@@ -302,24 +162,10 @@ class TransformModuleTest(unittest.TestCase):
s = pygame.Surface((32, 32))
s.fill((255, 0, 0))
gray_red = pygame.transform.grayscale(s)
self.assertEqual(pygame.transform.average_color(gray_red)[0], 76)
self.assertEqual(pygame.transform.average_color(gray_red)[1], 76)
self.assertEqual(pygame.transform.average_color(gray_red)[2], 76)
green_surf = pygame.Surface((32, 32))
green_surf.fill((0, 255, 0))
gray_green = pygame.transform.grayscale(green_surf)
self.assertEqual(pygame.transform.average_color(gray_green)[0], 150)
self.assertEqual(pygame.transform.average_color(gray_green)[1], 150)
self.assertEqual(pygame.transform.average_color(gray_green)[2], 150)
blue_surf = pygame.Surface((32, 32))
blue_surf.fill((0, 0, 255))
blue_green = pygame.transform.grayscale(blue_surf)
self.assertEqual(pygame.transform.average_color(blue_green)[0], 29)
self.assertEqual(pygame.transform.average_color(blue_green)[1], 29)
self.assertEqual(pygame.transform.average_color(blue_green)[2], 29)
s2 = pygame.transform.grayscale(s)
self.assertEqual(pygame.transform.average_color(s2)[0], 76)
self.assertEqual(pygame.transform.average_color(s2)[1], 76)
self.assertEqual(pygame.transform.average_color(s2)[2], 76)
dest = pygame.Surface((32, 32), depth=32)
pygame.transform.grayscale(s, dest)
@@ -330,16 +176,16 @@ class TransformModuleTest(unittest.TestCase):
dest = pygame.Surface((32, 32), depth=32)
s.fill((34, 12, 65))
pygame.transform.grayscale(s, dest)
self.assertEqual(pygame.transform.average_color(dest)[0], 27)
self.assertEqual(pygame.transform.average_color(dest)[1], 27)
self.assertEqual(pygame.transform.average_color(dest)[2], 27)
self.assertEqual(pygame.transform.average_color(dest)[0], 24)
self.assertEqual(pygame.transform.average_color(dest)[1], 24)
self.assertEqual(pygame.transform.average_color(dest)[2], 24)
dest = pygame.Surface((32, 32), depth=32)
s.fill((123, 123, 123))
pygame.transform.grayscale(s, dest)
self.assertIn(pygame.transform.average_color(dest)[0], [124, 122])
self.assertIn(pygame.transform.average_color(dest)[1], [124, 122])
self.assertIn(pygame.transform.average_color(dest)[2], [124, 122])
self.assertIn(pygame.transform.average_color(dest)[0], [123, 122])
self.assertIn(pygame.transform.average_color(dest)[1], [123, 122])
self.assertIn(pygame.transform.average_color(dest)[2], [123, 122])
s = pygame.Surface((32, 32), depth=24)
s.fill((255, 0, 0))
@@ -357,261 +203,6 @@ class TransformModuleTest(unittest.TestCase):
self.assertEqual(pygame.transform.average_color(dest)[1], 76)
self.assertEqual(pygame.transform.average_color(dest)[2], 72)
super_surf = pygame.Surface((64, 64), depth=32)
super_surf.fill((255, 255, 255))
super_surf.fill((255, 0, 0), pygame.Rect(0, 0, 32, 32))
sub_surf = super_surf.subsurface(pygame.Rect(0, 0, 32, 32))
gray_sub_surf = pygame.transform.grayscale(sub_surf)
self.assertEqual(pygame.transform.average_color(gray_sub_surf)[0], 76)
self.assertEqual(pygame.transform.average_color(gray_sub_surf)[0], 76)
self.assertEqual(pygame.transform.average_color(gray_sub_surf)[0], 76)
def test_hsl_args(self):
"""Ensures transform.hsl() correctly handles incorrect arguments"""
s = pygame.Surface((32, 32))
invalid_surf_args = [
None,
1,
0,
1.0,
0.0,
"1",
[],
{},
set(),
True,
False,
]
invalid_hsl_args = [
None,
"1",
[],
{},
set(),
]
invalid_sl_argsv = [
-2,
-2.0,
2,
2.0,
]
for arg in invalid_surf_args:
with self.assertRaises(TypeError):
pygame.transform.hsl(arg, 0)
with self.assertRaises(TypeError):
pygame.transform.hsl(s, 0, 0, 0, arg)
for arg in invalid_hsl_args:
with self.assertRaises(TypeError):
pygame.transform.hsl(s, arg)
with self.assertRaises(TypeError):
pygame.transform.hsl(s, 0, arg)
with self.assertRaises(TypeError):
pygame.transform.hsl(s, 0, 0, arg)
for arg in invalid_sl_argsv:
with self.assertRaises(ValueError):
pygame.transform.hsl(s, 0, arg)
with self.assertRaises(ValueError):
pygame.transform.hsl(s, 0, 0, arg)
# different sized surfaces
s2 = pygame.Surface((31, 32))
with self.assertRaises(ValueError):
pygame.transform.hsl(s, 0, dest_surface=s2)
# different depths
s2 = pygame.Surface((32, 32), depth=16)
s3 = pygame.Surface((32, 32), depth=24)
with self.assertRaises(ValueError):
pygame.transform.hsl(s, 0, dest_surface=s2)
with self.assertRaises(ValueError):
pygame.transform.hsl(s, 0, dest_surface=s3)
def test_hsl_return_value(self):
"""Ensures transform.hsl() returns a Surface"""
sources = [pygame.Surface((32, 32), depth=d) for d in [16, 24, 32]]
destinations = [pygame.Surface((32, 32), depth=d) for d in [16, 24, 32]]
hsl = pygame.transform.hsl
for src, dst in zip(sources, destinations):
# test that the return value is a surface
self.assertIsInstance(hsl(src, 1), pygame.Surface)
self.assertIsInstance(hsl(src, 1, 0.2), pygame.Surface)
self.assertIsInstance(hsl(src, 1, 0.2, 0.2), pygame.Surface)
# test that the return value is a surface when a destination surface is given
self.assertIsInstance(hsl(src, 1, dest_surface=dst), pygame.Surface)
self.assertIsInstance(hsl(src, 1, 0.2, dest_surface=dst), pygame.Surface)
self.assertIsInstance(
hsl(src, 1, 0.2, 0.2, dest_surface=dst), pygame.Surface
)
# test that the destination surface is returned
self.assertIs(hsl(src, 1, dest_surface=dst), dst)
self.assertIs(hsl(src, 1, 0.2, dest_surface=dst), dst)
self.assertIs(hsl(src, 1, 0.2, 0.12, dest_surface=dst), dst)
# test that the returned surface isn't the source surface
self.assertIsNot(hsl(src, 1), src)
self.assertIsNot(hsl(src, 1, 0.2), src)
self.assertIsNot(hsl(src, 1, 0.2, 0.2), src)
def test_hsl(self):
"""Ensures the hsl() function works correctly, meaning it correctly
modifies the hue, saturation, and lightness of a surface."""
surf = pygame.Surface((1, 1))
dest = pygame.Surface((1, 1))
colors = [
(0, 0, 0),
(255, 255, 255),
(255, 0, 0),
(0, 255, 0),
(0, 0, 255),
(127, 127, 127),
(11, 23, 34),
(1, 0, 1),
]
for color in colors:
for h in range(0, 360, 10):
for s in range(0, 100, 10):
for l in range(0, 100, 10):
surf.fill(color)
ns = s / 100.0
nl = l / 100.0
hsl_surf = pygame.transform.hsl(surf, h, ns, nl)
pygame.transform.hsl(surf, h, ns, nl, dest_surface=dest)
nh = h / 360.0
modified_hsl = modify_hsl(*rgb_to_hsl(color), nh, ns, nl)
expected_rgb = hsl_to_rgb(modified_hsl)
# without destination
actual_rgb = hsl_surf.get_at((0, 0)).rgb
for v1, v2 in zip(expected_rgb, actual_rgb):
self.assertAlmostEqual(v1, v2, delta=1)
# with destination
actual_rgb = dest.get_at((0, 0)).rgb
for v1, v2 in zip(expected_rgb, actual_rgb):
self.assertAlmostEqual(v1, v2, delta=1)
surf = pygame.Surface((1, 1), flags=pygame.SRCALPHA)
dest = pygame.Surface((1, 1), flags=pygame.SRCALPHA)
alpha_colors = [
(0, 0, 0, 0),
(255, 255, 255, 255),
(255, 0, 0, 255),
(0, 255, 0, 255),
(0, 0, 255, 255),
(127, 127, 127, 127),
(11, 23, 34, 255),
(1, 0, 1, 255),
]
for color in alpha_colors:
c_a = color[3]
for h in range(0, 360, 10):
for s in range(0, 100, 10):
for l in range(0, 100, 10):
surf.fill(color)
ns = s / 100.0
nl = l / 100.0
hsl_surf = pygame.transform.hsl(surf, h, ns, nl)
pygame.transform.hsl(surf, h, ns, nl, dest_surface=dest)
nh = h / 360.0
modified_hsl = modify_hsl(*rgb_to_hsl(color[:3]), nh, ns, nl)
expected_rgb = hsl_to_rgb(modified_hsl)
# without destination
actual_color = hsl_surf.get_at((0, 0))
actual_rgb = actual_color.rgb
for v1, v2 in zip(expected_rgb, actual_rgb):
self.assertAlmostEqual(v1, v2, delta=1)
self.assertEqual(c_a, actual_color.a)
# with destination
actual_color = dest.get_at((0, 0))
actual_rgb = actual_color.rgb
for v1, v2 in zip(expected_rgb, actual_rgb):
self.assertAlmostEqual(v1, v2, delta=1)
self.assertEqual(c_a, actual_color.a)
def test_solid_overlay(self):
test_surface = pygame.Surface((20, 20), pygame.SRCALPHA)
test_surface.fill((0, 0, 0, 0))
pygame.draw.rect(test_surface, (0, 0, 0), (10, 10, 10, 10))
surface = pygame.Surface((20, 20), pygame.SRCALPHA)
surface.fill((0, 0, 0, 0))
pygame.draw.rect(surface, (255, 0, 0), (10, 10, 10, 10))
surface = pygame.transform.solid_overlay(surface, (0, 0, 0))
for x in range(20):
for y in range(20):
self.assertEqual(surface.get_at((x, y)), test_surface.get_at((x, y)))
pygame.transform.solid_overlay(surface, (0, 0, 0), surface)
for x in range(20):
for y in range(20):
self.assertEqual(surface.get_at((x, y)), test_surface.get_at((x, y)))
test_surface.fill((0, 0, 0, 0))
pygame.draw.polygon(test_surface, (200, 100, 50), [(0, 0), (4, 4), (4, 2)])
surface.fill((0, 0, 0, 0))
pygame.draw.polygon(surface, (255, 0, 0), [(0, 0), (4, 4), (4, 2)])
surface = pygame.transform.solid_overlay(surface, (200, 100, 50))
for x in range(20):
for y in range(20):
self.assertEqual(surface.get_at((x, y)), test_surface.get_at((x, y)))
def test_solid_overlay_zero_surfaces(self):
# zero surfaces here means surfaces for which one or both of width and height have a value of 0
for size, flags, depth, keep_alpha in itertools.product(
[(0, 0), (0, 1), (0, 42), (1, 0), (42, 0)], # surface size
[pygame.SRCALPHA, 0], # surface flags
[32, 16, None], # surface depth
[True, False], # keep alpha
):
with self.subTest(
size=size, flags=flags, depth=depth, keep_alpha=keep_alpha
):
if depth is None:
surface = pygame.Surface(size, flags=flags)
else:
surface = pygame.Surface(size, flags=flags, depth=depth)
self.assertEqual(
pygame.transform.solid_overlay(
surface,
"white",
keep_alpha=keep_alpha,
).size,
size,
)
def test_grayscale_simd_assumptions(self):
# The grayscale SIMD algorithm relies on the destination surface pitch
# being exactly width * 4 (4 bytes per pixel), for maximum speed.
# This test is here to make sure that assumption is always true.
widths = [1, 5, 6, 23, 54, 233]
for width in widths:
self.assertEqual(
pygame.Surface((width, 1), depth=32).get_pitch(), width * 4
)
def test_threshold__honors_third_surface(self):
# __doc__ for threshold as of Tue 07/15/2008
@@ -981,35 +572,6 @@ class TransformModuleTest(unittest.TestCase):
self.assertEqual(result.get_at((0, 0)), diff_color)
def test_threshold_set_color_24bit(self):
"""set_color channels must round-trip correctly on both RGB24 and BGR24 surfaces.
On little-endian systems, SDL_PIXELFORMAT_RGB24 has Rmask=0xFF (R at byte 0)
and SDL_PIXELFORMAT_BGR24 has Rmask=0xFF0000 (R at byte 2). The old
_set_at_pixels code assumed the_color was always packed 0x00RRGGBB, which
happened to be correct for BGR24 but swapped R and B for RGB24.
"""
masks_and_names = [
((0xFF, 0xFF00, 0xFF0000, 0), "RGB24"),
((0xFF0000, 0xFF00, 0xFF, 0), "BGR24"),
]
set_color = (255, 0, 0)
for masks, name in masks_and_names:
with self.subTest(format=name):
surf = pygame.Surface((4, 4), depth=24, masks=masks)
surf.fill((0, 0, 0))
result = pygame.Surface((4, 4), depth=24, masks=masks)
pygame.transform.threshold(
dest_surface=result,
surface=surf,
search_color=(0, 0, 0),
threshold=(1, 1, 1),
set_color=set_color,
set_behavior=1,
inverse_set=True,
)
self.assertEqual(result.get_at((0, 0))[:3], set_color)
def test_threshold__uneven_colors(self):
(w, h) = size = (16, 16)
@@ -1252,13 +814,6 @@ class TransformModuleTest(unittest.TestCase):
self.assertEqual(dest_surface.get_size(), expected_size)
self.assertEqual(dest_surface.get_flags(), expected_flags)
def test_threshold_all_color_types(self):
s1 = pygame.Surface((32, 32), SRCALPHA, 32)
s2 = pygame.Surface((32, 32), SRCALPHA, 32)
for color in [(0, 255, 0), (255, 0, 0, 0), 0, "blue", pygame.Color("#FFFFFF")]:
pygame.transform.threshold(s1, s2, color, color, color)
def test_laplacian(self):
""" """
@@ -1325,39 +880,6 @@ class TransformModuleTest(unittest.TestCase):
finally:
pygame.display.quit()
def test_laplacian__cross_format(self):
# Regression: laplacian used to map the filtered RGB with the source
# format and write the bytes directly into the destination, which
# swapped channels when the surfaces had the same bytes-per-pixel
# (so the size check passed) but different channel layouts.
SIZE = 32
# RGBA layout for the source (R at the low byte).
s1 = pygame.Surface(
(SIZE, SIZE),
0,
32,
masks=(0xFF, 0xFF00, 0xFF0000, 0xFF000000),
)
s1.fill((10, 10, 70))
pygame.draw.line(s1, (255, 0, 0), (3, 10), (20, 20))
pygame.draw.line(s1, (255, 0, 0), (0, 31), (31, 31))
# BGRA layout for the destination — different channel order.
s2 = pygame.Surface(
(SIZE, SIZE),
0,
32,
masks=(0xFF0000, 0xFF00, 0xFF, 0xFF000000),
)
pygame.transform.laplacian(s1, s2)
# Compare RGB only; the alpha channel is also laplacian-filtered
# and isn't relevant to the channel-order bug under test.
self.assertEqual(s2.get_at((0, 0))[:3], (0, 0, 0))
self.assertEqual(s2.get_at((3, 10))[:3], (255, 0, 0))
self.assertEqual(s2.get_at((0, 31))[:3], (255, 0, 0))
self.assertEqual(s2.get_at((31, 31))[:3], (255, 0, 0))
def test_average_surfaces(self):
""" """
@@ -1588,39 +1110,6 @@ class TransformModuleTest(unittest.TestCase):
for pt, color in gradient:
self.assertTrue(s.get_at(pt) == color)
def test_rotate_after_convert_regression(self):
# Tests a regression found from https://github.com/pygame-community/pygame-ce/pull/3314
# Reported in https://github.com/pygame-community/pygame-ce/issues/3463
pygame.display.set_mode((1, 1))
output1 = pygame.transform.rotate(
pygame.image.load(
os.path.join(
os.path.abspath(os.path.dirname(__file__)),
"../examples/data/alien1.png",
)
).convert_alpha(),
180,
)
output2 = pygame.transform.rotate(
pygame.image.load(
os.path.join(
os.path.abspath(os.path.dirname(__file__)),
"../examples/data/alien1.png",
)
),
180,
).convert_alpha()
for x in range(50):
for y in range(50):
color1 = pygame.Color(output1.get_at((x, y)))
color2 = pygame.Color(output2.get_at((x, y)))
self.assertEqual(color1, color2)
pygame.quit()
def test_scale2x(self):
# __doc__ (as of 2008-06-25) for pygame.transform.scale2x:
@@ -1639,10 +1128,6 @@ class TransformModuleTest(unittest.TestCase):
self.assertEqual(s2.get_rect().size, (64, 64))
def test_scale2xraw(self):
# Even though transform.scale no longer has a special
# case for 2x upscaling, this test validates that the behavior
# is preserved.
w, h = 32, 32
s = pygame.Surface((w, h), pygame.SRCALPHA, 32)
s.fill((0, 0, 0))
@@ -1659,7 +1144,7 @@ class TransformModuleTest(unittest.TestCase):
def test_get_smoothscale_backend(self):
filter_type = pygame.transform.get_smoothscale_backend()
self.assertTrue(filter_type in ["GENERIC", "MMX", "SSE", "SSE2", "NEON"])
self.assertTrue(filter_type in ["GENERIC", "MMX", "SSE"])
# It would be nice to test if a non-generic type corresponds to an x86
# processor. But there is no simple test for this. platform.machine()
# returns process version specific information, like 'i686'.
@@ -1691,9 +1176,8 @@ class TransformModuleTest(unittest.TestCase):
pygame.transform.set_smoothscale_backend(1)
self.assertRaises(TypeError, change)
# Unsupported type, if possible.
if original_type == "GENERIC":
if original_type != "SSE":
def change():
pygame.transform.set_smoothscale_backend("SSE")
@@ -1703,14 +1187,6 @@ class TransformModuleTest(unittest.TestCase):
filter_type = pygame.transform.get_smoothscale_backend()
self.assertEqual(filter_type, original_type)
try:
with self.assertWarns(DeprecationWarning):
pygame.transform.set_smoothscale_backend("MMX")
with self.assertWarns(DeprecationWarning):
pygame.transform.set_smoothscale_backend("SSE")
except ValueError:
pass # Backends not supported on this CPU, also valid
def test_chop(self):
original_surface = pygame.Surface((20, 20))
pygame.draw.rect(original_surface, (255, 0, 0), (0, 0, 10, 10))
@@ -1795,105 +1271,6 @@ class TransformModuleTest(unittest.TestCase):
self.assertEqual(s1.get_rect(), pygame.Rect(0, 0, 0, 0))
self.assertEqual(s2.get_rect(), pygame.Rect(0, 0, 0, 0))
def test_rotozoom_keeps_colorkey(self):
image = pygame.Surface((64, 64))
image.set_colorkey("black")
pygame.draw.circle(image, "red", (32, 32), 32, width=0)
no_rot = pygame.transform.rotozoom(image, 0, 1.1)
self.assertEqual(image.get_colorkey(), no_rot.get_colorkey())
with_rot = pygame.transform.rotozoom(image, 5, 1.1)
self.assertEqual(image.get_colorkey(), with_rot.get_colorkey())
def test_invert(self):
surface = pygame.Surface((10, 10), depth=32)
surface.fill((255, 0, 0))
surface = pygame.transform.invert(surface)
self.assertEqual(surface.get_at((4, 4)), (0, 255, 255, 255))
surface.fill((200, 0, 45))
surface = pygame.transform.invert(surface)
self.assertEqual(surface.get_at((4, 4)), (55, 255, 210, 255))
surface.fill((38, 201, 12))
surface = pygame.transform.invert(surface)
self.assertEqual(surface.get_at((4, 4)), (217, 54, 243, 255))
surface.fill((39, 210, 30))
surface = pygame.transform.invert(surface)
self.assertEqual(surface.get_at((4, 4)), (216, 45, 225, 255))
surface.fill((255, 0, 0))
pygame.transform.invert(surface, surface)
self.assertEqual(surface.get_at((4, 4)), (0, 255, 255, 255))
surface.fill((200, 0, 45))
pygame.transform.invert(surface, surface)
self.assertEqual(surface.get_at((4, 4)), (55, 255, 210, 255))
surface.fill((38, 201, 12))
pygame.transform.invert(surface, surface)
self.assertEqual(surface.get_at((4, 4)), (217, 54, 243, 255))
surface.fill((39, 210, 30))
pygame.transform.invert(surface, surface)
self.assertEqual(surface.get_at((4, 4)), (216, 45, 225, 255))
self.assertRaises(
ValueError, pygame.transform.invert, surface, pygame.Surface((100, 100))
)
self.assertRaises(
ValueError, pygame.transform.invert, surface, pygame.Surface((5, 5))
)
self.assertRaises(
ValueError,
pygame.transform.invert,
surface,
pygame.Surface((10, 10), depth=24),
)
self.assertRaises(
ValueError,
pygame.transform.invert,
surface,
pygame.Surface((10, 10), depth=16),
)
self.assertRaises(
ValueError,
pygame.transform.invert,
surface,
pygame.Surface((10, 10), depth=8),
)
def test_invert__palette(self):
"""see if palette information from source is kept.
Test for newsurf_fromsurf regression reported in
https://github.com/pygame-community/pygame-ce/issues/3463"""
s = pygame.Surface((32, 32), depth=8)
s.set_palette([pygame.Color("orange") for _ in range(256)])
s.set_palette(
[
pygame.Color("red"),
pygame.Color("purple"),
pygame.Color("gold"),
pygame.Color("blue"),
pygame.Color("lightgreen"),
]
)
s.fill("red", [0, 0, 32, 16])
s.fill("blue", [0, 16, 32, 16])
self.assertTrue(len(s.get_palette()) > 0)
s2 = pygame.transform.invert(s)
self.assertEqual(s.get_palette()[0], s2.get_palette()[0])
self.assertEqual(s.get_palette(), s2.get_palette())
self.assertEqual(s2.get_at((0, 0)), pygame.Color("lightgreen"))
self.assertEqual(s2.get_at((0, 17)), pygame.Color("gold"))
def test_smoothscale(self):
"""Tests the stated boundaries, sizing, and color blending of smoothscale function"""
# __doc__ (as of 2008-08-02) for pygame.transform.smoothscale:
@@ -1960,42 +1337,6 @@ class TransformModuleTest(unittest.TestCase):
)
self.assertEqual(smaller_surface.get_size(), (k, 1))
def test_pixelate(self):
"""Test pygame.transform.pixelate"""
# test that pixelating the original with a pixel_size of 1 yields the original back
data_fname = example_path("data")
path = os.path.join(data_fname, "alien3.png")
image = pygame.image.load(path) # Get an indexed surface.
no_change = pygame.transform.pixelate(image, 1)
self.assertTrue(surfaces_have_same_pixels(image, no_change))
# test that pixelating a square image with a pixel_size equal to the side length
# yields a surface of a single color, which is the average of the surf
square = pygame.transform.scale(image, (50, 50))
square_pixelated = pygame.transform.pixelate(square, 50)
square_resized = pygame.transform.scale(
pygame.transform.scale(square, (1, 1)), square.get_size()
)
self.assertTrue(surfaces_have_same_pixels(square_pixelated, square_resized))
# test a variety of arguments raise an exception
for arg in (0, -1):
with self.assertRaises(ValueError, msg=f"Running with pixel_size = {arg}"):
pygame.transform.pixelate(image, arg)
for arg in (-1_000_000_000_000_000_000, 1_000_000_000_000_000_000):
with self.assertRaises(
OverflowError, msg=f"Running with pixel_size = {arg}"
):
pygame.transform.pixelate(image, arg)
for arg in ("one", 1.0, None):
with self.assertRaises(TypeError, msg=f"Running with pixel_size = {arg}"):
pygame.transform.pixelate(image, arg)
class TransformDisplayModuleTest(unittest.TestCase):
def setUp(self):
@@ -2005,146 +1346,9 @@ class TransformDisplayModuleTest(unittest.TestCase):
def tearDown(self):
pygame.display.quit()
def test_blur_indexed_surface(self):
data_fname = example_path("data")
path = os.path.join(data_fname, "alien3.png")
sf = pygame.image.load(path) # Get an indexed surface.
self.assertRaises(ValueError, lambda: pygame.transform.box_blur(sf, 10))
self.assertRaises(ValueError, lambda: pygame.transform.gaussian_blur(sf, 10))
def test_blur_in_place(self):
# When source and destination surfaces are the same,
# A ValueError should be raised.
data_fname = example_path("data")
path = os.path.join(data_fname, "peppers3.tif")
sf = pygame.image.load(path)
sub1 = sf.subsurface((0, 0, 128, 128))
sub2 = sf.subsurface((20, 20, 128, 128))
self.assertRaises(
ValueError, lambda: pygame.transform.box_blur(sf, 10, dest_surface=sf)
)
self.assertRaises(
ValueError, lambda: pygame.transform.box_blur(sub1, 10, dest_surface=sub2)
)
self.assertRaises(
ValueError, lambda: pygame.transform.gaussian_blur(sf, 10, dest_surface=sf)
)
self.assertRaises(
ValueError,
lambda: pygame.transform.gaussian_blur(sub1, 10, dest_surface=sub2),
)
def test_box_blur(self):
data1 = {
(1, 29): (67, 58, 26, 255),
(47, 66): (132, 124, 60, 255),
(84, 103): (139, 87, 51, 255),
(131, 140): (159, 133, 74, 255),
(158, 177): (161, 164, 81, 255),
(195, 214): (168, 137, 71, 255),
(232, 251): (130, 122, 67, 255),
(269, 280): (122, 159, 96, 255),
(306, 325): (113, 156, 84, 255),
(353, 362): (114, 152, 74, 255),
(380, 399): (107, 123, 58, 255),
(417, 436): (123, 90, 53, 255),
(458, 473): (146, 68, 52, 255),
(491, 510): (65, 36, 29, 255),
}
data2 = {
(1, 29): (67, 58, 26, 255),
(47, 66): (132, 124, 60, 255),
(84, 103): (139, 87, 51, 255),
(131, 140): (159, 133, 74, 255),
(158, 177): (161, 164, 81, 255),
(195, 214): (168, 137, 71, 255),
(232, 251): (130, 122, 67, 255),
(269, 280): (122, 159, 96, 255),
(306, 325): (113, 156, 84, 255),
(353, 362): (114, 152, 74, 255),
(380, 399): (107, 123, 58, 255),
(417, 436): (123, 90, 53, 255),
(458, 473): (146, 68, 52, 255),
(491, 510): (65, 36, 29, 255),
}
data_fname = example_path("data")
path = os.path.join(data_fname, "peppers3.tif")
sf = pygame.image.load(path).convert()
sf_b1 = pygame.transform.box_blur(sf, 50)
for pos in data1:
self.assertTrue(sf_b1.get_at(pos) == data1[pos])
sf_b2 = pygame.transform.box_blur(sf, 50, repeat_edge_pixels=False)
for pos in data2:
self.assertTrue(sf_b2.get_at(pos) == data2[pos])
def test_gaussian_blur(self):
data1 = {
(10, 49): (74, 67, 32, 255),
(47, 66): (112, 93, 47, 255),
(84, 103): (141, 104, 57, 255),
(121, 140): (153, 118, 64, 255),
(148, 177): (161, 140, 73, 255),
(195, 214): (162, 137, 72, 255),
(232, 21): (124, 50, 35, 255),
(269, 288): (123, 146, 83, 255),
(306, 325): (118, 154, 85, 255),
(343, 362): (114, 141, 73, 255),
(384, 379): (114, 116, 61, 255),
(417, 436): (121, 78, 47, 255),
(454, 473): (107, 54, 39, 255),
(491, 510): (57, 28, 22, 255),
}
data2 = {
(10, 49): (74, 67, 32, 255),
(47, 66): (112, 93, 47, 255),
(84, 103): (141, 104, 57, 255),
(121, 140): (153, 118, 64, 255),
(148, 177): (161, 140, 73, 255),
(195, 214): (162, 137, 72, 255),
(232, 21): (124, 50, 35, 255),
(269, 288): (123, 146, 83, 255),
(306, 325): (118, 154, 85, 255),
(343, 362): (114, 141, 73, 255),
(384, 379): (114, 116, 61, 255),
(417, 436): (121, 78, 47, 255),
(454, 473): (107, 54, 39, 255),
(491, 510): (57, 28, 22, 255),
}
data_fname = example_path("data")
path = os.path.join(data_fname, "peppers3.tif")
sf = pygame.image.load(path).convert()
sf_b1 = pygame.transform.gaussian_blur(sf, 50)
for pos in data1:
self.assertTrue(sf_b1.get_at(pos) == data1[pos])
sf_b2 = pygame.transform.gaussian_blur(sf, 50, repeat_edge_pixels=False)
for pos in data2:
self.assertTrue(sf_b2.get_at(pos) == data2[pos])
def test_blur_zero_size_surface(self):
surface = pygame.Surface((0, 0))
self.assertEqual(pygame.transform.box_blur(surface, 3).get_size(), (0, 0))
self.assertEqual(pygame.transform.gaussian_blur(surface, 3).get_size(), (0, 0))
surface = pygame.Surface((20, 0))
self.assertEqual(pygame.transform.box_blur(surface, 3).get_size(), (20, 0))
self.assertEqual(pygame.transform.gaussian_blur(surface, 3).get_size(), (20, 0))
surface = pygame.Surface((0, 20))
self.assertEqual(pygame.transform.box_blur(surface, 3).get_size(), (0, 20))
self.assertEqual(pygame.transform.gaussian_blur(surface, 3).get_size(), (0, 20))
def test_flip(self):
"""honors the set_color key on the returned surface from flip."""
image_loaded = pygame.image.load(example_path("data/chimp.webp"))
image_loaded = pygame.image.load(example_path("data/chimp.png"))
image = pygame.Surface(image_loaded.get_size(), 0, 32)
image.blit(image_loaded, (0, 0))
@@ -2188,7 +1392,7 @@ class TransformDisplayModuleTest(unittest.TestCase):
def test_flip_alpha(self):
"""returns a surface with the same properties as the input."""
image_loaded = pygame.image.load(example_path("data/chimp.webp"))
image_loaded = pygame.image.load(example_path("data/chimp.png"))
image_alpha = pygame.Surface(image_loaded.get_size(), pygame.SRCALPHA, 32)
image_alpha.blit(image_loaded, (0, 0))
@@ -2211,22 +1415,6 @@ class TransformDisplayModuleTest(unittest.TestCase):
self.assertEqual(surf.get_at((0, 0)), surf2.get_at((0, 0)))
self.assertEqual(surf2.get_at((0, 0)), (255, 0, 0, 255))
def test_unwanted_rle_not_added(self):
surf = pygame.Surface((16, 16))
surf.fill((255, 0, 0))
surf.set_colorkey((0, 0, 0))
surf.set_alpha(64)
# scale it to the same size (size doesn't matter here)
scaled_surf = pygame.transform.scale(surf, (16, 16))
pygame.Surface((100, 100)).blit(scaled_surf, (0, 0))
self.assertEqual(
surf.get_flags() & pygame.RLEACCEL,
scaled_surf.get_flags() & pygame.RLEACCEL,
)
self.assertEqual(scaled_surf.get_at((8, 8)), (255, 0, 0, 255))
if __name__ == "__main__":
unittest.main()
@@ -1,26 +0,0 @@
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()
@@ -1,29 +1,47 @@
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)
@unittest.skipIf(
not os.path.isfile(pg_header), "Skipping because we cannot find _pygame.h"
)
def test_pg_version_consistency(self):
from pygame import version
pgh_major = -1
pgh_minor = -1
pgh_patch = -1
import re
major_exp_search = re.compile(r"define\s+PG_MAJOR_VERSION\s+([0-9]+)").search
minor_exp_search = re.compile(r"define\s+PG_MINOR_VERSION\s+([0-9]+)").search
patch_exp_search = re.compile(r"define\s+PG_PATCH_VERSION\s+([0-9]+)").search
with open(pg_header) as f:
for line in f:
if pgh_major == -1:
m = major_exp_search(line)
if m:
pgh_major = int(m.group(1))
if pgh_minor == -1:
m = minor_exp_search(line)
if m:
pgh_minor = int(m.group(1))
if pgh_patch == -1:
m = patch_exp_search(line)
if m:
pgh_patch = int(m.group(1))
self.assertEqual(pgh_major, version.vernum[0])
self.assertEqual(pgh_minor, version.vernum[1])
self.assertEqual(pgh_patch, version.vernum[2])
def test_sdl_version(self):
self.assertEqual(len(pygame.version.SDL), 3)
self.assertEqual(tuple(pygame.version.SDL), pygame.get_sdl_version())
from pygame import version
def test_installed_version_and_dunder(self):
self.assertEqual(pygame.__version__, pygame.version.ver)
self.assertEqual(pygame.__version__, version("pygame-ce"))
self.assertEqual(len(version.SDL), 3)
if __name__ == "__main__":
@@ -1,11 +1,8 @@
import platform
import sys
import unittest
import sys
import pygame
from pygame._sdl2 import video
IS_PYPY = "PyPy" == platform.python_implementation()
from pygame._sdl2 import video
class VideoModuleTest(unittest.TestCase):
@@ -24,30 +21,6 @@ class VideoModuleTest(unittest.TestCase):
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()
@@ -1,461 +0,0 @@
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()