Files
gochat/backend/internal/handler/api/v1/team_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

263 lines
8.9 KiB
Go

package v1
import (
"bytes"
"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 TeamHandlerTestSuite struct {
suite.Suite
db *gorm.DB
handler *TeamHandler
account *model.Account
}
func (s *TeamHandlerTestSuite) 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.User{}, &model.AccountUser{}, &model.Team{}, &model.TeamMember{}))
s.db = db
teamRepo := repository.NewTeamRepo(db)
teamMemberRepo := repository.NewTeamMemberRepo(db)
svc := service.NewTeamService(teamRepo, teamMemberRepo, s.db)
s.handler = NewTeamHandler(svc)
s.account = &model.Account{Name: "test-team-account"}
s.Require().NoError(db.Create(s.account).Error)
}
func (s *TeamHandlerTestSuite) SetupTest() {
s.db.Exec("DELETE FROM teams")
}
func (s *TeamHandlerTestSuite) TearDownSuite() {
if s.db != nil {
sqlDB, _ := s.db.DB()
sqlDB.Close()
}
}
func TestTeamHandlerSuite(t *testing.T) {
suite.Run(t, new(TeamHandlerTestSuite))
}
func (s *TeamHandlerTestSuite) authMiddleware(c *gin.Context) {
c.Set("account_id", uint(s.account.ID))
}
func (s *TeamHandlerTestSuite) TestList_Success() {
r := gin.New()
r.GET("/api/v1/accounts/:account_id/teams", func(c *gin.Context) {
s.authMiddleware(c)
s.handler.List(c)
})
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/teams", s.account.ID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var payload []map[string]any
assert.NoError(s.T(), json.Unmarshal(w.Body.Bytes(), &payload))
}
func (s *TeamHandlerTestSuite) TestCreate_Success() {
r := gin.New()
r.POST("/api/v1/accounts/:account_id/teams", func(c *gin.Context) {
s.authMiddleware(c)
s.handler.Create(c)
})
w := httptest.NewRecorder()
body := `{"name":"test-team","description":"a test team","allow_auto_assign":false}`
req, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/%d/teams", 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 payload map[string]any
assert.NoError(s.T(), json.Unmarshal(w.Body.Bytes(), &payload))
assert.Equal(s.T(), "test-team", payload["name"])
assert.Equal(s.T(), false, payload["allow_auto_assign"])
}
func (s *TeamHandlerTestSuite) TestGet_Success() {
team := &model.Team{AccountID: s.account.ID, Name: "get-test-team"}
s.Require().NoError(s.db.Create(team).Error)
r := gin.New()
r.GET("/api/v1/accounts/:account_id/teams/:id", func(c *gin.Context) {
s.authMiddleware(c)
s.handler.Get(c)
})
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/teams/%d", s.account.ID, team.ID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var payload map[string]any
assert.NoError(s.T(), json.Unmarshal(w.Body.Bytes(), &payload))
assert.Equal(s.T(), "get-test-team", payload["name"])
assert.Contains(s.T(), payload, "is_member")
}
func (s *TeamHandlerTestSuite) TestGet_TeamIDParamSuccess() {
team := &model.Team{AccountID: s.account.ID, Name: "team-id-param"}
s.Require().NoError(s.db.Create(team).Error)
r := gin.New()
r.GET("/api/v1/accounts/:account_id/teams/:team_id", func(c *gin.Context) {
s.authMiddleware(c)
s.handler.Get(c)
})
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/teams/%d", s.account.ID, team.ID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
}
func (s *TeamHandlerTestSuite) TestUpdate_Success() {
team := &model.Team{AccountID: s.account.ID, Name: "update-test-team"}
s.Require().NoError(s.db.Create(team).Error)
r := gin.New()
r.PUT("/api/v1/accounts/:account_id/teams/:id", func(c *gin.Context) {
s.authMiddleware(c)
s.handler.Update(c)
})
w := httptest.NewRecorder()
body := `{"team":{"name":"updated-team","description":"updated description","allow_auto_assign":false}}`
req, _ := http.NewRequest("PUT", fmt.Sprintf("/api/v1/accounts/%d/teams/%d", s.account.ID, team.ID), bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var payload map[string]any
assert.NoError(s.T(), json.Unmarshal(w.Body.Bytes(), &payload))
assert.Equal(s.T(), "updated-team", payload["name"])
assert.Equal(s.T(), false, payload["allow_auto_assign"])
}
func (s *TeamHandlerTestSuite) TestUpdate_PatchRawPayloadSuccess() {
team := &model.Team{AccountID: s.account.ID, Name: "patch-test-team", AllowAutoAssignment: true}
s.Require().NoError(s.db.Create(team).Error)
r := gin.New()
r.PATCH("/api/v1/accounts/:account_id/teams/:team_id", func(c *gin.Context) {
s.authMiddleware(c)
s.handler.Update(c)
})
w := httptest.NewRecorder()
body := `{"name":"patched-team","description":"patched description","allow_auto_assign":false}`
req, _ := http.NewRequest("PATCH", fmt.Sprintf("/api/v1/accounts/%d/teams/%d", s.account.ID, team.ID), bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var payload map[string]any
assert.NoError(s.T(), json.Unmarshal(w.Body.Bytes(), &payload))
assert.NotContains(s.T(), payload, "success")
assert.NotContains(s.T(), payload, "data")
assert.Equal(s.T(), "patched-team", payload["name"])
assert.Equal(s.T(), false, payload["allow_auto_assign"])
}
func (s *TeamHandlerTestSuite) TestDelete_Success() {
team := &model.Team{AccountID: s.account.ID, Name: "delete-test-team"}
s.Require().NoError(s.db.Create(team).Error)
r := gin.New()
r.DELETE("/api/v1/accounts/:account_id/teams/:id", func(c *gin.Context) {
s.authMiddleware(c)
s.handler.Delete(c)
})
w := httptest.NewRecorder()
req, _ := http.NewRequest("DELETE", fmt.Sprintf("/api/v1/accounts/%d/teams/%d", s.account.ID, team.ID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
}
func (s *TeamHandlerTestSuite) TestTeamMembers_ChatwootPayloadAndDiffUpdate() {
team := &model.Team{AccountID: s.account.ID, Name: "members-test-team"}
s.Require().NoError(s.db.Create(team).Error)
agentOne := &model.User{AccountID: s.account.ID, Name: "Agent One", Email: "agent-one@example.test", Role: "agent"}
s.Require().NoError(s.db.Create(agentOne).Error)
s.Require().NoError(s.db.Create(&model.AccountUser{AccountID: s.account.ID, UserID: agentOne.ID, Role: "agent"}).Error)
agentTwo := &model.User{AccountID: s.account.ID, Name: "Agent Two", Email: "agent-two@example.test", Role: "agent"}
s.Require().NoError(s.db.Create(agentTwo).Error)
s.Require().NoError(s.db.Create(&model.AccountUser{AccountID: s.account.ID, UserID: agentTwo.ID, Role: "agent"}).Error)
s.Require().NoError(s.db.Create(&model.TeamMember{TeamID: team.ID, UserID: agentOne.ID, AvailabilityStatus: "online"}).Error)
r := gin.New()
r.GET("/api/v1/accounts/:account_id/teams/:team_id/team_members", func(c *gin.Context) {
s.authMiddleware(c)
s.handler.ListMembers(c)
})
r.PATCH("/api/v1/accounts/:account_id/teams/:team_id/team_members", func(c *gin.Context) {
s.authMiddleware(c)
s.handler.UpdateMembers(c)
})
listBefore := httptest.NewRecorder()
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/teams/%d/team_members", s.account.ID, team.ID), nil)
r.ServeHTTP(listBefore, req)
assert.Equal(s.T(), http.StatusOK, listBefore.Code)
var before []map[string]any
s.Require().NoError(json.Unmarshal(listBefore.Body.Bytes(), &before))
s.Require().Len(before, 1)
assert.Equal(s.T(), "Agent One", before[0]["name"])
assert.Equal(s.T(), "online", before[0]["availability_status"])
body := fmt.Sprintf(`{"user_ids":[%d]}`, agentTwo.ID)
update := httptest.NewRecorder()
req, _ = http.NewRequest("PATCH", fmt.Sprintf("/api/v1/accounts/%d/teams/%d/team_members", s.account.ID, team.ID), bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(update, req)
assert.Equal(s.T(), http.StatusOK, update.Code)
var after []map[string]any
s.Require().NoError(json.Unmarshal(update.Body.Bytes(), &after))
s.Require().Len(after, 1)
assert.Equal(s.T(), "Agent Two", after[0]["name"])
}
func (s *TeamHandlerTestSuite) TestGet_BadRequest_InvalidID() {
r := gin.New()
r.GET("/api/v1/accounts/:account_id/teams/:id", func(c *gin.Context) {
s.authMiddleware(c)
s.handler.Get(c)
})
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/teams/abc", s.account.ID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusBadRequest, w.Code)
}