GitHubGet started
Guides

Testing games

NSGo keeps game tests in the same fixed-step and headless paths used by the game. A small unit test checks a rule or system, an nsgotest test drives a loop and view, a replay test protects a complete input run, and a gametest golden test protects pixels. Keep each test deterministic so a failure is reproducible on a developer machine and in CI.

Choose a test by the behavior it protects

Behavior Test entry point What to compare
A component system or rule Ordinary Go test Component values and events after fixed dt steps
Input, menus and a loop nsgotest.Start View state, callbacks and recorded core.DrawOps
A complete player run replay.LoadFile and replay.AssertEndState Deterministic final state from a committed .replay.yaml
Exact 2D drawing gametest.RenderOps and AssertGolden A committed PNG and the generated diff image
Sprite placement or batching gametest.ImageDraws and AssertSameImages Image rectangles, transforms, alpha and clips
A 3D render path without a GPU gpu.NewSoftwareRenderer, nsgotest and package reference tests CPU reference values and golden PNGs
A long run or agent behavior go tool game playtest playtest.report.yaml, metrics, goals and recordings
Whole-world state statedump.Run and statedump.Diff Deterministic YAML state dumps

Test world logic with fixed steps

Construct the world directly and call the system with the same fixed dt as game.Loop. Seed every random stream and assert the state you care about. This keeps the test independent of a window and makes a failure small to diagnose.

func TestDamageSystem(t *testing.T) {
	world := entities.NewWorld()
	player := world.Spawn()
	enemy := world.Spawn()
	entities.Set(world, player, Health{HP: 10})
	entities.Set(world, enemy, ContactDamage{Amount: 3})

	DamageSystem(world, time.Second/60)

	health, _ := entities.Get[Health](world, player)
	if got := health.HP; got != 7 {
		t.Fatalf("health = %d, want 7", got)
	}
}

For procedural behavior, create a random.Stream with a fixed seed and pass it into the system. See Determinism for the rules that keep map iteration, floating-point evaluation and goroutines out of the simulation result.

Test a loop and input with nsgotest

nsgotest mounts the root node without opening a window. Start accepts the same root constructor as the app, Advance moves its test clock and runs display frames, and Find inspects a view by TestID or text. Add TestMain when the package uses platform-owned test setup.

func TestMain(m *testing.M) { nsgotest.Main(m) }

func TestMenuOpens(t *testing.T) {
	app := nsgotest.Start(t, Root, nsgotest.Size(360, 640))
	app.Advance(time.Second / 60)
	app.Find("text:Play")
	ops := app.Find("game-canvas").Ops
	_ = ops
}

Drive an input action through the same input.Actions value the game uses. Trigger injects one fixed-step press, while Step advances edge state. For touch, mouse and gamepad snapshots, use the input helpers described in input. The tutorial has complete loop and input tests.

Test what is drawn

A canvas records core.DrawOp values in nsgotest, and its view's Drawing holds the last frame's. Pass that drawing to gametest.RenderOps for deterministic software rendering, then compare the result with a committed golden PNG. Keep goldens under testdata/golden/ beside the test that owns them.

func TestHUDGolden(t *testing.T) {
	app := nsgotest.Start(t, Root, nsgotest.Size(320, 180))
	app.Advance(time.Second / 60)
	drawing := app.Find("game-canvas").Drawing
	frame := gametest.RenderOps(320, 180, drawing)
	gametest.AssertGolden(t, "hud", frame)
}

A mismatch leaves <name>.got.png and <name>.diff.png beside the golden. The diff dims matching pixels and highlights changed pixels in magenta. Inspect both files before deciding whether a visual change is intentional. Set GOLDEN_DIFF_DIR in CI when the workflow uploads failure images.

Update a golden only after reviewing the rendered change:

go tool nsgo test ./path/to/game -update-golden
# or
UPDATE_GOLDEN=1 go tool nsgo test ./path/to/game

Use a structural image assertion when pixels are too sensitive to test the behavior. gametest.ImageDraws(drawing) sees images from both DrawImageFrom and DrawAtlas, and gametest.AssertSameImages compares their source rectangles, transformed corners, alpha, composite, tint, sampling and clip. Use AssertOpsGolden when starting from draw operations is more convenient than calling RenderOps yourself. See gametest for the complete helper reference.

Test input runs with replays

Record a real or scripted run with replay.NewRecorder, save the result as readable .replay.yaml, and commit the recording under testdata/. The simulation reads an replay.ActionSource, so live play, recording and playback use the same update function.

func TestBossReplay(t *testing.T) {
	rec, err := replay.LoadFile("testdata/boss-bug.replay.yaml")
	if err != nil {
		t.Fatal(err)
	}
	want := SimState{Score: 1200, Cleared: true}
	replay.AssertEndState(t, rec, want, nil, func(seed uint64, src replay.ActionSource) (func(time.Duration), func() SimState) {
		sim := newGameSim(seed)
		return func(dt time.Duration) { sim.Step(src, dt) }, func() SimState { return sim.Snapshot() }
	})
}

Run go tool game replay to play every recording under the directories you give it and to run tests whose names contain Replay. Use replay for editing recordings and diagnosing a step mismatch. Use statedump when the final state is too large to express as one struct.

Effects and 3D without a GPU

Effects that have a CPU reference can be tested without a window or GPU. Build the input frame, call postfx.Chain.Reference or the effect's Reference function, and compare the resulting image with gametest.AssertGolden. The postfx guide shows the reference path and its uniforms.

The 3D packages use the software renderer and CPU equations in their reference tests. render3d compares EvaluateMaterial, ShadePoint and related functions with GPU output and golden PNGs. Use nsgotest.NoGPUCompute when a test must exercise the WebGL 2 and OpenGL ES 3.0 capability profile as well as the full software device. See render3d for the existing reference fixtures.

Bots, long runs and state dumps

Describe a seeded headless run in playtest.yaml and add a playtest_test.go that calls playtest.RunTest. Metrics record events, counters, timers and outcomes. go tool game playtest writes a deterministic playtest.report.yaml and .replay.yaml recordings for each run, so a failing bot run can become a focused replay regression test. The playtest guide documents built-in profiles and goal checks.

For an agent or a test that needs the whole world, run a recording through statedump.Run and compare the canonical YAML with statedump.Diff. A dump includes registered entity components, scene state and game-owned values. It is easier to review than a binary snapshot and isolates the first state line that changed.

Run locally and in CI

Run the package or project under test through the NSGo wrapper:

go tool nsgo test ./pkg/gametest
go tool nsgo test ./...
go tool nsgo check

The wrapper supplies the repository's build tags, linker settings and target checks. CI runs the same Go tests on Depot's Ubuntu and macOS runners, plus the example and template checks. Keep recordings and golden PNGs small, deterministic and checked in. Never regenerate a golden in the normal test command, since an unexpected visual change must fail visibly.

Start with one unit test for new game logic, add a loop or replay test for the player-visible path, and add a golden or structural draw test when the change affects rendering. The focused package guides remain authoritative for API details: gametest, replay, playtest, statedump and Determinism.

Edit this page