-
Notifications
You must be signed in to change notification settings - Fork 1
/
cmd_test.go
89 lines (80 loc) · 1.83 KB
/
cmd_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"bytes"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/crypto/bcrypt"
)
var tests = []struct {
name string
password string
wantErr bool
cost int
expectedErr interface{}
}{
{
name: "Hash sample password",
password: "foo",
},
{
name: "Hash very short password",
password: "x",
},
{
name: "Hash very short password",
password: "x",
},
{
name: "Hash long password",
password: "012345678901234567890123456789012345678901234567890123456",
},
{
name: "Invalid cost (too low)",
cost: 1,
expectedErr: "cost 1 is outside allowed range",
wantErr: true,
},
{
name: "Invalid cost (too high)",
cost: 32,
expectedErr: "cost 32 is outside allowed range",
wantErr: true,
},
{
name: "No password provided",
expectedErr: "you must provide the password through stdin",
wantErr: true,
},
}
func TestBcryptGenerateCmd_Execute(t *testing.T) {
for _, tt := range tests {
cmd := NewBcryptGenerateCmd()
t.Run(tt.name, func(t *testing.T) {
var err error
expectedCost := DefaultCost
if tt.cost != 0 {
expectedCost = tt.cost
}
cmd.Cost = expectedCost
out := &bytes.Buffer{}
cmd.OutWriter = out
if tt.password != "" {
in := bytes.NewBufferString(tt.password)
cmd.InReader = in
}
err = cmd.Execute([]string{})
stdout := out.String()
if (err != nil) != tt.wantErr {
t.Errorf("BcryptGenerateCmd.Execute() error = %v, wantErr %v", err, tt.wantErr)
}
if err != nil {
if tt.expectedErr != nil {
assert.Regexp(t, tt.expectedErr, err, "Expected error %v to match %v", err, tt.expectedErr)
}
} else {
require.NoError(t, bcrypt.CompareHashAndPassword([]byte(stdout), []byte(tt.password)))
}
})
}
}