Files
mtusi2026lab5/internal/user/service_test.go
T

190 lines
5.6 KiB
Go

package user_test
import (
"context"
"errors"
"strings"
"sync"
"testing"
"github.com/google/uuid"
"messenger/internal/platform/apperr"
"messenger/internal/platform/ident"
"messenger/internal/user"
"messenger/internal/user/store"
)
const pw = "correct-horse-battery"
// newService wires the service to the real store over an empty database.
func newService(t *testing.T) *user.Service {
t.Helper()
db.Reset(t)
return user.NewService(store.NewUsers(db.Pool))
}
func TestRegisterStoresUserWithPasswordHash(t *testing.T) {
svc := newService(t)
ctx := context.Background()
u, err := svc.Register(ctx, "alice", "Алиса", pw)
if err != nil {
t.Fatalf("Register error: %v", err)
}
if u.ID.Version() != 7 {
t.Fatalf("id must be UUIDv7, got version %d", u.ID.Version())
}
if !strings.HasPrefix(u.PasswordHash, "$argon2id$") || strings.Contains(u.PasswordHash, pw) {
t.Fatalf("password must be stored as an Argon2id hash, got %q", u.PasswordHash)
}
got, err := svc.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 TestRegisterRejectsInvalidInputAndStoresNothing(t *testing.T) {
svc := newService(t)
ctx := context.Background()
cases := map[string][3]string{
"username": {"Bad Name", "x", pw},
"display_name": {"alice", " ", pw},
"password": {"alice", "Алиса", "short"},
}
for field, in := range cases {
_, err := svc.Register(ctx, in[0], in[1], in[2])
if apperr.KindOf(err) != apperr.KindInvalid || !strings.Contains(err.Error(), field) {
t.Errorf("%s: err = %v, want KindInvalid naming the field", field, err)
}
}
var n int
if err := db.Pool.QueryRow(ctx, `SELECT count(*) FROM users`).Scan(&n); err != nil || n != 0 {
t.Fatalf("users = %d, %v; invalid input must not be stored", n, err)
}
}
func TestRegisterReportsDuplicateAsConflict(t *testing.T) {
svc := newService(t)
ctx := context.Background()
if _, err := svc.Register(ctx, "alice", "A", pw); err != nil {
t.Fatal(err)
}
_, err := svc.Register(ctx, "alice", "B", pw)
if !errors.Is(err, user.ErrUsernameTaken) || apperr.KindOf(err) != apperr.KindConflict {
t.Fatalf("err = %v, want ErrUsernameTaken with KindConflict", err)
}
}
// Concurrent registrations of one username race on the unique constraint:
// exactly one wins and every other gets the conflict, never a 500.
func TestConcurrentRegistrationOfOneUsernameHasOneWinner(t *testing.T) {
svc := newService(t)
ctx := context.Background()
const attempts = 10
errs := make(chan error, attempts)
var start, done sync.WaitGroup
start.Add(1)
for range attempts {
done.Add(1)
go func() {
defer done.Done()
start.Wait()
_, err := svc.Register(ctx, "racer", "Racer", pw)
errs <- err
}()
}
start.Done()
done.Wait()
close(errs)
won, lost := 0, 0
for err := range errs {
switch {
case err == nil:
won++
case errors.Is(err, user.ErrUsernameTaken):
lost++
default:
t.Errorf("unexpected error: %v", err)
}
}
if won != 1 || lost != attempts-1 {
t.Fatalf("won = %d, lost = %d; want 1 and %d", won, lost, attempts-1)
}
var n int
if err := db.Pool.QueryRow(ctx, `SELECT count(*) FROM users WHERE username = 'racer'`).Scan(&n); err != nil || n != 1 {
t.Fatalf("rows = %d, %v; want exactly one", n, err)
}
}
func TestGetByIDUnknownIsNotFound(t *testing.T) {
svc := newService(t)
_, err := svc.GetByID(context.Background(), ident.New())
if !errors.Is(err, user.ErrNotFound) || apperr.KindOf(err) != apperr.KindNotFound {
t.Fatalf("err = %v, want ErrNotFound with KindNotFound", err)
}
}
func TestExistingIDsReturnsOnlyRegistered(t *testing.T) {
svc := newService(t)
ctx := context.Background()
alice, _ := svc.Register(ctx, "alice", "A", pw)
bob, _ := svc.Register(ctx, "bob", "B", pw)
got, err := svc.ExistingIDs(ctx, []uuid.UUID{ident.New(), bob.ID, alice.ID})
if err != nil {
t.Fatal(err)
}
set := map[uuid.UUID]bool{}
for _, id := range got {
set[id] = true
}
if len(got) != 2 || !set[alice.ID] || !set[bob.ID] {
t.Fatalf("ExistingIDs = %v, want alice and bob", got)
}
if empty, err := svc.ExistingIDs(ctx, nil); err != nil || len(empty) != 0 {
t.Fatalf("ExistingIDs(nil) = %v, %v", empty, err)
}
}
func TestAuthenticateChecksPassword(t *testing.T) {
svc := newService(t)
ctx := context.Background()
const colonPassword = "пароль:с:двоеточием 👋"
alice, err := svc.Register(ctx, "alice", "Алиса", colonPassword)
if err != nil {
t.Fatal(err)
}
got, err := svc.Authenticate(ctx, "alice", colonPassword)
if err != nil || got != alice {
t.Fatalf("Authenticate = %+v, %v; want alice", got, err)
}
}
// A wrong password and an unknown username must be indistinguishable.
func TestAuthenticateFailuresLookTheSame(t *testing.T) {
svc := newService(t)
ctx := context.Background()
if _, err := svc.Register(ctx, "alice", "Алиса", pw); err != nil {
t.Fatal(err)
}
_, wrong := svc.Authenticate(ctx, "alice", pw+"!")
_, unknown := svc.Authenticate(ctx, "nobody", pw)
// Basic credentials are client bytes: a username the database cannot
// even compare must still be a plain credential failure.
_, nul := svc.Authenticate(ctx, "a\x00b", pw)
_, notUTF8 := svc.Authenticate(ctx, "\xff\xfe", pw)
for name, err := range map[string]error{
"wrong password": wrong, "unknown user": unknown, "nul username": nul, "invalid utf-8 username": notUTF8,
} {
if !errors.Is(err, user.ErrInvalidCredentials) || apperr.KindOf(err) != apperr.KindUnauthorized {
t.Errorf("%s: err = %v, want ErrInvalidCredentials", name, err)
}
}
if wrong.Error() != unknown.Error() {
t.Fatalf("messages differ: %q vs %q", wrong, unknown)
}
}