forked from mtusi2026/mtusi2026lab2
test: add resilience and benchmark verification
This commit is contained in:
@@ -0,0 +1,173 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
var errDependency = errors.New("dependency unavailable")
|
||||
|
||||
type repositoryStub struct {
|
||||
pingErr error
|
||||
userByID model.User
|
||||
userByIDErr error
|
||||
credentials model.UserCredentials
|
||||
credentialsErr error
|
||||
}
|
||||
|
||||
func (s repositoryStub) Ping(context.Context) error { return s.pingErr }
|
||||
func (repositoryStub) CreateUser(context.Context, string, string, string) (model.User, error) {
|
||||
return model.User{}, nil
|
||||
}
|
||||
func (s repositoryStub) UserByID(context.Context, string) (model.User, error) {
|
||||
return s.userByID, s.userByIDErr
|
||||
}
|
||||
func (s repositoryStub) UserByUsername(context.Context, string) (model.UserCredentials, error) {
|
||||
return s.credentials, s.credentialsErr
|
||||
}
|
||||
func (repositoryStub) CreateChat(context.Context, string, []string, string) (model.Chat, error) {
|
||||
return model.Chat{}, nil
|
||||
}
|
||||
func (repositoryStub) ChatForUser(context.Context, string, string) (model.Chat, error) {
|
||||
return model.Chat{}, nil
|
||||
}
|
||||
func (repositoryStub) ListChats(context.Context, string, *model.Position, int) ([]model.Chat, bool, error) {
|
||||
return nil, false, nil
|
||||
}
|
||||
func (repositoryStub) CreateMessage(context.Context, string, string, string) (model.Message, error) {
|
||||
return model.Message{}, nil
|
||||
}
|
||||
func (repositoryStub) ListMessages(context.Context, string, string, *model.Position, int) ([]model.Message, bool, error) {
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
type sessionStub struct {
|
||||
pingErr error
|
||||
userID string
|
||||
userIDErr error
|
||||
}
|
||||
|
||||
func (s sessionStub) Ping(context.Context) error { return s.pingErr }
|
||||
func (sessionStub) Create(context.Context, string, time.Duration) (string, time.Time, error) {
|
||||
return "token", time.Now().Add(time.Hour), nil
|
||||
}
|
||||
func (s sessionStub) UserID(context.Context, string) (string, error) { return s.userID, s.userIDErr }
|
||||
func (sessionStub) Delete(context.Context, string) error { return nil }
|
||||
|
||||
type passwordsStub struct {
|
||||
verified bool
|
||||
err error
|
||||
}
|
||||
|
||||
func (passwordsStub) Hash(string) (string, error) { return "hash", nil }
|
||||
func (passwordsStub) DummyHash() string { return "hash" }
|
||||
func (s passwordsStub) Verify(string, string) (bool, error) {
|
||||
return s.verified, s.err
|
||||
}
|
||||
|
||||
func TestReadinessReturnsUnavailableForDependencyFailure(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
repo repositoryStub
|
||||
sessions sessionStub
|
||||
}{
|
||||
{name: "postgres", repo: repositoryStub{pingErr: errDependency}},
|
||||
{name: "valkey", sessions: sessionStub{pingErr: errDependency}},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
server := newTestServer(tt.repo, tt.sessions, passwordsStub{})
|
||||
response := serveRequest(server, http.MethodGet, "/health/ready", "")
|
||||
if response.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want %d", response.Code, http.StatusServiceUnavailable)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBusinessRequestReturnsUnavailableForDependencyFailure(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
repo repositoryStub
|
||||
sessions sessionStub
|
||||
}{
|
||||
{name: "valkey", sessions: sessionStub{userIDErr: errDependency}},
|
||||
{name: "postgres", repo: repositoryStub{userByIDErr: errDependency}, sessions: sessionStub{userID: "user-id"}},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
server := newTestServer(tt.repo, tt.sessions, passwordsStub{})
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
|
||||
request.Header.Set("Authorization", "Bearer valid-token")
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want %d", response.Code, http.StatusServiceUnavailable)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticationChallenges(t *testing.T) {
|
||||
server := newTestServer(repositoryStub{}, sessionStub{}, passwordsStub{})
|
||||
bearer := serveRequest(server, http.MethodGet, "/api/v1/users/me", "")
|
||||
if bearer.Code != http.StatusUnauthorized || bearer.Header().Get("WWW-Authenticate") != `Bearer realm="messenger"` {
|
||||
t.Fatalf("business challenge = %d %q", bearer.Code, bearer.Header().Get("WWW-Authenticate"))
|
||||
}
|
||||
|
||||
repository := repositoryStub{credentials: model.UserCredentials{PasswordHash: "hash"}}
|
||||
server = newTestServer(repository, sessionStub{}, passwordsStub{verified: false})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
|
||||
request.SetBasicAuth("user", "wrong-password")
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusUnauthorized || response.Header().Get("WWW-Authenticate") != `Basic realm="messenger", charset="UTF-8"` {
|
||||
t.Fatalf("session challenge = %d %q", response.Code, response.Header().Get("WWW-Authenticate"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionCreationRejectsChunkedBody(t *testing.T) {
|
||||
server := newTestServer(repositoryStub{}, sessionStub{}, passwordsStub{})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", strings.NewReader("{}"))
|
||||
request.ContentLength = -1
|
||||
request.SetBasicAuth("user", "password")
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d", response.Code, http.StatusBadRequest)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrationRejectsWhitespacePassword(t *testing.T) {
|
||||
server := newTestServer(repositoryStub{}, sessionStub{}, passwordsStub{})
|
||||
response := serveRequest(server, http.MethodPost, "/api/v1/users", `{"username":"student","display_name":"Student","password":" "}`)
|
||||
if response.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d", response.Code, http.StatusBadRequest)
|
||||
}
|
||||
}
|
||||
|
||||
func newTestServer(repository Repository, sessions SessionStore, passwords Passwords) *Server {
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
return NewServer(logger, repository, sessions, passwords, time.Hour, time.Second, "8081")
|
||||
}
|
||||
|
||||
func serveRequest(server *Server, method, path, body string) *httptest.ResponseRecorder {
|
||||
request := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
if body != "" {
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
return response
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestUserTimestampHasFixedMicroseconds(t *testing.T) {
|
||||
createdAt := time.Date(2026, time.September, 23, 21, 28, 15, 423030000, time.UTC)
|
||||
data, err := json.Marshal(User{ID: "id", Username: "user", DisplayName: "User", CreatedAt: createdAt})
|
||||
if err != nil {
|
||||
t.Fatalf("Marshal() error = %v", err)
|
||||
}
|
||||
if string(data) != `{"id":"id","username":"user","display_name":"User","created_at":"2026-09-23T21:28:15.423030Z"}` {
|
||||
t.Fatalf("Marshal() = %s", data)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package password
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestHasher(t *testing.T) {
|
||||
hasher := Hasher{}
|
||||
hash, err := hasher.Hash("T3st-password-123")
|
||||
if err != nil {
|
||||
t.Fatalf("Hash() error = %v", err)
|
||||
}
|
||||
|
||||
verified, err := hasher.Verify("T3st-password-123", hash)
|
||||
if err != nil {
|
||||
t.Fatalf("Verify() error = %v", err)
|
||||
}
|
||||
if !verified {
|
||||
t.Fatal("Verify() = false for the original password")
|
||||
}
|
||||
|
||||
verified, err = hasher.Verify("wrong-password", hash)
|
||||
if err != nil {
|
||||
t.Fatalf("Verify() error = %v", err)
|
||||
}
|
||||
if verified {
|
||||
t.Fatal("Verify() = true for a different password")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyRejectsMalformedHash(t *testing.T) {
|
||||
if _, err := (Hasher{}).Verify("password", "invalid"); err == nil {
|
||||
t.Fatal("Verify() error = nil for malformed hash")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/database"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/postgres"
|
||||
)
|
||||
|
||||
func TestConcurrentUsernameCreation(t *testing.T) {
|
||||
pool := openTestDatabase(t)
|
||||
store := postgres.New(pool)
|
||||
username := "race_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:16]
|
||||
|
||||
const workers = 8
|
||||
results := make(chan error, workers)
|
||||
var group sync.WaitGroup
|
||||
for range workers {
|
||||
group.Add(1)
|
||||
go func() {
|
||||
defer group.Done()
|
||||
_, err := store.CreateUser(context.Background(), username, "Race user", "password-hash")
|
||||
results <- err
|
||||
}()
|
||||
}
|
||||
group.Wait()
|
||||
close(results)
|
||||
|
||||
var created, conflicts int
|
||||
for err := range results {
|
||||
switch {
|
||||
case err == nil:
|
||||
created++
|
||||
case errors.Is(err, postgres.ErrConflict):
|
||||
conflicts++
|
||||
default:
|
||||
t.Fatalf("CreateUser() error = %v", err)
|
||||
}
|
||||
}
|
||||
if created != 1 || conflicts != workers-1 {
|
||||
t.Fatalf("created = %d, conflicts = %d", created, conflicts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateChatRollsBackForUnknownMember(t *testing.T) {
|
||||
pool := openTestDatabase(t)
|
||||
store := postgres.New(pool)
|
||||
owner, err := store.CreateUser(context.Background(), uniqueUsername(), "Owner", "password-hash")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateUser() error = %v", err)
|
||||
}
|
||||
|
||||
before := chatCount(t, pool)
|
||||
_, err = store.CreateChat(context.Background(), "Invalid chat", []string{owner.ID, uuid.NewString()}, owner.ID)
|
||||
if !errors.Is(err, postgres.ErrInvalidMembers) {
|
||||
t.Fatalf("CreateChat() error = %v, want ErrInvalidMembers", err)
|
||||
}
|
||||
if after := chatCount(t, pool); after != before {
|
||||
t.Fatalf("chat count changed from %d to %d", before, after)
|
||||
}
|
||||
}
|
||||
|
||||
func openTestDatabase(t *testing.T) *pgxpool.Pool {
|
||||
t.Helper()
|
||||
url := testSecret(t, "TEST_DATABASE_URL", "TEST_DATABASE_URL_FILE")
|
||||
pool, err := database.Open(context.Background(), database.Config{
|
||||
URL: url, MinConnections: 0, MaxConnections: 10,
|
||||
MaxConnectionAge: time.Minute, MaxConnectionIdle: time.Minute,
|
||||
HealthCheckPeriod: time.Minute, ConnectTimeout: 5 * time.Second,
|
||||
MigrationTimeout: 30 * time.Second,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("database.Open() error = %v", err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
return pool
|
||||
}
|
||||
|
||||
func testSecret(t *testing.T, valueName, fileName string) string {
|
||||
t.Helper()
|
||||
if value := strings.TrimSpace(os.Getenv(valueName)); value != "" {
|
||||
return value
|
||||
}
|
||||
path := strings.TrimSpace(os.Getenv(fileName))
|
||||
if path == "" {
|
||||
t.Skipf("set %s or %s to run integration tests", valueName, fileName)
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", fileName, err)
|
||||
}
|
||||
return strings.TrimSpace(string(data))
|
||||
}
|
||||
|
||||
func uniqueUsername() string {
|
||||
return "u_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:20]
|
||||
}
|
||||
|
||||
func chatCount(t *testing.T, pool *pgxpool.Pool) int {
|
||||
t.Helper()
|
||||
var count int
|
||||
if err := pool.QueryRow(context.Background(), "SELECT count(*) FROM chats").Scan(&count); err != nil {
|
||||
t.Fatalf("count chats: %v", err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package session_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/session"
|
||||
)
|
||||
|
||||
func TestSessionLifecycle(t *testing.T) {
|
||||
store := openTestStore(t)
|
||||
userID := uuid.NewString()
|
||||
token, expiresAt, err := store.Create(context.Background(), userID, time.Minute)
|
||||
if err != nil {
|
||||
t.Fatalf("Create() error = %v", err)
|
||||
}
|
||||
if token == "" || !expiresAt.After(time.Now()) {
|
||||
t.Fatalf("invalid token or expiry: token length = %d, expires_at = %v", len(token), expiresAt)
|
||||
}
|
||||
|
||||
actualUserID, err := store.UserID(context.Background(), token)
|
||||
if err != nil {
|
||||
t.Fatalf("UserID() error = %v", err)
|
||||
}
|
||||
if actualUserID != userID {
|
||||
t.Fatalf("UserID() = %q, want %q", actualUserID, userID)
|
||||
}
|
||||
if err := store.Delete(context.Background(), token); err != nil {
|
||||
t.Fatalf("Delete() error = %v", err)
|
||||
}
|
||||
if _, err := store.UserID(context.Background(), token); !errors.Is(err, session.ErrNotFound) {
|
||||
t.Fatalf("UserID() after delete error = %v, want ErrNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionExpires(t *testing.T) {
|
||||
store := openTestStore(t)
|
||||
token, _, err := store.Create(context.Background(), uuid.NewString(), time.Second)
|
||||
if err != nil {
|
||||
t.Fatalf("Create() error = %v", err)
|
||||
}
|
||||
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
_, err := store.UserID(context.Background(), token)
|
||||
if errors.Is(err, session.ErrNotFound) {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("UserID() error = %v", err)
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
t.Fatal("session did not expire within three seconds")
|
||||
}
|
||||
|
||||
func openTestStore(t *testing.T) *session.Store {
|
||||
t.Helper()
|
||||
url := strings.TrimSpace(os.Getenv("TEST_CACHE_URL"))
|
||||
if url == "" {
|
||||
path := strings.TrimSpace(os.Getenv("TEST_CACHE_URL_FILE"))
|
||||
if path == "" {
|
||||
t.Skip("set TEST_CACHE_URL or TEST_CACHE_URL_FILE to run integration tests")
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("read TEST_CACHE_URL_FILE: %v", err)
|
||||
}
|
||||
url = strings.TrimSpace(string(data))
|
||||
}
|
||||
store, err := session.New(url)
|
||||
if err != nil {
|
||||
t.Fatalf("session.New() error = %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = store.Close() })
|
||||
return store
|
||||
}
|
||||
Reference in New Issue
Block a user