feat: port lab3 implementation

This commit is contained in:
kk10
2026-10-31 11:54:18 +03:00
parent ec540a1a72
commit 27af30c903
83 changed files with 5195 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()
}
+210
View File
@@ -0,0 +1,210 @@
package studenttests_test
import (
"bytes"
"encoding/json"
"flag"
"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()
resp, err := sendLoadMessage(actor, chatID, text)
if err != nil {
t.Fatalf("send message: %v", err)
}
return resp
}
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)
req.Header.Set("Idempotency-Key", uuid.NewString())
return httpClient.Do(req)
}
+169
View File
@@ -0,0 +1,169 @@
//go:build race
package studenttests_test
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/url"
"sync"
"testing"
"github.com/google/uuid"
)
const (
concurrentRequests = 20
concurrentRounds = 5
)
type keyedResult struct {
status int
instance string
body []byte
err error
}
func postWithKey(actor testUser, chatID uuid.UUID, key, text string) keyedResult {
body, err := json.Marshal(map[string]string{"text": text})
if err != nil {
return keyedResult{err: err}
}
req, err := http.NewRequest(
http.MethodPost,
*baseURL+"/api/v1/chats/"+chatID.String()+"/messages",
bytes.NewReader(body),
)
if err != nil {
return keyedResult{err: err}
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+actor.Token)
req.Header.Set("Idempotency-Key", key)
resp, err := httpClient.Do(req)
if err != nil {
return keyedResult{err: err}
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
return keyedResult{
status: resp.StatusCode,
instance: resp.Header.Get("X-Instance-Id"),
body: data,
err: err,
}
}
func TestConcurrentIdempotencyAcrossReplicas(t *testing.T) {
alice := createUser(t)
bob := createUser(t)
chat := createChat(t, alice, alice.ID, bob.ID)
instances := map[string]struct{}{}
for round := 0; round < concurrentRounds; round++ {
key := uuid.NewString()
text := "concurrent " + key
results := make([]keyedResult, concurrentRequests)
start := make(chan struct{})
var wg sync.WaitGroup
for i := range results {
wg.Add(1)
go func(i int) {
defer wg.Done()
<-start
results[i] = postWithKey(alice, chat.ID, key, text)
}(i)
}
close(start)
wg.Wait()
createdIDs := map[string]struct{}{}
succeeded := 0
for i, r := range results {
if r.err != nil {
t.Fatalf("round %d, request %d: %v", round, i, r.err)
}
if r.instance != "" {
instances[r.instance] = struct{}{}
}
switch r.status {
case http.StatusOK, http.StatusCreated:
succeeded++
var m struct {
ID string `json:"id"`
}
if err := json.Unmarshal(r.body, &m); err != nil || m.ID == "" {
t.Fatalf("round %d: bad success body %q: %v", round, r.body, err)
}
createdIDs[m.ID] = struct{}{}
case http.StatusConflict:
default:
t.Errorf("round %d, request %d: unexpected status %d, body: %s",
round, i, r.status, r.body)
}
}
if succeeded == 0 {
t.Fatalf("round %d: no request succeeded", round)
}
if len(createdIDs) != 1 {
t.Fatalf("round %d: responses returned %d different message ids, want 1: %v",
round, len(createdIDs), createdIDs)
}
if got := countMessagesWithText(t, bob, chat.ID, text); got != 1 {
t.Fatalf("round %d: %d messages with text %q in history, want exactly 1",
round, got, text)
}
}
if len(instances) < 2 {
t.Fatalf("requests were served by %d replica(s) %v, need at least 2",
len(instances), instances)
}
t.Logf("served by replicas: %v", instances)
}
func countMessagesWithText(t *testing.T, actor testUser, chatID uuid.UUID, text string) int {
t.Helper()
count := 0
path := "/api/v1/chats/" + chatID.String() + "/messages?limit=100"
for page := 0; page < 100; page++ {
resp := doRequest(t, http.MethodGet, path, actor.Token, nil)
requireStatus(t, resp, http.StatusOK)
var body struct {
Items []struct {
Text string `json:"text"`
} `json:"items"`
NextCursor *string `json:"next_cursor"`
}
mustDecode(t, resp, &body)
for _, m := range body.Items {
if m.Text == text {
count++
}
}
if body.NextCursor == nil {
return count
}
path = "/api/v1/chats/" + chatID.String() +
"/messages?limit=100&cursor=" + url.QueryEscape(*body.NextCursor)
}
t.Fatalf("history pagination exceeded safety bound")
return 0
}
+150
View File
@@ -0,0 +1,150 @@
//go:build load && action
package studenttests_test
import (
"flag"
"io"
"net/http"
"os"
"os/exec"
"strings"
"sync"
"testing"
"time"
)
var (
actionScript = flag.String("action", "", "script to run during the load (e.g. scripts/stop-one.sh)")
actionAt = flag.Duration("action-at", 10*time.Second, "when to run the action, from test start")
replica = flag.Int("replica", 1, "which api replica to stop (1-based)")
)
func resolveReplica(t *testing.T, n int) string {
t.Helper()
out, err := exec.Command("docker", "compose", "ps", "-q", "api").Output()
if err != nil {
t.Fatalf("docker compose ps: %v", err)
}
ids := strings.Fields(string(out))
if n < 1 || n > len(ids) {
t.Fatalf("replica %d requested, but %d api containers found", n, len(ids))
}
return ids[n-1]
}
func actionCommand(path string) *exec.Cmd {
if strings.HasSuffix(path, ".sh") {
return exec.Command("sh", path)
}
return exec.Command(path)
}
func TestLoadWithAction(t *testing.T) {
if *actionScript == "" {
t.Skip("-action is not set")
}
if *actionAt+10*time.Second > *duration {
t.Fatalf("-duration (%s) must exceed -action-at (%s) by at least 10s", *duration, *actionAt)
}
user1 := createUser(t)
user2 := createUser(t)
chat := createChat(t, user1, user1.ID, user2.ID)
type sample struct {
at time.Duration
ok bool
}
var (
mu sync.Mutex
samples []sample
wg sync.WaitGroup
)
targetID := resolveReplica(t, *replica)
start := time.Now()
deadline := start.Add(*duration)
interval := time.Second / time.Duration(*rate)
for w := 0; w < *workers; w++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
actor := user1
if id%2 == 1 {
actor = user2
}
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
<-ticker.C
if time.Now().After(deadline) {
return
}
resp, err := sendLoadMessage(actor, chat.ID, "load-msg")
ok := err == nil && resp.StatusCode == http.StatusCreated
if err == nil {
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}
mu.Lock()
samples = append(samples, sample{time.Since(start), ok})
mu.Unlock()
}
}(w)
}
var actionStart, actionEnd time.Duration
wg.Add(1)
go func() {
defer wg.Done()
time.Sleep(*actionAt)
actionStart = time.Since(start)
cmd := actionCommand(*actionScript)
cmd.Env = append(os.Environ(), "TARGET_INSTANCE_ID="+targetID)
out, err := cmd.CombinedOutput()
actionEnd = time.Since(start)
if err != nil {
t.Errorf("action failed: %v\n%s", err, out)
}
}()
wg.Wait()
elapsed := time.Since(start)
seconds := int(elapsed.Seconds()) + 1
okBySec := make([]int, seconds)
errBySec := make([]int, seconds)
var okTotal, errTotal int
var lastErr time.Duration
for _, s := range samples {
sec := int(s.at.Seconds())
if s.ok {
okBySec[sec]++
okTotal++
} else {
errBySec[sec]++
errTotal++
if s.at > lastErr {
lastErr = s.at
}
}
}
for i := 0; i < seconds; i++ {
t.Logf("t=%2ds ok=%4d err=%3d", i, okBySec[i], errBySec[i])
}
t.Logf("action: started at %.2fs, finished at %.2fs", actionStart.Seconds(), actionEnd.Seconds())
t.Logf("total ok=%d errors=%d, successful RPS=%.2f", okTotal, errTotal, float64(okTotal)/elapsed.Seconds())
if errTotal == 0 || lastErr < actionStart {
t.Logf("recovery time: 0s (no errors after action start)")
} else {
t.Logf("recovery time: %.2fs (last error at %.2fs)", (lastErr - actionStart).Seconds(), lastErr.Seconds())
}
}
+162
View File
@@ -0,0 +1,162 @@
//go:build load
package studenttests_test
import (
"flag"
"fmt"
"io"
"net/http"
"os"
"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")
csvPath = flag.String("csv", "", "append result row to this CSV file")
label = flag.String("label", "", "configuration label for CSV row")
)
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.AddInt64(&requestErrors, 1) == 1 {
t.Logf("first transport error: %v", err)
}
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))
}
if *csvPath != "" {
var p50, p95, p99 time.Duration
if len(latencies) > 0 {
p50 = percentile(latencies, 0.50)
p95 = percentile(latencies, 0.95)
p99 = percentile(latencies, 0.99)
}
f, err := os.OpenFile(*csvPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
t.Fatalf("open csv: %v", err)
}
defer f.Close()
fmt.Fprintf(f, "%s,%d,%d,%d,%d,%d,%d,%.2f,%.1f,%.1f,%.1f\n",
*label, *workers, *rate, *workers**rate,
successful, total-successful-requestErrors, requestErrors,
float64(successful)/elapsed.Seconds(),
float64(p50.Microseconds())/1000,
float64(p95.Microseconds())/1000,
float64(p99.Microseconds())/1000)
}
}
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()
}