1 回答

TA貢獻1827條經(jīng)驗 獲得超8個贊
Pygame 可以響應(yīng)自定義用戶事件,而不是按鍵或鼠標(biāo)事件。這是一個工作代碼,其中pytest將用戶事件發(fā)送到pygame,pygame對其作出反應(yīng)并將響應(yīng)發(fā)送回pytest以進行評估:
#!/usr/bin/env python
"""minimal_pygame.py"""
import pygame
TESTEVENT = pygame.event.custom_type()
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:
? ? ? ? # Hook for testing
? ? ? ? if testing:
? ? ? ? ? ? attr_dict = (yield)
? ? ? ? ? ? test_event = pygame.event.Event(TESTEVENT, attr_dict)
? ? ? ? ? ? pygame.event.post(test_event)
? ? ? ? # Main game loop:
? ? ? ? pygame.time.wait(1000)
? ? ? ? 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
? ? ? ? ? ? # React to TESTEVENTS:
? ? ? ? ? ? if event.type == TESTEVENT:
? ? ? ? ? ? ? ? if event.instruction == "draw_rectangle":
? ? ? ? ? ? ? ? ? ? filled_rect = game_window_sf.fill(pygame.Color("white"), pygame.Rect(50, 50, 50, 50))
? ? ? ? ? ? ? ? ? ? pygame.display.update([filled_rect])
? ? ? ? ? ? ? ? ? ? pygame.time.wait(1000)
? ? ? ? ? ? ? ? ? ? if testing:
? ? ? ? ? ? ? ? ? ? ? ? # Yield the color value of the pixel at (50, 50) back to pytest
? ? ? ? ? ? ? ? ? ? ? ? yield game_window_sf.get_at((50, 50))
? ? pygame.quit()
if __name__ == "__main__":
? ? minimal_pygame()
這是測試代碼:
#!/usr/bin/env python
"""test_minimal_pygame.py"""
import minimal_pygame
import pygame
def pygame_wrapper(coro):
? ? yield from coro
def test_minimal_pygame():
? ? wrap = pygame_wrapper(minimal_pygame.minimal_pygame(testing=True))
? ? wrap.send(None) # prime the coroutine
? ? # Create a dictionary of attributes for the future TESTEVENT
? ? attr_dict = {"instruction": "draw_rectangle"}
? ? response = wrap.send(attr_dict)
? ? assert response == pygame.Color("white")
它有效,但是,pytest作為無狀態(tài)單元測試而不是集成測試的工具,它使 pygame 在獲得第一個響應(yīng)(拆卸測試)后退出。不可能在當(dāng)前的 pygame 會話中繼續(xù)并做更多的測試和斷言。(只需嘗試復(fù)制測試代碼的最后兩行以重新發(fā)送事件,它將失敗。)Pytest 不是將一系列指令注入 pygame 以使其達到前提條件然后執(zhí)行一系列測試的正確工具.
至少這是我從 pygame discord 頻道的人們那里聽到的。對于自動化集成測試,他們建議使用像Cucumber這樣的 BDD 工具(或behave?for python)。
添加回答
舉報