forked from tcnksm/go-input
-
Notifications
You must be signed in to change notification settings - Fork 2
/
select_test.go
130 lines (114 loc) · 2.21 KB
/
select_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package input
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"testing"
)
func TestSelect(t *testing.T) {
cases := []struct {
list []string
opts *Options
userInput io.Reader
expect string
}{
{
list: []string{"A", "B", "C"},
opts: &Options{},
userInput: bytes.NewBufferString("1\n"),
expect: "A",
},
{
list: []string{"A", "B", "C"},
opts: &Options{
Default: "A",
},
userInput: bytes.NewBufferString("\n"),
expect: "A",
},
{
list: []string{"A", "B", "C"},
opts: &Options{
Default: "A",
},
userInput: bytes.NewBufferString("3\n"),
expect: "C",
},
// Loop
{
list: []string{"A", "B", "C"},
opts: &Options{
Loop: true,
},
userInput: bytes.NewBufferString("\n3\n"),
expect: "C",
},
// Loop
{
list: []string{"A", "B", "C"},
opts: &Options{
Loop: true,
},
userInput: bytes.NewBufferString("\n\n\n\n\n2\n"),
expect: "B",
},
// Loop
{
list: []string{"A", "B", "C"},
opts: &Options{
Loop: true,
},
userInput: bytes.NewBufferString("4\n3\n"),
expect: "C",
},
// Loop
{
list: []string{"A", "B", "C"},
opts: &Options{
Loop: true,
},
userInput: bytes.NewBufferString("A\n3\n"),
expect: "C",
},
}
for i, c := range cases {
ui := &UI{
Writer: ioutil.Discard,
Reader: c.userInput,
}
ans, err := ui.Select("", c.list, c.opts)
if err != nil {
t.Fatalf("#%d expect not to occurr error: %s", i, err)
}
if ans != c.expect {
t.Fatalf("#%d expect %q to be eq %q", i, ans, c.expect)
}
}
}
func TestSelect_invalidDefault(t *testing.T) {
ui := &UI{
Writer: ioutil.Discard,
}
_, err := ui.Select("Which?", []string{"A", "B", "C"}, &Options{
// "D" is not in select target list
Default: "D",
})
if err == nil {
t.Fatal("expect err to be occurr")
}
}
func ExampleUI_Select() {
ui := &UI{
// In real world, Reader is os.Stdin and input comes
// from user actual input.
Reader: bytes.NewBufferString("3\n"),
Writer: ioutil.Discard,
}
query := "Which language do you prefer to use?"
lang, _ := ui.Select(query, []string{"go", "Go", "golang"}, &Options{
Default: "Go",
})
fmt.Println(lang)
// Output: golang
}