Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
234 changes: 232 additions & 2 deletions src/test/python/preponderous/graphik/grid3d/test_grid3d_view.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""Grid3DView: why it can't start, and a headless render against a golden image.
"""Grid3DView: why it can't start, what it asks of Strata, and a headless
render against a golden image.

The render tests need Strata's Python binding and its library; they skip when
The engine-call tests drive Grid3DView against a fake `strata` module, so
they run everywhere. The render tests need Strata's Python binding and its library; they skip when
Strata can't load here (Grid3DView.open raises Unavailable).
"""

Expand All @@ -9,6 +11,7 @@
import shutil
import subprocess
import sys
import types

import pytest

Expand All @@ -18,8 +21,13 @@
GridBoard,
Grid3DView,
Label,
Light,
Panel,
Piece,
PieceStyle,
Scene,
SceneLimitError,
Shape,
Theme,
Unavailable,
)
Expand All @@ -43,6 +51,228 @@ def test_a_missing_binding_says_how_to_install_it(monkeypatch):
viewModule.loadStrata(platform="linux")


# -- what the view asks of Strata (a fake binding, no GPU needed)


class FakeEngine:
"""Records every call Grid3DView makes on a Strata engine."""

def __init__(self, lib, width, height, surface=None, title=None):
self.lib = lib
self.size = (width, height)
self.surface, self.title = surface, title
self.calls = []
self.events = []

def __getattr__(self, name):
if name.startswith("_"):
raise AttributeError(name)

def record(*args, **kwargs):
self.calls.append((name, args, kwargs))

return record

def poll_event(self):
return self.events.pop(0) if self.events else None

def names(self):
return [name for name, _, _ in self.calls]

def call(self, name):
(found,) = [(args, kwargs) for n, args, kwargs in self.calls if n == name]
return found


class FakeLib:
def __init__(self):
self.loaded = None

def lighting_defaults(self, kind):
return types.SimpleNamespace(kind=kind, shadow_distance=None, fog=None)

def look_at(self, eye, target, **kwargs):
return ("look_at", eye, target, kwargs)


def fakeStrata(engineError=None, loadError=None):
"""A stand-in for the `strata` module, with just what view.py uses."""
strata = types.ModuleType("strata")
strata.lib = FakeLib()
strata.EVENT_QUIT, strata.EVENT_KEY_DOWN = "quit", "key-down"
strata.EVENT_KEY_UP, strata.EVENT_RESIZED = "key-up", "resized"
strata.SURFACE_HEADLESS, strata.SURFACE_WINDOW = "headless", "window"
strata.LIGHTING_SUN = "sun"
strata.POINT_LIGHT_CAST_SHADOWS = 7
strata.TEXT_SHADOW = "shadow"
strata.PointLight = types.SimpleNamespace
strata.RenderItem = lambda *fields: ("item",) + fields
strata.Rect = lambda *fields: ("rect",) + fields
strata.Text = lambda *fields: ("text",) + fields
strata.engines = []

def load(*version):
if loadError is not None:
raise loadError
strata.lib.loaded = version
return strata.lib

strata.load = lambda: load()
strata.load_release = lambda version: load(version)

def engine(*args, **kwargs):
if engineError is not None:
raise engineError
made = FakeEngine(*args, **kwargs)
strata.engines.append(made)
return made

strata.Engine = engine
return strata


@pytest.fixture
def strata(monkeypatch):
module = fakeStrata()
monkeypatch.setitem(sys.modules, "strata", module)
monkeypatch.setattr(sys, "platform", "linux")
monkeypatch.delenv("STRATA_LIBRARY", raising=False)
monkeypatch.setenv("GALLIUM_DRIVER", "llvmpipe")
monkeypatch.setenv("SDL_VIDEODRIVER", "dummy")
return module


def test_a_release_library_is_loaded_at_the_pinned_version(strata):
module, lib = viewModule.loadStrata()
assert module is strata and lib is strata.lib
assert lib.loaded == (viewModule.STRATA_VERSION,)


def test_strata_library_loads_a_local_build_on_any_system(strata, monkeypatch):
monkeypatch.setenv("STRATA_LIBRARY", "/opt/libstrata.so")
_, lib = viewModule.loadStrata(platform="darwin")
assert lib.loaded == () # strata.load(), not load_release()


def test_a_library_that_fails_to_load_is_unavailable_with_the_reason(monkeypatch):
monkeypatch.setitem(sys.modules, "strata", fakeStrata(loadError=OSError("bad checksum")))
monkeypatch.delenv("STRATA_LIBRARY", raising=False)
monkeypatch.setenv("GALLIUM_DRIVER", "llvmpipe")
with pytest.raises(Unavailable, match="couldn't be loaded: bad checksum"):
viewModule.loadStrata(platform="linux")


