forked from mtusi2026/mtusi2026lab6
ЛР 6 — БПИ2302 — Нурлыгаянова — на 3
This commit is contained in:
@@ -0,0 +1,228 @@
|
||||
// Package e2e — проверки против запущенного стенда через балансировщик.
|
||||
//
|
||||
// Запуск: E2E_BASE_URL=http://localhost:8080 go test -count=1 -v ./e2e/
|
||||
// Без E2E_BASE_URL тесты пропускаются, поэтому обычный go test ./... стенд не требует.
|
||||
// Создаёт только синтетические данные, токены и пароли не печатает.
|
||||
package e2e
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
rounds = 20
|
||||
workers = 16
|
||||
)
|
||||
|
||||
type client struct {
|
||||
t *testing.T
|
||||
base string
|
||||
http *http.Client
|
||||
token string
|
||||
}
|
||||
|
||||
type result struct {
|
||||
status int
|
||||
instance string
|
||||
body []byte
|
||||
}
|
||||
|
||||
func randomHex(n int) string {
|
||||
b := make([]byte, n)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
// do не вызывает t.Fatal: он работает и из горутин.
|
||||
func (c *client) do(method, path string, headers map[string]string, payload any) (result, error) {
|
||||
var body io.Reader
|
||||
if payload != nil {
|
||||
b, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return result{}, err
|
||||
}
|
||||
body = bytes.NewReader(b)
|
||||
}
|
||||
req, err := http.NewRequest(method, c.base+path, body)
|
||||
if err != nil {
|
||||
return result{}, err
|
||||
}
|
||||
if payload != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if c.token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+c.token)
|
||||
}
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return result{}, fmt.Errorf("%s %s: %w", method, strings.Split(path, "?")[0], err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return result{}, err
|
||||
}
|
||||
return result{status: resp.StatusCode, instance: resp.Header.Get("X-Instance-Id"), body: data}, nil
|
||||
}
|
||||
|
||||
func (c *client) mustDo(method, path string, want int, payload any, out any) {
|
||||
c.t.Helper()
|
||||
res, err := c.do(method, path, nil, payload)
|
||||
if err != nil {
|
||||
c.t.Fatal(err)
|
||||
}
|
||||
if res.status != want {
|
||||
c.t.Fatalf("%s %s: status = %d, want %d", method, strings.Split(path, "?")[0], res.status, want)
|
||||
}
|
||||
if out != nil {
|
||||
if err := json.Unmarshal(res.body, out); err != nil {
|
||||
c.t.Fatalf("%s %s: decode: %v", method, path, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// bootstrap создаёт пользователя с сессией и чат с ним.
|
||||
func bootstrap(t *testing.T, base string) (*client, string) {
|
||||
t.Helper()
|
||||
c := &client{t: t, base: strings.TrimRight(base, "/"), http: &http.Client{Timeout: 10 * time.Second}}
|
||||
|
||||
username, password := "lb_"+randomHex(8), "T3st-"+randomHex(16)
|
||||
var user struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
c.mustDo(http.MethodPost, "/api/v1/users", http.StatusCreated, map[string]string{
|
||||
"username": username, "display_name": "LB test", "password": password,
|
||||
}, &user)
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, c.base+"/api/v1/auth/sessions", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.SetBasicAuth(username, password)
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("login: status = %d", resp.StatusCode)
|
||||
}
|
||||
var session struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&session); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.token = session.Token
|
||||
|
||||
var chat struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
c.mustDo(http.MethodPost, "/api/v1/chats", http.StatusCreated, map[string]any{
|
||||
"title": "LB test", "member_ids": []string{user.ID},
|
||||
}, &chat)
|
||||
return c, chat.ID
|
||||
}
|
||||
|
||||
// Одинаковый Idempotency-Key одновременно через разные реплики создаёт ровно одно сообщение.
|
||||
func TestLBSameKeyConcurrentlyThroughReplicas(t *testing.T) {
|
||||
base := os.Getenv("E2E_BASE_URL")
|
||||
if base == "" {
|
||||
t.Skip("E2E_BASE_URL не задан")
|
||||
}
|
||||
c, chatID := bootstrap(t, base)
|
||||
path := "/api/v1/chats/" + chatID + "/messages"
|
||||
|
||||
perInstance := map[string]int{}
|
||||
var created []string
|
||||
for round := range rounds {
|
||||
key, text := randomHex(16), fmt.Sprintf("гонка %d", round)
|
||||
results := make([]result, workers)
|
||||
errs := make([]error, workers)
|
||||
start := make(chan struct{})
|
||||
var wg sync.WaitGroup
|
||||
for i := range workers {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
results[i], errs[i] = c.do(http.MethodPost, path,
|
||||
map[string]string{"Idempotency-Key": key}, map[string]string{"text": text})
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
|
||||
instances := map[string]bool{}
|
||||
for i := range workers {
|
||||
if errs[i] != nil {
|
||||
t.Fatalf("round %d: %v", round, errs[i])
|
||||
}
|
||||
if results[i].status != http.StatusCreated {
|
||||
t.Fatalf("round %d: status = %d, want 201", round, results[i].status)
|
||||
}
|
||||
if !bytes.Equal(results[i].body, results[0].body) {
|
||||
t.Fatalf("round %d: реплики вернули разные сообщения", round)
|
||||
}
|
||||
instances[results[i].instance] = true
|
||||
perInstance[results[i].instance]++
|
||||
}
|
||||
if len(instances) < 2 {
|
||||
t.Fatalf("round %d обслужила одна реплика: проверьте LB", round)
|
||||
}
|
||||
var msg struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal(results[0].body, &msg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
created = append(created, msg.ID)
|
||||
}
|
||||
|
||||
var history []string
|
||||
for cursor := ""; ; {
|
||||
q := "?limit=100"
|
||||
if cursor != "" {
|
||||
q += "&cursor=" + url.QueryEscape(cursor)
|
||||
}
|
||||
var page struct {
|
||||
Items []struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
c.mustDo(http.MethodGet, path+q, http.StatusOK, nil, &page)
|
||||
for _, m := range page.Items {
|
||||
history = append(history, m.ID)
|
||||
}
|
||||
if page.NextCursor == nil {
|
||||
break
|
||||
}
|
||||
cursor = *page.NextCursor
|
||||
}
|
||||
slices.Sort(created)
|
||||
slices.Sort(history)
|
||||
if !slices.Equal(created, history) {
|
||||
t.Fatalf("история отличается от подтверждённого: %d сообщений, ожидалось %d", len(history), len(created))
|
||||
}
|
||||
t.Logf("раундов: %d, запросов в раунде: %d, запросов по репликам: %v, сообщений в истории: %d",
|
||||
rounds, workers, perInstance, len(history))
|
||||
}
|
||||
Reference in New Issue
Block a user