fix tests and ignore EOF

This commit is contained in:
左晓杰 2020-01-10 00:18:50 +08:00
parent fcf1f3cf76
commit 488513389b
2 changed files with 33 additions and 41 deletions

View file

@ -1629,11 +1629,7 @@ func (c *Command) ask() bool {
c.Println(c.Question) c.Println(c.Question)
reader := bufio.NewReader(c.getIn(os.Stdin)) reader := bufio.NewReader(c.getIn(os.Stdin))
for { for {
answer, err := reader.ReadString('\n') answer, _ := reader.ReadString('\n')
if err != nil {
c.PrintErrf("Read string failed, err: %v\n", err)
break
}
answer = strings.ToLower(strings.TrimSpace(answer)) answer = strings.ToLower(strings.TrimSpace(answer))
if answer == "y" || answer == "yes" { if answer == "y" || answer == "yes" {
return true return true
@ -1644,4 +1640,4 @@ func (c *Command) ask() bool {
} }
} }
return false return false
} }

View file

@ -95,25 +95,37 @@ func TestChildCommand(t *testing.T) {
} }
} }
func TestCommandWithAsk(t *testing.T) {
done := make(chan bool)
defer func() {
done <- true
}()
outBuf, inBuf1, inBuf2 := new(bytes.Buffer), new(bytes.Buffer), new(bytes.Buffer)
go func() {
for {
select {
case <-done:
break
default:
inBuf1.WriteString("no\r\n")
inBuf2.WriteString("Y\r\n")
}
}
}()
func TestCommandWithAskQuestionAndAnswerNo(t *testing.T) {
msg := "hello, world"
rootCmd := &Command{ rootCmd := &Command{
Use: "root", Use: "root",
Ask: true, Ask: true,
Run: func(c *Command, args []string) { Run: func(c *Command, args []string) {
c.Print(msg) c.Print("hello,world")
}, },
outWriter: outBuf,
} }
outBuf,inBuf := new(bytes.Buffer),new(bytes.Buffer) var err error
rootCmd.SetOut(outBuf) rootCmd.SetIn(inBuf1)
rootCmd.SetIn(inBuf) _, err = rootCmd.ExecuteC()
go func() {
inBuf.WriteString("n\n")
}()
_, err := rootCmd.ExecuteC()
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -122,31 +134,15 @@ func TestCommandWithAskQuestionAndAnswerNo(t *testing.T) {
if got != expected { if got != expected {
t.Errorf("expected: %q, got: %q", expected, got) t.Errorf("expected: %q, got: %q", expected, got)
} }
}
func TestCommandWithAskQuestionAndAnswerYes(t *testing.T) { outBuf.Reset()
msg := "hello,world" rootCmd.SetIn(inBuf2)
rootCmd := &Command{ _, err = rootCmd.ExecuteC()
Use: "root",
Ask: true,
Run: func(c *Command, args []string) {
c.Print(msg)
},
}
outBuf,inBuf := new(bytes.Buffer),new(bytes.Buffer)
rootCmd.SetOut(outBuf)
rootCmd.SetIn(inBuf)
go func() {
inBuf.WriteString("y\n")
}()
_, err := rootCmd.ExecuteC()
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
got := outBuf.String() got = outBuf.String()
expected := "continue? [Y/N]\nhello,world" expected = "continue? [Y/N]\nhello,world"
if got != expected { if got != expected {
t.Errorf("expected: %q, got: %q", expected, got) t.Errorf("expected: %q, got: %q", expected, got)
} }