Merge pull request #873 from sisantaChhatoi/refactor/go-modernize-server-tests

refactor(server): use modern Go idioms in tests
This commit is contained in:
BaaRai 2026-12-03 00:06:08 +01:00 • committed by GitHub
commit 09de4486ef
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
22 changed files with 63 additions and 89 deletions

View file

@ -23,8 +23,7 @@ func TestBedrockGatewaySavedProfileAndConnection(t *testing.T) {
if m.pg == nil {
db.SkipNoPG(t)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ctx := t.Context()
s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir())
s.allowLoopbackModels = true // the fake endpoint listens on loopback (test-only guard seam)
const token = "synthetic-gateway-token"

View file

@ -26,7 +26,7 @@ func TestPasswordChangeWaitBlocksByIPAndToken(t *testing.T) {
clk := newFakeClock()
s := &Server{pwdLimit: newLoginLimiter(clk.now)}
const tok = "stolen-session"
for i := 0; i < loginMaxAttempts; i++ {
for i := range loginMaxAttempts {
if wait := s.passwordChangeWait(changePasswordRequest("192.0.2.50:40000", tok)); wait != 0 {
t.Fatalf("attempt %d blocked after %v", i+1, wait)
}
@ -36,7 +36,7 @@ func TestPasswordChangeWaitBlocksByIPAndToken(t *testing.T) {
}
s = &Server{pwdLimit: newLoginLimiter(clk.now)}
for i := 0; i < loginMaxAttempts; i++ {
for i := range loginMaxAttempts {
remote := fmt.Sprintf("198.51.100.%d:40000", i+1)
if wait := s.passwordChangeWait(changePasswordRequest(remote, tok)); wait != 0 {
t.Fatalf("rotated IP attempt %d blocked after %v", i+1, wait)
@ -47,7 +47,7 @@ func TestPasswordChangeWaitBlocksByIPAndToken(t *testing.T) {
}
s = &Server{pwdLimit: newLoginLimiter(clk.now)}
for i := 0; i < loginMaxAttempts; i++ {
for i := range loginMaxAttempts {
if wait := s.passwordChangeWait(changePasswordRequest("192.0.2.51:40000", tok)); wait != 0 {
t.Fatalf("fill attempt %d blocked after %v", i+1, wait)
}
@ -107,7 +107,7 @@ func TestChangePasswordRateLimitReturns429WithRetryAfter(t *testing.T) {
clk := newFakeClock()
_, _, post := changePasswordServer(t, clk)
const ip = "192.0.2.40:40000"
for i := 0; i < loginMaxAttempts; i++ {
for i := range loginMaxAttempts {
if w := post(ip, "wrong-password-xx", "correct-horse-9"); w.Code != 401 {
t.Fatalf("attempt %d: status=%d want 401; body=%s", i+1, w.Code, w.Body.String())
}
@ -130,7 +130,7 @@ func TestChangePasswordRateLimitReturns429WithRetryAfter(t *testing.T) {
func TestChangePasswordRateLimitFollowsStolenTokenAcrossIPs(t *testing.T) {
clk := newFakeClock()
_, _, post := changePasswordServer(t, clk)
for i := 0; i < loginMaxAttempts; i++ {
for i := range loginMaxAttempts {
remote := fmt.Sprintf("198.51.100.%d:40000", i+1)
if w := post(remote, "wrong-password-xx", "correct-horse-9"); w.Code != 401 {
t.Fatalf("attempt %d from %s: status=%d want 401; body=%s", i+1, remote, w.Code, w.Body.String())
@ -145,7 +145,7 @@ func TestChangePasswordSuccessResetsCounter(t *testing.T) {
clk := newFakeClock()
s, tok, post := changePasswordServer(t, clk)
const ip = "192.0.2.41:40000"
for i := 0; i < loginMaxAttempts-1; i++ {
for i := range loginMaxAttempts - 1 {
if w := post(ip, "wrong-password-xx", "correct-horse-9"); w.Code != 401 {
t.Fatalf("attempt %d: status=%d want 401; body=%s", i+1, w.Code, w.Body.String())
}
@ -180,7 +180,7 @@ func TestChangePasswordSuccessResetsCounter(t *testing.T) {
s.authChangePassword(rec, r)
return rec
}
for i := 0; i < loginMaxAttempts; i++ {
for i := range loginMaxAttempts {
if w := post2("wrong-password-xx", "correct-horse-9"); w.Code != 401 {
t.Fatalf("after reset attempt %d: status=%d want 401; body=%s", i+1, w.Code, w.Body.String())
}
@ -195,7 +195,7 @@ func TestChangePasswordUnauthenticatedDoesNotCount(t *testing.T) {
s, _, post := changePasswordServer(t, clk)
const ip = "192.0.2.42:40000"
body := `{"old_password":"wrong-password-xx","new_password":"correct-horse-9"}`
for i := 0; i < loginMaxAttempts+1; i++ {
for i := range loginMaxAttempts + 1 {
r := httptest.NewRequest("POST", "/api/auth/change-password", strings.NewReader(body))
r.RemoteAddr = ip
r.Header.Set("Authorization", "Bearer not-a-token")

View file

@ -44,7 +44,7 @@ func TestChatMentionPagination(t *testing.T) {
s, fid := newRetestServer(t)
pg := s.m.pg
query := fmt.Sprintf("mention-pages-%d", fid)
for i := 0; i < 43; i++ {
for range 43 {
id, err := pg.AddFinding(0, 0, "xss", query, "low", query, "proof", "test", nil)
if err != nil {
t.Fatal(err)

View file

@ -53,7 +53,7 @@ func TestCoreTaskLifecyclePG(t *testing.T) {
doRetry := func(method, path string, body any) (int, map[string]any) {
var code int
var out map[string]any
for i := 0; i < 5; i++ {
for range 5 {
code, out = do(method, path, body)
if code < 500 {
break
@ -79,7 +79,7 @@ func TestCoreTaskLifecyclePG(t *testing.T) {
// the exploration owns goal node(s) — goal seeding is async, poll briefly
var goals []*db.Node
for i := 0; i < 30; i++ {
for range 30 {
goals, err = m.pg.Exploration(expID).ListByKind("goal", 10)
if err != nil || len(goals) > 0 {
break

View file

@ -2,7 +2,6 @@ package server
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
@ -80,8 +79,7 @@ func TestProfilePricesThroughAPI(t *testing.T) {
if m.pg == nil {
db.SkipNoPG(t)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ctx := t.Context()
s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir())
body, _ := json.Marshal(map[string]any{

View file

@ -384,8 +384,8 @@ func (p *toolScript) next(t *testing.T) string {
// lastToolResult is the text of the last tool result the model is shown.
func lastToolResult(msgs []llm.Message) string {
for i := len(msgs) - 1; i >= 0; i-- {
for _, b := range msgs[i].Content {
for _, msg := range slices.Backward(msgs) {
for _, b := range msg.Content {
if b.Type != llm.BlockToolResult {
continue
}

View file

@ -93,7 +93,7 @@ func TestSealedEnvironmentHandoff(t *testing.T) {
got := map[string]string{}
seen := map[string]bool{}
done := false
for _, line := range strings.Split(string(out), "\n") {
for line := range strings.SplitSeq(string(out), "\n") {
if !strings.HasPrefix(line, "SEAL ") {
continue
}

View file

@ -17,7 +17,7 @@ func noNewPrivsOfThread(t *testing.T) string {
if err != nil {
t.Fatal(err)
}
for _, line := range strings.Split(string(b), "\n") {
for line := range strings.SplitSeq(string(b), "\n") {
if v, ok := strings.CutPrefix(line, "NoNewPrivs:"); ok {
return strings.TrimSpace(v)
}

View file

@ -15,6 +15,7 @@ import (
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"syscall"
"testing"
@ -741,7 +742,7 @@ func TestNormaTaskDirPlantedByExecutorAsRoot(t *testing.T) {
// envNames returns the variable names of an `env` listing.
func envNames(out string) map[string]string {
m := map[string]string{}
for _, line := range strings.Split(out, "\n") {
for line := range strings.SplitSeq(out, "\n") {
if k, v, ok := strings.Cut(line, "="); ok && k != "" && !strings.ContainsAny(k, " \t") {
m[k] = v
}
@ -776,12 +777,7 @@ func checkExecutorEnv(t *testing.T, path, out, home string, want ...string) {
}
func slicesContains(s []string, v string) bool {
for _, x := range s {
if x == v {
return true
}
}
return false
return slices.Contains(s, v)
}
// Each executor path starts its process with the allowlisted environment: a

View file

@ -30,7 +30,7 @@ func TestExecDropShimInheritsNoNewPrivs(t *testing.T) {
if err != nil {
t.Fatalf("shim helper failed: %v\n%s", err, out)
}
for _, line := range strings.Split(string(out), "\n") {
for line := range strings.SplitSeq(string(out), "\n") {
if v, ok := strings.CutPrefix(line, "NoNewPrivs:"); ok {
if got := strings.TrimSpace(v); got != "1" {
t.Fatalf("exec'd program NoNewPrivs = %q, want 1 (thread migrated after prctl)\n%s", got, out)

View file

@ -1,7 +1,6 @@
package server
import (
"context"
"errors"
"sync"
"testing"
@ -12,8 +11,7 @@ import (
)
func TestHealthSyncLoopWritesLatest(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ctx := t.Context()
var mu sync.Mutex
saved := map[int64]db.LLMHealth{}
@ -73,8 +71,7 @@ func TestHealthSyncLoopWritesLatest(t *testing.T) {
}
func TestHealthSyncRetriesFailedSave(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ctx := t.Context()
var mu sync.Mutex
calls := 0
@ -110,8 +107,7 @@ func TestHealthSyncRetriesFailedSave(t *testing.T) {
}
func TestHealthSyncEnqueueDoesNotWaitOnSave(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ctx := t.Context()
started := make(chan struct{})
release := make(chan struct{})

View file

@ -314,8 +314,7 @@ func TestLogsHistoryMasksCredentialsInOldRows(t *testing.T) {
}
sink := &logSinkT{cap: 3000, subs: map[chan LogLine]struct{}{}, out: &lockedBuffer{}}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ctx := t.Context()
sink.SetDB(ctx, m.pg)
if got := sinkText(sink); strings.Contains(got, password) || !strings.Contains(got, "http://olduser:xxxxx@old.test:3128") {
t.Errorf("restored ring: want the old row with its password masked; password present=%v", strings.Contains(got, password))

View file

@ -53,7 +53,7 @@ func loginServer(t *testing.T, clk *fakeClock) (*Server, func(remote, password s
func failN(t *testing.T, post func(string, string, map[string]string) *httptest.ResponseRecorder, remote string, n int) {
t.Helper()
for i := 0; i < n; i++ {
for i := range n {
if w := post(remote, "wrong-password", nil); w.Code != 401 {
t.Fatalf("attempt %d from %s: status=%d want 401; body=%s", i+1, remote, w.Code, w.Body.String())
}
@ -213,7 +213,7 @@ func TestLoginRateLimitBehindTrustedProxy(t *testing.T) {
const proxy = "127.0.0.1:50000"
via := func(xff string) map[string]string { return map[string]string{"X-Forwarded-For": xff} }
for i := 0; i < loginMaxAttempts; i++ {
for i := range loginMaxAttempts {
if w := post(proxy, "wrong-password", via("198.51.100.20")); w.Code != 401 {
t.Fatalf("attempt %d: status=%d want 401", i+1, w.Code)
}

View file

@ -9,13 +9,11 @@ import (
func TestLogSinkUnsubscribeDuringAddDoesNotPanic(t *testing.T) {
s := &logSinkT{cap: 8, subs: map[chan LogLine]struct{}{}, out: io.Discard}
var wg sync.WaitGroup
for i := 0; i < 32; i++ {
for range 32 {
_, unsub := s.subscribe()
wg.Add(1)
go func() {
defer wg.Done()
wg.Go(func() {
unsub()
}()
})
s.add(LogLine{Text: "line"})
}
wg.Wait()

View file

@ -62,24 +62,20 @@ func TestTaskLifecycleSnapshotConcurrentConsistency(t *testing.T) {
writeState(1, true)
var wg sync.WaitGroup
for writer := 0; writer < 4; writer++ {
for writer := range 4 {
writer := writer
wg.Add(1)
go func() {
defer wg.Done()
wg.Go(func() {
for i := 1; i <= 1000; i++ {
generation := int64(writer*1000 + i)
writeState(generation, generation%2 == 0)
}
}()
})
}
errCh := make(chan error, 4)
for reader := 0; reader < 4; reader++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 1000; i++ {
for range 4 {
wg.Go(func() {
for range 1000 {
state := task.lifecycleSnapshot()
if state.Queued == state.Paused {
errCh <- fmt.Errorf("queued=%v paused=%v", state.Queued, state.Paused)
@ -99,7 +95,7 @@ func TestTaskLifecycleSnapshotConcurrentConsistency(t *testing.T) {
return
}
}
}()
})
}
wg.Wait()
close(errCh)

View file

@ -429,7 +429,7 @@ func TestNotifyDigestBatchesMultipleFindingsIntoOneMessage(t *testing.T) {
"mode": db.NotifyModeDigest,
"config": map[string]any{"webhook": hook.URL},
})
for i := 0; i < 3; i++ {
for i := range 3 {
f.record(t, fmt.Sprintf("digest vuln %d", i+1), "high")
}
ctx := context.Background()
@ -594,7 +594,7 @@ func TestNotifyDeliveriesHistoryAndRetry(t *testing.T) {
}
ch := f.channel(t, chID)
// Keep delivering until the retry budget is exhausted.
for i := 0; i < db.MaxNotifyAttempts; i++ {
for range db.MaxNotifyAttempts {
f.n.stepRealtime(ctx, ch, 50, "")
if _, err := f.pg.Exec(`UPDATE notification_deliveries SET next_attempt_at = now() - interval '1 minute' WHERE channel_id=$1`, chID); err != nil {
t.Fatal(err)
@ -881,7 +881,7 @@ func TestNotifyDigestSegmentsAndDefersRemainder(t *testing.T) {
// Make the titles long, so 60 entries far exceed 4096 bytes and segmentation
// is guaranteed.
longName := strings.Repeat("very long vulnerability name", 6)
for i := 0; i < total; i++ {
for i := range total {
f.record(t, longName+strconv.Itoa(i+1), "high")
}
ctx := context.Background()

View file

@ -208,11 +208,9 @@ func TestReadyConcurrentRequestsShareOnePing(t *testing.T) {
const callers = 20
results := make([]bool, callers)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
wg.Go(func() {
results[0] = cache.check(context.Background(), ping)
}()
})
<-started
for i := 1; i < callers; i++ {

View file

@ -65,7 +65,7 @@ func TestReportCountsOnlyTheTaskAssets(t *testing.T) {
t.Fatalf("report status=%d body=%s", rec.Code, rec.Body.String())
}
var line string
for _, l := range strings.Split(rec.Body.String(), "\n") {
for l := range strings.SplitSeq(rec.Body.String(), "\n") {
if strings.HasPrefix(l, "- Assets: ") {
line = l
}

View file

@ -63,7 +63,7 @@ func TestSideHTTPPreparationCancellationAndClear(t *testing.T) {
f := newSideHTTPFixture(t)
p, path := f.conversation(t)
snap := f.checkpoint(t, p)
for i := 0; i < 21; i++ {
for i := range 21 {
e, _, err := f.m.pg.StartSideRequest(t.Context(), snap, fmt.Sprint(i), "past question")
if err != nil {
t.Fatal(err)
@ -250,7 +250,7 @@ func TestSideHTTPBusyIsolationClearAndReconnect(t *testing.T) {
// SSE reconnect always starts with a cumulative snapshot even with Last-Event-ID.
httpServer := httptest.NewServer(f.handler)
defer httpServer.Close()
for i := 0; i < 2; i++ {
for range 2 {
req, _ := http.NewRequest("GET", httpServer.URL+"/api/side-questions/"+e.ID+"/events", nil)
req.Header.Set("Authorization", "Bearer "+f.token)
req.Header.Set("Last-Event-ID", "999")
@ -306,7 +306,7 @@ func TestSideHTTPBusyIsolationClearAndReconnect(t *testing.T) {
func TestSideHTTPGlobalLimitTaskWorkerAndDeletion(t *testing.T) {
f := newSideHTTPFixture(t)
var requests []sidequestion.Exchange
for i := 0; i < 20; i++ {
for i := range 20 {
p, path := f.conversation(t)
f.checkpoint(t, p)
want := 202

View file

@ -40,7 +40,7 @@ func TestRotationConcurrentProvidersAndPrecedence(t *testing.T) {
started := make(chan int, 3)
release := []chan struct{}{make(chan struct{}), make(chan struct{})}
ids := []int64{}
for i := 0; i < 2; i++ {
for i := range 2 {
i := i
endpoint := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
started <- i
@ -111,7 +111,7 @@ func TestRotationConcurrentProvidersAndPrecedence(t *testing.T) {
}
dispatch(0)
close(release[0])
for i := 0; i < 2; i++ {
for range 2 {
select {
case err := <-done:
if err != nil {
@ -163,17 +163,15 @@ func TestRotationConcurrentDispatchAndUpdates(t *testing.T) {
const workers = 100
counts := make(chan int64, workers)
var wg sync.WaitGroup
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for range workers {
wg.Go(func() {
id, ok := task.nextRotatedProfile()
if !ok {
t.Error("missing assignment")
return
}
counts <- id
}()
})
}
wg.Wait()
close(counts)
@ -185,14 +183,12 @@ func TestRotationConcurrentDispatchAndUpdates(t *testing.T) {
t.Fatalf("unbalanced assignments: %v", got)
}
// Replace the chain while dispatching, exercising the shared list lock.
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < workers; i++ {
wg.Go(func() {
for i := range workers {
task.setLLMState(nil, nil, []int64{3, 4}, int64(i+1), "ready", "", i%2 == 0)
}
}()
for i := 0; i < workers; i++ {
})
for range workers {
task.nextRotatedProfile()
task.llmStateSnapshot()
}
@ -323,7 +319,7 @@ func TestRunIntentRotatesPinnedProfileWithCachedExecCtx(t *testing.T) {
defer m.Close()
ids := make([]int64, 0, 2)
for i := 0; i < 2; i++ {
for i := range 2 {
id, err := m.pg.SaveProfile(&db.LLMProfile{
Name: fmt.Sprintf("runintent-rotate-%d-%d", time.Now().UnixNano(), i),
Format: "openai",

View file

@ -202,28 +202,26 @@ func TestTaskLLMStateSnapshotIsConcurrentAndDetached(t *testing.T) {
t.Parallel()
task := &Task{ID: "7"}
var wg sync.WaitGroup
for writer := 0; writer < 2; writer++ {
for writer := range 2 {
wg.Add(1)
go func(offset int) {
defer wg.Done()
for i := 0; i < 500; i++ {
for i := range 500 {
id := int64(offset*1000 + i + 1)
task.setLLMState(&id, &id, []int64{id, id + 1}, int64(i), "ready", "")
}
}(writer)
}
for reader := 0; reader < 4; reader++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 500; i++ {
for range 4 {
wg.Go(func() {
for range 500 {
state := task.llmStateSnapshot()
if len(state.ProfileIDs) > 0 {
state.ProfileIDs[0] = -1
}
_ = taskDTO(task, "running")
}
}()
})
}
wg.Wait()
state := task.llmStateSnapshot()

View file

@ -421,7 +421,7 @@ func TestRewriteRulesLimits(t *testing.T) {
return fmt.Sprintf(`{"name":"t-rwapi-limit-%03d","phase":"response","actions":[{"type":"set_header","name":"X-A","value":"v"}]}`, i)
}
var ids []int64
for i := 0; i < db.MaxTrafficRewriteRules; i++ {
for i := range db.MaxTrafficRewriteRules {
ids = append(ids, decodeRewriteRuleJSON(t, request(true, "POST", rewriteAPI, body(i))).ID)
}
if resp := request(true, "POST", rewriteAPI, body(100)); resp.Code != 400 || !strings.Contains(resp.Body.String(), "100") {