...
1 package cmdx
2
3 import (
4 "bytes"
5 "io/ioutil"
6 "testing"
7
8 "github.com/stretchr/testify/assert"
9 "github.com/stretchr/testify/require"
10 )
11
12 func TestAskForConfirmation(t *testing.T) {
13 t.Run("case=prints question", func(t *testing.T) {
14 testQuestion := "test-question"
15 stdin, stdout := new(bytes.Buffer), new(bytes.Buffer)
16
17 _, err := stdin.Write([]byte("y\n"))
18 require.NoError(t, err)
19
20 AskForConfirmation(testQuestion, stdin, stdout)
21
22 prompt, err := ioutil.ReadAll(stdout)
23 require.NoError(t, err)
24 assert.Contains(t, string(prompt), testQuestion)
25 })
26
27 t.Run("case=accept", func(t *testing.T) {
28 for _, input := range []string{
29 "y\n",
30 "yes\n",
31 } {
32 stdin := new(bytes.Buffer)
33
34 _, err := stdin.Write([]byte(input))
35 require.NoError(t, err)
36
37 confirmed := AskForConfirmation("", stdin, new(bytes.Buffer))
38
39 assert.True(t, confirmed)
40 }
41 })
42
43 t.Run("case=reject", func(t *testing.T) {
44 for _, input := range []string{
45 "n\n",
46 "no\n",
47 } {
48 stdin := new(bytes.Buffer)
49
50 _, err := stdin.Write([]byte(input))
51 require.NoError(t, err)
52
53 confirmed := AskForConfirmation("", stdin, new(bytes.Buffer))
54
55 assert.False(t, confirmed)
56 }
57 })
58
59 t.Run("case=reprompt on random input", func(t *testing.T) {
60 testQuestion := "question"
61
62 for _, input := range []string{
63 "foo\ny\n",
64 "bar\nn\n",
65 } {
66 stdin, stdout := new(bytes.Buffer), new(bytes.Buffer)
67
68 _, err := stdin.Write([]byte(input))
69 require.NoError(t, err)
70
71 AskForConfirmation(testQuestion, stdin, stdout)
72
73 output, err := ioutil.ReadAll(stdout)
74 require.NoError(t, err)
75 assert.Equal(t, 2, bytes.Count(output, []byte(testQuestion)))
76 }
77 })
78 }
79
View as plain text