package v1 import ( "bytes" "fmt" "net/http" "net/http/httptest" "testing" "github.com/gin-gonic/gin" "github.com/gochat/gochat/internal/model" "github.com/gochat/gochat/internal/repository" "github.com/gochat/gochat/internal/service" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" "gorm.io/driver/sqlite" "gorm.io/gorm" "gorm.io/gorm/logger" ) type NotificationSettingHandlerTestSuite struct { suite.Suite db *gorm.DB handler *NotificationSettingHandler account *model.Account } func (s *NotificationSettingHandlerTestSuite) SetupSuite() { gin.SetMode(gin.TestMode) db, err := gorm.Open(sqlite.Open("file::memory:"), &gorm.Config{ Logger: logger.Default.LogMode(logger.Silent), }) s.Require().NoError(err) s.Require().NoError(db.AutoMigrate(&model.Account{}, &model.NotificationSetting{})) s.db = db repo := repository.NewNotificationSettingRepo(db) svc := service.NewNotificationSettingService(repo) s.handler = NewNotificationSettingHandler(svc) s.account = &model.Account{Name: "test-notif-setting-account"} s.Require().NoError(db.Create(s.account).Error) } func (s *NotificationSettingHandlerTestSuite) TearDownSuite() { if s.db != nil { sqlDB, _ := s.db.DB() sqlDB.Close() } } func TestNotificationSettingHandlerSuite(t *testing.T) { suite.Run(t, new(NotificationSettingHandlerTestSuite)) } func (s *NotificationSettingHandlerTestSuite) TestShow_BadRequest_InvalidAccountID() { r := gin.New() r.GET("/api/v1/accounts/:account_id/notification_settings", func(c *gin.Context) { c.Set("user_id", float64(1)) s.handler.Show(c) }) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/api/v1/accounts/abc/notification_settings", nil) r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusBadRequest, w.Code) } func (s *NotificationSettingHandlerTestSuite) TestShow_Success() { r := gin.New() r.GET("/api/v1/accounts/:account_id/notification_settings", func(c *gin.Context) { c.Set("user_id", float64(1)) s.handler.Show(c) }) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/notification_settings", s.account.ID), nil) r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusOK, w.Code) } func (s *NotificationSettingHandlerTestSuite) TestUpdate_BadRequest_InvalidAccountID() { r := gin.New() r.PUT("/api/v1/accounts/:account_id/notification_settings", func(c *gin.Context) { c.Set("user_id", float64(1)) s.handler.Update(c) }) w := httptest.NewRecorder() req, _ := http.NewRequest("PUT", "/api/v1/accounts/abc/notification_settings", bytes.NewBufferString(`{"enable_email":true}`)) req.Header.Set("Content-Type", "application/json") r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusBadRequest, w.Code) }