test(handlers): RequireAuth distinguishes missing context from user id zero

This commit is contained in:
2026-05-06 20:13:56 +02:00
parent 2ede636bd6
commit b3f6f5b15e
+19 -8
View File
@@ -569,7 +569,8 @@ func TestParseUintParam(t *testing.T) {
func TestRequireAuth(t *testing.T) {
tests := []struct {
name string
userID uint
setUserKey bool
userIDValue uint
expectedID uint
expectedOK bool
expectedStatus int
@@ -577,25 +578,32 @@ func TestRequireAuth(t *testing.T) {
}{
{
name: "authenticated user",
userID: 123,
setUserKey: true,
userIDValue: 123,
expectedID: 123,
expectedOK: true,
expectedStatus: 0,
},
{
name: "unauthenticated user (no userID)",
userID: 0,
name: "unauthenticated user (missing context)",
setUserKey: false,
expectedID: 0,
expectedOK: false,
expectedStatus: http.StatusUnauthorized,
expectedError: "Authentication required",
},
{
name: "authenticated user with id zero",
setUserKey: true,
userIDValue: 0,
expectedID: 0,
expectedOK: true,
},
{
name: "authenticated user with large ID",
userID: 4294967295,
setUserKey: true,
userIDValue: 4294967295,
expectedID: 4294967295,
expectedOK: true,
expectedStatus: 0,
},
}
@@ -604,7 +612,10 @@ func TestRequireAuth(t *testing.T) {
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/", nil)
ctx := context.WithValue(r.Context(), middleware.UserIDKey, tt.userID)
ctx := context.Background()
if tt.setUserKey {
ctx = context.WithValue(ctx, middleware.UserIDKey, tt.userIDValue)
}
r = r.WithContext(ctx)
userID, ok := RequireAuth(w, r)