package handler_test import ( "bytes" "context" "encoding/json" "net/http" "net/http/httptest" "github.com/gin-gonic/gin" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "golang.org/x/crypto/bcrypt" "gorm.io/gorm" "bugulma/backend/internal/domain" "bugulma/backend/internal/handler" "bugulma/backend/internal/repository" "bugulma/backend/internal/service" "bugulma/backend/internal/testutils" ) var _ = Describe("AuthHandler", func() { var ( authHandler *handler.AuthHandler userRepo domain.UserRepository authService *service.AuthService router *gin.Engine db *gorm.DB ) BeforeEach(func() { gin.SetMode(gin.TestMode) // Setup PostgreSQL test database using testcontainers db = testutils.SetupTestDBWithTestcontainersForGinkgo(GinkgoT()) userRepo = repository.NewUserRepository(db) authService = service.NewAuthService(userRepo, "secret-key") authHandler = handler.NewAuthHandler(authService) router = gin.New() router.POST("/login", authHandler.Login) // Create a test user hashedPassword, _ := bcrypt.GenerateFromPassword([]byte("password123"), bcrypt.DefaultCost) user := &domain.User{ ID: "user-1", Email: "test@example.com", Password: string(hashedPassword), Name: "Test User", Role: domain.UserRoleUser, } err := userRepo.Create(context.Background(), user) Expect(err).NotTo(HaveOccurred()) }) AfterEach(func() { // pgtestdb automatically cleans up the database after each test }) Describe("Login", func() { It("should return token for valid credentials", func() { reqBody := handler.LoginRequest{ Email: "test@example.com", Password: "password123", } body, _ := json.Marshal(reqBody) req, _ := http.NewRequest("POST", "/login", bytes.NewBuffer(body)) req.Header.Set("Content-Type", "application/json") w := httptest.NewRecorder() router.ServeHTTP(w, req) Expect(w.Code).To(Equal(http.StatusOK)) var resp handler.LoginResponse err := json.Unmarshal(w.Body.Bytes(), &resp) Expect(err).NotTo(HaveOccurred()) Expect(resp.Token).NotTo(BeEmpty()) Expect(resp.User.Email).To(Equal("test@example.com")) }) It("should return 401 for invalid credentials", func() { reqBody := handler.LoginRequest{ Email: "test@example.com", Password: "wrongpassword", } body, _ := json.Marshal(reqBody) req, _ := http.NewRequest("POST", "/login", bytes.NewBuffer(body)) req.Header.Set("Content-Type", "application/json") w := httptest.NewRecorder() router.ServeHTTP(w, req) Expect(w.Code).To(Equal(http.StatusUnauthorized)) }) It("should return 400 for invalid request body", func() { req, _ := http.NewRequest("POST", "/login", bytes.NewBufferString("invalid json")) req.Header.Set("Content-Type", "application/json") w := httptest.NewRecorder() router.ServeHTTP(w, req) Expect(w.Code).To(Equal(http.StatusBadRequest)) }) }) })