chore: port lab 1 solution

This commit is contained in:
kk10
2026-10-02 11:45:26 +03:00
parent 65003b6119
commit 2f279a1715
43 changed files with 2402 additions and 0 deletions
+135
View File
@@ -0,0 +1,135 @@
//go:build contract
package studenttests_test
import (
"encoding/json"
"net/http"
"net/url"
"strconv"
"testing"
"github.com/google/uuid"
"mtusi2026-messenger/internal/dto"
)
func TestInvalidJSON(t *testing.T) {
resp := doRequest(t, http.MethodPost, "/api/v1/users", uuid.Nil, []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.ID, 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",
})
if err != nil {
t.Fatalf("marshal body: %v", err)
}
resp := doRequest(t, http.MethodPost, "/api/v1/users", uuid.Nil, 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.ID, 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)
}
}
}
+198
View File
@@ -0,0 +1,198 @@
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,
},
}
func doRequest(t *testing.T, method, path string, actorID uuid.UUID, 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 actorID != uuid.Nil {
req.Header.Set("X-User-Id", actorID.String())
}
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) dto.UserResponse {
t.Helper()
username := "u_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:12]
body, err := json.Marshal(map[string]string{
"username": username,
"display_name": "Test " + username,
})
if err != nil {
t.Fatalf("marshal user: %v", err)
}
resp := doRequest(
t,
http.MethodPost,
"/api/v1/users",
uuid.Nil,
body,
)
requireStatus(t, resp, http.StatusCreated)
var u dto.UserResponse
mustDecode(t, resp, &u)
return u
}
func createChat(
t *testing.T,
creator dto.UserResponse,
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.ID,
body,
)
requireStatus(t, resp, http.StatusCreated)
var c dto.ChatResponse
mustDecode(t, resp, &c)
return c
}
func sendMessage(
t *testing.T,
actor dto.UserResponse,
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.ID,
body,
)
}
func sendLoadMessage(
actor dto.UserResponse,
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("X-User-Id", actor.ID.String())
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.ID, 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))
}