Files

337 lines
10 KiB
Go

package postgres
import (
"context"
"errors"
"os"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store"
)
// testStore creates an isolated schema inside the explicitly configured test database.
func testStore(t *testing.T) *Store {
t.Helper()
url := os.Getenv("TEST_DATABASE_URL")
if url == "" {
t.Skip("TEST_DATABASE_URL is required for PostgreSQL integration tests")
}
admin, err := pgx.Connect(t.Context(), url)
if err != nil {
t.Fatal(err)
}
schema := "test_" + uuid.New().String()[:8]
identifier := pgx.Identifier{schema}.Sanitize()
if _, err := admin.Exec(t.Context(), "CREATE SCHEMA "+identifier); err != nil {
t.Fatal(err)
}
separator := "?"
if containsQuery(url) {
separator = "&"
}
s, err := New(Options{URL: url + separator + "search_path=" + schema, MaxConnections: 4, Timeout: 3 * time.Second})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
s.Close()
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if _, err := admin.Exec(ctx, "DROP SCHEMA "+identifier+" CASCADE"); err != nil {
t.Error(err)
}
if err := admin.Close(ctx); err != nil {
t.Error(err)
}
})
if err := s.Start(t.Context()); err != nil {
t.Fatal(err)
}
return s
}
// containsQuery identifies URL parameters without exposing credentials in test logs.
func containsQuery(value string) bool {
for _, char := range value {
if char == '?' {
return true
}
}
return false
}
// fixtureUser creates an independent profile for a persistence scenario.
func fixtureUser(t *testing.T, s *Store) dto.UserDTO {
t.Helper()
user, err := s.Register(t.Context(), dto.UserDTO{ID: uuid.New(), Username: "u_" + uuid.NewString()[:8], DisplayName: "Test"}, "test-hash")
if err != nil {
t.Fatal(err)
}
return user
}
// fixtureChat creates a chat containing an existing user.
func fixtureChat(t *testing.T, s *Store, user dto.UserDTO) dto.ChatDTO {
t.Helper()
chat, err := s.CreateChat(t.Context(), dto.ChatDTO{ID: uuid.New(), Title: "Test", MemberIDs: []uuid.UUID{user.ID}})
if err != nil {
t.Fatal(err)
}
return chat
}
// TestMigrationsRepeat verifies idempotent schema initialization.
func TestMigrationsRepeat(t *testing.T) {
s := testStore(t)
user := fixtureUser(t, s)
if err := s.Start(t.Context()); err != nil {
t.Fatal(err)
}
read, err := s.User(t.Context(), user.ID)
if err != nil || read.ID != user.ID || read.CreatedAt.Location() != time.UTC {
t.Fatalf("migration changed data or UTC: %v", err)
}
if err := s.Ping(t.Context()); err != nil {
t.Fatal(err)
}
}
// TestRegistrationRace verifies database uniqueness under concurrent registration.
func TestRegistrationRace(t *testing.T) {
s := testStore(t)
outcomes := make(chan error, 12)
var wg sync.WaitGroup
for range 12 {
wg.Go(func() {
_, err := s.Register(t.Context(), dto.UserDTO{ID: uuid.New(), Username: "same", DisplayName: "Test"}, "hash")
outcomes <- err
})
}
wg.Wait()
close(outcomes)
successes := 0
for err := range outcomes {
if err == nil {
successes++
} else if !errors.Is(err, store.ErrConflict) {
t.Fatal(err)
}
}
if successes != 1 {
t.Fatalf("got %d successful registrations", successes)
}
}
// TestCreateChatRollsBack verifies failure of membership insertion leaves no chat.
func TestCreateChatRollsBack(t *testing.T) {
s := testStore(t)
id := uuid.New()
_, err := s.CreateChat(t.Context(), dto.ChatDTO{ID: id, Title: "Rollback", MemberIDs: []uuid.UUID{uuid.New()}})
if err == nil {
t.Fatal("foreign key failure absent")
}
if _, err := s.Chat(t.Context(), id); !errors.Is(err, store.ErrNotFound) {
t.Fatalf("chat survived rollback: %v", err)
}
}
// TestChatPageUsesMembershipAndCursor verifies one compound visibility/page invariant.
func TestChatPageUsesMembershipAndCursor(t *testing.T) {
s := testStore(t)
owner := fixtureUser(t, s)
outsider := fixtureUser(t, s)
first := fixtureChat(t, s, owner)
second := fixtureChat(t, s, owner)
fixtureChat(t, s, outsider)
page, err := s.Chats(t.Context(), owner.ID, dto.PositionDTO{CreatedAt: first.CreatedAt, ID: first.ID}, 10)
if err != nil || len(page) != 1 || page[0].ID != second.ID || len(page[0].MemberIDs) != 1 {
t.Fatalf("invalid membership page: %+v %v", page, err)
}
}
// TestMessagePageOrdersConcurrentWrites verifies monotonic durable ordering and continuation.
func TestMessagePageOrdersConcurrentWrites(t *testing.T) {
s := testStore(t)
user := fixtureUser(t, s)
chat := fixtureChat(t, s, user)
var wg sync.WaitGroup
failures := make(chan error, 20)
for range 20 {
wg.Go(func() {
_, err := s.CreateMessage(t.Context(), dto.MessageDTO{ID: uuid.New(), ChatID: chat.ID, SenderID: user.ID, Text: "synthetic"})
failures <- err
})
}
wg.Wait()
close(failures)
for err := range failures {
if err != nil {
t.Fatal(err)
}
}
page, err := s.Messages(t.Context(), chat.ID, dto.PositionDTO{}, 10)
if err != nil || len(page) != 10 {
t.Fatalf("first page: %d %v", len(page), err)
}
for index := 1; index < len(page); index++ {
if !page[index].CreatedAt.After(page[index-1].CreatedAt) {
t.Fatal("timestamps are not monotonic")
}
}
last := page[len(page)-1]
next, err := s.Messages(t.Context(), chat.ID, dto.PositionDTO{CreatedAt: last.CreatedAt, ID: last.ID}, 20)
if err != nil || len(next) != 10 || !next[0].CreatedAt.After(last.CreatedAt) {
t.Fatalf("continuation: %d %v", len(next), err)
}
}
// TestCredentialsReadsStoredHash checks credential lookup independently of public profiles.
func TestCredentialsReadsStoredHash(t *testing.T) {
s := testStore(t)
user := fixtureUser(t, s)
got, hash, err := s.Credentials(t.Context(), user.Username)
if err != nil || got.ID != user.ID || hash != "test-hash" {
t.Fatalf("credentials mismatch: %v", err)
}
}
// TestUsersExistChecksAllIDs verifies the set membership contract.
func TestUsersExistChecksAllIDs(t *testing.T) {
for _, missing := range []bool{false, true} {
t.Run(map[bool]string{false: "all exist", true: "missing member"}[missing], func(t *testing.T) {
s := testStore(t)
ids := []uuid.UUID{fixtureUser(t, s).ID}
if missing {
ids = append(ids, uuid.New())
}
exists, err := s.UsersExist(t.Context(), ids)
if err != nil || exists == missing {
t.Fatalf("exists=%v error=%v", exists, err)
}
})
}
}
// TestSessionExpiry rejects persisted sessions whose absolute deadline has passed.
func TestSessionExpiry(t *testing.T) {
s := testStore(t)
user := fixtureUser(t, s)
if err := s.SaveSession(t.Context(), "expired", user.ID, time.Now().Add(-time.Second)); err != nil {
t.Fatal(err)
}
if _, err := s.SessionUser(t.Context(), "expired"); !errors.Is(err, store.ErrNotFound) {
t.Fatalf("expired session accepted: %v", err)
}
}
// TestSessionRevocation removes a still-valid session from the source of truth.
func TestSessionRevocation(t *testing.T) {
s := testStore(t)
user := fixtureUser(t, s)
if err := s.SaveSession(t.Context(), "live", user.ID, time.Now().Add(time.Hour)); err != nil {
t.Fatal(err)
}
if err := s.RevokeSession(t.Context(), "live"); err != nil {
t.Fatal(err)
}
if _, err := s.SessionUser(t.Context(), "live"); !errors.Is(err, store.ErrNotFound) {
t.Fatalf("revoked session accepted: %v", err)
}
}
// TestSessionResolvesOwner verifies a live session's immutable identity.
func TestSessionResolvesOwner(t *testing.T) {
s := testStore(t)
user := fixtureUser(t, s)
if err := s.SaveSession(t.Context(), "live", user.ID, time.Now().Add(time.Hour)); err != nil {
t.Fatal(err)
}
id, err := s.SessionUser(t.Context(), "live")
if err != nil || id != user.ID {
t.Fatalf("invalid owner: %v", err)
}
}
// TestNewRejectsInvalidOptions verifies pool construction errors without connecting.
func TestNewRejectsInvalidOptions(t *testing.T) {
for _, options := range []Options{{}, {URL: "://invalid", MaxConnections: 1, Timeout: time.Second}} {
if _, err := New(options); err == nil {
t.Fatal("invalid options accepted")
}
}
}
// TestCreateMessageMissingChat reports a typed missing-record error.
func TestCreateMessageMissingChat(t *testing.T) {
s := testStore(t)
_, err := s.CreateMessage(t.Context(), dto.MessageDTO{ID: uuid.New(), ChatID: uuid.New(), SenderID: uuid.New(), Text: "test"})
if !errors.Is(err, store.ErrNotFound) {
t.Fatal(err)
}
}
// TestMessagesCanceledReturnsError verifies bounded cancellation before query execution.
func TestMessagesCanceledReturnsError(t *testing.T) {
s := testStore(t)
ctx, cancel := context.WithCancel(t.Context())
cancel()
if _, err := s.Messages(ctx, uuid.New(), dto.PositionDTO{}, 10); err == nil {
t.Fatal("canceled query succeeded")
}
}
// TestChatsCanceledReturnsError verifies bounded cancellation of membership pages.
func TestChatsCanceledReturnsError(t *testing.T) {
s := testStore(t)
ctx, cancel := context.WithCancel(t.Context())
cancel()
if _, err := s.Chats(ctx, uuid.New(), dto.PositionDTO{}, 10); err == nil {
t.Fatal("canceled query succeeded")
}
}
// TestMigrationCancellationReturnsError checks startup cancellation before migration work.
func TestMigrationCancellationReturnsError(t *testing.T) {
s := testStore(t)
ctx, cancel := context.WithCancel(t.Context())
cancel()
if err := s.Start(ctx); err == nil {
t.Fatal("canceled migration succeeded")
}
}
// TestMigrationFailureRollsBackVersion verifies a failed migration is never marked applied.
func TestMigrationFailureRollsBackVersion(t *testing.T) {
s := testStore(t)
if _, err := s.pool.Exec(t.Context(), "DELETE FROM schema_migrations"); err != nil {
t.Fatal(err)
}
if err := s.Start(t.Context()); err == nil {
t.Fatal("conflicting unversioned schema accepted")
}
var count int
if err := s.pool.QueryRow(t.Context(), "SELECT count(*) FROM schema_migrations").Scan(&count); err != nil {
t.Fatal(err)
}
if count != 0 {
t.Fatal("failed migration version committed")
}
}
// TestMigrationRejectsBrokenVersionLedger verifies corrupt migration metadata stops startup safely.
func TestMigrationRejectsBrokenVersionLedger(t *testing.T) {
s := testStore(t)
if _, err := s.pool.Exec(t.Context(), "ALTER TABLE schema_migrations RENAME COLUMN version TO broken_version"); err != nil {
t.Fatal(err)
}
if err := s.Start(t.Context()); err == nil {
t.Fatal("broken version ledger accepted")
}
}