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

396 lines
15 KiB
Go

package v1
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/datatypes"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"github.com/gochat/gochat/internal/model"
"github.com/gochat/gochat/internal/repository"
"github.com/gochat/gochat/internal/service"
)
type linearHandlerRoundTripFunc func(*http.Request) (*http.Response, error)
func (f linearHandlerRoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req)
}
func linearHandlerJSONResponse(body string) *http.Response {
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}
}
func setupLinearIntegrationRouter() *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.RedirectTrailingSlash = false
handler := NewLinearIntegrationHandler(nil)
integrations := r.Group("/api/v1/accounts/:account_id/integrations")
RegisterLinearIntegrationRoutes(integrations, handler)
return r
}
func setupLinearIntegrationRouterWithService(svc *service.LinearIntegrationService) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.RedirectTrailingSlash = false
handler := NewLinearIntegrationHandler(svc)
integrations := r.Group("/api/v1/accounts/:account_id/integrations")
RegisterLinearIntegrationRoutes(integrations, handler)
return r
}
func setupLinearIntegrationHandlerFixture(t *testing.T) (*gorm.DB, uint) {
t.Helper()
db, err := gorm.Open(sqlite.Open("file:linear_handler_success?mode=memory&cache=shared"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
require.NoError(t, err)
t.Cleanup(func() { sqlDB, _ := db.DB(); _ = sqlDB.Close() })
require.NoError(t, db.AutoMigrate(&model.Account{}, &model.User{}, &model.Inbox{}, &model.Contact{}, &model.Conversation{}, &model.Message{}, &model.IntegrationHook{}))
account := &model.Account{Name: "Linear Handler Account", Locale: "en", Status: "active"}
require.NoError(t, db.Create(account).Error)
user := &model.User{AccountID: account.ID, Name: "Linear Agent", Email: "linear-agent@example.test", Role: "agent"}
require.NoError(t, db.Create(user).Error)
inbox := &model.Inbox{AccountID: account.ID, Name: "Website", ChannelType: "web_widget", Enabled: true}
require.NoError(t, db.Create(inbox).Error)
contact := &model.Contact{AccountID: account.ID, Name: "Visitor"}
require.NoError(t, db.Create(contact).Error)
displayID := uint(1)
conversation := &model.Conversation{AccountID: account.ID, InboxID: inbox.ID, ContactID: contact.ID, DisplayID: &displayID, Status: "open", ChannelType: "web_widget", Channel: "web_widget"}
require.NoError(t, db.Create(conversation).Error)
settings := datatypes.JSON([]byte(`{"access_token":"lin-handler-token","refresh_token":"refresh-token"}`))
require.NoError(t, db.Create(&model.IntegrationHook{AccountID: account.ID, AppID: "linear", HookType: model.HookTypeLinear, AccessToken: "lin-handler-token", Settings: settings, Status: model.HookStatusActive}).Error)
return db, account.ID
}
func setupLinearIntegrationSuccessRouter(t *testing.T) *gin.Engine {
t.Helper()
db, _ := setupLinearIntegrationHandlerFixture(t)
svc := service.NewLinearIntegrationService(repository.NewIntegrationHookRepo(db), service.WithLinearHTTPClient("https://linear.test", &http.Client{Transport: linearHandlerRoundTripFunc(func(req *http.Request) (*http.Response, error) {
require.Equal(t, "/graphql", req.URL.Path)
require.Equal(t, "Bearer lin-handler-token", req.Header.Get("Authorization"))
raw, err := io.ReadAll(req.Body)
require.NoError(t, err)
var payload map[string]string
require.NoError(t, json.Unmarshal(raw, &payload))
query := payload["query"]
switch {
case strings.Contains(query, "teams"):
return linearHandlerJSONResponse(`{"data":{"teams":{"nodes":[{"id":"team-1","name":"Support"}]}}}`), nil
case strings.Contains(query, "workflowStates") && strings.Contains(query, "issueLabels"):
return linearHandlerJSONResponse(`{"data":{"users":{"nodes":[{"id":"user-1","name":"Agent"}]},"projects":{"nodes":[{"id":"project-1","name":"Inbox"}]},"workflowStates":{"nodes":[{"id":"state-1","name":"Todo"}]},"issueLabels":{"nodes":[{"id":"label-1","name":"Bug"}]}}}`), nil
case strings.Contains(query, "issueCreate"):
return linearHandlerJSONResponse(`{"data":{"issueCreate":{"success":true,"issue":{"id":"issue-1","title":"Bug","identifier":"ENG-1"}}}}`), nil
case strings.Contains(query, "attachmentLinkURL"):
return linearHandlerJSONResponse(`{"data":{"attachmentLinkURL":{"success":true,"attachment":{"id":"link-1"}}}}`), nil
case strings.Contains(query, "attachmentDelete"):
return linearHandlerJSONResponse(`{"data":{"attachmentDelete":{"success":true}}}`), nil
case strings.Contains(query, "searchIssues"):
return linearHandlerJSONResponse(`{"data":{"searchIssues":{"nodes":[{"id":"issue-1","identifier":"ENG-1","title":"Bug"}]}}}`), nil
case strings.Contains(query, "attachmentsForURL"):
return linearHandlerJSONResponse(`{"data":{"attachmentsForURL":{"nodes":[{"id":"link-1","title":"Bug","issue":{"id":"issue-1","identifier":"ENG-1","title":"Bug"}}]}}}`), nil
default:
t.Fatalf("unexpected Linear GraphQL query: %s", query)
}
return nil, nil
})}))
return setupLinearIntegrationRouterWithService(svc)
}
// ========================================
// LinearIntegration — param validation tests
// ========================================
func TestLinearIntegration_Delete_BadAccountID(t *testing.T) {
r := setupLinearIntegrationRouter()
w := httptest.NewRecorder()
req, _ := http.NewRequest("DELETE", "/api/v1/accounts/abc/integrations/linear/", nil)
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code)
var resp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &resp)
errBody := resp["error"].(map[string]interface{})
assert.Contains(t, errBody["message"], "invalid account_id")
}
func TestLinearIntegration_GetTeams_BadAccountID(t *testing.T) {
r := setupLinearIntegrationRouter()
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/api/v1/accounts/abc/integrations/linear/teams", nil)
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code)
var resp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &resp)
errBody := resp["error"].(map[string]interface{})
assert.Contains(t, errBody["message"], "invalid account_id")
}
func TestLinearIntegration_GetTeamEntities_BadAccountID(t *testing.T) {
r := setupLinearIntegrationRouter()
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/api/v1/accounts/abc/integrations/linear/team_entities", nil)
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code)
var resp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &resp)
errBody := resp["error"].(map[string]interface{})
assert.Contains(t, errBody["message"], "invalid account_id")
}
func TestLinearIntegration_CreateIssue_BadAccountID(t *testing.T) {
r := setupLinearIntegrationRouter()
w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", "/api/v1/accounts/abc/integrations/linear/create_issue", nil)
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code)
var resp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &resp)
errBody := resp["error"].(map[string]interface{})
assert.Contains(t, errBody["message"], "invalid account_id")
}
func TestLinearIntegration_CreateIssue_InvalidJSON(t *testing.T) {
r := setupLinearIntegrationRouter()
w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", "/api/v1/accounts/1/integrations/linear/create_issue", bytes.NewReader([]byte("invalid json")))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
// account_id passes, ShouldBindJSON fails
assert.Equal(t, http.StatusBadRequest, w.Code)
var resp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &resp)
assert.False(t, resp["success"].(bool))
}
func TestLinearIntegration_LinkIssue_BadAccountID(t *testing.T) {
r := setupLinearIntegrationRouter()
w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", "/api/v1/accounts/abc/integrations/linear/link_issue", nil)
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code)
var resp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &resp)
errBody := resp["error"].(map[string]interface{})
assert.Contains(t, errBody["message"], "invalid account_id")
}
func TestLinearIntegration_LinkIssue_InvalidJSON(t *testing.T) {
r := setupLinearIntegrationRouter()
w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", "/api/v1/accounts/1/integrations/linear/link_issue", bytes.NewReader([]byte("invalid json")))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
// account_id passes, ShouldBindJSON fails
assert.Equal(t, http.StatusBadRequest, w.Code)
var resp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &resp)
assert.False(t, resp["success"].(bool))
}
func TestLinearIntegration_UnlinkIssue_BadAccountID(t *testing.T) {
r := setupLinearIntegrationRouter()
w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", "/api/v1/accounts/abc/integrations/linear/unlink_issue", nil)
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code)
var resp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &resp)
errBody := resp["error"].(map[string]interface{})
assert.Contains(t, errBody["message"], "invalid account_id")
}
func TestLinearIntegration_UnlinkIssue_InvalidJSON(t *testing.T) {
r := setupLinearIntegrationRouter()
w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", "/api/v1/accounts/1/integrations/linear/unlink_issue", bytes.NewReader([]byte("invalid json")))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
// account_id passes, ShouldBindJSON fails
assert.Equal(t, http.StatusBadRequest, w.Code)
var resp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &resp)
assert.False(t, resp["success"].(bool))
}
func TestLinearIntegration_SearchIssue_BadAccountID(t *testing.T) {
r := setupLinearIntegrationRouter()
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/api/v1/accounts/abc/integrations/linear/search_issue", nil)
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code)
var resp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &resp)
errBody := resp["error"].(map[string]interface{})
assert.Contains(t, errBody["message"], "invalid account_id")
}
func TestLinearIntegration_SearchIssue_BlankQuery(t *testing.T) {
r := setupLinearIntegrationRouter()
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/api/v1/accounts/1/integrations/linear/search_issue", nil)
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusUnprocessableEntity, w.Code)
var resp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &resp)
assert.Equal(t, "Specify search string with parameter q", resp["error"])
}
func TestLinearIntegration_GetLinkedIssues_BadAccountID(t *testing.T) {
r := setupLinearIntegrationRouter()
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/api/v1/accounts/abc/integrations/linear/linked_issues", nil)
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code)
var resp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &resp)
errBody := resp["error"].(map[string]interface{})
assert.Contains(t, errBody["message"], "invalid account_id")
}
func TestLinearIntegration_ChatwootFrontendRuntimeRoutes(t *testing.T) {
r := setupLinearIntegrationSuccessRouter(t)
t.Run("teams", func(t *testing.T) {
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/api/v1/accounts/1/integrations/linear/teams", nil)
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
var resp []map[string]interface{}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp))
require.Len(t, resp, 1)
assert.Equal(t, "team-1", resp[0]["id"])
assert.Equal(t, "Support", resp[0]["name"])
})
t.Run("team_entities", func(t *testing.T) {
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/api/v1/accounts/1/integrations/linear/team_entities?team_id=team-1", nil)
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
var resp map[string][]map[string]interface{}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp))
assert.Equal(t, "user-1", resp["users"][0]["id"])
assert.Equal(t, "project-1", resp["projects"][0]["id"])
assert.Equal(t, "state-1", resp["states"][0]["id"])
assert.Equal(t, "label-1", resp["labels"][0]["id"])
})
t.Run("create_issue", func(t *testing.T) {
w := httptest.NewRecorder()
body := bytes.NewReader([]byte(`{"title":"Bug","team_id":"team-1","conversation_id":1}`))
req, _ := http.NewRequest("POST", "/api/v1/accounts/1/integrations/linear/create_issue", body)
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
var resp map[string]interface{}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp))
assert.Equal(t, "issue-1", resp["id"])
assert.Equal(t, "ENG-1", resp["identifier"])
})
t.Run("link_issue", func(t *testing.T) {
w := httptest.NewRecorder()
body := bytes.NewReader([]byte(`{"issue_id":"issue-1","conversation_id":1,"title":"Bug"}`))
req, _ := http.NewRequest("POST", "/api/v1/accounts/1/integrations/linear/link_issue", body)
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
var resp map[string]interface{}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp))
assert.Equal(t, "issue-1", resp["id"])
assert.Equal(t, "link-1", resp["link_id"])
})
t.Run("unlink_issue", func(t *testing.T) {
w := httptest.NewRecorder()
body := bytes.NewReader([]byte(`{"link_id":"link-1","issue_id":"issue-1","conversation_id":1}`))
req, _ := http.NewRequest("POST", "/api/v1/accounts/1/integrations/linear/unlink_issue", body)
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
var resp map[string]interface{}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp))
assert.Equal(t, "link-1", resp["link_id"])
})
t.Run("search_issue", func(t *testing.T) {
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/api/v1/accounts/1/integrations/linear/search_issue?q=query", nil)
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
var resp []map[string]interface{}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp))
require.Len(t, resp, 1)
assert.Equal(t, "ENG-1", resp[0]["identifier"])
})
t.Run("linked_issues", func(t *testing.T) {
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/api/v1/accounts/1/integrations/linear/linked_issues?conversation_id=1", nil)
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
var resp []map[string]interface{}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp))
require.Len(t, resp, 1)
assert.Equal(t, "link-1", resp[0]["id"])
})
}