def test_open_makes_a_window_and_sets_the_sun(strata):
view = Grid3DView.open(320, 200, "Game")
(engine,) = strata.engines
assert view.engine is engine and view.isWindow
assert (engine.size, engine.surface, engine.title) == ((320, 200), "window", "Game")
(lighting,), _ = engine.call("set_lighting")
assert (lighting.kind, lighting.shadow_distance, lighting.fog) == ("sun", 40.0, 0)
assert engine.call("set_sun_direction") == (((-0.45, 0.85, 0.35),), {})
assert (view.EVENT_QUIT, view.EVENT_RESIZED) == ("quit", "resized")


def test_open_headless_has_no_window_or_title(strata):
view = Grid3DView.open(320, 200, "Game", headless=True)
(engine,) = strata.engines
assert not view.isWindow
assert (engine.surface, engine.title) == ("headless", None)


def test_an_engine_that_cant_open_is_unavailable_with_the_reason(monkeypatch):
monkeypatch.setitem(sys.modules, "strata", fakeStrata(engineError=RuntimeError("no GPU")))
monkeypatch.setattr(sys, "platform", "linux")
monkeypatch.delenv("STRATA_LIBRARY", raising=False)
monkeypatch.setenv("GALLIUM_DRIVER", "llvmpipe")
with pytest.raises(Unavailable, match="no Strata window could be opened: no GPU"):
Grid3DView.open(320, 200)


def test_pieces_and_scenes_need_a_board_first(strata):
view = Grid3DView.open(320, 200)
assert view.pickCell(10, 10) is None
with pytest.raises(RuntimeError, match="setBoard"):
view.setPieces([])
with pytest.raises(RuntimeError, match="setBoard"):
view.scene()
with pytest.raises(RuntimeError, match="setBoard"):
view.camera()


def test_a_cells_screen_position_picks_that_cell_back(strata):
view = Grid3DView.open(400, 300)
view.setBoard(GridBoard(5, 4))
x, y = view.cellScreenPosition(3, 1)
assert view.pickCell(x, y) == (3, 1)
cx, cz = view.board.cellCenter(3, 1)
assert view.projectToScreen((cx, 0.0, cz)) == (x, y)


def test_a_frame_draws_the_scene_through_the_engine(strata):
view = Grid3DView.open(400, 200, clock=lambda: 5.0)
theme = Theme(pieces={"pawn": PieceStyle(SPHERE, (0.9, 0.25, 0.2))})
view.setBoard(GridBoard(4, 3, theme), lights=[
Light((0, 1, 0), (1, 1, 1), 3.0, 2.0, castShadows=True),
Light((1, 1, 0), (1, 0, 0), 4.0, 1.0),
])
view.setPieces([Piece("p", 1, 1, "pawn")])
view.setLabels([Label("score", 4, 6, 12)], [Panel(0, 0, 50, 20)])
scene = view.scene()
engine = view.engine
engine.calls.clear()

view.frame()

assert engine.names() == ["set_camera", "set_point_lights", "begin_frame",
"submit_primitives", "submit_rects", "submit_text",
"end_frame", "present"]
(camera,), _ = engine.call("set_camera")
assert camera[1:3] == (scene.camera.eye, scene.camera.target)
assert camera[3]["aspect"] == 2.0
(lights,), _ = engine.call("set_point_lights")
assert [(l.range, l.intensity, l.flags) for l in lights] == [(3.0, 2.0, 7), (4.0, 1.0, 0)]
assert engine.call("begin_frame") == ((), {"clear_color": scene.clearColor})
(items,), _ = engine.call("submit_primitives")
assert len(items) == len(scene.shapes)
assert engine.call("submit_rects") == (([("rect", 0, 0, 50, 20, Panel(0, 0, 0, 0).color)],), {})
(texts,), _ = engine.call("submit_text")
assert texts == [("text", 4, 6, 12, "shadow", Label("", 0, 0, 0).color, b"score")]


def test_a_scene_without_text_panels_or_camera_skips_them_and_may_not_present(strata):
view = Grid3DView.open(320, 200)
view.drawScene(Scene(shapes=[Shape(SPHERE, (0, 0, 0), (1, 1, 1), (1, 1, 1, 1))]),
present=False)
assert view.engine.names()[2:] == ["set_point_lights", "begin_frame",
"submit_primitives", "end_frame"]


def test_a_scene_over_the_engine_limits_is_refused_before_drawing(strata):
view = Grid3DView.open(320, 200)
engine = view.engine
engine.calls.clear()
with pytest.raises(SceneLimitError):
view.drawScene(Scene(shapes=[Shape(99, (0, 0, 0), (1, 1, 1), (1, 1, 1, 1))]))
assert engine.calls == []


def test_events_are_drained_and_resize_and_close_reach_the_engine(strata):
view = Grid3DView.open(320, 200)
engine = view.engine
engine.events = ["quit", "key-down"]
assert view.pollEvents() == ["quit", "key-down"]
assert view.pollEvents() == []
view.resize(640, 480)
assert (view.width, view.height) == (640, 480)
assert engine.call("resize") == ((640, 480), {})
view.savePng("out.png")
assert engine.call("save_screenshot_png") == (("out.png",), {})
view.close()
view.close() # a second close is a no-op
assert engine.names().count("close") == 1 and view.engine is None


# -- rendering (needs Strata)


Expand Down
Loading