@@ -3,11 +3,15 @@ package handlers_test
3
3
import (
4
4
"bullet-cloud-api/internal/auth"
5
5
"bullet-cloud-api/internal/users"
6
+ "io"
7
+ "net/http"
8
+ "net/http/httptest"
6
9
"testing"
7
10
"time"
8
11
9
12
"github.com/google/uuid"
10
13
"github.com/gorilla/mux"
14
+ "github.com/stretchr/testify/assert"
11
15
)
12
16
13
17
// --- Common Test Setup --- //
@@ -37,3 +41,34 @@ func generateTestToken(userID uuid.UUID, secret string) string {
37
41
}
38
42
return token
39
43
}
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