All 48 libraries

SugarTesting

Test harness for SugarCraft programs

original — no 1:1 Go counterpart testing testing-harness foundation-package

SugarTesting code coverage

The test harness for SugarCraft programs. ProgramSimulator drives a TEA Model with scripted messages and records what it rendered, Assertions and GoldenFile pin the output as byte-exact snapshots, Graphics decodes inline-image streams back to pixels, and TapeRecorder writes VHS .tape scripts for demos. It is an original SugarCraft design, inspired by the Go teatest and golden-file prior art cited under Upstream mapping.

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. It needs PHP 8.3 or newer, sugarcraft/sugar-core, sugarcraft/sugar-cellbuffer and react/event-loop. ext-gd is optional and only needed to materialize pixels in the graphics assertions.

Quickstart

This block is self-contained. The inline counter stands in for a real app's Model, which a real suite would hand to the simulator instead.

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)
    ->addMsgs(...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);

Concepts

A SugarCraft program is a Model with init(), update(Msg): [Model, ?Cmd] and view(). ProgramSimulator runs that loop without a terminal: it queues the messages you send, feeds each one through update(), renders view() after every step, and returns a TestResult. Commands are either executed (the default) or captured with withRealCmdRunner(false) so a test can assert that a command was produced without running it.

Input is modeled as messages, not bytes. ScriptedInput builds the same KeyMsg, MouseMsg, WindowSizeMsg (from resize()) and paste messages a live session produces. When a test needs the real byte path, ScriptedInput::bytes() runs raw terminal input through sugar-core's InputReader.

Snapshots are create-only. A golden file is written once, from a deliberate seeding run, and a later mismatch fails loudly without rewriting the file. To re-baseline, delete the golden and rerun with the update variable set. The same rule applies to the TapeRecorder output: it is generated, never hand-edited.

Tasks

  • Pin a rendered screen. Drive the model with ScriptedInput, then call Assertions::assertGoldenAnsi($golden, $result->view) against a committed golden under fixtures/.
  • Check that a key produced a command. Build the simulator with withRealCmdRunner(false), queue the key with addMsgs(), call run(), then call $result->assertCmdCount(1) or assertCmdContains() on the captured list.
  • Catch render-time mutation. Call Assertions::assertViewIdempotent($model). A second view() must return identical bytes.
  • Test a paste exactly as the runtime sees it. Use ScriptedInput::new()->paste($text). Pasted payloads are sanitized by default, and withSanitizePaste(false) delivers them verbatim.
  • Assert an inline image. Feed a captured Kitty, Sixel or iTerm2 stream to GraphicsAssertions::assertRendersTo() with the expected PixelGrid, or to assertProtocolRoundTrip() to check that decode and re-encode agree.
  • Script a demo. Open a TapeRecorder::to($path), add header(), type(), enter() and sleep() directives, then call save(). CI renders the resulting tape.

API reference

The classes below are the public surface. Each block lists the methods a test typically calls. The full signature table follows the blocks.

ProgramSimulator

Configure first, then queue. Every with*() setter (withRealCmdRunner(), withFakeCmdRunner(), withWindowSize(), withEnvironment(), withColorProfile()) must be called before the first addMsgs(). A later with*() call throws RuntimeException instead of silently discarding the queued messages.

ProgramSimulator::for(Model|Program)Factory: wrap a Program, or a bare Model in a default Program, for deterministic testing.
ProgramSimulator::addMsgs(Msg ...$msgs)Fluent message enqueue. Chain as many addMsgs() calls as the scenario needs.
ProgramSimulator::withRealCmdRunner(bool) / ProgramSimulator::withFakeCmdRunner(Closure)Pass false to capture Cmds without executing them. The fake runner decides the message injected for each Cmd, and execution is otherwise unchanged.
ProgramSimulator::run()Drain the queue and return a TestResult with the model, last view, captured cmds, output and frames. Subscription output is delivered right after the message that triggered it. Messages still queued when a QuitMsg or InterruptMsg halts the drain are skipped and counted in droppedAfterStop. run() can be called again.
ProgramSimulator::withWindowSize() / ProgramSimulator::withEnvironment() / ProgramSimulator::withColorProfile()Arm the startup WindowSizeMsg, EnvMsg and ColorProfileMsg exactly as a real Program dispatches them, before init(). Each returns a clone.

