Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test(bcrypt): simplify test #11013

Merged
merged 7 commits into from
Oct 21, 2022
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 3 additions & 2 deletions cmd/argocd/commands/bcrypt.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ package commands

import (
"fmt"
"log"

"github.com/spf13/cobra"
"golang.org/x/crypto/bcrypt"
"log"
)

// bcryptCmd represents the bcrypt command
Expand All @@ -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))
},
}

Expand Down
53 changes: 6 additions & 47 deletions cmd/argocd/commands/bcrypt_test.go
Original file line number Diff line number Diff line change
@@ -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)
}