@@ -3,11 +3,15 @@ package handlers_test
33import (
44 "bullet-cloud-api/internal/auth"
55 "bullet-cloud-api/internal/users"
6+ "io"
7+ "net/http"
8+ "net/http/httptest"
69 "testing"
710 "time"
811
912 "github.com/google/uuid"
1013 "github.com/gorilla/mux"
14+ "github.com/stretchr/testify/assert"
1115)
1216
1317// --- Common Test Setup --- //
@@ -37,3 +41,34 @@ func generateTestToken(userID uuid.UUID, secret string) string {
3741 }
3842 return token
3943}
44+
45+ // executeRequestAndAssert performs the common steps of:
46+ // 1. Creating an HTTP request.
47+ // 2. Setting JSON Content-Type and optional Authorization headers.
48+ // 3. Executing the request against the provided router.
49+ // 4. Asserting the response status code.
50+ // 5. Asserting that the response body contains the expected substring.
51+ func executeRequestAndAssert (t * testing.T , router * mux.Router , method , url , token string , body io.Reader , expectedStatus int , expectedBodyContains string ) {
52+ req , err := http .NewRequest (method , url , body )
53+ assert .NoError (t , err , "Failed to create request" )
54+
55+ req .Header .Set ("Content-Type" , "application/json" )
56+ if token != "" {
57+ req .Header .Set ("Authorization" , "Bearer " + token )
58+ }
59+
60+ rr := httptest .NewRecorder ()
61+ router .ServeHTTP (rr , req )
62+
63+ assert .Equal (t , expectedStatus , rr .Code , "Status code mismatch for %s %s" , method , url )
64+
65+ if expectedBodyContains != "" {
66+ assert .Contains (t , rr .Body .String (), expectedBodyContains , "Response body mismatch for %s %s" , method , url )
67+ } else if expectedStatus < 300 { // Only assert empty body for non-redirect/non-error success cases if expectedBodyContains is empty
68+ // Special case for 204 No Content or similar where empty body is expected
69+ if rr .Code == http .StatusNoContent {
70+ assert .Empty (t , rr .Body .String (), "Body should be empty for 204 No Content on %s %s" , method , url )
71+ } // Other success cases might have bodies (like 200 OK returning an object)
72+ // We rely on expectedBodyContains for those. If it's empty, we don't assert emptiness for 200/201.
73+ }
74+ }
0 commit comments