ScriptedInput

ScriptedInput::key() / ScriptedInput::namedKey() / ScriptedInput::enter() / ScriptedInput::arrow() / ScriptedInput::mouse() / ScriptedInput::resize() / ScriptedInput::ticks()Fluent builders for the messages a session produces. build() returns the list, ready to splat into addMsgs().
ScriptedInput::bytes(...$reads)Raw terminal input parsed by sugar-core's real InputReader, one argument per read. Reads are split into 4096-byte chunks like the runtime. Afterwards the runtime's idle recovery applies: a lone ESC becomes an Escape key, and an unterminated paste is closed.
ScriptedInput::paste(content)A bracketed paste sent through bytes(), so the model sees the same PasteStartMsg, PasteEndMsg and PasteMsg sequence as at runtime. Longer pastes arrive in several PasteMsg chunks.
ScriptedInput::withSanitizePaste(bool)Pasted payloads are sanitized by default, as at runtime. Pass false to deliver them verbatim. Call it before bytes().

Assertions and GoldenFile

Assertions::assertGoldenAnsiByte-exact snapshot test against a committed golden file. Set SUGAR_TESTING_UPDATE_GOLDENS=1 to create a missing golden. Creation is one-way, and a mismatch never rewrites the file.
Assertions::assertCellGridCell-by-cell diff for Buffer-based renderers, using the cell-grid schema that the parser validates at the boundary.
Assertions::assertAnsiEqualsByte-exact ANSI comparison with a readable ESC diff.
Assertions::assertViewIdempotentRender-purity check. A second view() must return identical bytes. The model-unchanged leg uses a shallow clone, so nested mutation by reference is out of its reach. Output idempotence is the guarantee.
GoldenFileload() returns null only for a missing file, and unreadable or symlinked goldens throw. create() refuses an existing golden, update() is the deliberate re-baseline, and resolve() keeps fixture paths inside fixtures/.

Graphics stream assertions

GraphicsAssertionsassertRendersTo() 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()Sniffs whether a stream speaks Sixel, Kitty or iTerm2 inline images.
KittyStream / SixelStream / Iterm2StreamPer-protocol decoders that return value objects: KittyImage (PNG payload, placements, z-index), a sixel raster (width, height, palette, grid), and iTerm2 file keys.
PixelGridThe RGBA grid behind every comparison. Constructors are fromRgbGrid() and transparent(). uniformColor() and toGdImage() are the escape hatches, and the latter needs ext-gd.
DecodeLimitsHard caps on hostile streams: raster cells, number digits, decompressed bytes and image pixels. Breaches raise MalformedGraphicsException.

TapeRecorder

TapeRecorder::to(path)Factory: start a script builder whose save() writes the tape to that path.
TapeRecorder::header() / TapeRecorder::type() / TapeRecorder::enter() / TapeRecorder::sleep()Emit the VHS Set directives and the choreography lines. Typed text is escaped, so it can never forge a standalone directive line.
TapeRecorder::resize() / TapeRecorder::comment() / TapeRecorder::line()Resize and # comment directives. line() appends one raw directive verbatim.
TapeRecorder::save()Write the completed .tape file. Nothing is captured from a running program, and there is no playback API.
TapeRecorder::keyMsgToVhs(KeyMsg)Static: maps a decoded key message back to VHS Type syntax, or returns null when unsupported, so scripted sessions turn into directives.

Full signature table

