From 488513389b71dc714bf5ec38977977e405698059 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B7=A6=E6=99=93=E6=9D=B0?= Date: Fri, 10 Jan 2020 00:18:50 +0800 Subject: [PATCH] fix tests and ignore EOF --- command.go | 8 ++---- command_test.go | 66 +++++++++++++++++++++++-------------------------- 2 files changed, 33 insertions(+), 41 deletions(-) diff --git a/command.go b/command.go index 7e02b2dd..9b84d512 100644 --- a/command.go +++ b/command.go @@ -1629,11 +1629,7 @@ func (c *Command) ask() bool { c.Println(c.Question) reader := bufio.NewReader(c.getIn(os.Stdin)) for { - answer, err := reader.ReadString('\n') - if err != nil { - c.PrintErrf("Read string failed, err: %v\n", err) - break - } + answer, _ := reader.ReadString('\n') answer = strings.ToLower(strings.TrimSpace(answer)) if answer == "y" || answer == "yes" { return true @@ -1644,4 +1640,4 @@ func (c *Command) ask() bool { } } return false -} \ No newline at end of file +} diff --git a/command_test.go b/command_test.go index 3a15f54c..1624bffb 100644 --- a/command_test.go +++ b/command_test.go @@ -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{ - Use: "root", - Ask: true, - Run: func(c *Command, args []string) { - c.Print(msg) + Use: "root", + Ask: true, + Run: func(c *Command, args []string) { + c.Print("hello,world") }, + outWriter: outBuf, } - outBuf,inBuf := new(bytes.Buffer),new(bytes.Buffer) - rootCmd.SetOut(outBuf) - rootCmd.SetIn(inBuf) - - go func() { - inBuf.WriteString("n\n") - }() - _, err := rootCmd.ExecuteC() + var err error + rootCmd.SetIn(inBuf1) + _, err = rootCmd.ExecuteC() if err != nil { t.Errorf("Unexpected error: %v", err) } @@ -122,31 +134,15 @@ func TestCommandWithAskQuestionAndAnswerNo(t *testing.T) { if got != expected { t.Errorf("expected: %q, got: %q", expected, got) } -} -func TestCommandWithAskQuestionAndAnswerYes(t *testing.T) { - msg := "hello,world" - rootCmd := &Command{ - 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() + outBuf.Reset() + rootCmd.SetIn(inBuf2) + _, err = rootCmd.ExecuteC() if err != nil { t.Errorf("Unexpected error: %v", err) } - got := outBuf.String() - expected := "continue? [Y/N]\nhello,world" + got = outBuf.String() + expected = "continue? [Y/N]\nhello,world" if got != expected { t.Errorf("expected: %q, got: %q", expected, got) }