From 66808c6c8046ea987efc8e968536ba857c0fdc3c Mon Sep 17 00:00:00 2001 From: kk10 Date: Mon, 5 Oct 2026 22:43:09 +0300 Subject: [PATCH] test(auth): add concurrent registration race test --- student-tests/registration_race_test.go | 77 +++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 student-tests/registration_race_test.go diff --git a/student-tests/registration_race_test.go b/student-tests/registration_race_test.go new file mode 100644 index 00000000..1f49203f --- /dev/null +++ b/student-tests/registration_race_test.go @@ -0,0 +1,77 @@ +//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) + } +}