package repository_test import ( "context" "errors" "log/slog" "testing" "gitea.michaelthomson.dev/mthomson/habits/internal/auth" "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) argon2IdHash := auth.NewArgon2IdHash(1, 32, 64*1024, 32, 256) hashSalt, err := argon2IdHash.GenerateHash([]byte("supersecurepassword"), []byte("supersecuresalt")) if err != nil { t.Errorf("could not generate hash: %v", err) } t.Run("creates new user", func(t *testing.T) { newUser := repository.UserRow{Id: uuid, Email: "test@test.com", HashedPassword: hashSalt.Hash, Salt: hashSalt.Salt} _, err := r.Create(ctx, newUser) AssertNoError(t, err) }) t.Run("gets user by id", func(t *testing.T) { want := repository.UserRow{Id: uuid, Email: "test@test.com", HashedPassword: hashSalt.Hash, Salt: hashSalt.Salt} got, err := r.GetById(ctx, uuid) AssertNoError(t, err) AssertUserRows(t, got, want) }) t.Run("gets user by email", func(t *testing.T) { want := repository.UserRow{Id: uuid, Email: "test@test.com", HashedPassword: hashSalt.Hash, Salt: hashSalt.Salt} got, err := r.GetByEmail(ctx, "test@test.com") 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: hashSalt.Hash, Salt: hashSalt.Salt} 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 }