feat: port lab4 implementation

This commit is contained in:
kk10
2026-11-13 15:52:39 +03:00
parent 276dbdad8a
commit 36d9b0c8f6
101 changed files with 8426 additions and 6 deletions
+92
View File
@@ -0,0 +1,92 @@
//go:build failure
package studenttests_test
import (
"bytes"
"context"
"io"
"net/http"
"os/exec"
"strings"
"testing"
"time"
"mtusi2026-messenger/internal/dto"
)
func TestAttachmentUploaderFailover(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
original := makePNG(t, 32, 32)
resp := uploadAttachment(t, user, chat.ID, "failover.png", "image/png", original)
requireStatus(t, resp, http.StatusCreated)
uploader := resp.Header.Get("X-Instance-Id")
var att dto.AttachmentResponse
mustDecode(t, resp, &att)
if uploader == "" {
t.Fatal("upload response has no X-Instance-Id")
}
cmd := exec.Command("docker", "compose", "ps", "-q", "api")
cmd.Dir = ".."
out, err := cmd.Output()
if err != nil {
t.Fatalf("list API replicas: %v", err)
}
replicas := strings.Fields(string(out))
if len(replicas) < 2 {
t.Fatal("at least two running API replicas required")
}
var target string
for _, id := range replicas {
if strings.HasPrefix(id, uploader) {
target = id
break
}
}
if target == "" {
t.Fatal("upload instance is not an API container in this Compose project")
}
t.Cleanup(func() {
if err := exec.Command("docker", "start", target).Run(); err != nil {
t.Errorf("restart uploader replica: %v", err)
}
})
if err := exec.Command("docker", "stop", "-t", "5", target).Run(); err != nil {
t.Fatalf("stop uploader replica: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
for ctx.Err() == nil {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, *baseURL+"/api/v1/attachments/"+att.ID.String()+"/content", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+user.Token)
response, err := httpClient.Do(req)
if err == nil {
data, readErr := io.ReadAll(response.Body)
response.Body.Close()
if response.StatusCode == http.StatusOK {
downloader := response.Header.Get("X-Instance-Id")
if downloader == "" || downloader == uploader {
t.Fatal("download was not served by another replica")
}
if readErr != nil {
t.Fatal(readErr)
}
if !bytes.Equal(data, original) {
t.Fatal("downloaded original differs from uploaded file")
}
return
}
if response.StatusCode != http.StatusBadGateway && response.StatusCode != http.StatusServiceUnavailable && response.StatusCode != http.StatusGatewayTimeout {
t.Fatalf("unexpected download status: %d", response.StatusCode)
}
}
time.Sleep(200 * time.Millisecond)
}
t.Fatal("download through another replica did not recover within 10s")
}
+106
View File
@@ -0,0 +1,106 @@
//go:build contract || reconcile || failure
package studenttests_test
import (
"bytes"
"encoding/json"
"net/http"
"net/url"
"testing"
"github.com/google/uuid"
"mtusi2026-messenger/internal/dto"
)
const maxUploadBytes = 10 * 1024 * 1024
func uploadAttachment(
t *testing.T,
actor testUser,
chatID uuid.UUID,
filename string,
contentType string,
body []byte,
) *http.Response {
t.Helper()
req, err := http.NewRequest(
http.MethodPost,
*baseURL+"/api/v1/chats/"+chatID.String()+"/attachments?filename="+url.QueryEscape(filename),
bytes.NewReader(body),
)
if err != nil {
t.Fatalf("build upload request: %v", err)
}
req.Header.Set("Content-Type", contentType)
req.Header.Set("Authorization", "Bearer "+actor.Token)
resp, err := httpClient.Do(req)
if err != nil {
t.Fatalf("upload request failed: %v", err)
}
return resp
}
func uploadPNG(t *testing.T, actor testUser, chatID uuid.UUID) dto.AttachmentResponse {
t.Helper()
resp := uploadAttachment(t, actor, chatID, "sample.png", "image/png", makePNG(t, 32, 32))
requireStatus(t, resp, http.StatusCreated)
var att dto.AttachmentResponse
mustDecode(t, resp, &att)
return att
}
func postMessage(
t *testing.T,
actor testUser,
chatID uuid.UUID,
text string,
attachmentIDs []uuid.UUID,
) *http.Response {
t.Helper()
body, err := json.Marshal(map[string]any{
"text": text,
"attachment_ids": attachmentIDs,
})
if err != nil {
t.Fatalf("marshal message: %v", err)
}
req, err := http.NewRequest(
http.MethodPost,
*baseURL+"/api/v1/chats/"+chatID.String()+"/messages",
bytes.NewReader(body),
)
if err != nil {
t.Fatalf("build message request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+actor.Token)
req.Header.Set("Idempotency-Key", uuid.NewString())
resp, err := httpClient.Do(req)
if err != nil {
t.Fatalf("message request failed: %v", err)
}
return resp
}
func requireErrorCode(t *testing.T, resp *http.Response, code dto.ErrorCode) {
t.Helper()
var apiErr dto.ErrorResponse
mustDecode(t, resp, &apiErr)
if apiErr.Error.Code != code {
t.Errorf("expected error code %q, got %q", code, apiErr.Error.Code)
}
}
+180
View File
@@ -0,0 +1,180 @@
//go:build load
package studenttests_test
import (
"bytes"
"net/http"
"os/exec"
"sort"
"strconv"
"strings"
"sync"
"testing"
"time"
)
func dockerMem(filter string) map[string]float64 {
out, err := exec.Command("docker", "stats", "--no-stream", "--format", "{{.Name}}\t{{.MemUsage}}").Output()
if err != nil {
return nil
}
m := map[string]float64{}
for _, line := range strings.Split(string(out), "\n") {
parts := strings.SplitN(line, "\t", 2)
if len(parts) != 2 || (filter != "" && !strings.Contains(parts[0], filter)) {
continue
}
used := strings.SplitN(parts[1], "/", 2)[0]
m[parts[0]] = memBytes(used)
}
return m
}
func memBytes(s string) float64 {
s = strings.TrimSpace(s)
units := []struct {
suf string
mult float64
}{
{"GiB", 1 << 30}, {"MiB", 1 << 20}, {"KiB", 1 << 10},
{"GB", 1e9}, {"MB", 1e6}, {"kB", 1e3}, {"B", 1},
}
for _, u := range units {
if strings.HasSuffix(s, u.suf) {
v, _ := strconv.ParseFloat(strings.TrimSpace(strings.TrimSuffix(s, u.suf)), 64)
return v * u.mult
}
}
return 0
}
func mib(v float64) string {
return strconv.FormatFloat(v/(1<<20), 'f', 1, 64) + "MiB"
}
func TestConcurrentUploads(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
body := makePNG(t, 1870, 1870)
url := *baseURL + "/api/v1/chats/" + chat.ID.String() + "/attachments?filename=load.png"
baseline := dockerMem("api")
stop := make(chan struct{})
memDone := make(chan struct{})
peak := map[string]float64{}
go func() {
defer close(memDone)
for {
for name, v := range dockerMem("api") {
if v > peak[name] {
peak[name] = v
}
}
select {
case <-stop:
return
case <-time.After(500 * time.Millisecond):
}
}
}()
var (
mu sync.Mutex
statuses = make(map[int]int)
latencies []time.Duration
errors int
)
start := time.Now()
deadline := start.Add(*duration)
var wg sync.WaitGroup
for w := 0; w < *workers; w++ {
wg.Add(1)
go func() {
defer wg.Done()
for time.Now().Before(deadline) {
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(body))
if err != nil {
mu.Lock()
errors++
mu.Unlock()
return
}
req.Header.Set("Content-Type", "image/png")
req.Header.Set("Authorization", "Bearer "+user.Token)
reqStart := time.Now()
resp, err := httpClient.Do(req)
latency := time.Since(reqStart)
if err != nil {
mu.Lock()
errors++
mu.Unlock()
continue
}
mu.Lock()
statuses[resp.StatusCode]++
if resp.StatusCode == http.StatusCreated {
latencies = append(latencies, latency)
}
mu.Unlock()
resp.Body.Close()
}
}()
}
wg.Wait()
close(stop)
<-memDone
elapsed := time.Since(start)
total := 0
for _, n := range statuses {
total += n
}
total += errors
t.Logf("workers=%d duration=%.1fs elapsed=%.1fs", *workers, duration.Seconds(), elapsed.Seconds())
t.Logf("total uploads=%d transport_errors=%d", total, errors)
for status, n := range statuses {
t.Logf("HTTP %d: %d", status, n)
}
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("latency p50=%s p95=%s p99=%s",
percentile(latencies, 0.50),
percentile(latencies, 0.95),
percentile(latencies, 0.99),
)
}
names := make(map[string]struct{}, len(baseline)+len(peak))
for name := range baseline {
names[name] = struct{}{}
}
for name := range peak {
names[name] = struct{}{}
}
sorted := make([]string, 0, len(names))
for name := range names {
sorted = append(sorted, name)
}
sort.Strings(sorted)
if len(sorted) == 0 {
t.Log("memory: docker stats not available (no containers matched)")
return
}
t.Log("memory per container (idle -> peak):")
for _, name := range sorted {
t.Logf(" %s: %s -> %s", name, mib(baseline[name]), mib(peak[name]))
}
}
+139
View File
@@ -0,0 +1,139 @@
//go:build contract
package studenttests_test
import (
"bytes"
"image/jpeg"
"image/png"
"io"
"net/http"
"testing"
"github.com/google/uuid"
"mtusi2026-messenger/internal/dto"
)
func TestAttachmentJPEG(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
img, err := png.Decode(bytes.NewReader(makePNG(t, 32, 32)))
if err != nil {
t.Fatalf("decode png: %v", err)
}
var body bytes.Buffer
if err := jpeg.Encode(&body, img, nil); err != nil {
t.Fatalf("encode jpeg: %v", err)
}
resp := uploadAttachment(t, user, chat.ID, "sample.jpg", "image/jpeg", body.Bytes())
requireStatus(t, resp, http.StatusCreated)
var att dto.AttachmentResponse
mustDecode(t, resp, &att)
if att.Status != "ready" {
t.Fatalf("expected ready attachment, got %q", att.Status)
}
resp = doRequest(t, http.MethodGet, "/api/v1/attachments/"+att.ID.String()+"/content", user.Token, nil)
requireStatus(t, resp, http.StatusOK)
defer resp.Body.Close()
original, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read original: %v", err)
}
if !bytes.Equal(original, body.Bytes()) {
t.Error("downloaded JPEG differs from uploaded original")
}
}
func TestAttachmentTooManyPixels(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
body := makePNG(t, 8000, 5001)
if len(body) > maxUploadBytes {
t.Fatal("pixel-limit fixture exceeds upload byte limit")
}
resp := uploadAttachment(t, user, chat.ID, "large.png", "image/png", body)
requireStatus(t, resp, http.StatusRequestEntityTooLarge)
requireErrorCode(t, resp, dto.ErrorCodePayloadTooLarge)
}
func TestAttachmentUnsafeFilename(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
resp := uploadAttachment(t, user, chat.ID, "../image.png", "image/png", makePNG(t, 32, 32))
requireStatus(t, resp, http.StatusBadRequest)
requireErrorCode(t, resp, dto.ErrorCodeInvalidRequest)
}
func TestAttachmentTooLarge(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
body := bytes.Repeat([]byte{0x00}, maxUploadBytes+1)
resp := uploadAttachment(t, user, chat.ID, "big.png", "image/png", body)
requireStatus(t, resp, http.StatusRequestEntityTooLarge)
requireErrorCode(t, resp, dto.ErrorCodePayloadTooLarge)
}
func TestAttachmentCorruptedImage(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
body := []byte("this is definitely not a png or jpeg image")
resp := uploadAttachment(t, user, chat.ID, "broken.png", "image/png", body)
requireStatus(t, resp, http.StatusUnsupportedMediaType)
requireErrorCode(t, resp, dto.ErrorCodeUnsupportedMediaType)
}
func TestAttachmentMimeSubstitution(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
resp := uploadAttachment(t, user, chat.ID, "actually-png.jpg", "image/jpeg", makePNG(t, 32, 32))
requireStatus(t, resp, http.StatusUnsupportedMediaType)
requireErrorCode(t, resp, dto.ErrorCodeUnsupportedMediaType)
}
func TestAttachmentForeignID(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
foreign := uuid.New()
resp := doRequest(t, http.MethodGet, "/api/v1/attachments/"+foreign.String(), user.Token, nil)
requireStatus(t, resp, http.StatusNotFound)
requireErrorCode(t, resp, dto.ErrorCodeNotFound)
resp = doRequest(t, http.MethodGet, "/api/v1/attachments/"+foreign.String()+"/content", user.Token, nil)
requireStatus(t, resp, http.StatusNotFound)
requireErrorCode(t, resp, dto.ErrorCodeNotFound)
resp = postMessage(t, user, chat.ID, "", []uuid.UUID{foreign})
requireStatus(t, resp, http.StatusNotFound)
requireErrorCode(t, resp, dto.ErrorCodeNotFound)
}
func TestAttachmentFromAnotherChat(t *testing.T) {
user := createUser(t)
member := createUser(t)
chatA := createChat(t, user, user.ID, member.ID)
chatB := createChat(t, user, user.ID)
att := uploadPNG(t, user, chatA.ID)
// The attachment belongs to chatA; linking it to a chatB message must fail.
resp := postMessage(t, user, chatB.ID, "", []uuid.UUID{att.ID})
requireStatus(t, resp, http.StatusNotFound)
requireErrorCode(t, resp, dto.ErrorCodeNotFound)
}
+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)
}
}
}
+156
View File
@@ -0,0 +1,156 @@
//go:build failure
package studenttests_test
import (
"bytes"
"io"
"net/http"
"os/exec"
"testing"
"time"
"mtusi2026-messenger/internal/dto"
)
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()
}
func TestS3Down(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
original := makePNG(t, 32, 32)
att := uploadPNG(t, user, chat.ID)
stopService(t, "s3")
for _, path := range []string{"/health/ready", "/api/v1/attachments/" + att.ID.String() + "/content"} {
resp := doRequest(t, http.MethodGet, path, user.Token, nil)
requireStatus(t, resp, http.StatusServiceUnavailable)
requireErrorCode(t, resp, dto.ErrorCodeUnavailable)
}
resp := uploadAttachment(t, user, chat.ID, "outage.png", "image/png", original)
requireStatus(t, resp, http.StatusServiceUnavailable)
requireErrorCode(t, resp, dto.ErrorCodeUnavailable)
resp = doRequest(t, http.MethodGet, "/health/live", "", nil)
requireStatus(t, resp, http.StatusOK)
resp.Body.Close()
compose(t, "start", "s3")
waitReady(t)
deadline := time.Now().Add(60 * time.Second)
downloaded, uploaded := false, false
for time.Now().Before(deadline) && (!downloaded || !uploaded) {
if !downloaded {
req, err := http.NewRequest(http.MethodGet, *baseURL+"/api/v1/attachments/"+att.ID.String()+"/content", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+user.Token)
response, err := httpClient.Do(req)
if err == nil {
data, readErr := io.ReadAll(response.Body)
response.Body.Close()
if response.StatusCode == http.StatusOK && readErr == nil {
if !bytes.Equal(data, original) {
t.Fatal("original changed across S3 outage")
}
downloaded = true
} else if response.StatusCode != http.StatusServiceUnavailable && response.StatusCode != http.StatusBadGateway && response.StatusCode != http.StatusGatewayTimeout {
t.Fatalf("unexpected download recovery status: %d", response.StatusCode)
}
}
}
if !uploaded {
response := uploadAttachment(t, user, chat.ID, "recovery.png", "image/png", original)
status := response.StatusCode
response.Body.Close()
if status == http.StatusCreated {
uploaded = true
} else if status != http.StatusServiceUnavailable {
t.Fatalf("unexpected upload recovery status: %d", status)
}
}
if !downloaded || !uploaded {
time.Sleep(500 * time.Millisecond)
}
}
if !downloaded || !uploaded {
t.Fatalf("S3 did not recover in 60s: download=%t upload=%t", downloaded, uploaded)
}
}
+236
View File
@@ -0,0 +1,236 @@
package studenttests_test
import (
"bytes"
"encoding/json"
"flag"
"image"
"image/color"
"image/png"
"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)
}
func makePNG(t *testing.T, width, height int) []byte {
t.Helper()
img := image.NewRGBA(image.Rect(0, 0, width, height))
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
img.Set(x, y, color.RGBA{
R: uint8((x * 7) % 256),
G: uint8((y * 13) % 256),
B: uint8((x + y) % 256),
A: 255,
})
}
}
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
t.Fatalf("encode png: %v", err)
}
return buf.Bytes()
}
+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))
}
+169
View File
@@ -0,0 +1,169 @@
//go:build reconcile
package studenttests_test
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"os"
"os/exec"
"slices"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"mtusi2026-messenger/internal/reconcile"
)
func reconcileDB(t *testing.T) *pgx.Conn {
t.Helper()
secret, err := os.ReadFile("../secrets/test_database_url.txt")
if err != nil {
t.Fatalf("read test database URL: %v", err)
}
conn, err := pgx.Connect(context.Background(), strings.TrimSpace(string(secret)))
if err != nil {
t.Fatalf("connect to test database: %v", err)
}
t.Cleanup(func() { conn.Close(context.Background()) })
return conn
}
func reconcileSQL(t *testing.T, conn *pgx.Conn, query string, args ...any) {
t.Helper()
if _, err := conn.Exec(context.Background(), query, args...); err != nil {
t.Fatalf("prepare/check reconcile fixture: %v", err)
}
}
func runReconcile(t *testing.T, dryRun bool, grace string) reconcile.Report {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
dry := "false"
if dryRun {
dry = "true"
}
cmd := exec.CommandContext(ctx, "docker", "compose", "--env-file", ".env", "run", "--rm", "--no-deps", "reconcile", "-json", "-dry-run="+dry, "-grace="+grace)
cmd.Dir = ".."
var stderr bytes.Buffer
cmd.Stderr = &stderr
output, err := cmd.Output()
if err != nil {
t.Fatalf("run reconciler: %v\n%s", err, stderr.String())
}
var report reconcile.Report
if err := json.Unmarshal(output, &report); err != nil {
t.Fatalf("decode reconcile report: %v\n%s", err, output)
}
t.Logf("dry_run=%t objects=%d rows=%d list_pages=%d duration_ms=%d orphan=%d missing=%d stale=%d skipped_fresh=%d skipped_referenced=%d deleted_objects=%d deleted_rows=%d marked_failed=%d errors=%v", report.DryRun, report.ScannedObjects, report.ScannedRows, report.ListPages, report.DurationMS, len(report.OrphanObjects), len(report.MissingAttachments), len(report.StaleUploads), report.SkippedFresh, report.SkippedReferenced, report.DeletedObjects, report.DeletedRows, report.MarkedFailed, report.Errors)
if len(report.Errors) != 0 {
t.Fatal("reconciler reported errors")
}
return report
}
func TestReconcileRepair(t *testing.T) {
conn := reconcileDB(t)
user := createUser(t)
chat := createChat(t, user, user.ID)
att := uploadPNG(t, user, chat.ID)
var originalKey string
if err := conn.QueryRow(context.Background(), "SELECT s3_key FROM attachments WHERE id=$1", att.ID).Scan(&originalKey); err != nil {
t.Fatal(err)
}
// Simulate lost metadata for the original object and metadata pointing at a missing object.
reconcileSQL(t, conn, "UPDATE attachments SET s3_key=$2 WHERE id=$1", att.ID, "chats/reconcile-missing/"+uuid.NewString())
// Only this experiment uses a shortened grace period, to avoid waiting an hour.
time.Sleep(1100 * time.Millisecond)
dry := runReconcile(t, true, "1s")
if !slices.Contains(dry.OrphanObjects, originalKey) || !slices.Contains(dry.MissingAttachments, att.ID) {
t.Fatal("dry-run did not detect both injected inconsistencies")
}
if dry.DeletedObjects != 0 || dry.DeletedRows != 0 || dry.MarkedFailed != 0 {
t.Fatal("dry-run changed data")
}
var status, code string
if err := conn.QueryRow(context.Background(), "SELECT status::text FROM attachments WHERE id=$1", att.ID).Scan(&status); err != nil {
t.Fatal(err)
}
if status != "ready" {
t.Fatalf("dry-run changed status: %s", status)
}
repair := runReconcile(t, false, "1s")
if repair.DeletedObjects < 1 || repair.MarkedFailed < 1 {
t.Fatal("repair did not apply fixes")
}
if err := conn.QueryRow(context.Background(), "SELECT status::text, error_code FROM attachments WHERE id=$1", att.ID).Scan(&status, &code); err != nil {
t.Fatal(err)
}
if status != "failed" || code != "object_missing" {
t.Fatalf("unexpected repaired state: %s %s", status, code)
}
again := runReconcile(t, false, "1s")
if slices.Contains(again.OrphanObjects, originalKey) || slices.Contains(again.MissingAttachments, att.ID) {
t.Fatal("fixture still requires repair on repeat")
}
if again.DeletedObjects != 0 || again.DeletedRows != 0 || again.MarkedFailed != 0 {
t.Fatal("repeat repair changed data; run on an idle test stand")
}
t.Log("PASS: dry-run preserved data; orphan deleted; missing marked failed; repeat made no changes")
}
func TestReconcileSafety(t *testing.T) {
conn := reconcileDB(t)
user := createUser(t)
chat := createChat(t, user, user.ID)
fresh := uploadPNG(t, user, chat.ID)
used := uploadPNG(t, user, chat.ID)
resp := postMessage(t, user, chat.ID, "", []uuid.UUID{used.ID})
requireStatus(t, resp, http.StatusCreated)
resp.Body.Close()
// Exercise both grace-period protection and protection of referenced queued uploads.
reconcileSQL(t, conn, "UPDATE attachments SET status='queued' WHERE id=$1", fresh.ID)
reconcileSQL(t, conn, "UPDATE attachments SET status='queued', created_at=now()-interval '2 hours' WHERE id=$1", used.ID)
t.Cleanup(func() {
if _, err := conn.Exec(context.Background(), "UPDATE attachments SET status='ready' WHERE id=ANY($1::uuid[])", []uuid.UUID{fresh.ID, used.ID}); err != nil {
t.Errorf("restore fixture status: %v", err)
}
})
for _, dryRun := range []bool{true, false} {
report := runReconcile(t, dryRun, "1h")
if report.SkippedFresh < 1 || report.SkippedReferenced < 1 {
t.Fatal("fresh/referenced protection was not exercised")
}
for _, att := range []uuid.UUID{fresh.ID, used.ID} {
var status string
if err := conn.QueryRow(context.Background(), "SELECT status::text FROM attachments WHERE id=$1", att).Scan(&status); err != nil {
t.Fatal(err)
}
if status != "queued" {
t.Fatalf("protected fixture changed status: %s", status)
}
resp := doRequest(t, http.MethodGet, "/api/v1/attachments/"+att.String()+"/content", user.Token, nil)
requireStatus(t, resp, http.StatusOK)
data, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(data, makePNG(t, 32, 32)) {
t.Fatal("protected original changed")
}
}
}
t.Log("PASS: fresh and old referenced uploads preserved, originals unchanged")
}
func TestReconcileCost(t *testing.T) {
for i := 1; i <= 3; i++ {
t.Logf("scan %d/3", i)
runReconcile(t, true, "1h")
}
}
+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()
}