modtest

package
v0.4.0-rc.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 20 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package modtest is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package modtest runs TSX/JS game mods headlessly against a fake modding.GameBridge built from a game's modding.Surface (modkit.yaml), without opening a window or launching the host game. Mod authors can write declarative YAML test suites (mod.test.yaml, read by ParseSuite and executed by RunFile or `game mod test`), and Go tests can drive Harness directly to step mods, emit events, seed state, and assert spawns, state writes, emitted events, sounds, logs, and mounted panels.

Index

Examples

Constants

View Source
const (
	// SuiteVersion is the schema version of mod.test.yaml files read by [ParseSuite] and written by [EncodeSuite].
	SuiteVersion = 1

	// SchemaURL is where the JSON Schema of version 1 mod.test.yaml files is published.
	SchemaURL = "https://nsgo.games/schemas/modtest.v1.json"

	// DefaultTestFile is the conventional filename discovered by `game mod test <mod-dir>`.
	DefaultTestFile = "mod.test.yaml"
)

Variables

View Source
var ErrInvalidSuite = errors.New("modtest: invalid mod test suite")

ErrInvalidSuite is returned when a mod.test.yaml file fails parsing or validation.

Functions

func EncodeSuite

func EncodeSuite(s Suite) ([]byte, error)

EncodeSuite validates s and writes deterministic 2-space YAML.

func LoadSurfacePath

func LoadSurfacePath(path string) (modding.Surface, error)

LoadSurfacePath loads a modding.Surface from either a modkit.yaml file path or a kit directory containing modkit.yaml.

Types

type CaseResult

type CaseResult struct {
	Name     string
	Passed   bool
	Failures []string
	Duration time.Duration
}

CaseResult holds the outcome of one TestCase.

type EventExpect

type EventExpect struct {
	Name    string `yaml:"name" json:"name" schema:"required,minLength=1"`
	Payload any    `yaml:"payload,omitempty" json:"payload,omitempty"`
}

EventExpect matches a recorded modding.Event emitted by a mod.

type Expectation

type Expectation struct {
	Failed      *bool              `yaml:"failed,omitempty" json:"failed,omitempty"`
	Spawns      []SpawnExpect      `yaml:"spawns,omitempty" json:"spawns,omitempty"`
	SpawnCount  *int               `yaml:"spawnCount,omitempty" json:"spawnCount,omitempty"`
	Events      []EventExpect      `yaml:"events,omitempty" json:"events,omitempty"`
	EventCount  *int               `yaml:"eventCount,omitempty" json:"eventCount,omitempty"`
	State       map[string]any     `yaml:"state,omitempty" json:"state,omitempty"`
	StateWrites []StateWriteExpect `yaml:"stateWrites,omitempty" json:"stateWrites,omitempty"`
	Sounds      []SoundExpect      `yaml:"sounds,omitempty" json:"sounds,omitempty"`
	Logs        []LogExpect        `yaml:"logs,omitempty" json:"logs,omitempty"`
	Panels      []PanelExpect      `yaml:"panels,omitempty" json:"panels,omitempty"`
}

Expectation asserts the observed outputs of a TestCase.

type Harness

type Harness struct {
	// contains filtered or unexported fields
}

Harness runs one or more mods headlessly against a recording fake modding.GameBridge. Always call Harness.Close when finished.

func New

func New(opts Options) (*Harness, error)

New creates a headless mod test harness configured by opts.

Example
package main

import (
	"fmt"
	"testing/fstest"

	"github.com/nsgo-dev/game/pkg/modding"
	"github.com/nsgo-dev/game/pkg/modding/modtest"
)

func main() {
	surface := modding.Surface{
		Version:      modding.SurfaceVersion,
		Game:         "Example Game",
		GameVersion:  "0.1.0",
		Capabilities: modding.CapReadState | modding.CapWriteState,
		State: []modding.StateKeySpec{
			{Key: "score", Type: "number", Writable: true, Default: 10},
		},
	}

	h, err := modtest.New(modtest.Options{Surface: &surface})
	if err != nil {
		panic(err)
	}
	defer h.Close()

	mods := fstest.MapFS{
		"bonus/mod.yaml": &fstest.MapFile{Data: []byte("manifestVersion: 2\nid: com.example.bonus\nname: Bonus\nversion: 0.1.0\nentry: mod.tsx\ncapabilities: [readState, writeState]\n")},
		"bonus/mod.tsx":  &fstest.MapFile{Data: []byte(`import { onEvent, getState, setState } from "game"; onEvent("pickup", () => { setState("score", ((getState("score") as number) ?? 0) + 5); });`)},
	}
	if _, err := h.LoadFS(mods); err != nil {
		panic(err)
	}
	h.Emit("pickup", nil)
	score, _ := h.State("score")
	fmt.Println(score)
}
Output:
15

