expect

package
v1.8.2 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2023 License: Apache-2.0, BSD-3-Clause Imports: 16 Imported by: 0

Documentation

Overview

Package expect is a Go version of the classic TCL Expect.

Index

Constants

View Source
const (
	// BatchSend for invoking Send in a batch
	BatchSend = iota
	// BatchExpect for invoking Expect in a batch
	BatchExpect
	// BatchSwitchCase for invoking ExpectSwitchCase in a batch
	BatchSwitchCase
	// BatchSendSignal for invoking SendSignal in a batch.
	BatchSendSignal
)

BatchCommands.

View Source
const (
	// OKTag marks the desired state was reached.
	OKTag = Tag(iota)
	// FailTag means reaching this state will fail the Switch/Case.
	FailTag
	// ContinueTag will recheck for matches.
	ContinueTag
	// NextTag skips match and continues to the next one.
	NextTag
	// NoTag signals no tag was set for this case.
	NoTag
)
View Source
const DefaultTimeout = 60 * time.Second

DefaultTimeout is the default Expect timeout.

Variables

This section is empty.

Functions

func Continue

func Continue(s *Status) func() (Tag, *Status)

Continue returns the Continue Tag and status.

func Fail

func Fail(s *Status) func() (Tag, *Status)

Fail returns Fail Tag and status.

func LogContinue

func LogContinue(msg string, s *Status) func() (Tag, *Status)

LogContinue logs the message and returns the Continue Tag and status.

func Next

func Next() func() (Tag, *Status)

Next returns the Next Tag and status.

func OK

func OK() func() (Tag, *Status)

OK returns the OK Tag and status.

Types

type BCas

type BCas struct {
	// C holds the Caser array for the SwitchCase command.
	C []Caser
}

BCas implements the Batcher interface for SwitchCase commands.

func (*BCas) Arg

func (bc *BCas) Arg() string

Arg returns an empty string , not used for SwitchCase.

func (*BCas) Cases

func (bc *BCas) Cases() []Caser

Cases returns the Caser structure.

func (*BCas) Cmd

func (bc *BCas) Cmd() int

Cmd returns the SwitchCase command(BatchSwitchCase).

func (*BCas) Timeout

func (bc *BCas) Timeout() time.Duration

Timeout returns -1 , setting it to the default value.

type BCasT

type BCasT struct {
	// Cs holds the Caser array for the SwitchCase command.
	C []Caser
	// Tout holds the SwitchCase timeout in seconds.
	T int
}

BCasT implements the Batcher interfacs for SwitchCase commands, adding a timeout option to the BCas type.

func (*BCasT) Arg

func (bct *BCasT) Arg() string

Arg returns an empty string , not used for SwitchCase.

func (*BCasT) Cases

func (bct *BCasT) Cases() []Caser

Cases returns the Caser structure.

func (*BCasT) Cmd

func (bct *BCasT) Cmd() int

Cmd returns the SwitchCase command(BatchSwitchCase).

func (*BCasT) Timeout

func (bct *BCasT) Timeout() time.Duration

Timeout returns the timeout in seconds.

type BCase

type BCase struct {
	// R contains the string regular expression.
	R string
	// S contains the string to be sent if R matches.
	S string
	// T contains the Tag.
	T func() (Tag, *Status)
	// Rt contains the number of retries.
	Rt int
}

BCase with just a string is a bit more friendly to scripting. Implements the Caser interface.

func (*BCase) RE

func (b *BCase) RE() (*regexp.Regexp, error)

RE returns the compiled regular expression.

func (*BCase) Retry

func (b *BCase) Retry() bool

Retry decrements the Retry counter and checks if there are any retries left.

func (*BCase) String

func (b *BCase) String() string

Send returns the string to send.

func (*BCase) Tag

func (b *BCase) Tag() (Tag, *Status)

Tag returns the BCase Tag.

type BExp

type BExp struct {
	// R contains the Expect command regular expression.
	R string
}

BExp implements the Batcher interface for Expect commands using the default timeout.

func (*BExp) Arg

func (be *BExp) Arg() string

Arg returns the Expect regular expression.

func (*BExp) Cases

func (be *BExp) Cases() []Caser

Cases always returns nil for the Expect command.

func (*BExp) Cmd

func (be *BExp) Cmd() int

Cmd returns the Expect command (BatchExpect).

func (*BExp) Timeout

func (be *BExp) Timeout() time.Duration

Timeout always returns -1 which sets it to the value used to call the ExpectBatch function.

type BExpT

type BExpT struct {
	// R contains the Expect command regular expression.
	R string
	// T holds the Expect command timeout in seconds.
	T int
}

BExpT implements the Batcher interface for Expect commands adding a timeout option to the BExp type.

func (*BExpT) Arg

func (bt *BExpT) Arg() string

Arg returns the Expect regular expression.

func (*BExpT) Cases

func (bt *BExpT) Cases() []Caser

Cases always return nil for the Expect command.

func (*BExpT) Cmd

func (bt *BExpT) Cmd() int

Cmd returns the Expect command (BatchExpect).

func (*BExpT) Timeout

