All 42 libraries

SugarTesting

Test harness for SugarCraft programs

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

SugarTesting code coverage

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

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()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 Graphics namespace 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

Try the quickstart

API

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
ProgramSimulatorsend(Msg ...$msgs): selfFluent message enqueue
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() / getTempDirSuffix()Protected trait: a private 0700 scratch directory under the system temp dir, created in setUp and removed in tearDown