chore: port lab 2 solution

This commit is contained in:
kk10
2026-10-16 19:50:49 +03:00
parent 0ab3a341aa
commit 6e0829e628
71 changed files with 4305 additions and 6 deletions
+55
View File
@@ -0,0 +1,55 @@
//go:build contract
package studenttests_test
import (
"context"
"encoding/json"
"net/http"
"os"
"strings"
"testing"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
func TestCreateChatRollback(t *testing.T) {
data, err := os.ReadFile("../secrets/test_database_url.txt")
if err != nil {
t.Fatalf("read secrets/test_database_url: %v", err)
}
ctx := context.Background()
conn, err := pgx.Connect(ctx, strings.TrimSpace(string(data)))
if err != nil {
t.Fatalf("connect to database: %v", err)
}
defer conn.Close(ctx)
creator := createUser(t)
title := "rollback-" + uuid.NewString()
body, err := json.Marshal(map[string]any{
"title": title,
"member_ids": []uuid.UUID{creator.ID, uuid.New()},
})
if err != nil {
t.Fatalf("marshal body: %v", err)
}
resp := doRequest(t, http.MethodPost, "/api/v1/chats", creator.Token, body)
resp.Body.Close()
if resp.StatusCode < 400 || resp.StatusCode >= 500 {
t.Fatalf("expected 4xx, got %d", resp.StatusCode)
}
var n int
err = conn.QueryRow(ctx, "SELECT count(*) FROM chats WHERE title = $1", title).Scan(&n)
if err != nil {
t.Fatalf("count chats: %v", err)
}
if n != 0 {
t.Fatalf("expected no chat rows after failed creation, found %d", n)
}
}
+134
View File
@@ -0,0 +1,134 @@
//go:build contract
package studenttests_test
import (
"encoding/json"
"net/http"
"net/url"
"strconv"
"testing"
"mtusi2026-messenger/internal/dto"
)
func TestInvalidJSON(t *testing.T) {
resp := doRequest(t, http.MethodPost, "/api/v1/users", "", []byte(`{"username": "broken",`))
requireStatus(t, resp, http.StatusBadRequest)
var apiErr dto.ErrorResponse
mustDecode(t, resp, &apiErr)
if apiErr.Error.Code != dto.ErrorCodeInvalidRequest {
t.Errorf("expected code %q, got %q", dto.ErrorCodeInvalidRequest, apiErr.Error.Code)
}
}
func TestForeignChat(t *testing.T) {
user1 := createUser(t)
user2 := createUser(t)
user3 := createUser(t)
chat := createChat(t, user1, user1.ID, user2.ID)
resp := doRequest(t, http.MethodGet, "/api/v1/chats/"+chat.ID.String(), user3.Token, nil)
requireStatus(t, resp, http.StatusNotFound)
resp = sendMessage(t, user3, chat.ID, "should not land")
requireStatus(t, resp, http.StatusNotFound)
}
func TestEmptyMessage(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
for _, text := range []string{"", " ", "\t\n"} {
resp := sendMessage(t, user, chat.ID, text)
requireStatus(t, resp, http.StatusBadRequest)
}
}
func TestDuplicateUsername(t *testing.T) {
user := createUser(t)
body, err := json.Marshal(map[string]string{
"username": user.Username,
"display_name": "Someone else",
"password": testPassword,
})
if err != nil {
t.Fatalf("marshal body: %v", err)
}
resp := doRequest(t, http.MethodPost, "/api/v1/users", "", body)
requireStatus(t, resp, http.StatusConflict)
var apiErr dto.ErrorResponse
mustDecode(t, resp, &apiErr)
if apiErr.Error.Code != dto.ErrorCodeConflict {
t.Errorf("expected code %q, got %q", dto.ErrorCodeConflict, apiErr.Error.Code)
}
}
func TestPagination(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
const total = 25
const pageSize = 4
sent := make(map[string]bool, total)
for i := 0; i < total; i++ {
resp := sendMessage(t, user, chat.ID, "msg")
requireStatus(t, resp, http.StatusCreated)
var msg dto.MessageResponse
mustDecode(t, resp, &msg)
sent[msg.ID.String()] = true
}
seen := make(map[string]bool, total)
cursor := ""
pages := 0
for {
path := "/api/v1/chats/" + chat.ID.String() + "/messages?limit=" + strconv.Itoa(pageSize)
if cursor != "" {
path += "&cursor=" + url.QueryEscape(cursor)
}
resp := doRequest(t, http.MethodGet, path, user.Token, nil)
requireStatus(t, resp, http.StatusOK)
var page dto.MessagePageResponse
mustDecode(t, resp, &page)
pages++
for _, msg := range page.Items {
id := msg.ID.String()
if seen[id] {
t.Fatalf("duplicate message id across pages: %s", id)
}
seen[id] = true
}
if page.NextCursor == nil {
break
}
cursor = *page.NextCursor
if pages > total {
t.Fatalf("too many pages: got %d, expected at most %d", pages, total)
}
}
if len(seen) != total {
t.Fatalf("expected %d unique messages across all pages, got %d", total, len(seen))
}
for id := range sent {
if !seen[id] {
t.Fatalf("message %s sent but never seen while paginating", id)
}
}
}
+89
View File
@@ -0,0 +1,89 @@
//go:build failure
package studenttests_test
import (
"net/http"
"os/exec"
"testing"
"time"
)
func compose(t *testing.T, args ...string) {
t.Helper()
cmd := exec.Command("docker", append([]string{"compose"}, args...)...)
cmd.Dir = ".."
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("docker compose %v: %v\n%s", args, err, out)
}
}
func stopService(t *testing.T, name string) {
t.Helper()
compose(t, "stop", name)
t.Cleanup(func() {
compose(t, "start", name)
waitReady(t)
})
}
func waitReady(t *testing.T) {
t.Helper()
deadline := time.Now().Add(60 * time.Second)
for time.Now().Before(deadline) {
resp, err := httpClient.Get(*baseURL + "/health/ready")
if err == nil {
resp.Body.Close()
if resp.StatusCode == http.StatusOK {
return
}
}
time.Sleep(500 * time.Millisecond)
}
t.Fatal("service did not become ready in 60s")
}
func TestRedisDown(t *testing.T) {
user := createUser(t)
stopService(t, "redis")
// настоящий токен
resp := doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil)
requireStatus(t, resp, http.StatusOK)
resp.Body.Close()
// выдуманный токен
resp = doRequest(t, http.MethodGet, "/api/v1/users/me", "forged-"+user.Token, nil)
requireStatus(t, resp, http.StatusUnauthorized)
resp.Body.Close()
// без токена
resp = doRequest(t, http.MethodGet, "/api/v1/users/me", "", nil)
requireStatus(t, resp, http.StatusUnauthorized)
resp.Body.Close()
}
func TestDatabaseDown(t *testing.T) {
user := createUser(t) // токен ещё не использован, ключа в Redis нет
stopService(t, "postgres")
// ключа в кэше нет, проверить сессию негде
resp := doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil)
requireStatus(t, resp, http.StatusServiceUnavailable)
resp.Body.Close()
// выдуманный токен
resp = doRequest(t, http.MethodGet, "/api/v1/users/me", "forged-"+user.Token, nil)
requireStatus(t, resp, http.StatusServiceUnavailable)
resp.Body.Close()
// без токена
resp = doRequest(t, http.MethodGet, "/api/v1/users/me", "", nil)
requireStatus(t, resp, http.StatusUnauthorized)
resp.Body.Close()
}
+218
View File
@@ -0,0 +1,218 @@
package studenttests_test
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"net/http"
"strings"
"testing"
"time"
"github.com/google/uuid"
"mtusi2026-messenger/internal/dto"
)
var baseURL = flag.String("base-url", "http://127.0.0.1:8080", "base URL of the running server")
var httpClient = &http.Client{
Timeout: 10 * time.Second,
Transport: &http.Transport{
MaxIdleConns: 200,
IdleConnTimeout: 30 * time.Second,
MaxIdleConnsPerHost: 200,
MaxConnsPerHost: 200,
},
}
type testUser struct {
dto.UserResponse
Token string
}
const testPassword = "correct-horse-battery"
func doRequest(t *testing.T, method, path, token string, body []byte) *http.Response {
t.Helper()
req, err := http.NewRequest(method, *baseURL+path, bytes.NewReader(body))
if err != nil {
t.Fatalf("build request: %v", err)
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
resp, err := httpClient.Do(req)
if err != nil {
t.Fatalf("%s %s: request failed: %v", method, path, err)
}
return resp
}
func mustDecode(t *testing.T, resp *http.Response, dst any) {
t.Helper()
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read body: %v", err)
}
if err := json.Unmarshal(data, dst); err != nil {
t.Fatalf("decode body %q: %v", data, err)
}
}
func requireStatus(t *testing.T, resp *http.Response, expected int) {
t.Helper()
if resp.StatusCode != expected {
data, _ := io.ReadAll(resp.Body)
resp.Body.Close()
t.Fatalf(
"expected status %d, got %d, body: %s",
expected,
resp.StatusCode,
data,
)
}
if resp.Header.Get("X-Request-Id") == "" {
t.Errorf("missing X-Request-Id header")
}
}
func createUser(t *testing.T) testUser {
t.Helper()
username := "u_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:12]
body, err := json.Marshal(map[string]string{
"username": username,
"display_name": "Test " + username,
"password": testPassword,
})
if err != nil {
t.Fatalf("marshal user: %v", err)
}
resp := doRequest(t, http.MethodPost, "/api/v1/users", "", body)
requireStatus(t, resp, http.StatusCreated)
var u dto.UserResponse
mustDecode(t, resp, &u)
req, err := http.NewRequest(
http.MethodPost,
*baseURL+"/api/v1/auth/sessions",
nil,
)
if err != nil {
t.Fatalf("build login request: %v", err)
}
req.SetBasicAuth(username, testPassword)
resp, err = httpClient.Do(req)
if err != nil {
t.Fatalf("login request failed: %v", err)
}
requireStatus(t, resp, http.StatusCreated)
var session dto.SessionResponse
mustDecode(t, resp, &session)
return testUser{UserResponse: u, Token: session.Token}
}
func createChat(
t *testing.T,
creator testUser,
memberIDs ...uuid.UUID,
) dto.ChatResponse {
t.Helper()
body, err := json.Marshal(map[string]any{
"title": "Test chat " + uuid.NewString()[:8],
"member_ids": memberIDs,
})
if err != nil {
t.Fatalf("marshal chat: %v", err)
}
resp := doRequest(
t,
http.MethodPost,
"/api/v1/chats",
creator.Token,
body,
)
requireStatus(t, resp, http.StatusCreated)
var c dto.ChatResponse
mustDecode(t, resp, &c)
return c
}
func sendMessage(
t *testing.T,
actor testUser,
chatID uuid.UUID,
text string,
) *http.Response {
t.Helper()
body, err := json.Marshal(map[string]string{
"text": text,
})
if err != nil {
t.Fatalf("marshal message: %v", err)
}
return doRequest(
t,
http.MethodPost,
fmt.Sprintf("/api/v1/chats/%v/messages", chatID.String()),
actor.Token,
body,
)
}
func sendLoadMessage(
actor testUser,
chatID uuid.UUID,
text string,
) (*http.Response, error) {
body, err := json.Marshal(map[string]string{
"text": text,
})
if err != nil {
return nil, err
}
req, err := http.NewRequest(
http.MethodPost,
*baseURL+"/api/v1/chats/"+chatID.String()+"/messages",
bytes.NewReader(body),
)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+actor.Token)
return httpClient.Do(req)
}
+138
View File
@@ -0,0 +1,138 @@
//go:build load
package studenttests_test
import (
"flag"
"io"
"net/http"
"sort"
"sync"
"sync/atomic"
"testing"
"time"
)
var (
workers = flag.Int("workers", 20, "number of concurrent workers")
duration = flag.Duration("duration", 5*time.Second, "test duration")
rate = flag.Int("rate", 20, "maximum requests per second per worker")
)
func TestLoad(t *testing.T) {
var (
statuses = make(map[int]int64)
requestErrors int64
latencies []time.Duration
statusMu sync.Mutex
latencyMu sync.Mutex
wg sync.WaitGroup
)
user1 := createUser(t)
user2 := createUser(t)
chat := createChat(t, user1, user1.ID, user2.ID)
start := time.Now()
deadline := start.Add(*duration)
interval := time.Second / time.Duration(*rate)
for worker := 0; worker < *workers; worker++ {
wg.Add(1)
go func(workerID int) {
defer wg.Done()
actor := user1
if workerID%2 == 1 {
actor = user2
}
ticker := time.NewTicker(interval)
defer ticker.Stop()
for time.Now().Before(deadline) {
<-ticker.C
if time.Now().After(deadline) {
return
}
requestStart := time.Now()
resp, err := sendLoadMessage(
actor,
chat.ID,
"load-msg",
)
latency := time.Since(requestStart)
if err != nil {
if atomic.CompareAndSwapInt64(&requestErrors, 0, 1) {
t.Logf("first transport error: %v", err)
}
atomic.AddInt64(&requestErrors, 1)
continue
}
statusMu.Lock()
statuses[resp.StatusCode]++
statusMu.Unlock()
if resp.StatusCode == http.StatusCreated {
latencyMu.Lock()
latencies = append(latencies, latency)
latencyMu.Unlock()
}
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}
}(worker)
}
wg.Wait()
elapsed := time.Since(start)
var total int64
for _, count := range statuses {
total += count
}
total += requestErrors
t.Logf("duration: %.3fs", elapsed.Seconds())
t.Logf("workers: %d", *workers)
t.Logf("rate per worker: %d req/s", *rate)
t.Logf("target rate: %d req/s", *workers**rate)
t.Logf("total requests: %d", total)
for status, count := range statuses {
t.Logf("HTTP %d: %d", status, count)
}
t.Logf("request errors: %d", requestErrors)
successful := statuses[http.StatusCreated]
t.Logf("successful RPS: %.2f",
float64(successful)/elapsed.Seconds(),
)
if len(latencies) > 0 {
sort.Slice(latencies, func(i, j int) bool {
return latencies[i] < latencies[j]
})
t.Logf("successful latency p50: %s", percentile(latencies, 0.50))
t.Logf("successful latency p95: %s", percentile(latencies, 0.95))
t.Logf("successful latency p99: %s", percentile(latencies, 0.99))
}
}
func percentile(values []time.Duration, p float64) time.Duration {
index := int(float64(len(values)-1) * p)
return values[index]
}
+100
View File
@@ -0,0 +1,100 @@
//go:build race
package studenttests_test
import (
"net/http"
"sync"
"testing"
"mtusi2026-messenger/internal/dto"
)
func TestConcurrentMessages(t *testing.T) {
const clients = 10
const messagesPerClient = 10
const total = clients * messagesPerClient
user1 := createUser(t)
user2 := createUser(t)
chat := createChat(t, user1, user1.ID, user2.ID)
var wg sync.WaitGroup
var mu sync.Mutex
sentIDs := make(map[string]bool, total)
start := make(chan struct{})
for worker := 0; worker < clients; worker++ {
wg.Add(1)
go func(workerID int) {
defer wg.Done()
actor := user1
if workerID%2 == 1 {
actor = user2
}
<-start
for i := 0; i < messagesPerClient; i++ {
resp := sendMessage(t, actor, chat.ID, "race-msg")
if resp.StatusCode != http.StatusCreated {
t.Errorf("worker %d msg %d: expected 201, got %d", workerID, i, resp.StatusCode)
resp.Body.Close()
continue
}
var m dto.MessageResponse
mustDecode(t, resp, &m)
mu.Lock()
sentIDs[m.ID.String()] = true
mu.Unlock()
}
}(worker)
}
close(start)
wg.Wait()
if t.Failed() {
t.Fatal("one or more send requests failed, see errors above")
}
if len(sentIDs) != total {
t.Fatalf("expected %d successful sends, got %d unique ids", total, len(sentIDs))
}
seen := make(map[string]bool, total)
path := "/api/v1/chats/" + chat.ID.String() + "/messages?limit=100"
resp := doRequest(t, http.MethodGet, path, user1.Token, nil)
requireStatus(t, resp, http.StatusOK)
var page dto.MessagePageResponse
mustDecode(t, resp, &page)
if page.NextCursor != nil {
t.Fatalf("expected next_cursor to be nil, history may contain more than %d messages", total)
}
for _, msg := range page.Items {
id := msg.ID.String()
if seen[id] {
t.Fatalf("duplicate message id in history: %s", id)
}
if !sentIDs[id] {
t.Fatalf("message %s in history was never sent by this test", id)
}
seen[id] = true
}
if len(seen) != total {
t.Fatalf("expected exactly %d unique messages in history, got %d", total, len(seen))
}
t.Logf("PASS: %d concurrent clients sent %d messages, exactly %d unique messages persisted",
clients, total, len(seen))
}
+77
View File
@@ -0,0 +1,77 @@
//go:build race
package studenttests_test
import (
"bytes"
"encoding/json"
"net/http"
"strings"
"sync"
"testing"
"github.com/google/uuid"
)
func TestConcurrentRegistration(t *testing.T) {
const workers = 20
username := "u_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:12]
body, err := json.Marshal(map[string]string{
"username": username,
"display_name": "Racer",
"password": testPassword,
})
if err != nil {
t.Fatalf("marshal body: %v", err)
}
start := make(chan struct{})
statuses := make(chan int, workers)
var wg sync.WaitGroup
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
<-start
req, err := http.NewRequest(http.MethodPost, *baseURL+"/api/v1/users", bytes.NewReader(body))
if err != nil {
t.Errorf("build request: %v", err)
return
}
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.Do(req)
if err != nil {
t.Errorf("request failed: %v", err)
return
}
defer resp.Body.Close()
statuses <- resp.StatusCode
}()
}
close(start)
wg.Wait()
close(statuses)
created, conflict := 0, 0
for s := range statuses {
switch s {
case http.StatusCreated:
created++
case http.StatusConflict:
conflict++
default:
t.Errorf("unexpected status %d", s)
}
}
if created != 1 || conflict != workers-1 {
t.Fatalf("expected 1 created and %d conflict, got %d created and %d conflict", workers-1, created, conflict)
}
}
+42
View File
@@ -0,0 +1,42 @@
//go:build failure
package studenttests_test
import (
"net/http"
"os/exec"
"testing"
"time"
)
const shortTTLContainer = "api-short-ttl"
const shortTTLURL = "http://localhost:8081"
func TestSessionExpiry(t *testing.T) {
_ = exec.Command("docker", "rm", "-f", shortTTLContainer).Run()
compose(t, "run", "-d", "--no-deps", "--name", shortTTLContainer,
"-e", "SESSION_TTL_SECONDS=3",
"-p", "127.0.0.1:8081:8080", "api")
t.Cleanup(func() {
_ = exec.Command("docker", "rm", "-f", shortTTLContainer).Run()
})
old := *baseURL
*baseURL = shortTTLURL
t.Cleanup(func() { *baseURL = old })
waitReady(t)
user := createUser(t)
resp := doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil)
requireStatus(t, resp, http.StatusOK)
resp.Body.Close()
time.Sleep(4 * time.Second)
resp = doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil)
requireStatus(t, resp, http.StatusUnauthorized)
resp.Body.Close()
}
+58
View File
@@ -0,0 +1,58 @@
//go:build contract
package studenttests_test
import (
"net/http"
"testing"
)
func basicLogin(t *testing.T, username, password string) *http.Response {
t.Helper()
req, err := http.NewRequest(http.MethodPost, *baseURL+"/api/v1/auth/sessions", nil)
if err != nil {
t.Fatalf("build login request: %v", err)
}
req.SetBasicAuth(username, password)
resp, err := httpClient.Do(req)
if err != nil {
t.Fatalf("login request failed: %v", err)
}
return resp
}
func TestLoginWrongPassword(t *testing.T) {
user := createUser(t)
resp := basicLogin(t, user.Username, "wrong-"+testPassword)
requireStatus(t, resp, http.StatusUnauthorized)
resp.Body.Close()
resp = basicLogin(t, "no_such_user_"+user.Username, testPassword)
requireStatus(t, resp, http.StatusUnauthorized)
resp.Body.Close()
}
func TestLogout(t *testing.T) {
user := createUser(t)
resp := doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil)
requireStatus(t, resp, http.StatusOK)
resp.Body.Close()
resp = doRequest(t, http.MethodDelete, "/api/v1/auth/sessions/current", user.Token, nil)
if resp.StatusCode >= 300 {
t.Fatalf("logout: unexpected status %d", resp.StatusCode)
}
resp.Body.Close()
resp = doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil)
requireStatus(t, resp, http.StatusUnauthorized)
resp.Body.Close()
resp = doRequest(t, http.MethodDelete, "/api/v1/auth/sessions/current", user.Token, nil)
requireStatus(t, resp, http.StatusUnauthorized)
resp.Body.Close()
}