func (bt *BExpT) Timeout() time.Duration

Timeout returns the timeout in seconds.

type BSig

type BSig struct {
	// S contains the signal.
	S syscall.Signal
}

BSig implements the Batcher interface for SendSignal commands.

func (*BSig) Arg

func (bs *BSig) Arg() string

Arg returns the signal integer.

func (*BSig) Cases

func (bs *BSig) Cases() []Caser

Cases always returns nil for BSig.

func (*BSig) Cmd

func (bs *BSig) Cmd() int

Cmd returns the SendSignal command (BatchSendSignal).

func (*BSig) Timeout

func (bs *BSig) Timeout() time.Duration

Timeout always returns 0 for BSig.

type BSnd

type BSnd struct {
	S string
}

BSnd implements the Batcher interface for Send commands.

func (*BSnd) Arg

func (bs *BSnd) Arg() string

Arg returns the data to be sent.

func (*BSnd) Cases

func (bs *BSnd) Cases() []Caser

Cases always returns nil , not used for Send commands.

func (*BSnd) Cmd

func (bs *BSnd) Cmd() int

Cmd returns the Send command(BatchSend).

func (*BSnd) Timeout

func (bs *BSnd) Timeout() time.Duration

Timeout always returns 0 , Send doesn't have a timeout.

type BatchRes

type BatchRes struct {
	// Idx is used to match the result with the []Batcher commands sent in.
	Idx int
	// Out output buffer for the expect command at Batcher[Idx].
	Output string
	// Match regexp matches for expect command at Batcher[Idx].
	Match []string
}

BatchRes returned from ExpectBatch for every Expect command executed.

type Batcher

type Batcher interface {
	// cmd returns the Batch command.
	Cmd() int
	// Arg returns the command argument.
	Arg() string
	// Timeout returns the timeout duration for the command , <0 gives default value.
	Timeout() time.Duration
	// Cases returns the Caser structure for SwitchCase commands.
	Cases() []Caser
}

Batcher interface is used to make it more straightforward and readable to create batches of Expects.

var batch = []Batcher{
	&BExpT{"password",8},
	&BSnd{"password\n"},
	&BExp{"olakar@router>"},
	&BSnd{ "show interface description\n"},
	&BExp{ "olakar@router>"},
}

var batchSwCaseReplace = []Batcher{
	&BCasT{[]Caser{
		&BCase{`([0-9]) -- .*\(MASTER\)`, `\1` + "\n"}}, 1},
	&BExp{`prompt/>`},
}

type Case

type Case struct {
	// R is the compiled regexp to match.
	R *regexp.Regexp
	// S is the string to send if Regexp matches.
	S string
	// T is the Tag for this Case.
	T func() (Tag, *Status)
	// Rt specifies number of times to retry, only used for cases tagged with Continue.
	Rt int
}

Case used by the ExpectSwitchCase to take different Cases. Implements the Caser interface.

func (*Case) RE

func (c *Case) RE() (*regexp.Regexp, error)

RE returns the compiled regular expression.

func (*Case) Retry

func (c *Case) Retry() bool

Retry decrements the Retry counter and checks if there are any retries left.

func (*Case) String

func (c *Case) String() string

Send returns the string to send if regexp matches

func (*Case) Tag

func (c *Case) Tag() (Tag, *Status)

Tag returns the tag for this case.

type Caser

type Caser interface {
	// RE returns a compiled regexp
	RE() (*regexp.Regexp, error)
	// Send returns the send string
	String() string
	// Tag returns the Tag.
	Tag() (Tag, *Status)
	// Retry returns true if there are retries left.
	Retry() bool
}

Caser is an interface for ExpectSwitchCase and Batch to be able to handle both the Case struct and the more script friendly BCase struct.

type Expecter

type Expecter interface {
	// Expect reads output from a spawned session and tries matching it with the provided regular expression.
	// It returns  all output found until match.
	Expect(*regexp.Regexp, time.Duration) (string, []string, error)
	// ExpectBatch takes an array of BatchEntries and runs through them in order. For every Expect
	// command a BatchRes entry is created with output buffer and sub matches.
	// Failure of any of the batch commands will stop the execution, returning the results up to the
	// failure.
	ExpectBatch([]Batcher, time.Duration) ([]BatchRes, error)
	// ExpectSwitchCase makes it possible to Expect with multiple regular expressions and actions. Returns the
	// full output and submatches of the commands together with an index for the matching Case.
	ExpectSwitchCase([]Caser, time.Duration) (string, []string, int, error)
	// Send sends data into the spawned session.
	Send(string) error
	// Close closes the spawned session and files.
	Close() error
}

Expecter interface primarily to make testing easier.

type GExpect

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

GExpect implements the Expecter interface.

func SpawnFake

func SpawnFake(b []Batcher, timeout time.Duration, opt ...Option) (*GExpect, <-chan error, error)

SpawnFake spawns an expect.Batcher.

func SpawnGeneric

func SpawnGeneric(opt *GenOptions, timeout time.Duration, opts ...Option) (*GExpect, <-chan error, error)

