sessions/internal/service/api_key_test.go
Dawid Wysokiński ffcb965590
All checks were successful
continuous-integration/drone/push Build is passing
feat: add a new command - db apikey create (#6)
Reviewed-on: #6
2022-11-20 08:14:41 +00:00

56 lines
1.5 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,
Key: params.Key(),
UserID: params.UserID(),
CreatedAt: time.Now(),
}, nil
})
userSvc := &mock.FakeUserGetter{}
user := domain.User{ID: 1234}
userSvc.GetReturns(user, nil)
ak, err := service.NewAPIKey(apiKeyRepo, userSvc).Create(context.Background(), user.ID)
assert.NoError(t, err)
assert.Greater(t, ak.ID, int64(0))
_, 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(), userID)
assert.ErrorIs(t, err, domain.UserDoesNotExistError{ID: userID})
assert.Zero(t, ak)
})
}