sessions/internal/bundb/api_key_test.go

95 lines
2.4 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)
})
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)
})
}
func TestAPIKey_Get(t *testing.T) {
t.Parallel()
db := newDB(t)
fixture := loadFixtures(t, db)
repo := bundb.NewAPIKey(db)
apiKeyFromFixture := fixture.apiKey(t, "user-1-api-key-1")
t.Run("OK", func(t *testing.T) {
t.Parallel()
ak, err := repo.Get(context.Background(), apiKeyFromFixture.Key)
assert.NoError(t, err)
assert.Equal(t, apiKeyFromFixture, ak)
})
t.Run("ERR: API key not found", func(t *testing.T) {
t.Parallel()
ak, err := repo.Get(context.Background(), apiKeyFromFixture.Key+"1")
assert.ErrorIs(t, err, domain.APIKeyNotFoundError{
Key: apiKeyFromFixture.Key + "1",
})
assert.Zero(t, ak)
})
}