SpawnGeneric is used to write generic Spawners. It returns an Expecter. The returned channel will give the return status of the spawned session, in practice this means the return value of the provided Wait function.

func (*GExpect) Close

func (e *GExpect) Close() error

Close closes the Spawned session.

func (*GExpect) Expect

func (e *GExpect) Expect(re *regexp.Regexp, timeout time.Duration) (string, []string, error)

Expect reads spawned processes output looking for input regular expression. Timeout set to 0 makes Expect return the current buffer. Negative timeout value sets it to Default timeout.

func (*GExpect) ExpectBatch

func (e *GExpect) ExpectBatch(batch []Batcher, timeout time.Duration) ([]BatchRes, error)

ExpectBatch takes an array of BatchEntry and executes them in order filling in the BatchRes array for any Expect command executed.

func (*GExpect) ExpectSwitchCase

func (e *GExpect) ExpectSwitchCase(cs []Caser, timeout time.Duration) (string, []string, int, error)

ExpectSwitchCase checks each Case against the accumulated out buffer, sending specified string back. Leaving Send empty will Send nothing to the process. Substring expansion can be used eg.

Case{`vf[0-9]{2}.[a-z]{3}[0-9]{2}\.net).*UP`,`show arp \1`}
Given: vf11.hnd01.net            UP      35 (4)        34 (4)          CONNECTED         0              0/0
Would send: show arp vf11.hnd01.net

func (*GExpect) Options

func (e *GExpect) Options(opts ...Option) (prev Option)

Options sets the specified options.

func (*GExpect) Read

func (e *GExpect) Read(p []byte) (nr int, err error)

Read implements the reader interface for the out buffer.

func (*GExpect) Send

func (e *GExpect) Send(in string) error

Send sends a string to spawned process.

func (*GExpect) SendSignal

func (e *GExpect) SendSignal(sig os.Signal) error

SendSignal sends a signal to the Expect controlled process. Only works on Process Expecters.

func (*GExpect) String

func (e *GExpect) String() string

String implements the stringer interface.

type GenOptions

type GenOptions struct {
	// In is where Expect Send messages will be written.
	In io.WriteCloser
	// Out will be read and matched by the expecter.
	Out io.Reader
	// Wait is used by expect to know when the session is over and cleanup of io Go routines should happen.
	Wait func() error
	// Close will be called as part of the expect Close, should normally include a Close of the In WriteCloser.
	Close func() error
	// Check is called everytime a Send or Expect function is called to makes sure the session is still running.
	Check func() bool
}

GenOptions contains the options needed to set up a generic Spawner.

type Option

type Option func(*GExpect) Option

Option represents one Expecter option.

func BufferSize

func BufferSize(bufferSize int) Option

BufferSize sets the size of receive buffer in bytes.

func ChangeCheck

func ChangeCheck(f func() bool) Option

ChangeCheck changes the Expect check function.

func CheckDuration

func CheckDuration(d time.Duration) Option

CheckDuration changes the default duration checking for new incoming data.

func DebugCheck

func DebugCheck(l *log.Logger) Option

DebugCheck adds logging to the check function. The check function for the spawners are called at creation/timeouts and I/O so can be usable for printing current state during debugging.

func NoCheck

func NoCheck() Option

NoCheck turns off the Expect alive checks.

func PartialMatch

func PartialMatch(v bool) Option

PartialMatch enables/disables the returning of unmatched buffer so that consecutive expect call works.

func SendTimeout

func SendTimeout(timeout time.Duration) Option

SendTimeout set timeout for Send commands

func SetEnv

func SetEnv(env []string) Option

SetEnv sets the environmental variables of the spawned process.

func SetSysProcAttr

func SetSysProcAttr(args *syscall.SysProcAttr) Option

SetSysProcAttr sets the SysProcAttr syscall values for the spawned process. Because this modifies cmd, it will only work with the process spawners and not effect the GExpect option method.

func Tee

func Tee(w io.WriteCloser) Option

Tee duplicates all of the spawned process's output to the given writer and closes the writer when complete. Writes occur from another thread, so synchronization may be necessary.

func Verbose

func Verbose(v bool) Option

Verbose enables/disables verbose logging of matches and sends.

func VerboseWriter

func VerboseWriter(w io.Writer) Option

VerboseWriter sets an alternate destination for verbose logs.

type Status

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

Status contains an errormessage and a status code.

func NewStatus

func NewStatus(code codes.Code, msg string) *Status

NewStatus creates a Status with the provided code and message.

func NewStatusf

func NewStatusf(code codes.Code, format string, a ...interface{}) *Status

NewStatusf returns a Status with the provided code and a formatted message.

func (*Status) Err

func (s *Status) Err() error

Err is a helper to handle errors.

func (*Status) Error

func (s *Status) Error() string

Error is here to adhere to the error interface.

type Tag

type Tag int32

Tag represents the state for a Caser.

type TimeoutError

type TimeoutError int

TimeoutError is the error returned by all Expect functions upon timer expiry.

func (TimeoutError) Error

func (t TimeoutError) Error() string

Error implements the Error interface.

Jump to

Keyboard shortcuts

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