SugarTesting
Test harness for SugarCraft programs
The test harness SugarCraft pioneered: ProgramSimulator for driving SugarCraft apps with scripted input, Assertions for golden-file and cell-grid snapshots, and TapeRecorder for composing VHS demo scripts.
Install
composer require --dev sugarcraft/sugar-testing:@dev
This is a PHPUnit test harness: it belongs in require-dev and must not enter runtime dependencies.
Quickstart
This block runs exactly as copy-pasted — the lib's own test suite executes it as a test.
use SugarCraft\Core\Msg;
use SugarCraft\Core\Msg\KeyMsg;
use SugarCraft\Testing\Input\ScriptedInput;
use SugarCraft\Testing\ProgramSimulator;
use SugarCraft\Testing\Snapshot\Assertions;
use SugarCraft\Testing\Snapshot\GoldenFile;
// The smallest drivable counter — inline so this block is self-contained.
// A real suite hands the simulator its own app's Model (or Program).
$counter = new class implements \SugarCraft\Core\Model {
public function __construct(private int $count = 0)
{
}
public function init(): ?\Closure
{
return null;
}
public function update(Msg $msg): array
{
if ($msg instanceof KeyMsg && $msg->rune === 'a') {
return [new self($this->count + 1), null];
}
return [$this, null];
}
public function view(): string
{
return 'count: ' . $this->count;
}
public function subscriptions(): ?\SugarCraft\Core\Subscriptions
{
return null;
}
};
$result = ProgramSimulator::for($counter)
->send(...ScriptedInput::new()->key('a')->key('q')->build())
->run();
// Real suites COMMIT the golden file; a missing golden then fails loudly (see
// Assertions). The guarded save() below just stands in for that first seeding.
$golden = sys_get_temp_dir() . '/sugar-testing-quickstart.golden';
if (GoldenFile::load($golden) === null) {
GoldenFile::save($golden, $result->view);
}
Assertions::assertGoldenAnsi($golden, $result->view);
ProgramSimulator
for(Model|Program)Factory: wrap a Program, or a bare Model in a default Program, for deterministic testing.
send(Msg)Fluent message enqueue — chain multiple sends.
withFakeCmdRunner()Decide the message injected for each Cmd; the real closure still runs unless you also call withRealCmdRunner(false).
run()Drain the queue, return TestResult with model/view/cmds/output. Subscription output is delivered right after the message that triggered it; messages still queued when a QuitMsg/InterruptMsg halts the drain are skipped and counted in
droppedAfterStop. run() can be called again.withWindowSize() / withEnvironment() / withColorProfile()Arm the startup
WindowSizeMsg/EnvMsg/ColorProfileMsg exactly as a real Program dispatches them — before init(). Each returns a clone.ScriptedInput
key() / namedKey() / enter() / arrow() / mouse() / resize() / ticks()Fluent builders for the messages a session produces;
build() returns the list.bytes(...$reads)Raw terminal input parsed by sugar-core's real
InputReader, one argument per read (split into 4096-byte reads like the runtime), with the runtime's idle recovery afterwards: a lone ESC becomes an Escape key and an unterminated paste is closed.paste(content)A bracketed paste sent through
bytes(), so the model sees the same PasteStartMsg, PasteEndMsg, PasteMsg sequence as at runtime (longer pastes arrive in several PasteMsg chunks).withSanitizePaste(bool)Pasted payloads are sanitized by default, as at runtime; pass
false to deliver them verbatim. Call it before bytes().Assertions
assertGoldenAnsiByte-exact snapshot test — set
SUGAR_TESTING_UPDATE_GOLDENS=1 (legacy alias: UPDATE_GOLDENS=1) to create a missing golden; creation is one-way and a mismatch never rewrites, so to re-baseline, delete the file and rerun with it set.assertCellGridCell-by-cell diff for Buffer-based renderers.
assertAnsiEqualsByte-exact ANSI comparison with readable ESC diff.
assertViewIdempotentRender-purity check — a second
view() must return identical bytes; catches models that mutate state while rendering. The model-unchanged leg uses a shallow clone: nested mutation by reference is out of its reach — output idempotence is the guarantee, not deep-state purity.Graphics stream assertions
GraphicsAssertions
assertRendersTo() decodes a protocol byte stream and compares it to a pixel grid, assertInlineImageDimensions() checks placement and size, assertProtocolRoundTrip() re-encodes what it decoded, renderGrid() exposes the grid directly.Mode::detect()Sniff whether a stream speaks Sixel, Kitty, or iTerm2 inline images.
KittyStream / SixelStream / Iterm2StreamPer-protocol decoders returning value objects —
KittyImage (PNG payload, placements, z-index), sixel raster (width, height, palette, grid), iTerm2 file keys.PixelGridThe RGBA grid behind every comparison:
fromRgbGrid()/transparent() constructors, uniformColor() and toGdImage() escape hatches (ext-gd).DecodeLimitsHard caps on hostile streams — raster cells, number digits, decompressed bytes, image pixels — enforced with
MalformedGraphicsException.TapeRecorder
to(path)Factory: start a script builder whose
save() writes the tape to the given path.header()Write VHS header (theme, font size, width, height).
type() / enter() / sleep()Append the demo's choreography — Type/Enter/Sleep directive lines; nothing is captured from a running program and there is no playback API.
save()Write the completed .tape file.
keyMsgToVhs(KeyMsg)Static: map a decoded key message back to VHS
Type syntax (null when unsupported), so scripted sessions turn into directives.Use it for
- Deterministic Model–Update–View testing — ProgramSimulator drives Programs without real I/O.
- Snapshot regression testing — Golden files for ANSI output.
- Cell-grid assertions — assertCellGrid for Buffer-based renderers.
- Inline-image protocol tests — the
Graphicsnamespace decodes real kitty/sixel/iTerm2 streams to pixel grids with no terminal attached. - Demo script building — TapeRecorder emits VHS-compatible .tape files; CI renders them into GIFs.
- Test-infra hub for 22 sibling packages — incl. sugar-forms and sugar-widgets, which build their test support on it (census: sibling composer.json require/require-dev at commit time).
Source & demos
- Source on GitHub
- Full README
- Test suite
- Original SugarCraft design — no 1:1 Go counterpart.
API
| Class | Method | Description |
|---|---|---|
| ProgramSimulator | for(Model|Program): self | Factory: wrap a Program or a bare Model |
| ProgramSimulator | send(Msg ...$msgs): self | Fluent message enqueue |
| ProgramSimulator | withRealCmdRunner(bool): self | Pass false to capture Cmds without executing them (the default executes) |
| ProgramSimulator | withFakeCmdRunner(\Closure $runner): self | Per-Cmd injected-message hook (execution unchanged) |
| ProgramSimulator | run(): TestResult | Drain queue, return result |
| ProgramSimulator | withWindowSize(int cols, int rows): self | Arm the startup WindowSizeMsg (dispatched before init(), like Program) |
| ProgramSimulator | withEnvironment(array vars): self | Arm the startup EnvMsg (dispatched before init(), like Program) |
| ProgramSimulator | withColorProfile(ColorProfile): self | Arm the startup ColorProfileMsg — the message color vetoes key off |
| ScriptedInput | new() / key(char, shift:, ctrl:, alt:) / namedKey(KeyType, rune, shift:, ctrl:, alt:) / enter() / arrow(dir, shift:, ctrl:, alt:) / escape() / backspace() / tab() / quit() / ticks(count, seconds:, factory:) / resize(cols, rows) / mouse(button, action, x, y) / wheel(button, x, y) / push(Msg) / paste(string) / bytes(string ...$reads) / clipboard(string, selection:) / keyboardEnhancements(flags) / withSanitizePaste(bool) / build(): list<Msg> | Scripted terminal input — the key builders take optional modifier flags; paste payloads are sanitized by default, as at runtime |
| ScriptedInput | count(): int; constants READ_SIZE, PASTE_START, PASTE_END | Queued message count; the 4096-byte read chunk size and bracketed-paste sentinels |
| TestResult | model: object | Final model after all messages |
| TestResult | view: string | Last view() output |
| TestResult | cmds: list<Closure> | Captured commands |
| TestResult | output: string | Concatenated view() output across the run plus RawMsg/PrintMsg side-channel writes |
| TestResult | frames: list<string> | Every view() render, in order |
| TestResult | droppedAfterStop: int | Messages skipped when a QuitMsg/InterruptMsg ended the drain early |
| TestResult | assertCmdCount(int): void / assertCmdContains(callable, ?string): void / assertNoCmds(): void | Cmd-list assertions; failure messages name how many cmds were captured |
| Assertions | assertGoldenAnsi(string, string): void | Golden file snapshot assertion |
| Assertions | assertCellGrid(array, Buffer): void | Cell-by-cell buffer comparison |
| Assertions | assertAnsiEquals(string, string): void | Byte-exact ANSI diff |
| Assertions | assertViewIdempotent(Model): void | Render-purity check — view() twice must return identical bytes |
| GoldenFile | load(string): ?string | Load golden file contents |
| GoldenFile | save(string, string): void | Save golden file |
| GoldenFile | create(string, string): void | One-time seed write; refuses an existing golden (no-clobber enforced by link semantics) |
| GoldenFile | update(string, string): void | Deliberate overwrite — the re-baseline path, stated as intent |
| GoldenFile | resolve(string baseDir, string relative): string | Absolute path inside baseDir/fixtures; refuses traversal out of the fixtures base |
| TapeRecorder | to(string): self | Factory: start composing the tape saved to that path |
| TapeRecorder | header(...): self | Emit the VHS Set directives |
| TapeRecorder | type(string): self | Append a Type directive (escaped) |
| TapeRecorder | enter(): self | Append an Enter directive |
| TapeRecorder | sleep(float): self | Append a Sleep directive |
| TapeRecorder | save(): void | Write .tape file |
| TapeRecorder | resize(int cols, int rows): self / comment(string): self / line(string): self | Resize and #comment directives; line() appends one raw directive verbatim |
| TapeRecorder | keyMsgToVhs(KeyMsg): ?string | Static: map a decoded key back to VHS Type syntax, null when unsupported |
| Graphics\GraphicsAssertions | assertRendersTo(string, Mode, PixelGrid|array, int tolerance = 0, string message = ''): void | Static: decode an inline-image stream and compare it to the expected pixels |
| Graphics\GraphicsAssertions | assertInlineImageDimensions(string, Mode, ?int, ?int): void / assertProtocolRoundTrip(string, Mode): void / renderGrid(string, Mode): PixelGrid | Static: dimension checks, decode/re-encode round trip, direct grid access |
| Graphics\Mode | enum Sixel | Kitty | Iterm2; detect(string): self | Which inline-image protocol a byte stream speaks |
| Graphics\KittyStream | decode(string): self; images(): array; image(): KittyImage; count(): int; id() / action() / cols() / rows() / png() | kitty graphics parser — one or more images carried on the stream |
| Graphics\KittyImage | png(): string / cols() / rows() / action() / id() / number() / zIndex() / format() / compressed() / pixelDimensions(): array / toGdImage() | Decoded kitty image: PNG payload plus placement and encoding metadata |
| Graphics\SixelStream | decode(string): self; width() / height(): int / palette(): array / grid(): PixelGrid / pixel(int, int): ?array / toGdImage() | Sixel raster decoder |
| Graphics\Iterm2Stream | decode(string): self; command(): string / params(): array / payload(): string / hasPayload(): bool / png(): string / cellsWidth() / cellsHeight(): ?int / toGdImage() | iTerm2 inline-file (OSC 1337) decoder |
| Graphics\PixelGrid | fromRgbGrid(array): self / transparent(int, int): self; pixel(int, int): ?array / paintedPixels(): array / uniformColor(): ?array / toGdImage() | RGBA comparison grid; toGdImage() requires ext-gd |
| Graphics\DecodeLimits | MAX_RASTER_CELLS / MAX_NUMBER_DIGITS / MAX_DECOMPRESSED_BYTES / MAX_IMAGE_PIXELS; assertMaterializablePng(string, string): void | Hostile-input caps shared by the decoders; PNG materialization guard |
| Graphics\MalformedGraphicsException | extends RuntimeException | Thrown by all three decoders and the limit guards on malformed or over-cap streams |
| LoopPin | pinStableClock(): LoopInterface | Static: stop and replace the shared loop so arm-time deadlines compute correctly; process-wide (see README caveats) |
| LoopPin | hasStaleClockRisk(LoopInterface): bool | Static: fail-closed check — StreamSelectLoop is safe; extension-backed and unknown loops are reported at risk |
| TemporaryDirectoryTrait | setUpTemporaryDirectory() / tearDownTemporaryDirectory() / getTempDirSuffix() | Protected trait: a private 0700 scratch directory under the system temp dir, created in setUp and removed in tearDown |