From 5df1d725aacb3e756ea7c200dc6d9d80f82344e1 Mon Sep 17 00:00:00 2001 From: David Wittman Date: Sat, 23 May 2015 13:22:35 -0500 Subject: [PATCH] Add test for stdin input Shamelessly borrowed this pattern from write_test.go --- command/auth.go | 13 +++++++++++-- command/auth_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/command/auth.go b/command/auth.go index 5650a56d4..39eba1acb 100644 --- a/command/auth.go +++ b/command/auth.go @@ -27,6 +27,9 @@ type AuthCommand struct { Meta Handlers map[string]AuthHandler + + // The fields below can be overwritten for tests + testStdin io.Reader } func (c *AuthCommand) Run(args []string) int { @@ -66,9 +69,15 @@ func (c *AuthCommand) Run(args []string) int { // token is where the final token will go handler := c.Handlers[method] + // Read token from stdin if first arg is exactly "-" + var stdin io.Reader = os.Stdin + if c.testStdin != nil { + stdin = c.testStdin + } + if len(args) > 0 && args[0] == "-" { - stdin := bufio.NewReader(os.Stdin) - args[0], err = stdin.ReadString('\n') + stdinR := bufio.NewReader(stdin) + args[0], err = stdinR.ReadString('\n') if err != nil && err != io.EOF { c.Ui.Error(fmt.Sprintf("Error reading from stdin: %s", err)) return 1 diff --git a/command/auth_test.go b/command/auth_test.go index 482bd85ae..563d40002 100644 --- a/command/auth_test.go +++ b/command/auth_test.go @@ -2,6 +2,7 @@ package command import ( "fmt" + "io" "io/ioutil" "os" "path/filepath" @@ -82,6 +83,36 @@ func TestAuth_token(t *testing.T) { } } +func TestAuth_stdin(t *testing.T) { + core, _, token := vault.TestCoreUnsealed(t) + ln, addr := http.TestServer(t, core) + defer ln.Close() + + testAuthInit(t) + + stdinR, stdinW := io.Pipe() + ui := new(cli.MockUi) + c := &AuthCommand{ + Meta: Meta{ + Ui: ui, + }, + testStdin: stdinR, + } + + go func() { + stdinW.Write([]byte(token)) + stdinW.Close() + }() + + args := []string{ + "-address", addr, + "-", + } + if code := c.Run(args); code != 0 { + t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String()) + } +} + func TestAuth_badToken(t *testing.T) { core, _, _ := vault.TestCoreUnsealed(t) ln, addr := http.TestServer(t, core)