File: ask_test.go

package info (click to toggle)
golang-github-tcnksm-go-input 0.0~git20180404.548a7d7-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 136 kB
  • sloc: makefile: 20
file content (72 lines) | stat: -rw-r--r-- 1,213 bytes parent folder | download
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
package input

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"testing"
)

func TestAsk(t *testing.T) {
	cases := []struct {
		opts      *Options
		userInput io.Reader
		expect    string
	}{
		{
			opts:      &Options{},
			userInput: bytes.NewBufferString("Taichi\n"),
			expect:    "Taichi",
		},

		{
			opts: &Options{
				Default: "Nakashima",
			},
			userInput: bytes.NewBufferString("\n"),
			expect:    "Nakashima",
		},

		// Loop & Required
		{
			opts: &Options{
				Required: true,
				Loop:     true,
			},
			userInput: bytes.NewBufferString("\nNakashima\n"),
			expect:    "Nakashima",
		},
	}

	for i, c := range cases {
		ui := &UI{
			Writer: ioutil.Discard,
			Reader: c.userInput,
		}

		ans, err := ui.Ask("", 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 ExampleUI_Ask() {
	ui := &UI{
		// In real world, Reader is os.Stdin and input comes
		// from user actual input.
		Reader: bytes.NewBufferString("tcnksm"),
		Writer: ioutil.Discard,
	}

	query := "What is your name?"
	name, _ := ui.Ask(query, &Options{})

	fmt.Println(name)
	// Output: tcnksm
}