2022-09-05 03:06:08 -04:00
|
|
|
/*
|
|
|
|
Copyright (c) Edgeless Systems GmbH
|
|
|
|
|
|
|
|
SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
*/
|
|
|
|
|
2022-03-22 11:03:15 -04:00
|
|
|
package cmd
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"errors"
|
|
|
|
"io"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestAskToConfirm(t *testing.T) {
|
|
|
|
// errAborted is an error where the user aborted the action.
|
|
|
|
errAborted := errors.New("user aborted")
|
|
|
|
|
|
|
|
cmd := &cobra.Command{
|
|
|
|
Use: "test",
|
|
|
|
Args: cobra.NoArgs,
|
2024-02-21 07:30:31 -05:00
|
|
|
RunE: func(cmd *cobra.Command, _ []string) error {
|
2022-03-22 11:03:15 -04:00
|
|
|
ok, err := askToConfirm(cmd, "777")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if !ok {
|
|
|
|
return errAborted
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
testCases := map[string]struct {
|
2022-04-26 10:54:05 -04:00
|
|
|
input string
|
|
|
|
wantErr error
|
2022-03-22 11:03:15 -04:00
|
|
|
}{
|
|
|
|
"user confirms": {"y\n", nil},
|
|
|
|
"user confirms long": {"yes\n", nil},
|
|
|
|
"user disagrees": {"n\n", errAborted},
|
|
|
|
"user disagrees long": {"no\n", errAborted},
|
|
|
|
"user is first unsure, but agrees": {"what?\ny\n", nil},
|
|
|
|
"user is first unsure, but disagrees": {"wait.\nn\n", errAborted},
|
|
|
|
"repeated invalid input": {"h\nb\nq\n", ErrInvalidInput},
|
|
|
|
}
|
|
|
|
|
|
|
|
for name, tc := range testCases {
|
|
|
|
t.Run(name, func(t *testing.T) {
|
|
|
|
assert := assert.New(t)
|
|
|
|
|
2022-04-13 07:01:38 -04:00
|
|
|
out := &bytes.Buffer{}
|
2022-03-22 11:03:15 -04:00
|
|
|
cmd.SetOut(out)
|
2022-04-13 07:01:38 -04:00
|
|
|
cmd.SetErr(&bytes.Buffer{})
|
2022-03-22 11:03:15 -04:00
|
|
|
in := bytes.NewBufferString(tc.input)
|
|
|
|
cmd.SetIn(in)
|
2023-03-09 09:23:42 -05:00
|
|
|
cmd.SetArgs([]string{})
|
2022-03-22 11:03:15 -04:00
|
|
|
|
|
|
|
err := cmd.Execute()
|
2022-04-26 10:54:05 -04:00
|
|
|
assert.ErrorIs(err, tc.wantErr)
|
2022-03-22 11:03:15 -04:00
|
|
|
|
|
|
|
output, err := io.ReadAll(out)
|
|
|
|
assert.NoError(err)
|
|
|
|
assert.Contains(string(output), "777")
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|