如何从 pytest 测试模块将事件注入到正在运行的 pygame 中?
以下是一个 pygame 的最小示例,它在按下时绘制一个白色矩形并在按下J时退出游戏。Ctrl-Q
#!/usr/bin/env python
"""minimal_pygame.py"""
import pygame
def minimal_pygame(testing: bool=False):
pygame.init()
game_window_sf = pygame.display.set_mode(
size=(400, 300),
)
pygame.display.flip()
game_running = True
while game_running:
# Main game loop:
# the following hook to inject events from pytest does not work:
# if testing:
# test_input = (yield)
# pygame.event.post(test_input)
for event in pygame.event.get():
# React to closing the pygame window:
if event.type == pygame.QUIT:
game_running = False
break
# React to keypresses:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
# distinguish between Q and Ctrl-Q
mods = pygame.key.get_mods()
# End main loop if Ctrl-Q was pressed
if mods & pygame.KMOD_CTRL:
game_running = False
break
# Draw a white square when key J is pressed:
if event.key == pygame.K_j:
filled_rect = game_window_sf.fill(pygame.Color("white"), pygame.Rect(50, 50, 50, 50))
pygame.display.update([filled_rect])
pygame.quit()
if __name__ == "__main__":
minimal_pygame()
我想写一个pytest模块来自动测试它。我读过可以将事件注入 running pygame。在这里我读到yield from允许双向通信,所以我想我必须实现某种钩子以便pygame.events从模块注入pytest,但它并不像我想的那么简单,所以我把它注释掉了。如果我取消注释 下的测试挂钩while game_running,pygame甚至不等待任何输入。
这是 pytest 的测试模块:
#!/usr/bin/env python
"""test_minimal_pygame.py"""
import pygame
import minimal_pygame
def pygame_wrapper(coro):
yield from coro
慕仙森
相关分类