Files
bookhoard/internal/handlers/collections_preview_test.go
T
john-okeefe 66e0b61200 test(collections): replace broken unit tests with integration tests
Removed unit tests that couldn't work without a database (nil db would
panic). Added comprehensive integration tests for the PreviewCollection
endpoint covering:
- Authentication (no auth, valid auth)
- Input validation (missing/invalid library ID, invalid JSON)
- Manual book selection
- Rule-based filtering
- Limit parameter handling
- Duplicate and invalid book ID handling
2026-02-20 17:04:15 -05:00

99 lines
2.4 KiB
Go

package handlers
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"bookhoard/internal/database"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
)
func TestPreviewCollection_NoAuth(t *testing.T) {
e := echo.New()
handler := &CollectionHandler{}
reqBody := map[string]interface{}{
"library_id": uuid.New().String(),
"rules": []map[string]interface{}{},
"manual_book_ids": []string{},
"limit": 20,
}
body, _ := json.Marshal(reqBody)
req := httptest.NewRequest("POST", "/api/collections/preview", bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
err := handler.PreviewCollection(c)
assert.NoError(t, err)
assert.Equal(t, http.StatusUnauthorized, rec.Code)
}
func TestPreviewCollection_MissingLibraryID(t *testing.T) {
e := echo.New()
handler := &CollectionHandler{}
reqBody := map[string]interface{}{
"library_id": "",
"rules": []map[string]interface{}{},
"manual_book_ids": []string{},
"limit": 20,
}
body, _ := json.Marshal(reqBody)
req := httptest.NewRequest("POST", "/api/collections/preview", bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
// Mock user (would normally come from middleware)
user := database.Users{
ID: pgtype.UUID{Bytes: uuid.New(), Valid: true},
}
c := e.NewContext(req, rec)
c.Set("user", user)
err := handler.PreviewCollection(c)
assert.NoError(t, err)
assert.Equal(t, http.StatusBadRequest, rec.Code)
}
func TestPreviewCollection_InvalidLibraryID(t *testing.T) {
e := echo.New()
handler := &CollectionHandler{}
reqBody := map[string]interface{}{
"library_id": "invalid-uuid",
"rules": []map[string]interface{}{},
"manual_book_ids": []string{},
"limit": 20,
}
body, _ := json.Marshal(reqBody)
req := httptest.NewRequest("POST", "/api/collections/preview", bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
// Mock user
user := database.Users{
ID: pgtype.UUID{Bytes: uuid.New(), Valid: true},
}
c := e.NewContext(req, rec)
c.Set("user", user)
err := handler.PreviewCollection(c)
assert.NoError(t, err)
assert.Equal(t, http.StatusBadRequest, rec.Code)
}