func (*Harness) Close

func (h *Harness) Close()

Close unloads all mods and disposes the headless NSGo scope and view tree.

func (*Harness) Emit

func (h *Harness) Emit(name string, payload any)

Emit dispatches a host event to all subscribed mods.

func (*Harness) Events

func (h *Harness) Events() []modding.Event

Events returns a copy of all events emitted by mods via game.emit.

func (*Harness) LoadDir

func (h *Harness) LoadDir(dir string) (modding.ModManifest, error)

LoadDir installs and loads a single mod from dir on disk.

func (*Harness) LoadFS

func (h *Harness) LoadFS(fsys fs.FS) ([]modding.ModManifest, error)

LoadFS discovers and loads all mods from fsys.

func (*Harness) Logs

func (h *Harness) Logs() []modding.LogEntry

Logs returns a copy of all log entries emitted by mods via game.log.

func (*Harness) Manager

func (h *Harness) Manager() *modding.Manager

Manager returns the underlying *modding.Manager.

func (*Harness) Panels

func (h *Harness) Panels(slot string) []modding.Panel

Panels returns the currently mounted TSX panels (filtered by slot when non-empty).

func (*Harness) SetState

func (h *Harness) SetState(key string, value any)

SetState sets a key in the fake bridge's state map (as a host update, without recording a mod StateWrite).

func (*Harness) Sounds

func (h *Harness) Sounds() []modding.SoundRequest

Sounds returns a copy of all game.playSound calls made by mods.

func (*Harness) Spawns

func (h *Harness) Spawns() []modding.SpawnRequest

Spawns returns a copy of all entity spawns requested by mods.

func (*Harness) State

func (h *Harness) State(key string) (any, bool)

State reads a key from the fake bridge's state map.

func (*Harness) StateWrites

func (h *Harness) StateWrites() []StateWrite

StateWrites returns a copy of all game.setState calls made by mods.

func (*Harness) Step

func (h *Harness) Step(count int, dt float64)

Step advances all loaded mods by count fixed steps of dt seconds (defaulting to 1/60 s when dt <= 0).

type LogExpect

type LogExpect struct {
	Equals   string `yaml:"equals,omitempty" json:"equals,omitempty"`
	Contains string `yaml:"contains,omitempty" json:"contains,omitempty"`
}

LogExpect matches a recorded modding.LogEntry.

type Options

type Options struct {
	// Surface, when non-nil, seeds initial state defaults, gameVersion, built-in
	// capability grants, host capabilities, and host modules from the game's kit.
	Surface *modding.Surface
	// GameVersion overrides Surface.GameVersion when non-empty.
	GameVersion string
	// Platform overrides the host platform checked against v2 manifest platforms.
	Platform string
	// InitialState seeds scoped state values on top of Surface.State defaults.
	InitialState map[string]any
	// Grant overrides the built-in capability grant mask when non-nil.
	Grant *modding.Capability
	// GrantHost narrows host capabilities when non-nil.
	GrantHost []string
	// HostModules supplies additional or override Go host modules for testing.
	HostModules []modding.ModModule
	// Limits overrides tsx.DefaultLimits for each mod sandbox.
	Limits *tsx.Limits
}

Options configures a headless Harness.

type PanelExpect

type PanelExpect struct {
	ID   string `yaml:"id" json:"id" schema:"required,minLength=1"`
	Slot string `yaml:"slot,omitempty" json:"slot,omitempty"`
}

PanelExpect matches a currently mounted modding.Panel.

type Report

type Report struct {
	SuiteName string
	Results   []CaseResult
}

Report summarizes all cases executed by RunSuite or RunFile.

func RunFile

func RunFile(testPath string, opts RunOptions) (*Report, error)

RunFile parses the YAML test suite at testPath and executes every test case.

func RunSuite

func RunSuite(baseDir string, suite Suite, opts RunOptions) (*Report, error)

RunSuite executes every test case in suite with paths resolved relative to baseDir.

func (*Report) OK

func (r *Report) OK() bool

OK reports whether every test case in r passed.

