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) { func TestRequireAuth(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
userID uint setUserKey bool
userIDValue uint
expectedID uint expectedID uint
expectedOK bool expectedOK bool
expectedStatus int expectedStatus int
@@ -577,25 +578,32 @@ func TestRequireAuth(t *testing.T) {
}{ }{
{ {
name: "authenticated user", name: "authenticated user",
userID: 123, setUserKey: true,
userIDValue: 123,
expectedID: 123, expectedID: 123,
expectedOK: true, expectedOK: true,
expectedStatus: 0,
}, },
{ {
name: "unauthenticated user (no userID)", name: "unauthenticated user (missing context)",
userID: 0, setUserKey: false,
expectedID: 0, expectedID: 0,
expectedOK: false, expectedOK: false,
expectedStatus: http.StatusUnauthorized, expectedStatus: http.StatusUnauthorized,
expectedError: "Authentication required", expectedError: "Authentication required",
}, },
{
name: "authenticated user with id zero",
setUserKey: true,
userIDValue: 0,
expectedID: 0,
expectedOK: true,
},
{ {
name: "authenticated user with large ID", name: "authenticated user with large ID",
userID: 4294967295, setUserKey: true,
userIDValue: 4294967295,
expectedID: 4294967295, expectedID: 4294967295,
expectedOK: true, expectedOK: true,
expectedStatus: 0,
}, },
} }
@@ -604,7 +612,10 @@ func TestRequireAuth(t *testing.T) {
w := httptest.NewRecorder() w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/", nil) 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) r = r.WithContext(ctx)
userID, ok := RequireAuth(w, r) userID, ok := RequireAuth(w, r)