|
| 1 | +"""Tests for event parsing and handling.""" |
| 2 | + |
| 3 | +from typing import Any, Final |
| 4 | + |
| 5 | +import pytest |
| 6 | + |
| 7 | +import tcod.event |
| 8 | +import tcod.sdl.sys |
| 9 | +from tcod._internal import _check |
| 10 | +from tcod.cffi import ffi, lib |
| 11 | +from tcod.event import KeySym, Modifier, Scancode |
| 12 | + |
| 13 | +EXPECTED_EVENTS: Final = ( |
| 14 | + tcod.event.Quit(), |
| 15 | + tcod.event.KeyDown(scancode=Scancode.A, sym=KeySym.A, mod=Modifier(0), pressed=True), |
| 16 | + tcod.event.KeyUp(scancode=Scancode.A, sym=KeySym.A, mod=Modifier(0), pressed=False), |
| 17 | +) |
| 18 | +"""Events to compare with after passing though the SDL event queue.""" |
| 19 | + |
| 20 | + |
| 21 | +def as_sdl_event(event: tcod.event.Event) -> dict[str, dict[str, Any]]: |
| 22 | + """Convert events into SDL_Event unions using cffi's union format.""" |
| 23 | + match event: |
| 24 | + case tcod.event.Quit(): |
| 25 | + return {"quit": {"type": lib.SDL_EVENT_QUIT}} |
| 26 | + case tcod.event.KeyboardEvent(): |
| 27 | + return { |
| 28 | + "key": { |
| 29 | + "type": (lib.SDL_EVENT_KEY_UP, lib.SDL_EVENT_KEY_DOWN)[event.pressed], |
| 30 | + "scancode": event.scancode, |
| 31 | + "key": event.sym, |
| 32 | + "mod": event.mod, |
| 33 | + "down": event.pressed, |
| 34 | + "repeat": event.repeat, |
| 35 | + } |
| 36 | + } |
| 37 | + raise AssertionError |
| 38 | + |
| 39 | + |
| 40 | +EVENT_PACK: Final = ffi.new("SDL_Event[]", [as_sdl_event(_e) for _e in EXPECTED_EVENTS]) |
| 41 | +"""A custom C array of SDL_Event unions based on EXPECTED_EVENTS.""" |
| 42 | + |
| 43 | + |
| 44 | +def push_events() -> None: |
| 45 | + """Reset the SDL event queue to an expected list of events.""" |
| 46 | + tcod.sdl.sys.init(tcod.sdl.sys.Subsystem.EVENTS) # Ensure SDL event queue is enabled |
| 47 | + |
| 48 | + lib.SDL_PumpEvents() # Clear everything from the queue |
| 49 | + lib.SDL_FlushEvents(lib.SDL_EVENT_FIRST, lib.SDL_EVENT_LAST) |
| 50 | + |
| 51 | + assert _check( # Fill the queue with EVENT_PACK |
| 52 | + lib.SDL_PeepEvents(EVENT_PACK, len(EVENT_PACK), lib.SDL_ADDEVENT, lib.SDL_EVENT_FIRST, lib.SDL_EVENT_LAST) |
| 53 | + ) == len(EVENT_PACK) |
| 54 | + |
| 55 | + |
| 56 | +def test_get_events() -> None: |
| 57 | + push_events() |
| 58 | + assert tuple(tcod.event.get()) == EXPECTED_EVENTS |
| 59 | + |
| 60 | + assert tuple(tcod.event.get()) == () |
| 61 | + assert tuple(tcod.event.wait(timeout=0)) == () |
| 62 | + |
| 63 | + push_events() |
| 64 | + assert tuple(tcod.event.wait()) == EXPECTED_EVENTS |
| 65 | + |
| 66 | + |
| 67 | +def test_event_dispatch() -> None: |
| 68 | + push_events() |
| 69 | + with pytest.deprecated_call(): |
| 70 | + tcod.event.EventDispatch().event_wait(timeout=0) |
| 71 | + push_events() |
| 72 | + with pytest.deprecated_call(): |
| 73 | + tcod.event.EventDispatch().event_get() |
0 commit comments