Skip to content

Commit

Permalink
Add tests to apikey model (#4626)
Browse files Browse the repository at this point in the history
Signed-off-by: Kenta Kozuka <[email protected]>
  • Loading branch information
kentakozuka authored and ffjlabo committed Nov 13, 2023
1 parent 22a396c commit a903988
Showing 1 changed file with 93 additions and 0 deletions.
93 changes: 93 additions & 0 deletions pkg/model/apikey_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,13 @@
package model

import (
"errors"
"fmt"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/crypto/bcrypt"
)

func TestGenerateAPIKey(t *testing.T) {
Expand Down Expand Up @@ -49,3 +52,93 @@ func TestAPIKeyRedactSensitiveData(t *testing.T) {
apiKey.RedactSensitiveData()
assert.Equal(t, apiKey.KeyHash, "redacted")
}

func TestExtractAPIKeyID(t *testing.T) {
tests := []struct {
name string
input string
expected string
expectedErr error
}{
{
name: "Valid API Key",
input: "abc.def",
expected: "abc",
expectedErr: nil,
},
{
name: "Empty Key",
input: "",
expected: "",
expectedErr: errors.New("malformed api key"),
},
{
name: "Only one part",
input: "abc",
expected: "",
expectedErr: errors.New("malformed api key"),
},
{
name: "Multiple periods",
input: "abc.def.ghi",
expected: "",
expectedErr: errors.New("malformed api key"),
},
{
name: "Empty first part",
input: ".def",
expected: "",
expectedErr: errors.New("malformed api key"),
},
{
name: "Empty second part",
input: "abc.",
expected: "",
expectedErr: errors.New("malformed api key"),
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
actual, err := ExtractAPIKeyID(tt.input)
assert.Equal(t, tt.expected, actual)
assert.Equal(t, tt.expectedErr, err)
})
}
}

func TestCompareKey(t *testing.T) {
password := "my-secret-key"
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
hashedStr := string(hashedPassword)
apiKey := &APIKey{KeyHash: hashedStr}

tests := []struct {
name string
input string
expectedError error
}{
{
name: "Valid Key",
input: password,
expectedError: nil,
},
{
name: "Invalid Key",
input: "wrong-key",
expectedError: fmt.Errorf("wrong api key wrong-key: %w", bcrypt.ErrMismatchedHashAndPassword),
},
{
name: "Empty Key",
input: "",
expectedError: errors.New("key was empty"),
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := apiKey.CompareKey(tt.input)
assert.Equal(t, tt.expectedError, err)
})
}
}

0 comments on commit a903988

Please sign in to comment.