test(load): add load test with api replica stop

This commit is contained in:
kk10
2026-10-18 12:06:03 +03:00
parent ebfef7289a
commit 4cf60df572
3 changed files with 157 additions and 3 deletions
+146
View File
@@ -0,0 +1,146 @@
//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")
}
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())
}
}
+1 -2
View File
@@ -70,10 +70,9 @@ func TestLoad(t *testing.T) {
latency := time.Since(requestStart)
if err != nil {
if atomic.CompareAndSwapInt64(&requestErrors, 0, 1) {
if atomic.AddInt64(&requestErrors, 1) == 1 {
t.Logf("first transport error: %v", err)
}
atomic.AddInt64(&requestErrors, 1)
continue
}
+10 -1
View File
@@ -1,8 +1,10 @@
LOAD_ARGS = $(if $(LOAD_WORKERS),-workers=$(LOAD_WORKERS),) \
$(if $(LOAD_DURATION),-duration=$(LOAD_DURATION),) \
$(if $(LOAD_RATE),-rate=$(LOAD_RATE),)
REPLICA ?= 1
ACTION_AT ?= 10s
.PHONY: help-go contract-go race-go load-go failure-go
.PHONY: help-go contract-go race-go load-go failure-go load-action-go
help-go:
@echo "contract-go: contract tests"
@@ -21,3 +23,10 @@ load-go:
failure-go:
go test -tags=failure ./student-tests/... -v -args -base-url=$(BASE_URL)
load-action-go:
go test -tags=load,action ./student-tests/... -run TestLoadWithAction -v -args \
-base-url=$(BASE_URL) $(LOAD_ARGS) \
-replica=$(REPLICA) \
-action=$(CURDIR)/scripts/stop-one.sh \
-action-at=$(ACTION_AT)