Files
gochat/backend/internal/handler/api/v1/webhook_subscription_handler_test.go
T
rogee aeddedf2a3 Reorganize repo: backend/, deploy/, docs/ layout + AGENTS.md
Restructure the monorepo into clear top-level directories:
- backend/: Go module root (cmd, internal, pkg, configs, migrations,
  docs/swagger, scripts, tests, go.mod, Makefile, .air.toml)
- deploy/: Docker (Dockerfile, docker-compose*), quickstart, fluentd
- docs/: project documentation + reports/ (moved from repo root)
- AGENTS.md: new AI coding-agent guide at repo root

Update all references to the new layout:
- Dockerfile: COPY backend/go.mod, COPY backend/ (context = repo root)
- docker-compose files: context ../.., dockerfile deploy/docker/Dockerfile,
  env_file ../../.env, volume mounts ../../backend:/app
- deploy/quickstart/compose.yaml: dockerfile deploy/docker/Dockerfile
- CI: working-directory: backend for go commands, file deploy/docker/Dockerfile,
  coverage path backend/coverage.out, health_check backend/scripts/
- backend/Makefile: docker target uses -f ../deploy/docker/Dockerfile ../
- README: architecture tree, quickstart, config paths updated

Move root stray scripts (rename_models.*, run_m11_tests.sh, verify_build.sh,
gorm_bool_main.go) to backend/scripts/legacy/. All moves via git mv to
preserve history. Build, vet, SQLite tests, and docker compose config verified.
2026-07-07 14:44:12 +08:00

202 lines
7.2 KiB
Go

