Dawid Wysokiński
847ac51b38
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #18
101 lines
2.6 KiB
Go
101 lines
2.6 KiB
Go
package service_test
|
|
|
|
import (
|
|
"context"
|
|
"testing"
|
|
"time"
|
|
|
|
"gitea.dwysokinski.me/twhelp/sessions/internal/domain"
|
|
"gitea.dwysokinski.me/twhelp/sessions/internal/service"
|
|
"gitea.dwysokinski.me/twhelp/sessions/internal/service/internal/mock"
|
|
"github.com/google/uuid"
|
|
"github.com/stretchr/testify/assert"
|
|
)
|
|
|
|
func TestAPIKey_Create(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
t.Run("OK", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
apiKeyRepo := &mock.FakeAPIKeyRepository{}
|
|
apiKeyRepo.CreateCalls(func(ctx context.Context, params domain.CreateAPIKeyParams) (domain.APIKey, error) {
|
|
return domain.APIKey{
|
|
ID: 1,
|
|
Name: params.Name(),
|
|
Key: params.Key(),
|
|
UserID: params.UserID(),
|
|
CreatedAt: time.Now(),
|
|
}, nil
|
|
})
|
|
|
|
userSvc := &mock.FakeUserGetter{}
|
|
user := domain.User{ID: 1234}
|
|
userSvc.GetReturns(user, nil)
|
|
|
|
name := uuid.NewString()
|
|
ak, err := service.NewAPIKey(apiKeyRepo, userSvc).Create(context.Background(), name, user.ID)
|
|
assert.NoError(t, err)
|
|
assert.Greater(t, ak.ID, int64(0))
|
|
assert.Equal(t, name, ak.Name)
|
|
_, err = uuid.Parse(ak.Key)
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, user.ID, ak.UserID)
|
|
assert.WithinDuration(t, time.Now(), ak.CreatedAt, 100*time.Millisecond)
|
|
})
|
|
|
|
t.Run("ERR: user doesnt exist", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
userSvc := &mock.FakeUserGetter{}
|
|
var userID int64 = 1234
|
|
userSvc.GetReturns(domain.User{}, domain.UserNotFoundError{ID: userID})
|
|
|
|
ak, err := service.NewAPIKey(nil, userSvc).Create(context.Background(), uuid.NewString(), userID)
|
|
assert.ErrorIs(t, err, domain.UserDoesNotExistError{ID: userID})
|
|
assert.Zero(t, ak)
|
|
})
|
|
}
|
|
|
|
func TestAPIKey_Verify(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
t.Run("OK", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
apiKeyRepo := &mock.FakeAPIKeyRepository{}
|
|
apiKeyRepo.GetCalls(func(ctx context.Context, key string) (domain.APIKey, error) {
|
|
return domain.APIKey{
|
|
ID: 1,
|
|
Key: key,
|
|
UserID: 125,
|
|
CreatedAt: time.Now(),
|
|
}, nil
|
|
})
|
|
|
|
userSvc := &mock.FakeUserGetter{}
|
|
userSvc.GetCalls(func(ctx context.Context, id int64) (domain.User, error) {
|
|
return domain.User{
|
|
ID: id,
|
|
Name: uuid.NewString(),
|
|
CreatedAt: time.Now(),
|
|
}, nil
|
|
})
|
|
|
|
user, err := service.NewAPIKey(apiKeyRepo, userSvc).Verify(context.Background(), uuid.NewString())
|
|
assert.NoError(t, err)
|
|
assert.Greater(t, user.ID, int64(0))
|
|
})
|
|
|
|
t.Run("ERR: invalid uuid", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
key := "abcd"
|
|
user, err := service.NewAPIKey(nil, nil).Verify(context.Background(), key)
|
|
assert.ErrorIs(t, err, domain.APIKeyNotFoundError{
|
|
Key: key,
|
|
})
|
|
assert.Zero(t, user)
|
|
})
|
|
}
|