package handlers import ( "encoding/json" "fmt" "net/http" "testing" "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "gorm.io/gorm" "github.com/treytartt/casera-api/internal/models" "github.com/treytartt/casera-api/internal/repositories" "github.com/treytartt/casera-api/internal/services" "github.com/treytartt/casera-api/internal/testutil" ) func setupNotificationHandler(t *testing.T) (*NotificationHandler, *echo.Echo, *gorm.DB) { db := testutil.SetupTestDB(t) notifRepo := repositories.NewNotificationRepository(db) notifService := services.NewNotificationService(notifRepo, nil) handler := NewNotificationHandler(notifService) e := testutil.SetupTestRouter() return handler, e, db } func createTestNotifications(t *testing.T, db *gorm.DB, userID uint, count int) { for i := 0; i < count; i++ { notif := &models.Notification{ UserID: userID, NotificationType: models.NotificationTaskDueSoon, Title: fmt.Sprintf("Test Notification %d", i+1), Body: fmt.Sprintf("Body %d", i+1), } err := db.Create(notif).Error require.NoError(t, err) } } func TestNotificationHandler_ListNotifications_LimitCappedAt200(t *testing.T) { handler, e, db := setupNotificationHandler(t) user := testutil.CreateTestUser(t, db, "owner", "owner@test.com", "password") // Create 210 notifications to exceed the cap createTestNotifications(t, db, user.ID, 210) authGroup := e.Group("/api/notifications") authGroup.Use(testutil.MockAuthMiddleware(user)) authGroup.GET("/", handler.ListNotifications) t.Run("limit is capped at 200 when user requests more", func(t *testing.T) { w := testutil.MakeRequest(e, "GET", "/api/notifications/?limit=999", nil, "test-token") testutil.AssertStatusCode(t, w, http.StatusOK) var response map[string]interface{} err := json.Unmarshal(w.Body.Bytes(), &response) require.NoError(t, err) count := int(response["count"].(float64)) assert.Equal(t, 200, count, "response should contain at most 200 notifications when limit exceeds cap") }) t.Run("limit below cap is respected", func(t *testing.T) { w := testutil.MakeRequest(e, "GET", "/api/notifications/?limit=10", nil, "test-token") testutil.AssertStatusCode(t, w, http.StatusOK) var response map[string]interface{} err := json.Unmarshal(w.Body.Bytes(), &response) require.NoError(t, err) count := int(response["count"].(float64)) assert.Equal(t, 10, count, "response should respect limit when below cap") }) t.Run("default limit is used when no limit param", func(t *testing.T) { w := testutil.MakeRequest(e, "GET", "/api/notifications/", nil, "test-token") testutil.AssertStatusCode(t, w, http.StatusOK) var response map[string]interface{} err := json.Unmarshal(w.Body.Bytes(), &response) require.NoError(t, err) count := int(response["count"].(float64)) assert.Equal(t, 50, count, "response should use default limit of 50") }) }