69 lines
1.8 KiB
Go
69 lines
1.8 KiB
Go
|
package bundb_test
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"testing"
|
||
|
"time"
|
||
|
|
||
|
"gitea.dwysokinski.me/twhelp/sessions/internal/bundb"
|
||
|
"gitea.dwysokinski.me/twhelp/sessions/internal/domain"
|
||
|
"github.com/google/uuid"
|
||
|
"github.com/jackc/pgerrcode"
|
||
|
"github.com/stretchr/testify/assert"
|
||
|
"github.com/stretchr/testify/require"
|
||
|
"github.com/uptrace/bun/driver/pgdriver"
|
||
|
)
|
||
|
|
||
|
func TestAPIKey_Create(t *testing.T) {
|
||
|
t.Parallel()
|
||
|
|
||
|
db := newDB(t)
|
||
|
fixture := loadFixtures(t, db)
|
||
|
repo := bundb.NewAPIKey(db)
|
||
|
|
||
|
t.Run("OK", func(t *testing.T) {
|
||
|
t.Parallel()
|
||
|
|
||
|
params, err := domain.NewCreateAPIKeyParams(uuid.NewString(), fixture.user(t, "user-1").ID)
|
||
|
require.Nil(t, err)
|
||
|
|
||
|
apiKey, err := repo.Create(context.Background(), params)
|
||
|
assert.NoError(t, err)
|
||
|
assert.Greater(t, apiKey.ID, int64(0))
|
||
|
assert.Equal(t, params.Key(), apiKey.Key)
|
||
|
assert.Equal(t, params.UserID(), apiKey.UserID)
|
||
|
assert.WithinDuration(t, time.Now(), apiKey.CreatedAt, time.Second)
|
||
|
assert.Zero(t, apiKey.LastUsedAt)
|
||
|
})
|
||
|
|
||
|
t.Run("ERR: player doesn't exist", func(t *testing.T) {
|
||
|
t.Parallel()
|
||
|
|
||
|
params, err := domain.NewCreateAPIKeyParams(uuid.NewString(), fixture.user(t, "user-1").ID+1)
|
||
|
require.Nil(t, err)
|
||
|
|
||
|
apiKey, err := repo.Create(context.Background(), params)
|
||
|
assert.ErrorIs(t, err, domain.UserDoesNotExistError{
|
||
|
ID: params.UserID(),
|
||
|
})
|
||
|
assert.Zero(t, apiKey)
|
||
|
})
|
||
|
|
||
|
t.Run("ERR: key must be unique", func(t *testing.T) {
|
||
|
t.Parallel()
|
||
|
|
||
|
params, err := domain.NewCreateAPIKeyParams(
|
||
|
fixture.apiKey(t, "user-1-api-key-1").Key,
|
||
|
fixture.user(t, "user-1").ID,
|
||
|
)
|
||
|
require.Nil(t, err)
|
||
|
|
||
|
apiKey, err := repo.Create(context.Background(), params)
|
||
|
var pgError pgdriver.Error
|
||
|
assert.ErrorAs(t, err, &pgError)
|
||
|
assert.Equal(t, pgerrcode.UniqueViolation, pgError.Field('C'))
|
||
|
assert.Equal(t, "api_keys_key_key", pgError.Field('n'))
|
||
|
assert.Zero(t, apiKey)
|
||
|
})
|
||
|
}
|