expect

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Jun 15, 2026 License: Apache-2.0 Imports: 17 Imported by: ? modules, 0 packages

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

README

go-expect

Go GoDoc OSS Lifecycle

Package expect provides an expect-like interface to automate control of interactive applications through a pseudo-terminal.

This project is a fork of the original dead Netflix/go-expect, with the goal of providing cross-platform support (specifcally Windows) via charmbracelet/x/xpty.

Usage

Cross-platform exec.Cmd example
package main

import (
	"context"
	"log"
	"os"
	"os/exec"
	"time"

	expect "github.com/pete-woods/go-expect"
)

func main() {
	c, err := expect.NewConsole(
		expect.WithStdout(os.Stdout),
		expect.WithDefaultTimeout(10*time.Second),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()

	// Start attaches the command to the console's pseudo-terminal on all
	// platforms. (On Unix you can alternatively assign c.Tty() to the
	// command's Stdin/Stdout/Stderr yourself.)
	cmd := exec.Command("vi")
	if err = c.Start(cmd); err != nil {
		log.Fatal(err)
	}

	time.Sleep(time.Second)
	c.Send("iHello world\x1b")
	time.Sleep(time.Second)
	c.SendLine(":q!")

	// On Windows cmd.Wait does not work for processes attached to a ConPTY,
	// so use expect.WaitProcess instead.
	if err = expect.WaitProcess(context.Background(), cmd); err != nil {
		log.Fatal(err)
	}

	// The console holds the pseudo-terminal open, so the process exiting
	// does not produce an EOF by itself. Close the console to unblock
	// ExpectEOF once you are done.
	c.Close()
	c.ExpectEOF()
}
Expecting output
c.ExpectString("What is 1+1?")
c.SendLine("2")
c.ExpectEOF()

Windows notes

  • Console.Tty() only exists on Unix: ConPTY has no slave file. Use Console.Start to attach commands.
  • SendLine terminates lines with "\n" on Unix and "\r" on Windows, where the ConPTY treats carriage return as enter.
  • Wait for processes with expect.WaitProcess rather than cmd.Wait.
  • ConPTY output contains VT escape sequences (cursor movement, colors) in addition to the raw program output. String matchers still work because the program's text appears literally within the stream, but exact-match assertions on full output will differ from Unix.

Documentation

Overview

Package expect provides an expect-like interface to automate control of interactive applications through a pseudo-terminal. It works cross-platform: on Unix the Console is backed by a classic pty pair, on Windows by a ConPTY pseudo console (via github.com/charmbracelet/x/xpty).

Attach a command to the Console with Console.Start. On Unix the slave file is also available via Console.Tty for in-process use or manual stdio assignment; Windows ConPTY has no slave file, so Start is the only way to attach a process there, and processes started this way must be waited on with WaitProcess instead of exec.Cmd.Wait.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func EOF

func EOF(opts *Opts) error

EOF adds an Expect condition to exit if io.EOF is returned from reading Console's tty.

func NewChanReader

func NewChanReader(ctx context.Context, bytec <-chan byte) io.Reader

NewChanReader returns a io.Reader over a byte chan. If context is cancelled, future Reads will return io.EOF.

func NewTestWriter

func NewTestWriter(t *testing.T) (io.Writer, error)

NewTestWriter returns an io.Writer where bytes written to the file are logged by go's testing logger. Bytes are flushed to the logger on line end.

func PTSClosed

func PTSClosed(opts *Opts) error

PTSClosed adds an Expect condition to exit if the pseudo-terminal was closed while reading. The errors that signal this differ by platform: on Linux reading from the ptm after the pts is closed returns EIO (see https://github.com/kr/pty/issues/21#issuecomment-129381749), on Windows a closed ConPTY surfaces as a broken pipe, and on all platforms a closed Console returns a closed-file error.

func StripTrailingEmptyLines

func StripTrailingEmptyLines(out string) string

StripTrailingEmptyLines returns a copy of s stripped of trailing lines that consist of only space characters.

func WaitProcess

func WaitProcess(ctx context.Context, cmd *exec.Cmd) error

WaitProcess waits for a process started with Console.Start to exit. This exists because on Windows cmd.Wait() does not work with processes spawned on a ConPTY. On other platforms it simply calls cmd.Wait().

Types

type CallbackMatcher

type CallbackMatcher interface {
	// Callback executes the matcher's callback with the content buffer at the
	// time of match.
	Callback(buf *bytes.Buffer) error
}

CallbackMatcher is a matcher that provides a Callback function.

type Console

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

Console is an interface to automate input and output for interactive applications. Console can block until a specified output is received and send input back on it's tty. Console can also multiplex other sources of input and multiplex its output to other writers.

Example (Echo)
c, err := NewConsole(WithStdout(os.Stdout))
if err != nil {
	log.Fatal(err)
}

cmd := exec.Command("echo")
cmd.Stdin = c.Tty()
cmd.Stdout = c.Tty()
cmd.Stderr = c.Tty()

err = cmd.Start()
if err != nil {
	log.Fatal(err)
}

c.Send("Hello world")
c.ExpectString("Hello world")
c.Tty().Close()
c.ExpectEOF()

err = cmd.Wait()
if err != nil {
	log.Fatal(err)
}

c.Close()
Output:
Hello world

func NewConsole

func NewConsole(opts ...ConsoleOpt) (*Console, error)

NewConsole returns a new Console with the given options.

func NewTestConsole

func NewTestConsole(t *testing.T, opts ...ConsoleOpt) (*Console, error)

NewTestConsole returns a new Console that multiplexes the application's stdout to go's testing logger. Primarily so that outputs from parallel tests using t.Parallel() is not interleaved.

func (*Console) Close

func (c *Console) Close() error

Close closes Console's tty. Calling Close will unblock Expect and ExpectEOF.

func (*Console) Expect

func (c *Console) Expect(opts ...Opt) (string, error)

Expect reads from Console's tty until a condition specified from opts is encountered or an error occurs, and returns the buffer read by console. No extra bytes are read once a condition is met, so if a program isn't expecting input yet, it will be blocked. Sends are queued up in tty's internal buffer so that the next Expect will read the remaining bytes (i.e. rest of prompt) as well as its conditions.

func (*Console) ExpectEOF

func (c *Console) ExpectEOF() (string, error)

ExpectEOF reads from Console's tty until EOF or an error occurs, and returns the buffer read by Console. We also treat the PTSClosed error as an EOF.

func (*Console) ExpectString

func (c *Console) ExpectString(s string) (string, error)

ExpectString reads from Console's tty until the provided string is read or an error occurs, and returns the buffer read by Console.

func (*Console) Expectf

func (c *Console) Expectf(format string, args ...interface{}) (string, error)

Expectf reads from the Console's tty until the provided formatted string is read or an error occurs, and returns the buffer read by Console.

func (*Console) Fd

func (c *Console) Fd() uintptr

Fd returns Console's file descriptor. On Unix this is the master part of its pty, on Windows the ConPTY handle.

func (*Console) Log

func (c *Console) Log(v ...interface{})

Log prints to Console's logger. Arguments are handled in the manner of fmt.Print.

func (*Console) Logf

func (c *Console) Logf(format string, v ...interface{})

Logf prints to Console's logger. Arguments are handled in the manner of fmt.Printf.

func (*Console) Pty

func (c *Console) Pty() xpty.Pty

Pty returns the underlying cross-platform pseudo-terminal. On Unix this is a *xpty.UnixPty wrapping a classic pty pair, on Windows a *xpty.ConPty wrapping a ConPTY pseudo console.

func (*Console) Read

func (c *Console) Read(b []byte) (int, error)

Read reads bytes b from Console's tty.

func (*Console) Send

func (c *Console) Send(s string) (int, error)

Send writes string s to Console's tty.

func (*Console) SendLine

func (c *Console) SendLine(s string) (int, error)

SendLine writes string s to Console's tty with a trailing line separator: "\n" on Unix, and "\r" on Windows where the ConPTY line discipline treats carriage return as enter.

func (*Console) Start

func (c *Console) Start(cmd *exec.Cmd) error

Start starts cmd attached to the Console's pseudo-terminal, with its standard input, output, and error connected to the terminal unless already set. Mirroring creack/pty's StartWithSize, the command is run in a new session with the pty as its controlling terminal, so that programs opening /dev/tty and job-control signals work.

Wait for commands started this way with WaitProcess, which is also safe on Windows where cmd.Wait does not work with a ConPTY.

func (*Console) Tty

func (c *Console) Tty() *os.File

Tty returns Console's pts (slave part of a pty). A pseudoterminal, or pty is a pair of pseudo-devices, one of which, the slave, emulates a real text terminal device.

Tty is only available on Unix; Windows ConPTY has no slave file. Use Console.Start to attach a command to the Console on all platforms.

func (*Console) Write

func (c *Console) Write(b []byte) (int, error)

Write writes bytes b to Console's tty.

type ConsoleCallback

type ConsoleCallback func(buf *bytes.Buffer) error

ConsoleCallback is a callback function to execute if a match is found for the chained matcher.

type ConsoleOpt

type ConsoleOpt func(*ConsoleOpts) error

ConsoleOpt allows setting Console options.

func WithCloser

func WithCloser(closer ...io.Closer) ConsoleOpt

WithCloser adds closers that are closed in order when Console is closed.

func WithDefaultTimeout

func WithDefaultTimeout(timeout time.Duration) ConsoleOpt

WithDefaultTimeout sets a default read timeout during Expect statements.

func WithExpectObserver

func WithExpectObserver(observers ...Observer) ConsoleOpt

WithExpectObserver adds an Observer to allow monitoring Expect operations.

func WithLogger

func WithLogger(logger *log.Logger) ConsoleOpt

WithLogger adds a logger for Console to log debugging information to. By default Console will discard logs.

func WithSendObserver

func WithSendObserver(observers ...SendObserver) ConsoleOpt

WithSendObserver adds a SendObserver to allow monitoring Send operations.

func WithStdin

func WithStdin(readers ...io.Reader) ConsoleOpt

WithStdin adds readers that bytes read are written to Console's tty. If a listed reader returns an error, that reader will not be continued to read.

func WithStdout

func WithStdout(writers ...io.Writer) ConsoleOpt

WithStdout adds writers that Console duplicates writes to, similar to the Unix tee(1) command.

Each write is written to each listed writer, one at a time. Console is the last writer, writing to it's internal buffer for matching expects. If a listed writer returns an error, that overall write operation stops and returns the error; it does not continue down the list.

func WithTermSize

func WithTermSize(width, height int) ConsoleOpt

WithTermSize sets the width and height of the Console's terminal. The default is 80x24.

type ConsoleOpts

type ConsoleOpts struct {
	Logger          *log.Logger
	Stdins          []io.Reader
	Stdouts         []io.Writer
	Closers         []io.Closer
	ExpectObservers []Observer
	SendObservers   []SendObserver
	ReadTimeout     *time.Duration
	TermWidth       int
	TermHeight      int
}

ConsoleOpts provides additional options on creating a Console.

type Matcher

type Matcher interface {
	// Match returns true iff a match is found.
	Match(v interface{}) bool
	Criteria() interface{}
}

Matcher provides an interface for finding a match in content read from Console's tty.

type Observer

type Observer func(matchers []Matcher, buf string, err error)

Observer provides an interface for a function callback that will be called after each Expect operation. matchers will be the list of active matchers when an error occurred, or a list of matchers that matched `buf` when err is nil. buf is the captured output that was matched against. err is error that might have occurred. May be nil.

type Opt

type Opt func(*Opts) error

Opt allows settings Expect options.

func All

func All(expectOpts ...Opt) Opt

All adds an Expect condition to exit if the content read from Console's tty matches all of the provided Opt, in any order.

func Error

func Error(errs ...error) Opt

Error adds an Expect condition to exit if reading from Console's tty returns one of the provided errors.

func Regexp

func Regexp(res ...*regexp.Regexp) Opt

Regexp adds an Expect condition to exit if the content read from Console's tty matches the given Regexp.

func RegexpPattern

func RegexpPattern(ps ...string) Opt

RegexpPattern adds an Expect condition to exit if the content read from Console's tty matches the given Regexp patterns. Expect returns an error if the patterns were unsuccessful in compiling the Regexp.

func String

func String(strs ...string) Opt

String adds an Expect condition to exit if the content read from Console's tty contains any of the given strings.

func WithTimeout

func WithTimeout(timeout time.Duration) Opt

WithTimeout sets a read timeout for an Expect statement.

func (Opt) Then

func (eo Opt) Then(f ConsoleCallback) Opt

Then returns an Expect condition to execute a callback if a match is found for the chained matcher.

type Opts

type Opts struct {
	Matchers    []Matcher
	ReadTimeout *time.Duration
}

Opts provides additional options on Expect.

func (Opts) Match

func (eo Opts) Match(v interface{}) Matcher

Match sequentially calls Match on all matchers in Opts and returns the first matcher if a match exists, otherwise nil.

type PassthroughPipe

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

PassthroughPipe pipes data from a io.Reader and allows setting a read deadline. If a timeout is reached the error is returned, otherwise the error from the provided io.Reader is passed through instead.

The implementation is intentionally not backed by an os.Pipe so that it works with readers whose platform offers no deadline support (e.g. the ConPTY output pipe on Windows).

func NewPassthroughPipe

func NewPassthroughPipe(reader io.Reader) (*PassthroughPipe, error)

NewPassthroughPipe returns a new pipe for a io.Reader that passes through non-timeout errors.

func (*PassthroughPipe) Close

func (pp *PassthroughPipe) Close() error

Close unblocks any pending reads. It does not close the underlying reader.

func (*PassthroughPipe) Read

func (pp *PassthroughPipe) Read(p []byte) (n int, err error)

func (*PassthroughPipe) SetReadDeadline

func (pp *PassthroughPipe) SetReadDeadline(t time.Time) error

SetReadDeadline sets the deadline for future and pending Read calls. A zero value for t means Read will not time out.

type ReaderLease

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

ReaderLease provides cancellable io.Readers from an underlying io.Reader.

func NewReaderLease

func NewReaderLease(reader io.Reader) *ReaderLease

NewReaderLease returns a new ReaderLease that begins reading the given io.Reader.

func (*ReaderLease) NewReader

func (rm *ReaderLease) NewReader(ctx context.Context) io.Reader

NewReader returns a cancellable io.Reader for the underlying io.Reader. Readers can be cancelled without interrupting other Readers, and once a reader is a cancelled it will not read anymore bytes from ReaderLease's underlying io.Reader.

type SendObserver

type SendObserver func(msg string, num int, err error)

SendObserver provides an interface for a function callback that will be called after each Send operation. msg is the string that was sent. num is the number of bytes actually sent. err is the error that might have occurred. May be nil.

Jump to

Keyboard shortcuts

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