Documentation
¶
Overview ¶
Package tuitest is a headless testing harness for terminal programs. It drives a program under test through a real pseudo-terminal, interprets its output with a VT emulator, and lets tests assert on the resulting screen as a grid of cells rather than as a raw byte stream.
The typical flow: Start (or StartT under go test) spawns the program, SendKeys and Type drive input, the WaitFor family synchronizes on screen state without sleeping, and Snapshot / AssertGolden capture the result. Close (registered automatically by StartT) tears down the whole process group.
Example ¶
Start a program, type into it, wait for its answer, and read the screen.
"gopher" is not on the screen. tuitest turns the PTY's echo off before the program starts, so the screen holds only what the program drew, and a line-oriented program that relies on the terminal to echo its input shows none. A TUI draws its own input, so this only shows up with programs like this one. See docs/limits.md.
package main
import (
"fmt"
"time"
"github.com/Gaurav-Gosain/tuitest"
)
// greeter is a tiny interactive program: it asks for a name and answers.
var greeter = []string{"sh", "-c", `printf 'name? '; read name; printf 'hello, %s\n' "$name"`}
func main() {
term, err := tuitest.Start(greeter, tuitest.WithSize(40, 5))
if err != nil {
fmt.Println(err)
return
}
defer term.Close() //nolint:errcheck
if err := term.WaitForText("name?", 5*time.Second); err != nil {
fmt.Println(err)
return
}
_ = term.SendKeys("gopher", tuitest.Enter)
if err := term.WaitForText("hello, gopher", 5*time.Second); err != nil {
fmt.Println(err)
return
}
code, _ := term.WaitExit(5 * time.Second)
fmt.Println(term.Snapshot())
fmt.Println("exit", code)
}
Output: name? hello, gopher exit 0
Index ¶
- Constants
- Variables
- func Diff(want, got string) string
- func Find(s Screen, substr string) (col, row int, ok bool)
- type Cell
- type ClosedError
- type Color
- type ColorKind
- type EmulatorPanicError
- type ExitStatus
- type Key
- type KeyMods
- type MouseAction
- type MouseButton
- type MouseEncoding
- type MouseEvent
- type Option
- func WithCastDir(dir string) Option
- func WithCellSize(width, height int) Option
- func WithDir(path string) Option
- func WithEnv(kv ...string) Option
- func WithFullTestLog() Option
- func WithInheritEnv() Option
- func WithKillGrace(d time.Duration) Option
- func WithLog(w io.Writer) Option
- func WithOutputMirror(w io.Writer) Option
- func WithSemanticMarkers() Option
- func WithSixel() Option
- func WithSize(cols, rows int) Option
- func WithStabilizeInterval(d time.Duration) Option
- func WithTerm(term string) Option
- func WithTrueColor() Option
- func WithWriteTimeout(d time.Duration) Option
- type Program
- type Scope
- type Screen
- type TermState
- type Terminal
- func (t *Terminal) AssertGolden(tb testing.TB, name string)
- func (t *Terminal) AssertGoldenStyled(tb testing.TB, name string)
- func (t *Terminal) Close() error
- func (t *Terminal) Done() <-chan struct{}
- func (t *Terminal) ExitCode() (int, bool)
- func (t *Terminal) ExitStatus() (ExitStatus, bool)
- func (t *Terminal) InputBytes() int64
- func (t *Terminal) LastCommandExit() (int, bool)
- func (t *Terminal) Paste(s string) error
- func (t *Terminal) Pid() int
- func (t *Terminal) Progress() (bytes int64, last time.Time)
- func (t *Terminal) Resize(cols, rows int) error
- func (t *Terminal) Screen() Screen
- func (t *Terminal) SendKeys(items ...any) error
- func (t *Terminal) SendMouse(ev MouseEvent) error
- func (t *Terminal) Snapshot() string
- func (t *Terminal) SnapshotStyled() string
- func (t *Terminal) TermState() TermState
- func (t *Terminal) Type(s string) error
- func (t *Terminal) Wait(timeout time.Duration) (int, error)deprecated
- func (t *Terminal) WaitExit(timeout time.Duration) (int, error)
- func (t *Terminal) WaitFor(cond func(Screen) bool, timeout time.Duration) error
- func (t *Terminal) WaitForCommand(timeout time.Duration) error
- func (t *Terminal) WaitForDesc(desc string, cond func(Screen) bool, timeout time.Duration) error
- func (t *Terminal) WaitForMatch(re *regexp.Regexp, scope Scope, timeout time.Duration) error
- func (t *Terminal) WaitForOutput(timeout time.Duration) error
- func (t *Terminal) WaitForPrompt(timeout time.Duration) error
- func (t *Terminal) WaitForStable(cond func(Screen) bool, timeout time.Duration) error
- func (t *Terminal) WaitForText(substr string, timeout time.Duration) error
- func (t *Terminal) WaitStable(timeout time.Duration) error
- func (t *Terminal) WriteCast(w io.Writer) error
- type TimeoutError
Examples ¶
Constants ¶
const CastDirEnv = "TUITEST_CAST_DIR"
CastDirEnv names the environment variable that turns on recording for StartT and StartProgramT. When it is set, a terminal whose test fails is written to that directory as an asciicast v2 file. See WithCastDir.
const DefaultStabilizeInterval = 150 * time.Millisecond
DefaultStabilizeInterval is the quiet window WaitStable uses unless overridden.
const DefaultWriteTimeout = 10 * time.Second
DefaultWriteTimeout is how long input may wait for the program to read it, unless WithWriteTimeout sets another limit.
const StartTLogTail = 32 * 1024
StartTLogTail is how many bytes of PTY I/O StartT keeps for the test log.
Variables ¶
var ( // ErrTimeout is wrapped by every wait that runs out of time. ErrTimeout = errors.New("tuitest: timed out") // ErrChildExited is wrapped when the program under test exits before a // wait's condition is met, and by input (Type, SendKeys, Paste, SendMouse, // Resize) that failed because the program has exited. ErrChildExited = errors.New("tuitest: child exited before the condition was met") // ErrSemanticMarkers is wrapped by the OSC 133 waits when the terminal was // started without WithSemanticMarkers. ErrSemanticMarkers = errors.New("tuitest: semantic markers are not enabled (use WithSemanticMarkers)") )
Sentinel errors for the three ways a wait can fail. Every wait returns an error that wraps one of these, so a caller can branch on the kind of failure without type-asserting the concrete error:
if err := term.WaitForText("ready", time.Second); errors.Is(err, tuitest.ErrTimeout) {
// the program is merely slow
}
var ErrEmulatorPanic = errors.New("tuitest: the terminal emulator panicked")
ErrEmulatorPanic is wrapped by every call made on a terminal whose VT emulator panicked while it read the program's output.
Functions ¶
func Diff ¶
Diff returns a compact line-oriented diff of want versus got, the same encoding AssertGolden uses in its failure messages. It is exported so out-of-package golden runners (such as the tape player) can reuse it.
Example ¶
Diff is the line diff AssertGolden prints on a mismatch.
package main
import (
"fmt"
"github.com/Gaurav-Gosain/tuitest"
)
func main() {
fmt.Print(tuitest.Diff("title\nok\n", "title\nfail\n"))
}
Output:
func Find ¶
Find locates the first occurrence of substr on the screen, scanning rows top to bottom, and returns the zero-based cell column and row where it starts. It reports false when no single row contains substr, which includes text that soft-wrapped across two rows.
The column is a cell column, the coordinate SendMouse takes, and not an offset into the row's text. The two differ as soon as anything before the match is not one byte wide: a box-drawing border is three bytes and one cell, a CJK character or an emoji is two cells, so clicking at a byte or rune offset lands to one side of the text.
Types ¶
type Cell ¶
type Cell struct {
// Rune is the cell's first rune. A cell can hold a whole grapheme cluster,
// so this is not always the character a user sees: "e" plus a combining
// acute reports 'e' here. Use Content to compare against text.
Rune rune
// Content is the cell's full grapheme cluster: the base rune together with
// any combining marks, joiners and modifiers that attach to it. It is what
// Line and Text render, and what a caller should match against. Empty for
// the continuation column of a wide rune.
Content string
// Width is 1 for normal runes, 2 for wide runes, and 0 for the
// continuation column that follows a wide rune.
Width int
// Fg and Bg are the foreground and background colors.
Fg, Bg Color
Bold bool
Faint bool
Italic bool
Underline bool
Reverse bool
Strikethrough bool
Blink bool
// Conceal reports SGR 8 (hidden). A real terminal draws a concealed cell as
// a blank, so Line and Text render these cells as spaces; the rune is still
// available here for a caller that needs to know what was concealed.
Conceal bool
}
Cell is a single grid cell with its rune and visual attributes.
type ClosedError ¶
type ClosedError struct {
// Op is the wait that failed, such as "WaitForText".
Op string
// Want describes the condition in words.
Want string
// ExitCode is the child's exit code, or -1 if it could not be determined.
ExitCode int
// Screen is the plain-text screen at the moment of the failure.
Screen string
// TailLog is the tail of the mirrored PTY I/O.
TailLog string
}
ClosedError is returned when the child exits before a wait's condition is met. It unwraps to ErrChildExited.
func (*ClosedError) Error ¶
func (e *ClosedError) Error() string
func (*ClosedError) Unwrap ¶
func (e *ClosedError) Unwrap() error
Unwrap makes errors.Is(err, ErrChildExited) true for every early exit.
type Color ¶
type Color struct {
// Kind selects which of the remaining fields is meaningful.
Kind ColorKind
// Index is the palette entry when Kind is ColorIndexed.
Index uint8
// R, G and B are the channel values when Kind is ColorRGB.
R, G, B uint8
}
Color is a cell color in one of three encodings. Only the fields matching Kind carry meaning; the others are zero.
type ColorKind ¶
type ColorKind int
ColorKind distinguishes the three color encodings a cell can carry.
type EmulatorPanicError ¶
type EmulatorPanicError struct {
// Op is the call that failed, such as "WaitForText" or "Type".
Op string
// During says what the emulator was doing when it panicked, such as
// "reading the program's output" or "resizing to 80x24".
During string
// Value is what the emulator panicked with.
Value any
// Stack is the stack of the goroutine that panicked.
Stack string
// Chunk is the output the emulator was reading when it panicked. It is
// empty when the panic came from something other than the output.
Chunk []byte
// Screen is the plain-text screen when the emulator panicked.
Screen string
// TailLog is the tail of the mirrored PTY I/O.
TailLog string
}
EmulatorPanicError is returned by every wait, every input call and Resize once the emulator has panicked. It unwraps to ErrEmulatorPanic.
The panic usually happens on the goroutine that reads the program's output, where no test can catch it. Left alone it ends the whole test binary: every other result is lost and no cleanup runs, so the programs the tests started are left running. The terminal recovers it instead, keeps reading the program's output so the program does not block on a full PTY, and stops feeding that output to the emulator, whose state can no longer be trusted. A panic in a resize or in a read of the screen is recovered the same way.
The calls that return no error (Screen, Snapshot, TermState and LastCommandExit) return the state the emulator had when it panicked. They do not read the emulator again.
func (*EmulatorPanicError) Error ¶
func (e *EmulatorPanicError) Error() string
func (*EmulatorPanicError) Unwrap ¶
func (e *EmulatorPanicError) Unwrap() error
Unwrap makes errors.Is(err, ErrEmulatorPanic) true.
type ExitStatus ¶
type ExitStatus struct {
// Code is the exit status, or -1 when the child died from a signal.
Code int
// Signaled is true when the child was killed by a signal rather than
// exiting on its own.
Signaled bool
// Signal is the killing signal when Signaled is true.
Signal syscall.Signal
}
ExitStatus describes how the child finished.
func (ExitStatus) Crashed ¶
func (s ExitStatus) Crashed() bool
Crashed reports whether the child died in a way that indicates a bug: killed by a fault signal, or exited non-zero. A clean zero exit is not a crash.
func (ExitStatus) String ¶
func (s ExitStatus) String() string
type Key ¶
type Key string
Key is a named key or chord expressed as the escape sequence it sends. Using typed values means a mistyped key name is a compile error, not a silent mismatch at runtime.
const ( Enter Key = "\r" Tab Key = "\t" Esc Key = "\x1b" Space Key = " " Backspace Key = "\x7f" Delete Key = "\x1b[3~" Up Key = "\x1b[A" Down Key = "\x1b[B" Right Key = "\x1b[C" Left Key = "\x1b[D" Home Key = "\x1b[H" End Key = "\x1b[F" PageUp Key = "\x1b[5~" PageDown Key = "\x1b[6~" Insert Key = "\x1b[2~" F1 Key = "\x1bOP" F2 Key = "\x1bOQ" F3 Key = "\x1bOR" F4 Key = "\x1bOS" F5 Key = "\x1b[15~" F6 Key = "\x1b[17~" F7 Key = "\x1b[18~" F8 Key = "\x1b[19~" F9 Key = "\x1b[20~" F10 Key = "\x1b[21~" F11 Key = "\x1b[23~" F12 Key = "\x1b[24~" )
Named keys. Values are the byte sequences a terminal sends for each key.
func Alt ¶
Alt returns k with Alt held. It accepts the same items as SendKeys.
A named key with a CSI or SS3 form (the cursor keys, Home, End, Insert, Delete, PageUp, PageDown and F1 to F12) gets the xterm modifier form, the way xterm sends it: Alt(Up) is CSI 1;3 A, not ESC followed by CSI A. Any other item is prefixed with ESC, the conventional meta encoding, so Alt('x') is ESC x.
An item of an unsupported type yields a bare Esc, since Alt has no way to report an error. Pass a string, rune, Key, or slice of those and that cannot happen.
func Ctrl ¶
Ctrl returns the byte a terminal sends for a rune typed with Control held, so Ctrl('b') is 0x02. Letters are case-insensitive.
It follows the xterm table rather than masking every rune to five bits, which is what makes the non-letter chords come out right: Ctrl('@'), Ctrl(' ') and Ctrl('2') are NUL, Ctrl('[') and Ctrl('3') are ESC, Ctrl('\\'), Ctrl(']'), Ctrl('^') and Ctrl('_') are 0x1c to 0x1f as are Ctrl('4') to Ctrl('7'), Ctrl('~') is 0x1e like Ctrl('^'), Ctrl('/') is 0x1f like Ctrl('_'), and Ctrl('?') and Ctrl('8') are DEL. A rune with no control encoding, such as a digit other than 2 to 8 or anything outside ASCII, is sent unchanged, since that is what a terminal without the kitty keyboard protocol sends for it.
Example ¶
Ctrl and Alt build chords as the bytes a terminal sends for them.
package main
import (
"fmt"
"github.com/Gaurav-Gosain/tuitest"
)
func main() {
fmt.Printf("%q %q %q\n", tuitest.Ctrl('c'), tuitest.Alt('x'), tuitest.Alt(tuitest.Enter))
}
Output: "\x03" "\x1bx" "\x1b\r"
func Mod ¶ added in v0.3.0
Mod returns a named key with modifiers held, in the xterm modifier form: the key's CSI sequence with the parameter 1 plus the modifier bits. Mod(Up, ModCtrl) is CSI 1;5 A, Mod(Delete, ModShift) is CSI 3;2 ~, and Mod(F1, ModCtrl|ModShift) is CSI 1;6 P. Modifiers add up, so Mod(Mod(Up, ModCtrl), ModShift) is Mod(Up, ModCtrl|ModShift). A modified key is sent in this form whatever the cursor key mode, as xterm does.
It applies to the named keys with a CSI or SS3 form: the cursor keys, Home, End, Insert, Delete, PageUp, PageDown and F1 to F12. Any other key is returned as it is, since it has no xterm modifier form. Use Ctrl for a control character and Alt for the ESC prefix.
type MouseAction ¶
type MouseAction int
MouseAction is what the button did.
const ( // MousePress is a button going down. MousePress MouseAction = iota // MouseRelease is a button coming up. MouseRelease // MouseMove is motion with no button held. MouseMove // MouseDrag is motion with a button held. On the wire it is the same // motion bit as MouseMove; the two are distinguished by whether a button // is reported, and separating them is what lets a tape read as a drag. MouseDrag )
type MouseButton ¶
type MouseButton int
MouseButton identifies a mouse button or wheel direction.
const ( // MouseLeft is the primary button. MouseLeft MouseButton = iota // MouseMiddle is the middle button or wheel click. MouseMiddle // MouseRight is the secondary button. MouseRight // MouseWheelUp is one wheel notch away from the user. MouseWheelUp // MouseWheelDown is one wheel notch toward the user. MouseWheelDown // MouseWheelLeft is one horizontal wheel notch to the left. MouseWheelLeft // MouseWheelRight is one horizontal wheel notch to the right. MouseWheelRight // MouseBackward is the fourth button, "back" on most mice. MouseBackward // MouseForward is the fifth button, "forward" on most mice. MouseForward // MouseNone is no button: the button field of a motion report with nothing // held, and of a legacy release report, which does not say which button // came up. MouseNone )
type MouseEncoding ¶
type MouseEncoding int
MouseEncoding is the wire format a mouse report used.
It is part of the event because replaying a recorded session has to send the program the same bytes it originally received: a program that enabled only mode 1000 does not understand an SGR report, so re-encoding a captured X10 report as SGR would silently change what the test exercises.
const ( // MouseSGR is the modern SGR encoding (mode 1006), and the default for // events constructed by hand. It is the only encoding with no coordinate // limit and the only one that reports which button was released. MouseSGR MouseEncoding = iota // MouseX10 is the original encoding (modes 9, 1000, 1002 and 1003), which // packs each field into one byte offset by 32. MouseX10 // MouseURXVT is the urxvt encoding (mode 1015): X10's packing written as // decimal parameters, so it has no coordinate limit but still cannot say // which button was released. MouseURXVT )
type MouseEvent ¶
type MouseEvent struct {
// Col and Row are zero-based cell coordinates; the wire format's 1-based
// coordinates are produced during encoding. When Pixel is set they are
// zero-based pixel offsets instead.
Col, Row int
// Button is the button or wheel direction involved. It is ignored for
// MouseMove, which is motion with nothing held: to send motion with a
// button down, use MouseDrag.
Button MouseButton
// Action is what the button did.
Action MouseAction
// Mods are the modifier keys held at the time.
Mods KeyMods
// Pixel reports coordinates in pixels rather than cells (mode 1016). The
// wire format is identical to SGR's, so this can only ever be known from
// whether the program asked for pixel reporting.
Pixel bool
// Enc is the wire encoding to use. The zero value is MouseSGR.
Enc MouseEncoding
}
MouseEvent is a single mouse event at a zero-based cell coordinate.
func (MouseEvent) Encode ¶
func (e MouseEvent) Encode() (string, bool)
Encode renders the event in whichever wire encoding Enc names.
func (MouseEvent) EncodeSGR ¶
func (e MouseEvent) EncodeSGR() (string, bool)
EncodeSGR renders the event as an SGR (1006) or SGR-pixel (1016) sequence. Coordinates in the wire format are 1-based. It reports false for an event the encoding cannot express.
func (MouseEvent) EncodeURXVT ¶
func (e MouseEvent) EncodeURXVT() (string, bool)
EncodeURXVT renders the event in the urxvt encoding (mode 1015): X10's control byte and 1-based coordinates written as decimal parameters, which lifts X10's coordinate limit but keeps its inability to name a released button.
func (MouseEvent) EncodeX10 ¶
func (e MouseEvent) EncodeX10() (string, bool)
EncodeX10 renders the event in the original encoding, where the control byte and both coordinates are single bytes offset by 32.
It reports false for anything that packing cannot hold: a coordinate past column 223, which has no representation at all, and a release, which the encoding reports as the button-3 code without saying which button came up. Falling back rather than approximating is what keeps a recorded session's bytes intact.
type Option ¶
type Option func(*config)
Option configures a spawn.
func WithCastDir ¶ added in v0.3.0
WithCastDir records everything the terminal shows and is sent, as an asciicast v2 recording that asciinema and other players can scrub. Every wait and every input call adds a mark, so a player can jump to each step of the test.
Under StartT and StartProgramT a terminal whose test fails is written to a new file in dir, and the test log names the file. A test that passes writes nothing. Setting TUITEST_CAST_DIR does the same for every terminal those functions start. WriteCast writes the recording at any time.
Recording keeps the output in memory, up to 16 MiB for each terminal, so it is off unless one of the two asks for it.
func WithCellSize ¶ added in v0.3.2
WithCellSize sets the size of one cell in pixels. The terminal reports it the way a real terminal does: in the PTY's window size, in the answers to CSI 14 t and CSI 16 t, and in the mode 2048 report. Without it the cell is the emulator's fallback, 10 by 20 pixels. Both must be positive; anything else keeps the fallback.
func WithFullTestLog ¶
func WithFullTestLog() Option
WithFullTestLog makes StartT copy every chunk of PTY I/O to t.Log as it arrives. Without it StartT keeps only the last StartTLogTail bytes and logs them when the test fails. A program that writes a lot then fills the log with escape sequences, so use it only to debug one test.
func WithInheritEnv ¶
func WithInheritEnv() Option
WithInheritEnv starts from the parent process environment instead of the minimal hermetic default.
func WithKillGrace ¶
WithKillGrace sets how long Close waits for the program to exit after SIGTERM before it sends SIGKILL. The default is two seconds. Zero or less sends SIGTERM and then SIGKILL with no wait. A short grace makes Close fast for a program that ignores SIGTERM.
func WithOutputMirror ¶
WithOutputMirror copies the child's output to w as it arrives. Unlike WithLog, which mirrors both directions for debugging, this carries only what the program wrote, so w can be a real terminal the program is rendered onto while the harness still drives it headlessly. Used by tuitest record and tuitest replay.
func WithSemanticMarkers ¶
func WithSemanticMarkers() Option
WithSemanticMarkers enables OSC 133 tracking so the WaitForPrompt / WaitForCommand / LastCommandExit primitives work.
func WithSixel ¶ added in v0.3.2
func WithSixel() Option
WithSixel makes the terminal say it draws sixel images: its answer to the primary device attributes query (DA1) carries attribute 4, as a sixel terminal's does. The terminal does not draw the images; the program can tell what it sent from the screen and the log.
func WithSize ¶
WithSize sets the initial PTY size in cells. Both must be between 1 and 65535, the range the kernel can store; Start refuses anything else.
func WithStabilizeInterval ¶
WithStabilizeInterval sets the quiet window used by WaitStable.
func WithTrueColor ¶
func WithTrueColor() Option
WithTrueColor sets COLORTERM=truecolor for programs that gate 24-bit color.
func WithWriteTimeout ¶
WithWriteTimeout sets how long input (SendKeys, Type, Paste, SendMouse) waits for the program to read it. The default is DefaultWriteTimeout. Zero or less removes the limit.
A write that times out returns a *TimeoutError with the screen. Part of the input can already be in the program's input buffer, possibly half an escape sequence, so after a timeout the terminal refuses all further input. Raise the limit for a large paste into a program that reads slowly.
The write that timed out stays blocked, and keeps the PTY open, until the test binary exits. Close still returns.
type Program ¶ added in v0.3.0
type Program interface {
// Run runs the program until it ends and returns its exit code. It reads
// its input from in and writes its output to out, and starts at a
// terminal of cols by rows cells. in reports io.EOF once the Terminal
// is closed. A panic in Run ends the program with exit code 2 and the
// panic on the screen, as it would for a Go program on a PTY.
Run(in io.Reader, out io.Writer, cols, rows int) int
// Resize tells the program that its terminal is now cols by rows. It is
// called from the test's goroutine while Run runs.
Resize(cols, rows int)
// Stop asks the program to end. Run must return soon after. Close calls
// it, and it may be called after Run has returned.
Stop()
}
Program is a terminal program that runs inside the test process instead of as a child on a PTY. StartProgram puts it behind a Terminal, and the Terminal treats its output and input exactly as it treats a PTY child's: the same emulator reads the output, and the same waits, screen reads and key encoding apply. A test written against a Terminal runs against either.
There is no line discipline in between. The program reads the bytes a terminal sends, as a program in raw mode does, and what it writes reaches the screen as it is, so it writes "\r\n" to start a new line.
type Screen ¶
type Screen interface {
// Size returns the grid size in cells.
Size() (cols, rows int)
// Cell returns the cell at the given zero-based column and row. Out-of-bounds
// coordinates return the zero Cell.
Cell(col, row int) Cell
// Cursor returns the cursor position (zero-based) and whether it is visible.
Cursor() (col, row int, visible bool)
// Text returns the plain-text screen, one row per line, with each line's
// trailing blanks trimmed and trailing blank lines dropped.
Text() string
// Line returns the plain text of a single physical row with trailing blanks
// trimmed, or "" for an out-of-range row. It does not de-wrap: a logical
// line that soft-wrapped at the right margin occupies several rows and will
// not match as one string. Match per row, or use Text and account for the
// wrap, or widen the terminal with WithSize so the line fits.
Line(row int) string
// ExitCode reports the child's exit code and whether it has exited.
ExitCode() (code int, exited bool)
}
Screen is a read-only view of the terminal grid handed to wait conditions and returned by snapshots. Every Screen value is an immutable copy taken under the terminal's lock, so a condition callback may stash it without observing a torn write from the output pump.
type TermState ¶
type TermState struct {
// AltScreen is set while any of the alternate screen modes (47, 1047,
// 1049) is.
AltScreen bool
// MouseTracking is set while any mouse reporting mode (9, 1000, 1001,
// 1002, 1003) is.
MouseTracking bool
// BracketedPaste is mode 2004.
BracketedPaste bool
// FocusReporting is mode 1004.
FocusReporting bool
// CursorHidden is mode 25 reset.
CursorHidden bool
// contains filtered or unexported fields
}
TermState is a snapshot of the terminal modes a program has left set, plus cursor visibility. It answers "did this TUI restore the terminal?", which is a common and user-visible bug class: a program that exits without leaving the alternate screen, or with mouse reporting still on, leaves the user's shell unusable.
func (TermState) Describe ¶
Describe lists the offending modes in a stable order, for error messages.
type Terminal ¶
type Terminal struct {
// contains filtered or unexported fields
}
Terminal is the harness handle for one spawned program.
func StartProgram ¶ added in v0.3.0
StartProgram runs prog in the test process behind a Terminal.
The options that shape a child process do not apply: WithEnv, WithInheritEnv, WithDir, WithTerm and WithTrueColor are ignored, since the program has no environment or directory of its own. WithKillGrace bounds how long Close waits for Run to return after Stop.
func StartProgramT ¶ added in v0.3.0
StartProgramT is StartProgram for a test: it registers Close with t.Cleanup, fails the test if the program cannot start, and keeps the same debug log as StartT.
func StartT ¶
StartT is the testing.TB-friendly constructor: it registers Close via t.Cleanup, fails the test on spawn error, and keeps a debug log for t.Log.
The log holds the last StartTLogTail bytes of PTY I/O in both directions, and goes to t.Log only when the test fails. WithFullTestLog copies every chunk to t.Log instead, and WithLog sends the log to a writer of your choice.
The test also fails when the terminal emulator panicked during the test, even if the test made no call that returned the error. A test that makes the emulator panic on purpose uses Start.
Example ¶
StartT is Start for use inside a test: it fails the test if the spawn fails, mirrors PTY traffic into t.Log, and closes the terminal in t.Cleanup.
package main
import (
"testing"
"time"
"github.com/Gaurav-Gosain/tuitest"
)
// greeter is a tiny interactive program: it asks for a name and answers.
var greeter = []string{"sh", "-c", `printf 'name? '; read name; printf 'hello, %s\n' "$name"`}
func main() {
test := func(t *testing.T) {
term := tuitest.StartT(t, greeter, tuitest.WithSize(40, 5))
if err := term.WaitForText("name?", 5*time.Second); err != nil {
t.Fatal(err)
}
_ = term.SendKeys("gopher", tuitest.Enter)
if err := term.WaitForText("hello, gopher", 5*time.Second); err != nil {
t.Fatal(err)
}
// Compare against testdata/greeting.golden; UPDATE_GOLDEN=1 writes it.
term.AssertGolden(t, "greeting")
}
_ = test
}
Output:
func (*Terminal) AssertGolden ¶
AssertGolden compares the plain-text snapshot against testdata/<name>.golden, failing the test on mismatch with a unified diff. When UPDATE_GOLDEN is set in the environment or -update is passed, it rewrites the golden instead.
It reads the screen once, as it is at the moment of the call, so wait for the state first; WaitForStable is the wait that makes sure the frame has finished drawing. Trailing newlines and CRLF line endings in the golden file are ignored, so a golden saved by an editor or checked out on Windows still matches.
func (*Terminal) AssertGoldenStyled ¶
AssertGoldenStyled is AssertGolden for the styled encoding.
func (*Terminal) Done ¶
func (t *Terminal) Done() <-chan struct{}
Done returns a channel closed once the child has exited and been reaped. It lets a caller select on program exit alongside its own events, which Wait cannot express because it blocks.
func (*Terminal) ExitCode ¶
ExitCode reports the child's exit code and whether it has exited.
The code is -1 for a child killed by a signal, not the shell's 128+signal convention, so that it can never be confused with a program that exited with that number itself. It is -1 before the child has exited too, and the second return value is the only thing that separates those two cases. Use ExitStatus to tell a crash apart from an ordinary non-zero exit.
func (*Terminal) ExitStatus ¶
func (t *Terminal) ExitStatus() (ExitStatus, bool)
ExitStatus reports how the child finished and whether it has exited at all.
Example ¶
ExitStatus separates a signal death from an ordinary non-zero exit, which ExitCode flattens to -1.
package main
import (
"fmt"
"time"
"github.com/Gaurav-Gosain/tuitest"
)
func main() {
term, err := tuitest.Start([]string{"sh", "-c", "kill -SEGV $$"}, tuitest.WithSize(40, 3))
if err != nil {
fmt.Println(err)
return
}
defer term.Close() //nolint:errcheck
_, _ = term.WaitExit(5 * time.Second)
st, _ := term.ExitStatus()
fmt.Println(st.Signaled, st.Crashed(), st)
}
Output: true true killed by SIGSEGV
func (*Terminal) InputBytes ¶
InputBytes reports how many bytes have been written to the child's input so far: everything sent with SendKeys, Type, Paste and SendMouse, and the answers the terminal gave to the program's own queries, which the program reads from the same stream.
It is the input side of Progress, and it exists for the one question no quiet window can answer: whether the program has caught up with its input. A program that reports how many bytes it has read can be compared against this count, and once the two agree the program has seen everything, however long the machine took to schedule it. WaitStable can only guess, and a program starved of CPU for longer than the stabilize interval defeats the guess.
It does not take the terminal's lock, so it is safe to call from inside a WaitFor condition.
func (*Terminal) LastCommandExit ¶
LastCommandExit returns the exit code of the last finished command (OSC 133 D) and whether one has been seen. It reports false both when no command has finished and when the terminal was started without WithSemanticMarkers, so enable that option before relying on it; the WaitForPrompt and WaitForCommand waits return ErrSemanticMarkers in that case and are the better signal.
After an emulator panic it returns the value at the panic. See EmulatorPanicError.
func (*Terminal) Paste ¶
Paste sends text wrapped in bracketed-paste markers, the way a terminal delivers a real paste to a program that enabled mode 2004. Such programs take a different code path for pasted text than for typed text, and that path is often the less tested one.
The markers are sent whether or not the program enabled the mode, so a test can check how a program copes with markers it did not ask for. A real terminal sends a paste to such a program as plain text; to reproduce that, use Type.
Example ¶
Paste wraps text in bracketed-paste markers, the way a terminal delivers a real paste. cat -v makes the markers visible.
package main
import (
"fmt"
"time"
"github.com/Gaurav-Gosain/tuitest"
)
func main() {
term, err := tuitest.Start([]string{"sh", "-c", `echo ready; IFS= read -r line; printf '%s\n' "$line" | cat -v; sleep 5`}, tuitest.WithSize(40, 3))
if err != nil {
fmt.Println(err)
return
}
defer term.Close() //nolint:errcheck
_ = term.WaitForText("ready", 5*time.Second)
_ = term.Paste("hi")
_ = term.SendKeys(tuitest.Enter)
_ = term.WaitForText("201~", 5*time.Second)
fmt.Println(term.Screen().Line(1))
}
Output: ^[[200~hi^[[201~
func (*Terminal) Progress ¶
Progress reports how many bytes the child has written so far and when the most recent write landed. A caller that sends input and then sees neither counter move has evidence the program stopped responding.
func (*Terminal) Resize ¶
Resize changes the PTY window size and the emulator grid; the child receives SIGWINCH. Like sending keys, a resize counts as input for WaitStable, since the redraw it provokes has not arrived yet.
A program that enabled in-band resize notifications (mode 2048) is sent the report as part of the call, after the PTY has its new size, the way a real terminal sends it.
Example ¶
Resize changes the PTY size, so the program receives SIGWINCH and sees the new size, and resizes the emulator grid to match.
package main
import (
"fmt"
"time"
"github.com/Gaurav-Gosain/tuitest"
)
func main() {
term, err := tuitest.Start([]string{"sh", "-c", "stty size; read x; stty size; sleep 5"}, tuitest.WithSize(80, 24))
if err != nil {
fmt.Println(err)
return
}
defer term.Close() //nolint:errcheck
_ = term.WaitForText("24 80", 5*time.Second)
_ = term.Resize(50, 10)
_ = term.SendKeys(tuitest.Enter)
_ = term.WaitForText("10 50", 5*time.Second)
cols, rows := term.Screen().Size()
fmt.Println(cols, rows)
fmt.Println(term.Snapshot())
}
Output: 50 10 24 80 10 50
func (*Terminal) Screen ¶
Screen returns an immutable view of the current screen.
While the program is inside a synchronized update (DEC mode 2026) this is the last complete frame, not the half-drawn one being built, which is what a real terminal shows too. The waits read the screen the same way.
func (*Terminal) SendKeys ¶
SendKeys types a sequence of named keys, chords, runes, and strings. Plain strings and runes are sent literally; Key values carry their own escape sequences. Items may be string, rune, Key, []string, []Key, or []any of those; anything else is rejected with an error rather than sent. Example:
term.SendKeys("git status", tuitest.Enter)
term.SendKeys(tuitest.Ctrl('b'), "%")
A Key is sent the way a terminal sends that key under the keyboard modes the program has set, the way a user's terminal would:
- With no mode set, a Key is sent as its constant says.
- Once the program has set DECCKM (mode 1), the unmodified arrow keys, Home and End are sent as SS3 sequences (ESC O A), which full-screen programs built on terminfo set at startup and then match against.
- Once the program has pushed kitty keyboard flags (CSI > flags u), keys follow the kitty protocol for those flags: Ctrl('b') is CSI 98;5 u, Esc is CSI 27 u, and with the flag that reports every key Enter is CSI 13 u.
- At modifyOtherKeys level 2 (CSI > 4;2 m), a key with Ctrl or Alt is sent as CSI 27;mod;code ~.
Strings and runes are text and are sent as they are, whatever the modes: use Key values for keystrokes. Only key presses are sent, never key releases.
func (*Terminal) SendMouse ¶
func (t *Terminal) SendMouse(ev MouseEvent) error
SendMouse encodes a mouse event and sends it to the child, using the wire encoding named by the event's Enc field. The program under test must have enabled the matching mouse reporting mode for it to react.
func (*Terminal) SnapshotStyled ¶
SnapshotStyled returns the styled, diff-friendly encoding of the screen: each row's plain text followed by indented attribute runs for spans that differ from the default style. A screen with no styling degrades to the plain form.
func (*Terminal) TermState ¶
TermState returns the current mode state of the emulated terminal. Call it after the child has exited to check that it restored the terminal.
After an emulator panic it returns the state at the panic. See EmulatorPanicError.
Example ¶
TermState reports the modes a program left set. A program that exits on the alternate screen leaves the user's shell unusable, and Dirty catches it.
package main
import (
"fmt"
"time"
"github.com/Gaurav-Gosain/tuitest"
)
func main() {
term, err := tuitest.Start([]string{"sh", "-c", `printf '\033[?1049h\033[?25l'`}, tuitest.WithSize(40, 3))
if err != nil {
fmt.Println(err)
return
}
defer term.Close() //nolint:errcheck
_, _ = term.WaitExit(5 * time.Second)
st := term.TermState()
fmt.Println(st.Dirty(), st.AltScreen, st.CursorHidden)
}
Output: true true true
func (*Terminal) Type ¶
Type sends literal text with no key-name interpretation (tmux send-keys -l).
func (*Terminal) Wait
deprecated
func (*Terminal) WaitExit ¶
WaitExit blocks until the child exits or timeout elapses, returning the exit code. On timeout it returns -1 and a *TimeoutError, which unwraps to ErrTimeout like every other wait. A child killed by a signal also returns -1, with a nil error; ExitStatus is what tells the two apart.
func (*Terminal) WaitFor ¶
WaitFor blocks until cond returns true on the current screen, or timeout.
cond is called with the terminal's lock held, once at the start and then each time the screen can have changed: the program wrote output, the terminal was resized, input reached the program, or the program exited. It is not called on a timer in between, so a condition that reads the clock instead of the screen does not work. cond must be quick and must not call back into the Terminal. The Screen it receives is immutable and may be kept.
Like every wait, WaitFor treats a timeout of zero or less as one second, and returns an error wrapping ErrChildExited if the program exits before the condition holds, or ErrTimeout if time runs out. The error message carries the screen at that moment.
The error describes the condition as "custom condition". Use WaitForDesc to say what the condition waits for.
Example ¶
WaitFor takes any condition on the screen. Here it waits for a cell to be drawn bold, which no text match can see.
package main
import (
"fmt"
"time"
"github.com/Gaurav-Gosain/tuitest"
)
func main() {
term, err := tuitest.Start([]string{"sh", "-c", `printf 'plain \033[1mBOLD\033[0m'; sleep 5`}, tuitest.WithSize(40, 3))
if err != nil {
fmt.Println(err)
return
}
defer term.Close() //nolint:errcheck
err = term.WaitFor(func(s tuitest.Screen) bool {
return s.Cell(6, 0).Bold
}, 5*time.Second)
fmt.Println(err, term.Screen().Cell(6, 0).Content, term.Screen().Cell(0, 0).Bold)
}
Output: <nil> B false
func (*Terminal) WaitForCommand ¶
WaitForCommand blocks until the current command finishes (OSC 133 D). Requires WithSemanticMarkers.
Example ¶
WaitForPrompt and WaitForCommand follow a shell through OSC 133 semantic markers, which the shell (or its prompt framework) has to emit.
Both wait for a marker newer than the call, so a marker that arrives before the wait starts is not seen. The script sleeps before each one to keep this example deterministic; a real shell is slower than the Go side anyway.
package main
import (
"fmt"
"time"
"github.com/Gaurav-Gosain/tuitest"
)
func main() {
// A stand-in for a shell with shell integration: prompt, command, exit 7.
script := `sleep 0.2; printf '\033]133;A\007$ \033]133;B\007'; read x; sleep 0.2; printf '\033]133;C\007ran\n\033]133;D;7\007'; sleep 5`
term, err := tuitest.Start([]string{"sh", "-c", script}, tuitest.WithSize(40, 5), tuitest.WithSemanticMarkers())
if err != nil {
fmt.Println(err)
return
}
defer term.Close() //nolint:errcheck
if err := term.WaitForPrompt(5 * time.Second); err != nil {
fmt.Println(err)
return
}
_ = term.SendKeys(tuitest.Enter)
if err := term.WaitForCommand(5 * time.Second); err != nil {
fmt.Println(err)
return
}
fmt.Println(term.LastCommandExit())
}
Output: 7 true
func (*Terminal) WaitForDesc ¶
WaitForDesc is WaitFor with a description of the condition. The description is the Want field of the error, and the error message says "waiting for" desc, so write it to complete that phrase:
term.WaitForDesc("the status bar to show 3 windows", func(s tuitest.Screen) bool {
return strings.Contains(s.Line(23), "3 windows")
}, time.Second)
func (*Terminal) WaitForMatch ¶
WaitForMatch blocks until re matches within the given scope.
Example ¶
WaitForMatch takes a regexp, and ScopeLastLine restricts it to the last non-blank row, which is where a prompt or a status line usually is.
package main
import (
"fmt"
"regexp"
"time"
"github.com/Gaurav-Gosain/tuitest"
)
func main() {
term, err := tuitest.Start([]string{"sh", "-c", "echo 'build 1 of 3'; echo 'done in 42ms'; sleep 5"}, tuitest.WithSize(40, 5))
if err != nil {
fmt.Println(err)
return
}
defer term.Close() //nolint:errcheck
re := regexp.MustCompile(`done in \d+ms`)
if err := term.WaitForMatch(re, tuitest.ScopeLastLine, 5*time.Second); err != nil {
fmt.Println(err)
return
}
fmt.Println(re.FindString(term.Screen().Text()))
}
Output: done in 42ms
func (*Terminal) WaitForOutput ¶
WaitForOutput blocks until the child writes anything at all after the call begins, or it exits, or timeout elapses.
This is the primitive for "wait until the program reacts to what I just sent", which WaitStable does not express: WaitStable asks whether output has been quiet for a window, and after a pause that is already true, so it returns immediately without the program having done anything. Use WaitStable to wait for a burst of output to finish, and WaitForOutput to wait for a reaction to begin. A child that has exited counts as settled, since no further output can arrive.
func (*Terminal) WaitForPrompt ¶
WaitForPrompt blocks until a new shell prompt (OSC 133 A) is drawn. Requires WithSemanticMarkers.
func (*Terminal) WaitForStable ¶
WaitForStable blocks until cond holds on a screen whose content has not changed for the stabilize interval (see WithStabilizeInterval), or until timeout.
It is for the case WaitFor handles badly: the text a test waits for is drawn before the rest of the frame it belongs to. A program redraws from the top down and the PTY delivers the frame in pieces, so the moment a marker near the top appears, the rows below it can still hold the previous frame, and an assertion on them made straight after WaitFor fails against a screen that is correct a moment later. WaitForStable waits for the frame to finish as well. It is also the way to read a value off the screen that is still moving, such as a counter or a scroll position: wait for it to stop, then read it.
Only the content of the cells counts as a change: text, colours and attributes, and the size. Output that repaints the same content, and cursor movement, do not restart the window. As with WaitStable, the window is not considered to start before the last input tuitest sent, so a screen that already satisfied cond before a keystroke is not reported until the program has had the interval to react to it. A child that has exited cannot change the screen again, so once it has, cond holding is enough.
Programs that draw inside synchronized updates (mode 2026) are already never seen half drawn, since the harness shows the previous frame until the update closes, the way a real terminal does. WaitForStable still helps with the ones that do not, and with a program that draws one logical frame in several updates.
func (*Terminal) WaitForText ¶
WaitForText blocks until the plain-text screen contains substr.
Example ¶
A wait that runs out of time says what it waited for and carries the screen, and errors.Is tells a timeout apart from the program exiting early.
package main
import (
"errors"
"fmt"
"time"
"github.com/Gaurav-Gosain/tuitest"
)
func main() {
term, err := tuitest.Start([]string{"sh", "-c", "echo starting; sleep 5"}, tuitest.WithSize(40, 3))
if err != nil {
fmt.Println(err)
return
}
defer term.Close() //nolint:errcheck
if err := term.WaitForText("starting", 5*time.Second); err != nil {
fmt.Println(err)
return
}
err = term.WaitForText("ready", 200*time.Millisecond)
fmt.Println(errors.Is(err, tuitest.ErrTimeout))
var te *tuitest.TimeoutError
if errors.As(err, &te) {
fmt.Println(te.Screen)
}
}
Output: true starting
func (*Terminal) WaitStable ¶
WaitStable blocks until the terminal has been quiet for the stabilize interval (see WithStabilizeInterval), or until timeout. A child that has exited counts as stable.
The quiet window is measured from the later of the last output byte and the last input tuitest sent. That matters: measured from output alone, calling WaitStable immediately after SendKeys would return against the pre-keystroke screen whenever the program had already been idle for the interval. Waiting out the window from the keystroke instead gives the program that long to start reacting, and any byte it produces restarts the window.
A program that has not written anything yet is never stable. Starting a process takes long enough, on a loaded machine or under -race, that a quiet window measured from spawn used to elapse before the first byte arrived, and WaitStable then returned a blank screen. A program that never writes at all makes WaitStable time out.
It is still a heuristic. A program that takes longer than the stabilize interval to react to input will be reported stable too early, and no quiescence rule can distinguish that from a program with nothing to say. Prefer WaitForText, WaitForMatch or WaitFor whenever the expected end state is known, and WaitForStable when the state is known but may still be drawing. Reach for WaitStable only after heavy output where it is not known at all.
type TimeoutError ¶
type TimeoutError struct {
// Op is the wait that failed, such as "WaitForText".
Op string
// Want describes the condition in words, such as `text "ready"`.
Want string
// Elapsed is how long the wait actually took.
Elapsed time.Duration
// Screen is the plain-text screen at the moment of the failure.
Screen string
// TailLog is the tail of the mirrored PTY I/O.
TailLog string
}
TimeoutError is returned by every wait that times out. Its message includes a full screen dump and the tail of the mirrored I/O log, so a failing CI run shows exactly what was on screen instead of a bare "timeout". It unwraps to ErrTimeout.
func (*TimeoutError) Error ¶
func (e *TimeoutError) Error() string
func (*TimeoutError) Unwrap ¶
func (e *TimeoutError) Unwrap() error
Unwrap makes errors.Is(err, ErrTimeout) true for every wait timeout.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
tuitest
command
Command tuitest tests terminal programs from the command line.
|
Command tuitest tests terminal programs from the command line. |
|
Package fixtures provides in-process helpers for testing code that consumes terminal output: FakeShell, an io.ReadWriteCloser that stands in for the shell side of a PTY, and ANSIBuilder, which assembles escape sequences without hand-written byte strings.
|
Package fixtures provides in-process helpers for testing code that consumes terminal output: FakeShell, an io.ReadWriteCloser that stands in for the shell side of a PTY, and ANSIBuilder, which assembles escape sequences without hand-written byte strings. |
|
Package fuzz drives a terminal program with randomised but structured input and watches for the ways a TUI breaks: crashing, hanging, corrupting the screen model, growing without bound, or exiting without restoring the terminal.
|
Package fuzz drives a terminal program with randomised but structured input and watches for the ways a TUI breaks: crashing, hanging, corrupting the screen model, growing without bound, or exiting without restoring the terminal. |
|
vtgen
Package vtgen generates terminal input that looks like something a program would actually emit, by grammar rather than by byte, for fuzzing a VT parser.
|
Package vtgen generates terminal input that looks like something a program would actually emit, by grammar rather than by byte, for fuzzing a VT parser. |
|
internal
|
|
|
cli
Package cli implements the tuitest command line.
|
Package cli implements the tuitest command line. |
|
emu
Package emu holds the VT emulator adapter used by tuitest.
|
Package emu holds the VT emulator adapter used by tuitest. |
|
ptyproc
Package ptyproc owns the process and PTY lifecycle for tuitest: spawning a child attached to a pseudo-terminal, pumping its output, resizing, EOF and exit-code handling, and process-tree teardown.
|
Package ptyproc owns the process and PTY lifecycle for tuitest: spawning a child attached to a pseudo-terminal, pumping its output, resizing, EOF and exit-code handling, and process-tree teardown. |
|
textdist
Package textdist provides the string distance behind "did you mean" hints.
|
Package textdist provides the string distance behind "did you mean" hints. |
|
Package tape implements the small VHS-inspired tape language for tuitest's CLI and a player that drives a tuitest.Terminal.
|
Package tape implements the small VHS-inspired tape language for tuitest's CLI and a player that drives a tuitest.Terminal. |
|
Package tuiosx holds the tuios-specific conveniences for tuitest: a prefix chord helper and a spawn helper that isolates each tuios instance in its own temporary XDG state so parallel tests do not collide on a shared daemon socket.
|
Package tuiosx holds the tuios-specific conveniences for tuitest: a prefix chord helper and a spawn helper that isolates each tuios instance in its own temporary XDG state so parallel tests do not collide on a shared daemon socket. |