package v1
import (
"bytes"
"context"
"encoding/json"
"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 WebhookSubscriptionHandlerTestSuite struct {
suite.Suite
db *gorm.DB
handler *WebhookSubscriptionHandler
account *model.Account
}
func (s *WebhookSubscriptionHandlerTestSuite) 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.Inbox{}, &model.WebhookSubscription{}))
s.db = db
repo := repository.NewWebhookSubscriptionRepo(db)
svc := service.NewWebhookSubscriptionService(repo)
s.handler = NewWebhookSubscriptionHandler(svc)
s.account = &model.Account{Name: "test-webhook-account"}
s.Require().NoError(db.Create(s.account).Error)
}
func (s *WebhookSubscriptionHandlerTestSuite) TearDownSuite() {
if s.db != nil {
sqlDB, _ := s.db.DB()
sqlDB.Close()
}
}
func TestWebhookSubscriptionHandlerSuite(t *testing.T) {
suite.Run(t, new(WebhookSubscriptionHandlerTestSuite))
}
func (s *WebhookSubscriptionHandlerTestSuite) TestList_Success() {
r := gin.New()
r.GET("/api/v1/accounts/:account_id/webhooks", s.handler.List)
_, err := s.handler.webhookSubscriptionService.CreateWebhook(context.Background(), s.account.ID, service.WebhookSubscriptionMutation{
Name: "List hook",
URL: "https://example.com/list-hook",
Subscriptions: []string{"message_created"},
})
s.Require().NoError(err)
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/webhooks", s.account.ID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var body map[string]any
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &body))
payload := body["payload"].(map[string]any)
webhooks := payload["webhooks"].([]any)
s.NotEmpty(webhooks)
}
func (s *WebhookSubscriptionHandlerTestSuite) TestCreate_Success_ChatwootPayload() {
r := gin.New()
r.POST("/api/v1/accounts/:account_id/webhooks", s.handler.Create)
body := `{"webhook":{"name":"Created hook","url":"https://example.com/created-hook","subscriptions":["conversation_created","message_created"]}}`
w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/%d/webhooks", s.account.ID), bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var parsed map[string]any
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &parsed))
webhook := parsed["payload"].(map[string]any)["webhook"].(map[string]any)
s.Equal("Created hook", webhook["name"])
s.Equal("https://example.com/created-hook", webhook["url"])
s.NotEmpty(webhook["secret"])
s.Equal([]any{"conversation_created", "message_created"}, webhook["subscriptions"])
}
func (s *WebhookSubscriptionHandlerTestSuite) TestUpdate_Success_ChatwootPayload() {
created, err := s.handler.webhookSubscriptionService.CreateWebhook(context.Background(), s.account.ID, service.WebhookSubscriptionMutation{
Name: "Before",
URL: "https://example.com/update-before",
Subscriptions: []string{"message_created"},
})
s.Require().NoError(err)
r := gin.New()
r.PATCH("/api/v1/accounts/:account_id/webhooks/:webhook_id", s.handler.Update)
body := `{"webhook":{"name":"After","url":"https://example.com/update-after","subscriptions":["contact_created"]}}`
w := httptest.NewRecorder()
req, _ := http.NewRequest("PATCH", fmt.Sprintf("/api/v1/accounts/%d/webhooks/%d", s.account.ID, created.ID), bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var parsed map[string]any
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &parsed))
webhook := parsed["payload"].(map[string]any)["webhook"].(map[string]any)
s.Equal("After", webhook["name"])
s.Equal("https://example.com/update-after", webhook["url"])
s.Equal([]any{"contact_created"}, webhook["subscriptions"])
}
func (s *WebhookSubscriptionHandlerTestSuite) TestDelete_Success_ReturnsEmptyOK() {
created, err := s.handler.webhookSubscriptionService.CreateWebhook(context.Background(), s.account.ID, service.WebhookSubscriptionMutation{
Name: "Delete",
URL: "https://example.com/delete-hook",
Subscriptions: []string{"message_created"},
})
s.Require().NoError(err)
r := gin.New()
r.DELETE("/api/v1/accounts/:account_id/webhooks/:webhook_id", s.handler.Delete)
w := httptest.NewRecorder()
req, _ := http.NewRequest("DELETE", fmt.Sprintf("/api/v1/accounts/%d/webhooks/%d", s.account.ID, created.ID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
s.Empty(w.Body.String())
}
func (s *WebhookSubscriptionHandlerTestSuite) TestCreate_BadRequest_EmptyBody() {
r := gin.New()
r.POST("/api/v1/accounts/:account_id/webhooks", s.handler.Create)
w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/%d/webhooks", 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 *WebhookSubscriptionHandlerTestSuite) TestGet_BadRequest_InvalidID() {
r := gin.New()
r.GET("/api/v1/accounts/:account_id/webhooks/:webhook_id", s.handler.Get)
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/webhooks/abc", s.account.ID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusBadRequest, w.Code)
}
func (s *WebhookSubscriptionHandlerTestSuite) TestUpdate_BadRequest_InvalidID() {
r := gin.New()
r.PATCH("/api/v1/accounts/:account_id/webhooks/:webhook_id", s.handler.Update)
w := httptest.NewRecorder()
req, _ := http.NewRequest("PATCH", fmt.Sprintf("/api/v1/accounts/%d/webhooks/abc", s.account.ID), bytes.NewBufferString(`{"webhook":{"url":"https://example.com","subscriptions":["message_created"]}}`))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusBadRequest, w.Code)
}
func (s *WebhookSubscriptionHandlerTestSuite) TestDelete_BadRequest_InvalidID() {
r := gin.New()
r.DELETE("/api/v1/accounts/:account_id/webhooks/:webhook_id", s.handler.Delete)
w := httptest.NewRecorder()
req, _ := http.NewRequest("DELETE", fmt.Sprintf("/api/v1/accounts/%d/webhooks/abc", s.account.ID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusBadRequest, w.Code)
}
func (s *WebhookSubscriptionHandlerTestSuite) TestListDeliveries_BadRequest_InvalidID() {
r := gin.New()
r.GET("/api/v1/accounts/:account_id/webhooks/:webhook_id/subscriptions/:webhook_id/deliveries", s.handler.ListDeliveries)
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/webhooks/1/subscriptions/abc/deliveries", s.account.ID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusBadRequest, w.Code)
}