...
1
21
22 package fosite
23
24 import (
25 "context"
26 "testing"
27
28 "github.com/stretchr/testify/assert"
29 "golang.org/x/crypto/bcrypt"
30 )
31
32 func TestCompare(t *testing.T) {
33 workfactor := 10
34 hasher := &BCrypt{
35 WorkFactor: workfactor,
36 }
37
38 expectedPassword := "hello world"
39 expectedPasswordHash, err := hasher.Hash(context.TODO(), []byte(expectedPassword))
40 assert.NoError(t, err)
41 assert.NotNil(t, expectedPasswordHash)
42
43 testCases := []struct {
44 testDescription string
45 providedPassword string
46 shouldError bool
47 }{
48 {
49 testDescription: "should not return an error if hash of provided password matches hash of expected password",
50 providedPassword: expectedPassword,
51 shouldError: false,
52 },
53 {
54 testDescription: "should return an error if hash of provided password does not match hash of expected password",
55 providedPassword: "some invalid password",
56 shouldError: true,
57 },
58 }
59
60 for _, test := range testCases {
61 t.Run(test.testDescription, func(t *testing.T) {
62 hash, err := hasher.Hash(context.TODO(), []byte(test.providedPassword))
63 assert.NoError(t, err)
64 assert.NotNil(t, hash)
65
66 err = hasher.Compare(context.TODO(), expectedPasswordHash, []byte(test.providedPassword))
67 if test.shouldError {
68 assert.Error(t, err)
69 } else {
70 assert.NoError(t, err)
71 }
72 })
73 }
74 }
75
76 func TestHash(t *testing.T) {
77 validWorkFactor := 10
78 invalidWorkFactor := 1000
79 password := []byte("bar")
80
81 testCases := []struct {
82 testDescription string
83 workFactor int
84 shouldError bool
85 }{
86 {
87 testDescription: "should succeed if work factor is valid",
88 workFactor: validWorkFactor,
89 shouldError: false,
90 },
91 {
92 testDescription: "should fail with error if work factor is invalid",
93 workFactor: invalidWorkFactor,
94 shouldError: true,
95 },
96 }
97
98 for _, test := range testCases {
99 t.Run(test.testDescription, func(t *testing.T) {
100 hasher := &BCrypt{
101 WorkFactor: test.workFactor,
102 }
103
104 _, err := hasher.Hash(context.TODO(), password)
105
106 if test.shouldError {
107 assert.Error(t, err)
108 } else {
109 assert.NoError(t, err)
110 }
111 })
112 }
113 }
114
115 func TestDefaultWorkFactor(t *testing.T) {
116 b := &BCrypt{}
117 data := []byte("secrets")
118 hash, err := b.Hash(context.TODO(), data)
119 if err != nil {
120 t.Fatal(err)
121 }
122
123 cost, err := bcrypt.Cost(hash)
124 if cost != 12 {
125 t.Errorf("got cost factor %d", cost)
126 }
127 }
128
View as plain text