Dawid Wysokiński
847ac51b38
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #18
97 lines
2.5 KiB
Go
97 lines
2.5 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(), uuid.NewString(), fixture.user(t, "user-1").ID)
|
|
require.NoError(t, err)
|
|
|
|
apiKey, err := repo.Create(context.Background(), params)
|
|
assert.NoError(t, err)
|
|
assert.Greater(t, apiKey.ID, int64(0))
|
|
assert.Equal(t, params.Name(), apiKey.Name)
|
|
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: user doesn't exist", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
params, err := domain.NewCreateAPIKeyParams(uuid.NewString(), uuid.NewString(), fixture.user(t, "user-1").ID+11111)
|
|
require.NoError(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(
|
|
uuid.NewString(),
|
|
fixture.apiKey(t, "user-1-api-key-1").Key,
|
|
fixture.user(t, "user-1").ID,
|
|
)
|
|
require.NoError(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)
|
|
})
|
|
}
|