diff --git a/cmd/argocd/commands/bcrypt.go b/cmd/argocd/commands/bcrypt.go index 2b798e0fa9a1c..2aaf94fe9450d 100644 --- a/cmd/argocd/commands/bcrypt.go +++ b/cmd/argocd/commands/bcrypt.go @@ -2,9 +2,10 @@ package commands import ( "fmt" + "log" + "github.com/spf13/cobra" "golang.org/x/crypto/bcrypt" - "log" ) // bcryptCmd represents the bcrypt command @@ -22,7 +23,7 @@ func NewBcryptCmd() *cobra.Command { if err != nil { log.Fatalf("Failed to genarate bcrypt hash: %v", err) } - fmt.Println(string(hash)) + fmt.Fprint(cmd.OutOrStdout(), string(hash)) }, } diff --git a/cmd/argocd/commands/bcrypt_test.go b/cmd/argocd/commands/bcrypt_test.go index ea26270be0d1a..c5949977a1425 100644 --- a/cmd/argocd/commands/bcrypt_test.go +++ b/cmd/argocd/commands/bcrypt_test.go @@ -1,63 +1,22 @@ package commands import ( + "bytes" + "testing" + "github.com/stretchr/testify/assert" "golang.org/x/crypto/bcrypt" - "io" - "os" - "strings" - "testing" ) -// capture replaces os.Stdout with a writer that buffers any data written -// to os.Stdout. Call the returned function to clean up and get the data -// as a string. -func capture() func() (string, error) { - r, w, err := os.Pipe() - if err != nil { - panic(err) - } - - done := make(chan error, 1) - - save := os.Stdout - os.Stdout = w - - var buf strings.Builder - - go func() { - _, err = io.Copy(&buf, r) - err = r.Close() - if err != nil { - return - } - done <- err - }() - - return func() (string, error) { - os.Stdout = save - err := w.Close() - if err != nil { - return "", err - } - err = <-done - return buf.String(), err - } -} - func TestGeneratePassword(t *testing.T) { - - done := capture() bcryptCmd := NewBcryptCmd() - bcryptCmd.SetArgs([]string{"--password", "abc"}) + output := new(bytes.Buffer) + bcryptCmd.SetOutput(output) err := bcryptCmd.Execute() if err != nil { return } - capturedOutput, err := done() - assert.NoError(t, err) - - err = bcrypt.CompareHashAndPassword([]byte(capturedOutput), []byte("abc")) + err = bcrypt.CompareHashAndPassword(output.Bytes(), []byte("abc")) assert.NoError(t, err) }