85 lines
1.9 KiB
Go
85 lines
1.9 KiB
Go
package repository_test
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"log/slog"
|
|
"testing"
|
|
|
|
"gitea.michaelthomson.dev/mthomson/habits/internal/test"
|
|
"gitea.michaelthomson.dev/mthomson/habits/internal/user/repository"
|
|
"github.com/gofrs/uuid/v5"
|
|
)
|
|
|
|
func TestCRUD(t *testing.T) {
|
|
ctx := context.Background()
|
|
logger := slog.Default()
|
|
tdb := test.NewTestDatabase(t)
|
|
defer tdb.TearDown()
|
|
r := repository.NewUserRepository(logger, tdb.Db)
|
|
uuid := NewUUID(t)
|
|
|
|
t.Run("creates new user", func(t *testing.T) {
|
|
newUser := repository.UserRow{Id: uuid, Email: "test@test.com", HashedPassword: "supersecurehash"}
|
|
_, err := r.Create(ctx, newUser)
|
|
AssertNoError(t, err)
|
|
})
|
|
|
|
t.Run("gets user", func(t *testing.T) {
|
|
want := repository.UserRow{Id: uuid, Email: "test@test.com", HashedPassword: "supersecurehash"}
|
|
got, err := r.GetById(ctx, uuid)
|
|
AssertNoError(t, err)
|
|
AssertUserRows(t, got, want)
|
|
})
|
|
|
|
t.Run("updates user", func(t *testing.T) {
|
|
want := repository.UserRow{Id: uuid, Email: "new@test.com", HashedPassword: "supersecurehash"}
|
|
err := r.Update(ctx, want)
|
|
AssertNoError(t, err)
|
|
|
|
got, err := r.GetById(ctx, uuid)
|
|
AssertNoError(t, err)
|
|
AssertUserRows(t, got, want)
|
|
})
|
|
|
|
t.Run("deletes user", func(t *testing.T) {
|
|
err := r.Delete(ctx, uuid)
|
|
AssertNoError(t, err)
|
|
|
|
want := repository.ErrNotFound
|
|
_, got := r.GetById(ctx, uuid)
|
|
|
|
AssertErrors(t, got, want)
|
|
})
|
|
}
|
|
|
|
func AssertErrors(t testing.TB, got, want error) {
|
|
t.Helper()
|
|
if !errors.Is(got, want) {
|
|
t.Errorf("got error: %v, want error: %v", want, got)
|
|
}
|
|
}
|
|
|
|
func AssertNoError(t testing.TB, err error) {
|
|
t.Helper()
|
|
if err != nil {
|
|
t.Errorf("expected no error, got %v", err)
|
|
}
|
|
}
|
|
|
|
func AssertUserRows(t testing.TB, got, want repository.UserRow) {
|
|
t.Helper()
|
|
if !got.Equal(want) {
|
|
t.Errorf("got %+v want %+v", got, want)
|
|
}
|
|
}
|
|
|
|
func NewUUID(t testing.TB) uuid.UUID {
|
|
t.Helper()
|
|
uuid, err := uuid.NewV4()
|
|
if err != nil {
|
|
t.Errorf("error generation uuid: %v", err)
|
|
}
|
|
return uuid
|
|
}
|