sugar-testing public API — every class, method, and constant named above, verified against the shipped source.
ClassMethodDescription
ProgramSimulatorfor(Model|Program): selfFactory: wrap a Program or a bare Model
ProgramSimulatoraddMsgs(Msg ...$msgs): selfFluent message enqueue; configure with*() before the first call
ProgramSimulatorwithRealCmdRunner(bool): selfPass false to capture Cmds without executing them (the default executes)
ProgramSimulatorwithFakeCmdRunner(\Closure $runner): selfPer-Cmd injected-message hook (execution unchanged)
ProgramSimulatorrun(): TestResultDrain queue, return result
ProgramSimulatorwithWindowSize(int cols, int rows): selfArm the startup WindowSizeMsg (dispatched before init(), like Program)
ProgramSimulatorwithEnvironment(array vars): selfArm the startup EnvMsg (dispatched before init(), like Program)
ProgramSimulatorwithColorProfile(ColorProfile): selfArm the startup ColorProfileMsg — the message color vetoes key off
ScriptedInputnew() / 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
ScriptedInputcount(): int; constants READ_SIZE, PASTE_START, PASTE_ENDQueued message count; the 4096-byte read chunk size and bracketed-paste sentinels
TestResultmodel: objectFinal model after all messages
TestResultview: stringLast view() output
TestResultcmds: list<Closure>Captured commands
TestResultoutput: stringConcatenated view() output across the run plus RawMsg/PrintMsg side-channel writes
TestResultframes: list<string>Every view() render, in order
TestResultdroppedAfterStop: intMessages skipped when a QuitMsg/InterruptMsg ended the drain early
TestResultassertCmdCount(int): void / assertCmdContains(callable, ?string): void / assertNoCmds(): voidCmd-list assertions; failure messages name how many cmds were captured
AssertionsassertGoldenAnsi(string, string): voidGolden file snapshot assertion
AssertionsassertCellGrid(array, Buffer): voidCell-by-cell buffer comparison
AssertionsassertAnsiEquals(string, string): voidByte-exact ANSI diff
AssertionsassertViewIdempotent(Model): voidRender-purity check — view() twice must return identical bytes
GoldenFileload(string): ?stringLoad golden file contents
GoldenFilesave(string, string): voidSave golden file
GoldenFilecreate(string, string): voidOne-time seed write; refuses an existing golden (no-clobber enforced by link semantics)
GoldenFileupdate(string, string): voidDeliberate overwrite — the re-baseline path, stated as intent
GoldenFileresolve(string baseDir, string relative): stringAbsolute path inside baseDir/fixtures; refuses traversal out of the fixtures base
TapeRecorderto(string): selfFactory: start composing the tape saved to that path
TapeRecorderheader(...): selfEmit the VHS Set directives
TapeRecordertype(string): selfAppend a Type directive (escaped)
TapeRecorderenter(): selfAppend an Enter directive
TapeRecordersleep(float): selfAppend a Sleep directive
TapeRecordersave(): voidWrite .tape file
TapeRecorderresize(int cols, int rows): self / comment(string): self / line(string): selfResize and #comment directives; line() appends one raw directive verbatim
TapeRecorderkeyMsgToVhs(KeyMsg): ?stringStatic: map a decoded key back to VHS Type syntax, null when unsupported
Graphics\GraphicsAssertionsassertRendersTo(string, Mode, PixelGrid|array, int tolerance = 0, string message = ''): voidStatic: decode an inline-image stream and compare it to the expected pixels
Graphics\GraphicsAssertionsassertInlineImageDimensions(string, Mode, ?int, ?int): void / assertProtocolRoundTrip(string, Mode): void / renderGrid(string, Mode): PixelGridStatic: dimension checks, decode/re-encode round trip, direct grid access
Graphics\Modeenum Sixel | Kitty | Iterm2; detect(string): selfWhich inline-image protocol a byte stream speaks
Graphics\KittyStreamdecode(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\KittyImagepng(): string / cols() / rows() / action() / id() / number() / zIndex() / format() / compressed() / pixelDimensions(): array / toGdImage()Decoded kitty image: PNG payload plus placement and encoding metadata
Graphics\SixelStreamdecode(string): self; width() / height(): int / palette(): array / grid(): PixelGrid / pixel(int, int): ?array / toGdImage()Sixel raster decoder
Graphics\Iterm2Streamdecode(string): self; command(): string / params(): array / payload(): string / hasPayload(): bool / png(): string / cellsWidth() / cellsHeight(): ?int / toGdImage()iTerm2 inline-file (OSC 1337) decoder
Graphics\PixelGridfromRgbGrid(array): self / transparent(int, int): self; pixel(int, int): ?array / paintedPixels(): array / uniformColor(): ?array / toGdImage()RGBA comparison grid; toGdImage() requires ext-gd
Graphics\DecodeLimitsMAX_RASTER_CELLS / MAX_NUMBER_DIGITS / MAX_DECOMPRESSED_BYTES / MAX_IMAGE_PIXELS; assertMaterializablePng(string, string): voidHostile-input caps shared by the decoders; PNG materialization guard
Graphics\MalformedGraphicsExceptionextends RuntimeExceptionThrown by all three decoders and the limit guards on malformed or over-cap streams
LoopPinpinStableClock(): LoopInterfaceStatic: stop and replace the shared loop so arm-time deadlines compute correctly; process-wide (see README caveats)
LoopPinhasStaleClockRisk(LoopInterface): boolStatic: fail-closed check — StreamSelectLoop is safe; extension-backed and unknown loops are reported at risk
TemporaryDirectoryTraitsetUpTemporaryDirectory() / tearDownTemporaryDirectory() / tempDirPrefix()Protected trait: a private 0700 scratch directory under the system temp dir, created in setUp and removed in tearDown

Only methods declared in sugar-testing/src, or inherited from a parent declared there, are listed. A type that extends a class outside that tree, such as \RuntimeException, does not show the methods of that class.

SugarCraft\Testing

Lang final class

Per-library translation facade for sugar-testing.

LoopPin final class

Pins the shared ReactPHP event loop to an implementation whose timer deadlines stay honest inside a test process.

MethodSummary
static pinStableClock(): LoopInterfacePin the shared loop to a clock-fresh implementation and return it.
static hasStaleClockRisk(LoopInterface $loop): boolWhether a loop computes timer deadlines against a clock that can go stale between the moment it was last refreshed and the moment a timer is armed.

ProgramSimulator final class

Drives a Program (or bare Model) with scripted input, deterministically.

MethodSummary
static new(Model|Program $program): selfFactory — wrap a Program or a bare Model for testing.
static for(Model|Program $program): self
addMsgs(Msg ...$msgs): selfEnqueue messages for the run() cycle, mutating this handle.
withFakeCmdRunner(\Closure $runner): selfInstall a fake runner that decides the message injected for each Cmd.
withRealCmdRunner(bool $execute): selfOpt-out of cmd execution for deterministic capture-only mode.
captureCmds(): selfCapture-only arm in one call: every cmd emitted during the run lands in the result's cmds list but nothing executes — the direct spelling of withRealCmdRunner(false), side-effect-free by construction.
withCmdCapture(\Closure $onCmd): selfCapture without executing AND substitute each cmd's result, in one clone: the pair withFakeCmdRunner($onCmd) + withRealCmdRunner(false). The closure receives the cmd — and only the cmd; it must not invoke it, since nothing here executes — and returns the message to inject in place of whatever the real cmd would have produced.
withFrameCapture(bool $capture = true): selfControl per-frame retention in TestResult::$frames.
withWindowSize(int $cols, int $rows): selfArm the startup WindowSizeMsg (dispatched before init(), like Program).
withEnvironment(array $vars): selfArm the startup EnvMsg (dispatched before init(), like Program).
withColorProfile(ColorProfile $profile): selfArm the startup ColorProfileMsg (dispatched before init(), like Program) — the message candy-top's color veto keys off.
run(): TestResultDrain the message queue, running init/update/view in sequence.

TestResult final readonly class

The result of a ProgramSimulator::run() call.

MethodSummary
__construct(public Model $model, public string $view, public array $cmds, public string $output, public array $frames = [], public int $droppedAfterStop = 0)
assertCmdCount(int $expected): voidAssert the exact number of commands was emitted.
assertCmdContains(callable $filter, ?string $message = null): voidAssert that at least one command matches the given filter.
assertNoCmds(): voidAssert that no commands were emitted.

SugarCraft\Testing\Concerns

FilesystemErrorCapture trait

Runs a filesystem call and captures the diagnostic that call itself raised, instead of reading the process-global error_get_last().

TemporaryDirectoryTrait trait

Provides temporary directory setup and cleanup for tests.

SugarCraft\Testing\Graphics

DecodeLimits final class

Decode budgets shared by the graphics stream decoders.

MethodSummary
static assertMaterializablePng(string $png, string $notImageKey): voidHeader-only budget check to run BEFORE GD materializes an image.

GraphicsAssertions final class

Assertions that decode a terminal graphics stream and compare it to intent.

MethodSummary
static assertRendersTo(string $stream, Mode $mode, PixelGrid|array $expected, int $tolerance = 0, string $message = ''): voidAssert that a stream renders to the expected RGB raster.
static assertInlineImageDimensions(string $stream, Mode $mode, ?int $width, ?int $height, string $message = ''): voidAssert the pixel dimensions the stream renders at (either axis may be null to skip).
static assertProtocolRoundTrip(string $stream, Mode $mode, string $message = ''): voidAssert the stream decodes cleanly and stays internally consistent.
static renderGrid(string $stream, Mode $mode): PixelGrid

Iterm2Stream final class

Byte-level decoder for the iTerm2 inline-image protocol.

MethodSummary
static decode(string $stream): selfDecode the first iTerm2 sequence found in a byte stream.
command(): stringThe OSC command verb, e.g. File or Pop.
params(): array
payload(): stringThe decoded payload bytes (empty for control-only sequences).
hasPayload(): bool
png(): stringThe decoded PNG bytes.
cellsWidth(): ?intDeclared width in character cells (width=).
cellsHeight(): ?intDeclared height in character cells (height=).
pixelDimensions(): arrayThe real pixel size carried by the PNG payload.
toGdImage(): \GdImage

KittyImage final class

One decoded Kitty graphics transmission (a single image or placement).

MethodSummary
static fromTransmit(array $params, string $payload): self
action(): string
id(): ?int
number(): ?int
cols(): ?intDeclared width in character cells (c).
rows(): ?intDeclared height in character cells (r).
pixelWidth(): ?intDeclared pixel width (s).
pixelHeight(): ?intDeclared pixel height (v).
offsetX(): ?int
offsetY(): ?int
zIndex(): ?intThe z stacking index — deliberately NOT a compression flag.
format(): ?stringThe raw f transmission-format value, or null when the sender omitted it.
compressed(): boolWhether the payload was transmitted zlib-compressed (o=z) and already inflated here.
pngPassthrough(): boolWhether the f code declares the payload a complete PNG — f=100 (the upstream code) or f=12 (the synonym accepted alongside it), both listed in PNG_PASSTHROUGH_FORMATS. Orthogonal to compressed(): an f=100,o=z transmit is a PNG that arrived zlib-wrapped and was inflated here.
rawPayload(): stringThe reassembled, decoded payload bytes for this transmit — already zlib-inflated for an o=z image and empty for a data-less placement. Unlike png() this never throws on an empty payload.
hasPayload(): boolWhether this transmit carries image data at all (placements do not).
png(): stringThe image payload bytes for this transmit: a PNG for a PNG-format (f=100/f=12) transmit — arrived plain or o=z-inflated — raw pixel data for an f=24/f=32 transmit.
params(): array
pixelDimensions(): arrayDecode the PNG payload into a GD image and report its real pixel size.
toGdImage(): \GdImage

KittyStream final class

Byte-level decoder for the Kitty graphics protocol.

MethodSummary
static decode(string $stream): selfDecode every Kitty transmit found in a byte stream.
images(): array
image(): KittyImageThe first decoded image.
count(): int
id(): ?int
action(): string
cols(): ?int
rows(): ?int
png(): string

MalformedGraphicsException final class

Thrown when a byte stream cannot be parsed as the graphics protocol it claims.

Mode enum

The terminal graphics protocols a stream can speak.

Cases: Sixel · Kitty · Iterm2

PHP also provides cases(), from() and tryFrom().

MethodSummary
static detect(string $stream): selfSniff the protocol a byte stream speaks from its control introducer.

PixelGrid final class

An immutable RGB raster produced by a graphics decoder.

MethodSummary
static fromRgbGrid(array $pixels): selfBuild a grid from a fully-formed row-major array of RGB triples.
static transparent(int $width, int $height): selfBuild an empty (fully transparent) grid of the given dimensions.
width(): int
height(): int
pixel(int $x, int $y): ?arrayThe RGB triple at (x, y), or null when that cell was never painted.
paintedPixels(): arrayEvery cell that was painted, as a flat list — handy for sampling palettes.
uniformColor(): ?arrayTrue when the whole raster carries a single color, returned as that triple.
toGdImage(): \GdImageMaterialize the grid as a GD truecolor image (alpha for unpainted cells).

SixelStream final class

Byte-level decoder for the Sixel graphics protocol.

MethodSummary
static decode(string $stream): selfDecode a Sixel byte stream (which may be embedded in surrounding text).
width(): int
height(): int
palette(): array
grid(): PixelGrid
pixel(int $x, int $y): ?array
toGdImage(): \GdImage

SugarCraft\Testing\Input

ScriptedInput final readonly class

Builder for sequences of input messages to feed a \SugarCraft\Testing\ProgramSimulator.

MethodSummary
static new(): selfDefault factory.
withSanitizePaste(bool $sanitize): selfMirror \SugarCraft\Core\ProgramOptions::$sanitizePaste for the pastes this script builds. On (the default, as in the runtime) a pasted payload is neutralized by \SugarCraft\Core\Util\Sanitize::untrustedForMarkedFrames(); off, it reaches the model verbatim.
key(string $char, bool $shift = false, bool $ctrl = false, bool $alt = false): selfAppend a character key message.
namedKey(\SugarCraft\Core\KeyType $type, string $rune = '', bool $shift = false, bool $ctrl = false, bool $alt = false): selfAppend a named key message.
enter(): selfAppend pressing Enter.
escape(): selfAppend pressing Escape.
backspace(): selfAppend pressing Backspace.
tab(): selfAppend pressing Tab.
arrow(string $dir, bool $shift = false, bool $ctrl = false, bool $alt = false): selfAppend arrow keys.
ticks(int $count, float $seconds = 1.0, ?callable $factory = null): selfAppend $count tick messages, one per interval of $seconds.
resize(int $cols, int $rows): selfAppend a window resize message.
quit(): selfAppend a quit message.
mouse(\SugarCraft\Core\MouseButton $button, \SugarCraft\Core\MouseAction $action, int $x, int $y): selfAppend a mouse event.
push(Msg $msg): selfAppend an arbitrary message.
build(): arrayReturn the built message sequence.
count(): intReturn the count of messages.
wheel(\SugarCraft\Core\MouseButton $button, int $x, int $y): selfAppend a mouse wheel scroll event.
paste(string $content): selfAppend the messages a terminal paste of $content produces.
bytes(string ...$reads): selfAppend the messages raw terminal input decodes to.
clipboard(string $content, string $selection = 'c'): selfAppend a clipboard message with the given content.
keyboardEnhancements(int $flags): selfAppend a keyboard enhancements reply message.

TickMsg final readonly class

The harness's own tick message.

MethodSummary
__construct(public float $seconds)

SugarCraft\Testing\Snapshot

Assertions final class

Static assertion helpers for terminal snapshot testing.

MethodSummary
static assertViewIdempotent(Model $model): voidAssert that a model's view() is idempotent and side-effect free.
static assertGoldenAnsi(string $goldenPath, string $actual): voidAssert that $actual matches the golden file at $goldenPath.
static golden(string $testFileDir, string $name, string $actual): voidConvenience wrapper over assertGoldenAnsi() for the standard layout: the golden lives in a fixtures directory next to the test file that asserts it.
static assertCellGrid(array $expected, Buffer $actual): voidAssert that $expected matches the Buffer's cell grid — EVERY cell.
static assertAnsiEquals(string $expected, string $actual): voidAssert that $expected and $actual ANSI byte sequences are identical.

GoldenFile final class

Load/save helper for golden ANSI snapshot files.

MethodSummary
static load(string $path): ?stringLoad a golden file's contents.
static save(string $path, string $content): voidWrite content to a golden file (atomic; replaces an existing file).
static create(string $path, string $content): voidCreate a golden file only if it does not already exist (atomic).
static update(string $path, string $content): voidDeliberately replace a golden file (the re-baseline path).
static resolve(string $baseDir, string $relative): stringResolve a fixture-relative path to an absolute path.
static writeFailureReason(int|false $written, ?string $diagnostic, int $expected): stringClassify a failed write for the error message: an int return is a short write (the count says how short — the old is_string() test made that branch dead code), false is a hard failure whose reason comes from the scoped capture. Public so the shape roster is directly testable without failing devices.

GoldenFileExistsException final class

Thrown by GoldenFile::create() when the golden already exists.

SugarCraft\Testing\Tape

TapeRecorder final class

Builds VHS-compatible .tape files for demo-GIF rendering.

MethodSummary
static new(string $outputPath): selfFactory — create a new tape recorder writing to $outputPath.
static to(string $outputPath): self
header(string $theme = 'TokyoNight', int $width = 800, int $height = 480, int $fontSize = 14, ?float $typingSpeed = null): selfWrite the VHS header with theme and dimensions.
type(string $keys): selfRecord literal typed text as a quoted Type directive.
enter(): selfRecord pressing Enter.
sleep(float $seconds): selfRecord a sleep delay.
resize(int $cols, int $rows): selfEmit a resize annotation.
comment(string $comment): selfRecord a comment.
line(string $line): selfAppend an arbitrary line verbatim.
save(): voidFinalize and publish the tape file to disk (atomic).
static keyMsgToVhs(KeyMsg $msg): ?stringConvert a KeyMsg to VHS Type syntax.

Configuration and options

OptionTypeDefaultEffect
SUGAR_TESTING_UPDATE_GOLDENSenv, 1 to armunsetCreates a missing golden on the next assertGoldenAnsi() run. It never rewrites an existing golden.
UPDATE_GOLDENSenv, 1 to armunsetDeprecated legacy alias of the variable above. It is read until the alias is dropped.
ProgramSimulator::withWindowSize()int, intnoneArms the startup WindowSizeMsg, dispatched before init().
ProgramSimulator::withEnvironment()arraynoneArms the startup EnvMsg with the given variables.
ProgramSimulator::withColorProfile()ColorProfilenoneArms the startup ColorProfileMsg, the message that color vetoes read.
ProgramSimulator::withRealCmdRunner()booltruePass false to capture Cmds without executing them.
ScriptedInput::withSanitizePaste()booltrueSanitizes paste payloads as at runtime. Set before bytes().
TestResult::droppedAfterStopintcomputedCount of messages skipped after a QuitMsg or InterruptMsg ended the drain.

Keys and input

The harness has no keymap of its own. A key is a KeyMsg built by ScriptedInput, so the keys a test sends are exactly the keys the model's update() matches. Use key('a', ctrl: true) for modifiers, namedKey() or arrow() for special keys, escape(), backspace(), tab() and quit() as shortcuts, and mouse() and wheel() for pointer input. TestResult::assertCmdCount() and assertNoCmds() check what a key produced.

Theme and color profile

The harness does not style output or define a theme. Themes belong to the model under test. What the harness controls is the color profile the model sees. withColorProfile() arms the startup ColorProfileMsg, so a golden captured under one profile can be reproduced exactly. Pin the profile in every snapshot test that renders color, because the same model emits different SGR bytes under a different profile.

Examples

Both examples run without a terminal and need only composer install in the lib root.

  • examples/program-simulator.php: drives an inline counter with ScriptedInput, prints the final view, the frame count and the captured command count. Run it with php examples/program-simulator.php.
  • examples/tape-recorder.php: builds a VHS tape, prints it, and removes the temporary file it wrote. Run it with php examples/tape-recorder.php. The output includes an escaped Type line, which shows how typed control bytes are handled.

Testing

Run the lib's own suite from its root:

composer install && vendor/bin/phpunit

The suite tests the harness through the same Model contract it simulates. Its fixtures, such as CounterModel and ControlRecorderModel, are small TEA models. tests/bootstrap.php calls LoopPin::pinStableClock() before anything else. Under ext-uv, deadlines are computed against a clock refreshed once per loop iteration, so a timer armed after synchronous idle would already be overdue.

In your own suite, call LoopPin::pinStableClock() from your bootstrap when your tests bound waits with timers on \React\EventLoop\Loop::get(). Use ProgramSimulator for the model and Assertions::assertGoldenAnsi() for the output, and commit the goldens under fixtures/.

Troubleshooting and FAQ

  • The golden is missing and the test fails with "No golden file found". Seed it once with SUGAR_TESTING_UPDATE_GOLDENS=1 and commit the new file. Creation is one-way, so a golden that already exists is never rewritten by this variable.
  • The output changed, the test fails with "Golden file mismatch", and you want the new output. Delete the golden, rerun with the variable set, and review the diff in version control. Do not edit the golden by hand.
  • A timer-based wait times out or fires early on a developer machine. The loop clock is stale. Call LoopPin::pinStableClock() first in the bootstrap. LoopPin::hasStaleClockRisk() reports whether the current loop is at risk.
  • toGdImage() throws in a graphics test. Pixel materialization needs ext-gd. Install the extension, or stay on the stream-level checks such as assertProtocolRoundTrip(), which work without it.
  • assertViewIdempotent() passes but a nested object still changed. The model-unchanged leg uses a shallow clone. The check guarantees identical output on a second render, not deep state purity. Keep render methods free of nested mutation by convention.
  • A message queued after QuitMsg never reached update(). That is intended. The drain stops at the quit, and the skipped count is in TestResult::droppedAfterStop.

Upstream mapping

There is no one-to-one port. The table maps the Go prior art named in the lib's README credits to the SugarCraft classes that take their place.

Upstream (Go)SugarCraft classNotes
charmbracelet/teatestProgramSimulator, ScriptedInput, TestResultDrives a model with scripted messages and captures the final output. The dispatch table mirrors the private dispatch method of Program, and divergences are named in the README.
charmbracelet/x/exp/goldenAssertions::assertGoldenAnsi(), GoldenFileGolden-file snapshots. SugarCraft makes the lifecycle explicit with create-only seeding and a separate re-baseline path.
VHS demo scriptsTapeRecorderBuilds .tape files. CI renders them into GIFs, and the render step lives in candy-vcr rather than upstream VHS.

Architecture

Five parts sit side by side. ProgramSimulator and ScriptedInput form the TEA runner. Assertions and GoldenFile form the snapshot layer, which rejects malformed expectation shapes before comparing. The Graphics namespace decodes Kitty, Sixel and iTerm2 streams into a PixelGrid, with DecodeLimits capping hostile input at every allocation. TapeRecorder is a standalone builder for demo scripts. LoopPin replaces the shared ReactPHP loop with StreamSelectLoop so that timer deadlines are computed at arm time. The simulator's dispatch table is an explicit mirror of the private dispatch method of Program, and the README's "Simulation subset" section is the contract for that mirror.

Changelog and versioning

The package ships no CHANGELOG file. The commit history of sugar-testing/ in the monorepo is the record of changes. The install line above pins the development branch with @dev, so pin a tagged release in your own manifest once one is published.

  • sugar-core: the Model, Msg and Program contract the simulator drives.
  • sugar-cellbuffer: the Buffer that cell-grid assertions compare.
  • sugar-image: consumes the Graphics assertions in its renderer tests.
  • The sugarcraft/sugar-testing package is required in require-dev by 25 sibling packages, so changes here reach most suites.

Source & demos

Try the quickstart