From f8836fc96464ad3c54162d5e8c068f3f7192ce67 Mon Sep 17 00:00:00 2001 From: Stavros Date: Wed, 3 Sep 2025 13:36:11 +0300 Subject: [PATCH] tests: test user context handler with no context --- .../controller/context_controller_test.go | 40 +++++++++++++++---- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/internal/controller/context_controller_test.go b/internal/controller/context_controller_test.go index 61d2e8b..af64b21 100644 --- a/internal/controller/context_controller_test.go +++ b/internal/controller/context_controller_test.go @@ -34,16 +34,17 @@ var userContext = config.UserContext{ TotpEnabled: false, } -func setupContextController() (*gin.Engine, *httptest.ResponseRecorder) { +func setupContextController(middlewares *[]gin.HandlerFunc) (*gin.Engine, *httptest.ResponseRecorder) { // Setup gin.SetMode(gin.TestMode) router := gin.Default() recorder := httptest.NewRecorder() - router.Use(func(c *gin.Context) { - c.Set("context", &userContext) - c.Next() - }) + if middlewares != nil { + for _, m := range *middlewares { + router.Use(m) + } + } group := router.Group("/api") @@ -67,7 +68,7 @@ func TestAppContextHandler(t *testing.T) { OAuthAutoRedirect: controllerCfg.OAuthAutoRedirect, } - router, recorder := setupContextController() + router, recorder := setupContextController(nil) req := httptest.NewRequest("GET", "/api/context/app", nil) router.ServeHTTP(recorder, req) @@ -94,7 +95,14 @@ func TestUserContextHandler(t *testing.T) { TotpPending: userContext.TotpPending, } - router, recorder := setupContextController() + // Test with context + router, recorder := setupContextController(&[]gin.HandlerFunc{ + func(c *gin.Context) { + c.Set("context", &userContext) + c.Next() + }, + }) + req := httptest.NewRequest("GET", "/api/context/user", nil) router.ServeHTTP(recorder, req) @@ -106,4 +114,22 @@ func TestUserContextHandler(t *testing.T) { assert.NilError(t, err) assert.DeepEqual(t, expectedRes, ctrlRes) + + // Test no context + expectedRes = controller.UserContextResponse{ + Status: 401, + Message: "Unauthorized", + IsLoggedIn: false, + } + + router, recorder = setupContextController(nil) + req = httptest.NewRequest("GET", "/api/context/user", nil) + router.ServeHTTP(recorder, req) + + assert.Equal(t, 200, recorder.Code) + + err = json.Unmarshal(recorder.Body.Bytes(), &ctrlRes) + + assert.NilError(t, err) + assert.DeepEqual(t, expectedRes, ctrlRes) }