//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) } }