surveyexpect is an Expect library for AlecAivazis/survey/v2
Go >= 1.17
go get go.nhat.io/surveyexpect
Type | Supported | Supported Actions |
---|---|---|
Confirm |
✓ |
|
Editor |
✘ | There is no plan for support |
Input |
✓ |
|
Multiline |
✓ |
|
Multiselect |
✓ |
|
Password |
✓ |
|
Select |
✓ |
|
There are 2 steps:
Step 1: Create an expectation.
Call surveyexpect.Expect()
s := surveyexpect.Expect(func(s *surveyexpect.Survey) {
s.ExpectPassword("Enter a password:").
Answer("secret")
})(t) // t is *testing.T
Step 2: Run it.
Important: Use the stdio
arg and inject it into the survey.Prompt
otherwise it won't work.
s.Start(func(stdio terminal.Stdio)) {
// For example
p := &survey.Password{Message: "Enter a password:"}
var answer string
err := survey.AskOne(p, &answer, surveyexpect.WithStdio(stdio))
// Asserts.
assert.Equal(t, "123456", answer)
assert.NoError(t, err)
})
package mypackage_test
import (
"testing"
"github.com/AlecAivazis/survey/v2"
"github.com/AlecAivazis/survey/v2/terminal"
"github.com/stretchr/testify/assert"
"go.nhat.io/surveyexpect"
)
func TestMyPackage(t *testing.T) {
t.Parallel()
testCases := []struct {
scenario string
expectSurvey surveyexpect.Expector
expectedAnswer string
expectedError string
}{
{
scenario: "empty answer",
expectSurvey: surveyexpect.Expect(func(s *surveyexpect.Survey) {
s.ExpectPassword("Enter a password:").
Answer("")
}),
},
{
scenario: "password without help",
expectSurvey: surveyexpect.Expect(func(s *surveyexpect.Survey) {
s.ExpectPassword("Enter a password:").
Answer("secret")
}),
expectedAnswer: "secret",
},
{
scenario: "input is interrupted",
expectSurvey: surveyexpect.Expect(func(s *surveyexpect.Survey) {
s.ExpectPassword("Enter a password:").
Interrupt()
}),
expectedError: "interrupt",
},
}
for _, tc := range testCases {
tc := tc
t.Run(tc.scenario, func(t *testing.T) {
t.Parallel()
p := &survey.Password{Message: "Enter a password:"}
// Start the survey.
tc.expectSurvey(t).Start(func(stdio terminal.Stdio) {
// Run your logic here.
// For example.
var answer string
err := survey.AskOne(p, &answer, surveyexpect.WithStdio(stdio))
assert.Equal(t, tc.expectedAnswer, answer)
if tc.expectedError == "" {
assert.NoError(t, err)
} else {
assert.EqualError(t, err, tc.expectedError)
}
})
})
}
}
You can find more examples in the tests of this library:
- Confirm: https://github.com/nhatthm/surveyexpect/blob/master/confirm_test.go
- Input: https://github.com/nhatthm/surveyexpect/blob/master/input_test.go
- Multiline: https://github.com/nhatthm/surveyexpect/blob/master/multiline_test.go
- Multiselect: https://github.com/nhatthm/surveyexpect/blob/master/multiselect_test.go
- Password: https://github.com/nhatthm/surveyexpect/blob/master/password_test.go
- Select: https://github.com/nhatthm/surveyexpect/blob/master/select_test.go
If this project help you reduce time to develop, you can give me a cup of coffee :)
or scan this