"""Headless regression tests; do not construct Control or touch game saves. Load selected production definitions via AST to avoid the client's circular imports and asset-loading startup. Pixel comparisons use real pygame Surfaces. """ import ast import os from pathlib import Path from types import SimpleNamespace import unittest from unittest.mock import Mock os.environ.setdefault("SDL_VIDEODRIVER", "dummy") os.environ.setdefault("SDL_AUDIODRIVER", "dummy") os.environ.setdefault("PYGAME_HIDE_SUPPORT_PROMPT", "1") import numpy as np import pygame from client_local.algo import blender ROOT = Path(__file__).resolve().parents[1] def load_definitions(path, namespace, functions=(), classes=None): tree = ast.parse((ROOT / path).read_text(encoding="utf-8-sig")) nodes = [] for node in tree.body: if isinstance(node, ast.FunctionDef) and node.name in functions: nodes.append(node) elif isinstance(node, ast.ClassDef) and node.name in (classes or {}): methods = classes[node.name] if methods is not None: node.body = [n for n in node.body if isinstance(n, ast.FunctionDef) and n.name in methods] node.bases = [] nodes.append(node) exec(compile(ast.Module(body=nodes, type_ignores=[]), str(ROOT / path), "exec"), namespace) return namespace def pixels(surface): return pygame.image.tobytes(surface, "RGBA") class CountingSurface(pygame.Surface): def __init__(self, size): super().__init__(size, pygame.SRCALPHA) self.fills = 0 def fill(self, *args, **kwargs): self.fills += 1 return super().fill(*args, **kwargs) class NameCacheTest(unittest.TestCase): def setUp(self): pygame.font.init() self.flags = SimpleNamespace(DISPLAY_NPC_NAME_CARD=True, DISPLAY_NPC_BLOOD=False) ns = load_definitions( "client_local/sprite/npc.py", {"G": self.flags}, classes={"Npc": {"update_npc_blood_display"}}, ) self.npc = ns["Npc"]() self.npc.chs_name = "Boss" self.npc.remain_blood = 100 self.npc.fake_blood = 2 self.npc.chs_name_font = Mock(wraps=pygame.font.Font(None, 13)) self.npc._name_display_cache_key = None def test_unchanged_name_reuses_both_images_and_alpha(self): npc = self.npc npc.update_npc_blood_display(0) images = (npc.chs_name_text, npc.chs_name_text_shadow) npc.chs_name_text.set_alpha(123) for t in range(100): npc.update_npc_blood_display(t) self.assertEqual(npc.chs_name_font.render.call_count, 2) self.assertIs(npc.chs_name_text, images[0]) self.assertIs(npc.chs_name_text_shadow, images[1]) self.assertEqual(npc.chs_name_text.get_alpha(), 123) def test_name_blood_font_and_visibility_changes(self): npc = self.npc npc.update_npc_blood_display(0) npc.chs_name = "New boss" npc.update_npc_blood_display(0) self.assertEqual(npc.chs_name_font.render.call_count, 4) self.flags.DISPLAY_NPC_BLOOD = True npc.update_npc_blood_display(0) self.assertEqual(npc._name_display_cache_key[1], "98") npc.remain_blood -= 1 npc.update_npc_blood_display(0) self.assertEqual(npc.chs_name_font.render.call_count, 8) self.flags.DISPLAY_NPC_NAME_CARD = False npc.remain_blood = 10 npc.update_npc_blood_display(0) self.assertEqual(npc.chs_name_font.render.call_count, 8) self.flags.DISPLAY_NPC_NAME_CARD = True npc.update_npc_blood_display(0) self.assertEqual(npc._name_display_cache_key[1], "8") npc.chs_name_font = Mock(wraps=pygame.font.Font(None, 15)) npc.update_npc_blood_display(0) self.assertEqual(npc.chs_name_font.render.call_count, 2) self.flags.DISPLAY_NPC_BLOOD = False npc.update_npc_blood_display(0) self.assertEqual(npc._name_display_cache_key[1], "New boss") class BlendClipTest(unittest.TestCase): def test_all_modes_match_full_blend_inside_clip(self): rng = np.random.RandomState(42) source = pygame.surfarray.make_surface(rng.randint(0, 256, (31, 27, 3), dtype=np.uint8)) alpha = rng.randint(0, 256, (31, 27), dtype=np.uint8) for mode in (blender.BLEND_SCREEN, blender.BLEND_MULTIPLY, blender.BLEND_OVERLAY): # Existing overlay uses 2D byte alpha; screen/multiply use expanded alpha. a = alpha if mode == blender.BLEND_OVERLAY else blender.broaden_alpha(alpha) for pos in ((-7, -4), (8, 9), (43, 37), (0, -50), (90, 0)): for clip in (pygame.Rect(7, 6, 25, 23), pygame.Rect(0, 0, 60, 50), pygame.Rect(0, 0, 0, 0)): with self.subTest(mode=mode, pos=pos, clip=clip): base = pygame.surfarray.make_surface(rng.randint(0, 256, (60, 50, 3), dtype=np.uint8)) full = base.copy() blender.blit(source, a, full, pos, mode) expected = base.copy() expected.blit(full, clip, clip) actual = base.copy() actual.set_clip(clip) blender.blit(source, a, actual, pos, mode) self.assertEqual(pixels(expected), pixels(actual)) self.assertFalse(actual.get_locked()) self.assertFalse(source.get_locked()) def test_offscreen_blend_does_not_read_pixels(self): surface = pygame.Surface((50, 50)) surface.set_clip((10, 10, 10, 10)) # Invalid pixel sources would fail if the fast rejection didn't happen. blender.blit(pygame.Surface((5, 5)), None, surface, (30, 30), blender.BLEND_SCREEN) def light(x, y, strength, hidden=False): return SimpleNamespace(x_pos=x, y_pos=y, light=strength, is_hide_sight=lambda: hidden) class WorldRenderTest(unittest.TestCase): def setUp(self): self.flags = SimpleNamespace(MAIN_AREA_X_POS=80, MAIN_AREA_Y_POS=52) masks = {} for i in range(1, 10): radius = i * 20 surface = pygame.Surface((radius * 2, radius * 2), pygame.SRCALPHA) for r in range(radius): distance = radius - r value = 255 - int(255 / radius * distance) pygame.draw.circle(surface, (value,) * 4, (radius, radius), distance) masks[i] = surface self.ns = load_definitions( "client_local/level/level.py", {"pygame": pygame, "G": self.flags, "Y_SCALE_FACTOR": 1, "circleMasks": masks, "MASK_STEP": 20, "_last_light_states": None, "_last_colour_light_states": None}, functions={"_render_light_mask", "get_player_mask", "special_colour_mask"}, classes={"MainArea": None, "Level": {"get_render_view_rect", "apply_light_masks", "refresh_top_update_obstacles", "update"}}, ) self.level = self.ns["Level"]() self.level.top_update_obstacles = [] self.level._visible_top_update_obstacles = () self.ns["current_level"] = self.level self.level.scroll_x_pos = 30 self.level.scroll_y_pos = 40 self.level.main_area = self.ns["MainArea"]((180, 160)) self.level.mask_surface = CountingSurface((80, 52)) self.level.colour_mask_surface = CountingSurface((81, 52)) self.level.bg_light = 47 self.level.rgb_light = [120, 60, 30] self.level.special_rgb = True self.level.haunt_Mode = True self.level.me = light(63.5, 81.2, 1) self.level.npcs = [light(142, 125, 2), light(0.5, 1.5, 3, True)] obstacle = light(20, 40, 2) self.level.obstacle_instances = {(0, 0): obstacle, (0, 1): obstacle} def legacy_blit(self, dest, source, pos, area=None, flags=0): x, y = pos bias = (y - self.level.scroll_y_pos - 26) * (1 - self.ns["Y_SCALE_FACTOR"]) dest.blit(source, (x, int(y - bias)), area, flags) def legacy_lighting(self, dest): cl = self.level if cl.special_rgb: mask = pygame.Surface(dest.get_size(), pygame.SRCALPHA) mask.fill((*[max(0, min(v, 255)) for v in cl.rgb_light], 0)) for p in [cl.me] + cl.npcs + list(cl.obstacle_instances.values()): if p.light: r = p.light * 20 mask.blit(self.ns["circleMasks"][p.light], (p.x_pos-r, p.y_pos-r-15), special_flags=pygame.BLEND_RGBA_ADD) self.legacy_blit(dest, mask, (0, 0), flags=pygame.BLEND_RGBA_MULT) if cl.haunt_Mode: mask = pygame.Surface(dest.get_size(), pygame.SRCALPHA) bgl = max(0, min(cl.bg_light, 255)) mask.fill((bgl, bgl, bgl, 0)) players = [p for p in [cl.me] + cl.npcs if not p.is_hide_sight()] view = pygame.Rect(cl.scroll_x_pos, cl.scroll_y_pos, 80, 52) for p in players + list(cl.obstacle_instances.values()): if p.light: r = p.light * 20 if view.inflate(2*r, 2*(r+15)).collidepoint(p.x_pos, p.y_pos): mask.blit(self.ns["circleMasks"][p.light], (p.x_pos-cl.scroll_x_pos-r, p.y_pos-cl.scroll_y_pos-r-15), special_flags=pygame.BLEND_RGBA_ADD) view = view.clip(dest.get_rect()) if view.w and view.h: self.legacy_blit(dest.subsurface(view), mask, (0, 0), flags=pygame.BLEND_RGBA_MULT) def test_clipped_world_matches_full_render_including_large_sprites_and_quake(self): cl = self.level small = pygame.Surface((17, 23), pygame.SRCALPHA) small.fill((190, 50, 70, 150)) large = pygame.Surface((130, 100), pygame.SRCALPHA) large.fill((20, 100, 230, 90)) for factor in (1, 0.7, 1.2): self.ns["Y_SCALE_FACTOR"] = factor for scroll in ((0, 0), (30.7, 40.3), (100, 108)): cl.scroll_x_pos, cl.scroll_y_pos = scroll expected = pygame.Surface((180, 160)) expected.fill((21, 43, 65)) actual = cl.main_area actual.set_clip(None) actual.fill((21, 43, 65)) actual.set_clip(cl.get_render_view_rect()) for image, pos in ((small, (-10.7, -5.2)), (large, (-40, -20)), (small, (80, 65)), (large, (100, 110)), (small, (150, 10))): self.legacy_blit(expected, image, pos) actual.blit(image, pos) rect = cl.get_render_view_rect() self.assertEqual(pixels(expected.subsurface(rect)), pixels(actual.subsurface(rect))) def test_masks_match_legacy_pixels_at_scroll_edges_and_during_quake(self): cl = self.level for size in ((180, 160), (40, 30)): cl.main_area = self.ns["MainArea"](size) scrolls = ((0, 0),) if size == (40, 30) else ((0, 0), (30.7, 40.3), (100, 108)) for factor in (1, 0.8, 1.2): self.ns["Y_SCALE_FACTOR"] = factor for scroll in scrolls: cl.scroll_x_pos, cl.scroll_y_pos = scroll for colour, haunt in ((True, False), (False, True), (True, True)): with self.subTest(size=size, factor=factor, scroll=scroll, colour=colour, haunt=haunt): cl.special_rgb, cl.haunt_Mode = colour, haunt for _ in range(2): # Repeat also checks simultaneous-mode cache isolation. expected = pygame.Surface(size) expected.fill((200, 180, 130)) self.legacy_lighting(expected) cl.main_area.set_clip(None) cl.main_area.fill((200, 180, 130)) cl.main_area.set_clip(cl.get_render_view_rect()) cl.apply_light_masks() rect = cl.get_render_view_rect() self.assertEqual(pixels(expected.subsurface(rect)), pixels(cl.main_area.subsurface(rect))) def test_mask_cache_reuses_unchanged_pixels_and_invalidates_when_needed(self): cl = self.level cl.main_area.set_clip(cl.get_render_view_rect()) cl.apply_light_masks() for _ in range(10): cl.apply_light_masks() self.assertEqual(cl.mask_surface.fills, 1) self.assertEqual(cl.colour_mask_surface.fills, 1) cl.npcs.append(light(10000, 10000, 1)) cl.apply_light_masks() self.assertEqual(cl.mask_surface.fills, 1) cl.me.x_pos += 3 cl.apply_light_masks() self.assertEqual(cl.mask_surface.fills, 2) cl.bg_light = 55 cl.rgb_light[0] = 90 cl.apply_light_masks() self.assertEqual(cl.mask_surface.fills, 3) self.assertEqual(cl.colour_mask_surface.fills, 3) def test_level_update_keeps_offscreen_logic_and_restores_clip_before_ui(self): cl = self.level self.ns["BombInstance"] = SimpleNamespace(sound_played=True) cl.score_board = cl.time_board = None cl.intro_chat_started = cl.intro_chat_active = True cl.grid_damage_frame = 0 cl.wanderers = [] cl.teammates = [] cl.pets = [] cl.ghosts = [] cl.bomb_instances = [] cl.flame_instances = [] cl.item_instances = {} cl.obstacle_instances_need_to_update = False cl.obstacle_instances_update = [] cl.map_text_triggers = [] cl.transport_obstacle = [] cl._cached_item_count = 0 cl._static_dirty = False cl._static_sorted = [] cl.grid_damage_orientations = set() cl.floor_image = pygame.Surface(cl.main_area.get_size()) cl.floor_image.fill((50, 80, 120)) cl.left_black = pygame.Surface((1, 1)) for name in ("run_earth_quake_effect", "display_frame_rate", "start_ending_sequence_if_needed", "pass_map", "portal_map", "draw_background_png", "update_particles"): setattr(cl, name, Mock()) cl.skill_instances = [SimpleNamespace(update=Mock())] image = pygame.Surface((10, 10), pygame.SRCALPHA) image.fill((220, 110, 20, 128)) def make_actor(x, y): actor = light(x, y, 0) actor.remain_blood = 10 actor.update = Mock() actor.get_y = lambda: y def draw(surface): self.assertEqual(surface.get_clip(), cl.get_render_view_rect()) surface.blit(image, (x, y)) actor.draw = Mock(side_effect=draw) return actor cl.me = make_actor(60, 70) offscreen = make_actor(150, 145) cl.npcs = [offscreen] cl.effects_behind = [make_actor(500, 500)] cl.effects_front = [make_actor(70, 50)] cl.effects_screen = [] cl.draw_dynamic_object = lambda obj: obj.draw(cl.main_area) original_clip = cl.main_area.get_clip() def draw_ui(screen): self.assertEqual(cl.main_area.get_clip(), original_clip) cl.ui_instances_top = [SimpleNamespace(update=Mock(), draw=Mock(side_effect=draw_ui))] cl.ui_instances_bot = [SimpleNamespace(update=Mock(), draw=Mock(side_effect=draw_ui))] screen = pygame.Surface((120, 100)) for scroll in (30, 35, 40): cl.scroll_x_pos = scroll cl.update(screen) self.assertEqual(cl.main_area.get_clip(), original_clip) self.assertEqual(offscreen.update.call_count, 3) self.assertEqual(offscreen.draw.call_count, 3) self.assertEqual(cl.skill_instances[0].update.call_count, 3) self.assertEqual(cl.effects_behind[0].update.call_count, 3) class ClockLifetimeTest(unittest.TestCase): def test_clock_created_once_for_multiple_frames(self): class Finished(Exception): pass clock = Mock() clock.tick.side_effect = [None, None, Finished()] fake_pygame = SimpleNamespace( time=SimpleNamespace(Clock=Mock(return_value=clock)), event=SimpleNamespace(get=lambda: []), display=SimpleNamespace(flip=Mock()), ) ns = load_definitions("client_local/control.py", {"pygame": fake_pygame}, classes={"Control": {"update"}}) control = ns["Control"]() control.current_level = SimpleNamespace(finish_flag=False, custom_finish_flag=False, update=Mock()) control.screen = object() control.description_shown = False control.frame_rate = 60 control.key_pressed = Mock() with self.assertRaises(Finished): control.update() fake_pygame.time.Clock.assert_called_once_with() self.assertEqual(clock.tick.call_count, 3) self.assertEqual(control.current_level.update.call_count, 3) self.assertEqual(fake_pygame.display.flip.call_count, 3) if __name__ == "__main__": unittest.main()