AlecAivazis/survey: Difference between revisions
Jump to navigation
Jump to search
Line 24: | Line 24: | ||
"github.com/AlecAivazis/survey/v2/terminal" | "github.com/AlecAivazis/survey/v2/terminal" | ||
) | ) | ||
func NewTestFileReader(input string) *TestFileReader { | func NewTestFileReader(input string) *TestFileReader { | ||
Line 36: | Line 32: | ||
input}, | input}, | ||
} | } | ||
} | |||
type TestFileReader struct { | |||
sequences []string | |||
} | } | ||
Revision as of 20:17, 6 November 2024
External
Internal
go.mod
go get github.com/AlecAivazis/survey/v2@v2.3.7
Concepts
Unit Testing
Create a test FileReader
and a test terminal.Studio
:
import (
"fmt"
"io"
"os"
"github.com/AlecAivazis/survey/v2"
"github.com/AlecAivazis/survey/v2/terminal"
)
func NewTestFileReader(input string) *TestFileReader {
return &TestFileReader{
sequences: []string{
"\x1b[1;1R",
"\x1b[0;0R",
input},
}
}
type TestFileReader struct {
sequences []string
}
func (fr *TestFileReader) Read(p []byte) (n int, err error) {
if len(fr.sequences) != 0 {
seq := fr.sequences[0]
fr.sequences = fr.sequences[1:]
n = copy(p, seq)
return n, nil
}
return 0, io.EOF
}
func (fr *TestFileReader) Fd() uintptr {
return 0
}
func NewTestTerminalStudio(input string) terminal.Stdio {
return terminal.Stdio{
In: NewTestFileReader(input),
Out: os.Stdout,
Err: os.Stderr,
}
}
Then configure the survey.AskOne
with the Stdio
that returns "Y\n" or "N\n":
prompt := &survey.Confirm{
Message: "Something",
Default: false,
}
var accepted bool
err := survey.AskOne(prompt, &accepted, func(options *survey.AskOptions) error {
options.Stdio = NewTestTerminalStudio("Y\n")
return nil
})
if err != nil {
panic(err)
}
fmt.Println(accepted)