package tests import ( "context" "messenger/src/backend/handlers" "messenger/src/backend/repositories" "messenger/src/backend/services" "net/http" "net/http/httptest" "strings" "testing" ) func TestCreateUserInvalidJSON(t *testing.T) { store := repositories.NewUserStore(nil) handler := handlers.NewRouter(nil, services.NewUserService(store), nil, nil, nil) request := httptest.NewRequest( http.MethodPost, "/api/v1/users", strings.NewReader(`{"username":`), ) request.Header.Set("Content-Type", "application/json") response := httptest.NewRecorder() handler.ServeHTTP(response, request) if response.Code != http.StatusBadRequest { t.Fatalf( "expected status %d, got %d; body: %s", http.StatusBadRequest, response.Code, response.Body.String(), ) } if response.Header().Get("Content-Type") != "application/json" { t.Fatalf( "expected Content-Type application/json, got %q", response.Header().Get("Content-Type"), ) } if response.Header().Get("X-Request-Id") == "" { t.Fatal("expected non-empty X-Request-Id header") } body := response.Body.String() if !strings.Contains(body, `"code":"invalid_request"`) { t.Fatalf( "expected invalid_request error code, got body: %s", body, ) } if !strings.Contains(body, "request_id") { t.Fatalf( "expected request_id in error body, got body: %s", body, ) } } func TestCreateUserDuplicateUsername(t *testing.T) { fixture := newTestFixture(t) handler := fixture.router firstRequest := httptest.NewRequest( http.MethodPost, "/api/v1/users", strings.NewReader(`{ "username": "alice", "display_name": "Алиса", "password": "lab2-test-password" }`), ) firstRequest.Header.Set("Content-Type", "application/json") firstResponse := httptest.NewRecorder() handler.ServeHTTP(firstResponse, firstRequest) if firstResponse.Code != http.StatusCreated { t.Fatalf( "expected first request status %d, got %d; body: %s", http.StatusCreated, firstResponse.Code, firstResponse.Body.String(), ) } secondRequest := httptest.NewRequest( http.MethodPost, "/api/v1/users", strings.NewReader(`{ "username": "alice", "display_name": "Другая Алиса", "password": "lab2-test-password" }`), ) secondRequest.Header.Set("Content-Type", "application/json") secondResponse := httptest.NewRecorder() handler.ServeHTTP(secondResponse, secondRequest) if secondResponse.Code != http.StatusConflict { t.Fatalf( "expected duplicate username status %d, got %d; body: %s", http.StatusConflict, secondResponse.Code, secondResponse.Body.String(), ) } if secondResponse.Header().Get("X-Request-Id") == "" { t.Fatal("expected non-empty X-Request-Id header") } if !strings.Contains( secondResponse.Body.String(), `"code":"conflict"`, ) { t.Fatalf( "expected conflict error code, got body: %s", secondResponse.Body.String(), ) } var count int if err := fixture.db.QueryRow(context.Background(), "SELECT count(*) FROM users").Scan(&count); err != nil { t.Fatal(err) } if count != 1 { t.Fatalf("expected one user, got %d", count) } }