98 lines
2.3 KiB
Go
98 lines
2.3 KiB
Go
package store_test
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"sync"
|
|
"testing"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"messenger/internal/platform/ident"
|
|
"messenger/internal/user"
|
|
"messenger/internal/user/store"
|
|
)
|
|
|
|
func mustUser(t *testing.T, username string) user.User {
|
|
t.Helper()
|
|
u, err := user.New(ident.New(), username, "Display")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return u
|
|
}
|
|
|
|
func TestCreateThenGetByID(t *testing.T) {
|
|
repo := store.NewInMemUsers()
|
|
ctx := context.Background()
|
|
u := mustUser(t, "alice")
|
|
if err := repo.Create(ctx, u); err != nil {
|
|
t.Fatalf("Create error: %v", err)
|
|
}
|
|
got, err := repo.GetByID(ctx, u.ID)
|
|
if err != nil {
|
|
t.Fatalf("GetByID error: %v", err)
|
|
}
|
|
if got != u {
|
|
t.Fatalf("GetByID = %+v, want %+v", got, u)
|
|
}
|
|
}
|
|
|
|
func TestGetByIDUnknownReturnsErrNotFound(t *testing.T) {
|
|
_, err := store.NewInMemUsers().GetByID(context.Background(), ident.New())
|
|
if !errors.Is(err, user.ErrNotFound) {
|
|
t.Fatalf("err = %v, want ErrNotFound", err)
|
|
}
|
|
}
|
|
|
|
func TestCreateRejectsDuplicateUsername(t *testing.T) {
|
|
repo := store.NewInMemUsers()
|
|
ctx := context.Background()
|
|
if err := repo.Create(ctx, mustUser(t, "alice")); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
err := repo.Create(ctx, mustUser(t, "alice"))
|
|
if !errors.Is(err, user.ErrUsernameTaken) {
|
|
t.Fatalf("err = %v, want ErrUsernameTaken", err)
|
|
}
|
|
}
|
|
|
|
func TestCreateIsAtomicUnderConcurrency(t *testing.T) {
|
|
repo := store.NewInMemUsers()
|
|
ctx := context.Background()
|
|
const workers = 50
|
|
var wg sync.WaitGroup
|
|
var mu sync.Mutex
|
|
created := 0
|
|
for i := 0; i < workers; i++ {
|
|
wg.Add(1)
|
|
go func() {
|
|
defer wg.Done()
|
|
if err := repo.Create(ctx, mustUser(t, "same_name")); err == nil {
|
|
mu.Lock()
|
|
created++
|
|
mu.Unlock()
|
|
}
|
|
}()
|
|
}
|
|
wg.Wait()
|
|
if created != 1 {
|
|
t.Fatalf("exactly one Create must win, got %d", created)
|
|
}
|
|
}
|
|
|
|
func TestExistingIDsReturnsOnlyKnownIDs(t *testing.T) {
|
|
repo := store.NewInMemUsers()
|
|
ctx := context.Background()
|
|
alice, bob := mustUser(t, "alice"), mustUser(t, "bob")
|
|
_ = repo.Create(ctx, alice)
|
|
_ = repo.Create(ctx, bob)
|
|
got, err := repo.ExistingIDs(ctx, []uuid.UUID{ident.New(), bob.ID, alice.ID, bob.ID})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(got) != 3 || got[0] != bob.ID || got[1] != alice.ID || got[2] != bob.ID {
|
|
t.Fatalf("ExistingIDs must keep input order and drop unknown ids, got %v", got)
|
|
}
|
|
}
|