package v1 import ( "bytes" "encoding/json" "fmt" "net/http" "net/http/httptest" "testing" "github.com/gin-gonic/gin" canned "github.com/gochat/gochat/internal/canned" "github.com/gochat/gochat/internal/model" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" "gorm.io/driver/sqlite" "gorm.io/gorm" "gorm.io/gorm/logger" ) type cannedDBProvider struct { db *gorm.DB } func (p *cannedDBProvider) DB() *gorm.DB { return p.db } type CannedResponseHandlerTestSuite struct { suite.Suite db *gorm.DB handler *CannedResponseHandler account *model.Account } func (s *CannedResponseHandlerTestSuite) 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{}, &canned.CannedResponse{})) s.db = db provider := &cannedDBProvider{db: db} svc := canned.NewCannedResponseService(provider) s.handler = NewCannedResponseHandler(svc) s.account = &model.Account{Name: "test-canned-account"} s.Require().NoError(db.Create(s.account).Error) } func (s *CannedResponseHandlerTestSuite) TearDownSuite() { if s.db != nil { sqlDB, _ := s.db.DB() sqlDB.Close() } } func TestCannedResponseHandlerSuite(t *testing.T) { suite.Run(t, new(CannedResponseHandlerTestSuite)) } func (s *CannedResponseHandlerTestSuite) SetupTest() { s.Require().NoError(s.db.Exec("DELETE FROM canned_responses").Error) } func (s *CannedResponseHandlerTestSuite) router() *gin.Engine { r := gin.New() r.GET("/api/v1/accounts/:account_id/canned_responses", s.handler.List) r.GET("/api/v1/accounts/:account_id/canned_responses/", s.handler.List) r.POST("/api/v1/accounts/:account_id/canned_responses", s.handler.Create) r.POST("/api/v1/accounts/:account_id/canned_responses/", s.handler.Create) r.GET("/api/v1/accounts/:account_id/canned_responses/search", s.handler.Search) r.GET("/api/v1/accounts/:account_id/canned_responses/:id", s.handler.Get) r.PATCH("/api/v1/accounts/:account_id/canned_responses/:id", s.handler.Update) r.PUT("/api/v1/accounts/:account_id/canned_responses/:id", s.handler.Update) r.DELETE("/api/v1/accounts/:account_id/canned_responses/:id", s.handler.Delete) return r } func (s *CannedResponseHandlerTestSuite) seedCannedResponse(shortCode, content string) *canned.CannedResponse { cr := &canned.CannedResponse{AccountID: s.account.ID, ShortCode: shortCode, Content: content} s.Require().NoError(s.db.Create(cr).Error) return cr } func (s *CannedResponseHandlerTestSuite) TestList_BadRequest_InvalidAccountID() { r := gin.New() r.GET("/api/v1/accounts/:account_id/canned_responses", s.handler.List) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/api/v1/accounts/abc/canned_responses", nil) r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusBadRequest, w.Code) } func (s *CannedResponseHandlerTestSuite) TestList_Success() { s.seedCannedResponse("hello", "Hello there") r := s.router() w := httptest.NewRecorder() req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/canned_responses", s.account.ID), nil) r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusOK, w.Code) var payload []map[string]interface{} s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &payload)) s.Require().Len(payload, 1) assert.Equal(s.T(), "hello", payload[0]["short_code"]) assert.NotContains(s.T(), payload[0], "deleted_at") } func (s *CannedResponseHandlerTestSuite) TestList_SearchParamReturnsRawRankedArray() { s.seedCannedResponse("hey_start", "Generic content") s.seedCannedResponse("say_hey", "Generic content") s.seedCannedResponse("body_match", "Please say hey to the customer") r := s.router() w := httptest.NewRecorder() req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/canned_responses?search=hey", s.account.ID), nil) r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusOK, w.Code) var payload []map[string]interface{} s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &payload)) s.Require().Len(payload, 3) assert.Equal(s.T(), "hey_start", payload[0]["short_code"]) assert.Equal(s.T(), "say_hey", payload[1]["short_code"]) assert.Equal(s.T(), "body_match", payload[2]["short_code"]) } func (s *CannedResponseHandlerTestSuite) TestCreate_RawFrontendBodyReturnsRawPayload() { r := s.router() w := httptest.NewRecorder() body := bytes.NewBufferString(`{"short_code":"welcome","content":"Welcome!"}`) req, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/%d/canned_responses", s.account.ID), body) req.Header.Set("Content-Type", "application/json") r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusOK, w.Code) var payload map[string]interface{} s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &payload)) assert.Equal(s.T(), "welcome", payload["short_code"]) assert.Equal(s.T(), "Welcome!", payload["content"]) assert.Equal(s.T(), float64(s.account.ID), payload["account_id"]) assert.NotContains(s.T(), payload, "success") assert.NotContains(s.T(), payload, "data") } func (s *CannedResponseHandlerTestSuite) TestUpdate_PatchRawBodyIsAccountScoped() { cr := s.seedCannedResponse("old", "Old content") r := s.router() w := httptest.NewRecorder() body := bytes.NewBufferString(`{"short_code":"new","content":"New content"}`) req, _ := http.NewRequest("PATCH", fmt.Sprintf("/api/v1/accounts/%d/canned_responses/%d", s.account.ID, cr.ID), body) req.Header.Set("Content-Type", "application/json") r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusOK, w.Code) var payload map[string]interface{} s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &payload)) assert.Equal(s.T(), "new", payload["short_code"]) assert.Equal(s.T(), "New content", payload["content"]) } func (s *CannedResponseHandlerTestSuite) TestUpdate_CrossAccountReturnsNotFound() { cr := s.seedCannedResponse("private", "Private content") otherAccount := &model.Account{Name: "other-canned-account"} s.Require().NoError(s.db.Create(otherAccount).Error) r := s.router() w := httptest.NewRecorder() body := bytes.NewBufferString(`{"content":"Nope"}`) req, _ := http.NewRequest("PATCH", fmt.Sprintf("/api/v1/accounts/%d/canned_responses/%d", otherAccount.ID, cr.ID), body) req.Header.Set("Content-Type", "application/json") r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusNotFound, w.Code) } func (s *CannedResponseHandlerTestSuite) TestDelete_ReturnsOKEmptyAndScopesAccount() { cr := s.seedCannedResponse("delete_me", "Delete me") r := s.router() w := httptest.NewRecorder() req, _ := http.NewRequest("DELETE", fmt.Sprintf("/api/v1/accounts/%d/canned_responses/%d", s.account.ID, cr.ID), nil) r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusOK, w.Code) assert.Empty(s.T(), w.Body.String()) } func (s *CannedResponseHandlerTestSuite) TestDelete_CrossAccountReturnsNotFound() { cr := s.seedCannedResponse("private_delete", "Private content") otherAccount := &model.Account{Name: "other-delete-account"} s.Require().NoError(s.db.Create(otherAccount).Error) r := s.router() w := httptest.NewRecorder() req, _ := http.NewRequest("DELETE", fmt.Sprintf("/api/v1/accounts/%d/canned_responses/%d", otherAccount.ID, cr.ID), nil) r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusNotFound, w.Code) } func (s *CannedResponseHandlerTestSuite) TestCreate_BadRequest_EmptyBody() { r := gin.New() r.POST("/api/v1/accounts/:account_id/canned_responses", s.handler.Create) w := httptest.NewRecorder() req, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/%d/canned_responses", s.account.ID), nil) req.Header.Set("Content-Type", "application/json") r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusBadRequest, w.Code) } func (s *CannedResponseHandlerTestSuite) TestGet_BadRequest_InvalidID() { r := gin.New() r.GET("/api/v1/accounts/:account_id/canned_responses/:id", s.handler.Get) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/canned_responses/abc", s.account.ID), nil) r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusBadRequest, w.Code) } func (s *CannedResponseHandlerTestSuite) TestUpdate_BadRequest_InvalidID() { r := gin.New() r.PUT("/api/v1/accounts/:account_id/canned_responses/:id", s.handler.Update) w := httptest.NewRecorder() req, _ := http.NewRequest("PUT", fmt.Sprintf("/api/v1/accounts/%d/canned_responses/abc", s.account.ID), bytes.NewBufferString(`{"content":"updated"}`)) req.Header.Set("Content-Type", "application/json") r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusBadRequest, w.Code) } func (s *CannedResponseHandlerTestSuite) TestDelete_BadRequest_InvalidID() { r := gin.New() r.DELETE("/api/v1/accounts/:account_id/canned_responses/:id", s.handler.Delete) w := httptest.NewRecorder() req, _ := http.NewRequest("DELETE", fmt.Sprintf("/api/v1/accounts/%d/canned_responses/abc", s.account.ID), nil) r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusBadRequest, w.Code) } func (s *CannedResponseHandlerTestSuite) TestSearch_BadRequest_InvalidAccountID() { r := gin.New() r.GET("/api/v1/accounts/:account_id/canned_responses/search", s.handler.Search) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/api/v1/accounts/abc/canned_responses/search?q=test", nil) r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusBadRequest, w.Code) }