func (*Report) String

func (r *Report) String() string

String formats r as a readable test report.

type RunOptions

type RunOptions struct {
	// Surface overrides the kit surface loaded from suite.Kit or KitPath.
	Surface *modding.Surface
	// KitPath overrides suite.Kit (accepting a kit directory or modkit.yaml file).
	KitPath string
	// ModDir overrides suite.Mod when non-empty.
	ModDir string
	// HostModules supplies live Go host modules for mods importing custom modules.
	HostModules []modding.ModModule
}

RunOptions configures RunSuite and RunFile.

type SoundExpect

type SoundExpect struct {
	Name string `yaml:"name" json:"name" schema:"required,minLength=1"`
	Loop *bool  `yaml:"loop,omitempty" json:"loop,omitempty"`
}

SoundExpect matches a recorded modding.SoundRequest.

type SpawnExpect

type SpawnExpect struct {
	Prefab string         `yaml:"prefab" json:"prefab" schema:"required,minLength=1"`
	X      *float64       `yaml:"x,omitempty" json:"x,omitempty"`
	Y      *float64       `yaml:"y,omitempty" json:"y,omitempty"`
	Props  map[string]any `yaml:"props,omitempty" json:"props,omitempty"`
}

SpawnExpect matches a recorded modding.SpawnRequest.

type StateWrite

type StateWrite struct {
	ModID string
	Key   string
	Value any
}

StateWrite records one call to game.setState by a mod.

type StateWriteExpect

type StateWriteExpect struct {
	Key   string `yaml:"key" json:"key" schema:"required,minLength=1"`
	Value any    `yaml:"value" json:"value"`
}

StateWriteExpect matches a recorded StateWrite from game.setState.

type Step

type Step struct {
	Step     *StepTick     `yaml:"step,omitempty" json:"step,omitempty"`
	Emit     *StepEmit     `yaml:"emit,omitempty" json:"emit,omitempty"`
	SetState *StepSetState `yaml:"setState,omitempty" json:"setState,omitempty"`
	Reload   bool          `yaml:"reload,omitempty" json:"reload,omitempty"`
}

Step performs one action inside a TestCase. Exactly one field must be set.

type StepEmit

type StepEmit struct {
	Name    string `yaml:"name" json:"name" schema:"required,minLength=1"`
	Payload any    `yaml:"payload,omitempty" json:"payload,omitempty"`
}

StepEmit sends a host event to loaded mods.

type StepSetState

type StepSetState struct {
	Key   string `yaml:"key" json:"key" schema:"required,minLength=1"`
	Value any    `yaml:"value" json:"value"`
}

StepSetState updates a key in the fake bridge's state map before subsequent steps.

type StepTick

type StepTick struct {
	Count int     `yaml:"count,omitempty" json:"count,omitempty"`
	DT    float64 `yaml:"dt,omitempty" json:"dt,omitempty"`
}

StepTick advances the mod manager by Count fixed steps of DT seconds.

type Suite

type Suite struct {
	Version     int            `yaml:"version" json:"version" schema:"required"`
	Name        string         `yaml:"name" json:"name" schema:"required,minLength=1"`
	Mod         string         `yaml:"mod,omitempty" json:"mod,omitempty"`
	Kit         string         `yaml:"kit,omitempty" json:"kit,omitempty"`
	GameVersion string         `yaml:"gameVersion,omitempty" json:"gameVersion,omitempty"`
	Platform    string         `yaml:"platform,omitempty" json:"platform,omitempty"`
	State       map[string]any `yaml:"state,omitempty" json:"state,omitempty"`
	Cases       []TestCase     `yaml:"cases" json:"cases" schema:"required,minItems=1"`
}

Suite describes a declarative YAML test suite for a mod.

func ParseSuite

func ParseSuite(data []byte) (Suite, error)

ParseSuite parses and strictly validates a mod.test.yaml file.

func (Suite) Validate

func (s Suite) Validate() error

Validate verifies that s is structurally well-formed.

type TestCase

type TestCase struct {
	Name   string         `yaml:"name" json:"name" schema:"required,minLength=1"`
	State  map[string]any `yaml:"state,omitempty" json:"state,omitempty"`
	Steps  []Step         `yaml:"steps,omitempty" json:"steps,omitempty"`
	Expect Expectation    `yaml:"expect,omitempty" json:"expect,omitempty"`
}

TestCase is one isolated scenario inside a Suite.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL