Documentation ¶
Overview ¶
Package expect is a Go version of the classic TCL Expect.
Index ¶
- Constants
- func Continue(s *Status) func() (Tag, *Status)
- func Fail(s *Status) func() (Tag, *Status)
- func LogContinue(msg string, s *Status) func() (Tag, *Status)
- func Next() func() (Tag, *Status)
- func OK() func() (Tag, *Status)
- type BCas
- type BCasT
- type BCase
- type BExp
- type BExpT
- type BSig
- type BSnd
- type BatchRes
- type Batcher
- type Case
- type Caser
- type Expecter
- type GExpect
- func (e *GExpect) Close() error
- func (e *GExpect) Expect(re *regexp.Regexp, timeout time.Duration) (string, []string, error)
- func (e *GExpect) ExpectBatch(batch []Batcher, timeout time.Duration) ([]BatchRes, error)
- func (e *GExpect) ExpectSwitchCase(cs []Caser, timeout time.Duration) (string, []string, int, error)
- func (e *GExpect) Options(opts ...Option) (prev Option)
- func (e *GExpect) Read(p []byte) (nr int, err error)
- func (e *GExpect) Send(in string) error
- func (e *GExpect) SendSignal(sig os.Signal) error
- func (e *GExpect) String() string
- type GenOptions
- type Option
- func BufferSize(bufferSize int) Option
- func ChangeCheck(f func() bool) Option
- func CheckDuration(d time.Duration) Option
- func DebugCheck(l *log.Logger) Option
- func NoCheck() Option
- func PartialMatch(v bool) Option
- func SendTimeout(timeout time.Duration) Option
- func SetEnv(env []string) Option
- func SetSysProcAttr(args *syscall.SysProcAttr) Option
- func Tee(w io.WriteCloser) Option
- func Verbose(v bool) Option
- func VerboseWriter(w io.Writer) Option
- type Status
- type Tag
- type TimeoutError
Constants ¶
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.
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 )
const DefaultTimeout = 60 * time.Second
DefaultTimeout is the default Expect timeout.
Variables ¶
This section is empty.
Functions ¶
func LogContinue ¶
LogContinue logs the message and returns the Continue 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.
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.
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.
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.
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.
type BSnd ¶
type BSnd struct {
S string
}
BSnd implements the Batcher interface for Send commands.
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.
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 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) Expect ¶
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 ¶
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) SendSignal ¶
SendSignal sends a signal to the Expect controlled process. Only works on Process Expecters.
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 every time 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 ¶
Option represents one Expecter option.
func BufferSize ¶
BufferSize sets the size of receive buffer in bytes.
func ChangeCheck ¶
ChangeCheck changes the Expect check function.
func CheckDuration ¶
CheckDuration changes the default duration checking for new incoming data.
func DebugCheck ¶
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 PartialMatch ¶
PartialMatch enables/disables the returning of unmatched buffer so that consecutive expect call works.
func SendTimeout ¶
SendTimeout set timeout for Send commands
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 VerboseWriter ¶
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 NewStatusf ¶
NewStatusf returns a Status with the provided code and a formatted message.
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.