Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0bf7eb92e5 |
@@ -0,0 +1,408 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
"github.com/Molecule-AI/molecule-monorepo/platform/internal/db"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// setupQueueStatusHandlerDB creates a sqlmock DB with QueryMatcherEqual for exact SQL string matching.
|
||||
func setupQueueStatusHandlerDB(t *testing.T) sqlmock.Sqlmock {
|
||||
t.Helper()
|
||||
mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual))
|
||||
if err != nil {
|
||||
t.Fatalf("sqlmock.New: %v", err)
|
||||
}
|
||||
prevDB := db.DB
|
||||
db.DB = mockDB
|
||||
t.Cleanup(func() { db.DB = prevDB; mockDB.Close() })
|
||||
return mock
|
||||
}
|
||||
|
||||
// Exact SQL strings used by the production code.
|
||||
const (
|
||||
sqlQueueRowAuthFields = `SELECT caller_id, workspace_id FROM a2a_queue WHERE id = $1`
|
||||
sqlQueueStatusByID = `
|
||||
SELECT
|
||||
q.id,
|
||||
q.workspace_id,
|
||||
q.status,
|
||||
q.priority,
|
||||
q.attempts,
|
||||
q.last_error,
|
||||
q.enqueued_at::text,
|
||||
q.dispatched_at::text,
|
||||
q.completed_at::text,
|
||||
q.expires_at::text,
|
||||
al.response_body::text
|
||||
FROM a2a_queue q
|
||||
LEFT JOIN activity_logs al
|
||||
ON al.method = 'delegate_result'
|
||||
AND al.target_id = q.workspace_id
|
||||
AND al.workspace_id = q.caller_id
|
||||
AND al.response_body->>'delegation_id' = (q.body->'params'->'message'->'metadata'->>'delegation_id')
|
||||
WHERE q.id = $1`
|
||||
)
|
||||
|
||||
// ── GetA2AQueueStatus HTTP handler tests ──────────────────────────────────────
|
||||
|
||||
// TestGetA2AQueueStatus_QueueIDEmpty_Returns400 exercises the handler directly
|
||||
// (not via router) so we can verify the empty-value branch without relying on
|
||||
// Gin route-matching behaviour.
|
||||
func TestGetA2AQueueStatus_QueueIDEmpty_Returns400(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
setupQueueStatusHandlerDB(t)
|
||||
h := &WorkspaceHandler{}
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"}}
|
||||
// queue_id param is empty string
|
||||
c.Params = gin.Params{
|
||||
{Key: "id", Value: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"},
|
||||
{Key: "queue_id", Value: ""},
|
||||
}
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
|
||||
h.GetA2AQueueStatus(c)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("got %d, want 400", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetA2AQueueStatus_NoIdentity_NoOrgToken_Returns404(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
setupQueueStatusHandlerDB(t)
|
||||
h := &WorkspaceHandler{}
|
||||
|
||||
r := gin.New()
|
||||
r.GET("/workspaces/:id/a2a/queue/:queue_id", h.GetA2AQueueStatus)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet,
|
||||
"/workspaces/wsid/a2a/queue/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
// No identity derivable → 404 (not 401) per existence-non-inference policy.
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("got %d, want 404", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetA2AQueueStatus_OrgToken_SkipsCallerCheck(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupQueueStatusHandlerDB(t)
|
||||
h := &WorkspaceHandler{}
|
||||
|
||||
queueID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
wsID := "cccccccc-cccc-cccc-cccc-cccccccccccc"
|
||||
|
||||
authRows := sqlmock.NewRows([]string{"caller_id", "workspace_id"}).
|
||||
AddRow("other-ws", wsID)
|
||||
mock.ExpectQuery(sqlQueueRowAuthFields).
|
||||
WithArgs(queueID).
|
||||
WillReturnRows(authRows)
|
||||
|
||||
statusRows := sqlmock.NewRows([]string{
|
||||
"id", "workspace_id", "status", "priority", "attempts",
|
||||
"last_error", "enqueued_at", "dispatched_at", "completed_at", "expires_at",
|
||||
"response_body",
|
||||
}).AddRow(
|
||||
queueID, wsID, "queued", 50, 0,
|
||||
nil, "2026-01-01T00:00:00Z", nil, nil, nil, nil,
|
||||
)
|
||||
mock.ExpectQuery(sqlQueueStatusByID).
|
||||
WithArgs(queueID).
|
||||
WillReturnRows(statusRows)
|
||||
|
||||
r := gin.New()
|
||||
// Simulate org-token middleware setting org_token_id.
|
||||
r.GET("/workspaces/:id/a2a/queue/:queue_id", func(c *gin.Context) {
|
||||
c.Set("org_token_id", "org-admin")
|
||||
h.GetA2AQueueStatus(c)
|
||||
})
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/workspaces/wsid/a2a/queue/"+queueID, nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("got %d, want 200: %s", w.Code, w.Body.String())
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetA2AQueueStatus_CallerWorkspaceMatchesCallerID_Success(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupQueueStatusHandlerDB(t)
|
||||
h := &WorkspaceHandler{}
|
||||
|
||||
queueID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
callerID := "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
|
||||
wsID := "cccccccc-cccc-cccc-cccc-cccccccccccc"
|
||||
|
||||
authRows := sqlmock.NewRows([]string{"caller_id", "workspace_id"}).
|
||||
AddRow(callerID, wsID)
|
||||
mock.ExpectQuery(sqlQueueRowAuthFields).
|
||||
WithArgs(queueID).
|
||||
WillReturnRows(authRows)
|
||||
|
||||
statusRows := sqlmock.NewRows([]string{
|
||||
"id", "workspace_id", "status", "priority", "attempts",
|
||||
"last_error", "enqueued_at", "dispatched_at", "completed_at", "expires_at",
|
||||
"response_body",
|
||||
}).AddRow(
|
||||
queueID, wsID, "completed", 50, 1,
|
||||
nil, "2026-01-01T00:00:00Z", "2026-01-01T00:01:00Z", "2026-01-01T00:02:00Z",
|
||||
nil, []byte(`{"text":"result"}`),
|
||||
)
|
||||
mock.ExpectQuery(sqlQueueStatusByID).
|
||||
WithArgs(queueID).
|
||||
WillReturnRows(statusRows)
|
||||
|
||||
r := gin.New()
|
||||
r.GET("/workspaces/:id/a2a/queue/:queue_id", h.GetA2AQueueStatus)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet,
|
||||
"/workspaces/"+wsID+"/a2a/queue/"+queueID, nil)
|
||||
req.Header.Set("X-Workspace-ID", callerID)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("got %d, want 200: %s", w.Code, w.Body.String())
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetA2AQueueStatus_CallerWorkspaceMatchesWorkspaceID_Success(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupQueueStatusHandlerDB(t)
|
||||
h := &WorkspaceHandler{}
|
||||
|
||||
queueID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
callerID := "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
|
||||
wsID := "cccccccc-cccc-cccc-cccc-cccccccccccc"
|
||||
|
||||
authRows := sqlmock.NewRows([]string{"caller_id", "workspace_id"}).
|
||||
AddRow(callerID, wsID)
|
||||
mock.ExpectQuery(sqlQueueRowAuthFields).
|
||||
WithArgs(queueID).
|
||||
WillReturnRows(authRows)
|
||||
|
||||
statusRows := sqlmock.NewRows([]string{
|
||||
"id", "workspace_id", "status", "priority", "attempts",
|
||||
"last_error", "enqueued_at", "dispatched_at", "completed_at", "expires_at",
|
||||
"response_body",
|
||||
}).AddRow(
|
||||
queueID, wsID, "queued", 50, 0,
|
||||
nil, "2026-01-01T00:00:00Z", nil, nil, nil, nil,
|
||||
)
|
||||
mock.ExpectQuery(sqlQueueStatusByID).
|
||||
WithArgs(queueID).
|
||||
WillReturnRows(statusRows)
|
||||
|
||||
r := gin.New()
|
||||
r.GET("/workspaces/:id/a2a/queue/:queue_id", h.GetA2AQueueStatus)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet,
|
||||
"/workspaces/"+wsID+"/a2a/queue/"+queueID, nil)
|
||||
req.Header.Set("X-Workspace-ID", wsID)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("got %d, want 200: %s", w.Code, w.Body.String())
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetA2AQueueStatus_QueueNotFound_Returns404(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupQueueStatusHandlerDB(t)
|
||||
h := &WorkspaceHandler{}
|
||||
|
||||
queueID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
callerID := "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
|
||||
wsID := "cccccccc-cccc-cccc-cccc-cccccccccccc"
|
||||
|
||||
mock.ExpectQuery(sqlQueueRowAuthFields).
|
||||
WithArgs(queueID).
|
||||
WillReturnError(sql.ErrNoRows)
|
||||
|
||||
r := gin.New()
|
||||
r.GET("/workspaces/:id/a2a/queue/:queue_id", h.GetA2AQueueStatus)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet,
|
||||
"/workspaces/"+wsID+"/a2a/queue/"+queueID, nil)
|
||||
req.Header.Set("X-Workspace-ID", callerID)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("got %d, want 404: %s", w.Code, w.Body.String())
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetA2AQueueStatus_QueueAuthFieldsDBError_Returns500(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupQueueStatusHandlerDB(t)
|
||||
h := &WorkspaceHandler{}
|
||||
|
||||
queueID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
callerID := "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
|
||||
wsID := "cccccccc-cccc-cccc-cccc-cccccccccccc"
|
||||
|
||||
mock.ExpectQuery(sqlQueueRowAuthFields).
|
||||
WithArgs(queueID).
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
|
||||
r := gin.New()
|
||||
r.GET("/workspaces/:id/a2a/queue/:queue_id", h.GetA2AQueueStatus)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet,
|
||||
"/workspaces/"+wsID+"/a2a/queue/"+queueID, nil)
|
||||
req.Header.Set("X-Workspace-ID", callerID)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("got %d, want 500: %s", w.Code, w.Body.String())
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetA2AQueueStatus_WrongCallerWorkspace_Returns404(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupQueueStatusHandlerDB(t)
|
||||
h := &WorkspaceHandler{}
|
||||
|
||||
queueID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
callerID := "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
|
||||
wsID := "cccccccc-cccc-cccc-cccc-cccccccccccc"
|
||||
wrongCaller := "dddddddd-dddd-dddd-dddd-dddddddddddd"
|
||||
|
||||
authRows := sqlmock.NewRows([]string{"caller_id", "workspace_id"}).
|
||||
AddRow(callerID, wsID)
|
||||
mock.ExpectQuery(sqlQueueRowAuthFields).
|
||||
WithArgs(queueID).
|
||||
WillReturnRows(authRows)
|
||||
|
||||
r := gin.New()
|
||||
r.GET("/workspaces/:id/a2a/queue/:queue_id", h.GetA2AQueueStatus)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet,
|
||||
"/workspaces/"+wsID+"/a2a/queue/"+queueID, nil)
|
||||
req.Header.Set("X-Workspace-ID", wrongCaller)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("got %d, want 404: %s", w.Code, w.Body.String())
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetA2AQueueStatus_StatusFetchDBError_Returns500(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupQueueStatusHandlerDB(t)
|
||||
h := &WorkspaceHandler{}
|
||||
|
||||
queueID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
callerID := "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
|
||||
wsID := "cccccccc-cccc-cccc-cccc-cccccccccccc"
|
||||
|
||||
authRows := sqlmock.NewRows([]string{"caller_id", "workspace_id"}).
|
||||
AddRow(callerID, wsID)
|
||||
mock.ExpectQuery(sqlQueueRowAuthFields).
|
||||
WithArgs(queueID).
|
||||
WillReturnRows(authRows)
|
||||
|
||||
mock.ExpectQuery(sqlQueueStatusByID).
|
||||
WithArgs(queueID).
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
|
||||
r := gin.New()
|
||||
r.GET("/workspaces/:id/a2a/queue/:queue_id", h.GetA2AQueueStatus)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet,
|
||||
"/workspaces/"+wsID+"/a2a/queue/"+queueID, nil)
|
||||
req.Header.Set("X-Workspace-ID", callerID)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("got %d, want 500: %s", w.Code, w.Body.String())
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetA2AQueueStatus_FullHappyPath_ReturnsJSON(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupQueueStatusHandlerDB(t)
|
||||
h := &WorkspaceHandler{}
|
||||
|
||||
queueID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
callerID := "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
|
||||
wsID := "cccccccc-cccc-cccc-cccc-cccccccccccc"
|
||||
|
||||
authRows := sqlmock.NewRows([]string{"caller_id", "workspace_id"}).
|
||||
AddRow(callerID, wsID)
|
||||
mock.ExpectQuery(sqlQueueRowAuthFields).
|
||||
WithArgs(queueID).
|
||||
WillReturnRows(authRows)
|
||||
|
||||
respBody := []byte(`{"text":"delegation result"}`)
|
||||
statusRows := sqlmock.NewRows([]string{
|
||||
"id", "workspace_id", "status", "priority", "attempts",
|
||||
"last_error", "enqueued_at", "dispatched_at", "completed_at", "expires_at",
|
||||
"response_body",
|
||||
}).AddRow(
|
||||
queueID, wsID, "completed", 50, 1,
|
||||
nil, "2026-01-01T00:00:00Z", "2026-01-01T00:01:00Z", "2026-01-01T00:02:00Z",
|
||||
nil, respBody,
|
||||
)
|
||||
mock.ExpectQuery(sqlQueueStatusByID).
|
||||
WithArgs(queueID).
|
||||
WillReturnRows(statusRows)
|
||||
|
||||
r := gin.New()
|
||||
r.GET("/workspaces/:id/a2a/queue/:queue_id", h.GetA2AQueueStatus)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet,
|
||||
"/workspaces/"+wsID+"/a2a/queue/"+queueID, nil)
|
||||
req.Header.Set("X-Workspace-ID", wsID)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("got %d, want 200: %s", w.Code, w.Body.String())
|
||||
}
|
||||
if w.Body.Len() == 0 {
|
||||
t.Error("response body is empty")
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -516,283 +516,3 @@ func TestDrainQueueForWorkspace_ClaimGuarding_SecondDrainGetsEmpty(t *testing.T)
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
// QueueDepth — pure function: COUNT(*) for queued items in a workspace.
|
||||
// No errors are surfaced to callers; any DB error returns 0.
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const sqlQueueDepthCount = `SELECT COUNT(*) FROM a2a_queue WHERE workspace_id = $1 AND status = 'queued'`
|
||||
|
||||
func TestQueueDepth_ZeroItems(t *testing.T) {
|
||||
mock := setupTestDBForQueueTests(t)
|
||||
mock.ExpectQuery(sqlQueueDepthCount).
|
||||
WithArgs("ws-empty").
|
||||
WillReturnError(sql.ErrNoRows) // COUNT never errors this way; function must not panic
|
||||
|
||||
got := QueueDepth(context.Background(), "ws-empty")
|
||||
if got != 0 {
|
||||
t.Errorf("QueueDepth(ws-empty) = %d, want 0", got)
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQueueDepth_MultipleItems(t *testing.T) {
|
||||
mock := setupTestDBForQueueTests(t)
|
||||
rows := sqlmock.NewRows([]string{"count"}).AddRow(3)
|
||||
mock.ExpectQuery(sqlQueueDepthCount).
|
||||
WithArgs("ws-busy").
|
||||
WillReturnRows(rows)
|
||||
|
||||
got := QueueDepth(context.Background(), "ws-busy")
|
||||
if got != 3 {
|
||||
t.Errorf("QueueDepth(ws-busy) = %d, want 3", got)
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQueueDepth_DBError_ReturnsZero(t *testing.T) {
|
||||
mock := setupTestDBForQueueTests(t)
|
||||
mock.ExpectQuery(sqlQueueDepthCount).
|
||||
WithArgs("ws-err").
|
||||
WillReturnError(fmt.Errorf("connection reset"))
|
||||
|
||||
// Function must not panic; any error returns 0 silently.
|
||||
got := QueueDepth(context.Background(), "ws-err")
|
||||
if got != 0 {
|
||||
t.Errorf("QueueDepth(ws-err) = %d, want 0 on DB error", got)
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQueueDepth_EmptyWorkspaceID(t *testing.T) {
|
||||
mock := setupTestDBForQueueTests(t)
|
||||
rows := sqlmock.NewRows([]string{"count"}).AddRow(0)
|
||||
mock.ExpectQuery(sqlQueueDepthCount).
|
||||
WithArgs("").
|
||||
WillReturnRows(rows)
|
||||
|
||||
got := QueueDepth(context.Background(), "")
|
||||
if got != 0 {
|
||||
t.Errorf("QueueDepth(\"\") = %d, want 0", got)
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
// MarkQueueItemCompleted — fires UPDATE; errors are logged, not returned.
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const sqlMarkCompleted = `UPDATE a2a_queue SET status = 'completed', completed_at = now() WHERE id = $1`
|
||||
|
||||
func TestMarkQueueItemCompleted_Success(t *testing.T) {
|
||||
mock := setupTestDBForQueueTests(t)
|
||||
mock.ExpectExec(sqlMarkCompleted).
|
||||
WithArgs("item-abc").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
|
||||
// Must not panic.
|
||||
MarkQueueItemCompleted(context.Background(), "item-abc")
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarkQueueItemCompleted_DBError_LogsNoPanic(t *testing.T) {
|
||||
mock := setupTestDBForQueueTests(t)
|
||||
mock.ExpectExec(sqlMarkCompleted).
|
||||
WithArgs("item-xyz").
|
||||
WillReturnError(fmt.Errorf("connection reset"))
|
||||
|
||||
// Must not panic even when DB errors.
|
||||
MarkQueueItemCompleted(context.Background(), "item-xyz")
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarkQueueItemCompleted_ZeroRows_NoPanic(t *testing.T) {
|
||||
mock := setupTestDBForQueueTests(t)
|
||||
mock.ExpectExec(sqlMarkCompleted).
|
||||
WithArgs("item-gone").
|
||||
WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
|
||||
MarkQueueItemCompleted(context.Background(), "item-gone")
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
// MarkQueueItemFailed — returns item to 'queued' (attempts < 5) or 'failed'.
|
||||
// maxAttempts is hard-coded to 5 in the handler; we test both CASE branches.
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const sqlMarkFailed = `UPDATE a2a_queue SET status = CASE WHEN attempts >= $2 THEN 'failed' ELSE 'queued' END, last_error = $3, dispatched_at = NULL WHERE id = $1`
|
||||
|
||||
func TestMarkQueueItemFailed_UnderMaxAttempts(t *testing.T) {
|
||||
mock := setupTestDBForQueueTests(t)
|
||||
mock.ExpectExec(sqlMarkFailed).
|
||||
WithArgs("item-retry", 5, "service unavailable").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
|
||||
// Must not panic; function is void.
|
||||
MarkQueueItemFailed(context.Background(), "item-retry", "service unavailable")
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarkQueueItemFailed_DBError_NoPanic(t *testing.T) {
|
||||
mock := setupTestDBForQueueTests(t)
|
||||
mock.ExpectExec(sqlMarkFailed).
|
||||
WithArgs("item-err", 5, "timeout").
|
||||
WillReturnError(fmt.Errorf("deadlock detected"))
|
||||
|
||||
// Must not panic on DB error.
|
||||
MarkQueueItemFailed(context.Background(), "item-err", "timeout")
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
// DropStaleQueueItems — marks stale queued items as 'dropped'.
|
||||
// workspaceID scoped vs. global sweep based on whether the param is empty.
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
// Scoped drop: workspaceID provided → query takes ($1=workspaceID, $2=maxAgeMinutes).
|
||||
// Go strips minimum leading tab from raw string literal, leaving one tab for the WITH line.
|
||||
const sqlDropStaleScoped = `WITH dropped AS (
|
||||
UPDATE a2a_queue
|
||||
SET status = 'dropped',
|
||||
last_error = last_error ||
|
||||
E'\n[DropStaleQueueItems] auto-dropped: queue item age exceeded the post-incident TTL. '
|
||||
|| 'Dropped at ' || now()::text
|
||||
WHERE id IN (
|
||||
SELECT id FROM a2a_queue
|
||||
WHERE workspace_id = $1
|
||||
AND status = 'queued'
|
||||
AND enqueued_at < now() - interval '1 minute' * $2
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
RETURNING id
|
||||
)
|
||||
SELECT count(*) FROM dropped`
|
||||
|
||||
// Global sweep: workspaceID empty → query takes ($1=maxAgeMinutes) only.
|
||||
const sqlDropStaleGlobal = `WITH dropped AS (
|
||||
UPDATE a2a_queue
|
||||
SET status = 'dropped',
|
||||
last_error = last_error ||
|
||||
E'\n[DropStaleQueueItems] auto-dropped: queue item age exceeded the post-incident TTL. '
|
||||
|| 'Dropped at ' || now()::text
|
||||
WHERE id IN (
|
||||
SELECT id FROM a2a_queue
|
||||
WHERE status = 'queued'
|
||||
AND enqueued_at < now() - interval '1 minute' * $1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
RETURNING id
|
||||
)
|
||||
SELECT count(*) FROM dropped`
|
||||
|
||||
func TestDropStaleQueueItems_Scoped_SomeDropped(t *testing.T) {
|
||||
mock := setupTestDBForQueueTests(t)
|
||||
rows := sqlmock.NewRows([]string{"count"}).AddRow(3)
|
||||
mock.ExpectQuery(sqlDropStaleScoped).
|
||||
WithArgs("ws-alpha", 60).
|
||||
WillReturnRows(rows)
|
||||
|
||||
got, err := DropStaleQueueItems(context.Background(), "ws-alpha", 60)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got != 3 {
|
||||
t.Errorf("DropStaleQueueItems(ws-alpha, 60) = %d, want 3", got)
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDropStaleQueueItems_Scoped_NoneStale(t *testing.T) {
|
||||
mock := setupTestDBForQueueTests(t)
|
||||
rows := sqlmock.NewRows([]string{"count"}).AddRow(0)
|
||||
mock.ExpectQuery(sqlDropStaleScoped).
|
||||
WithArgs("ws-fresh", 30).
|
||||
WillReturnRows(rows)
|
||||
|
||||
got, err := DropStaleQueueItems(context.Background(), "ws-fresh", 30)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got != 0 {
|
||||
t.Errorf("DropStaleQueueItems(ws-fresh, 30) = %d, want 0", got)
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDropStaleQueueItems_Global_SomeDropped(t *testing.T) {
|
||||
mock := setupTestDBForQueueTests(t)
|
||||
rows := sqlmock.NewRows([]string{"count"}).AddRow(7)
|
||||
mock.ExpectQuery(sqlDropStaleGlobal).
|
||||
WithArgs(120).
|
||||
WillReturnRows(rows)
|
||||
|
||||
got, err := DropStaleQueueItems(context.Background(), "", 120)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got != 7 {
|
||||
t.Errorf("DropStaleQueueItems(\"\", 120) = %d, want 7", got)
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDropStaleQueueItems_Scoped_DBError(t *testing.T) {
|
||||
mock := setupTestDBForQueueTests(t)
|
||||
mock.ExpectQuery(sqlDropStaleScoped).
|
||||
WithArgs("ws-err", 60).
|
||||
WillReturnError(fmt.Errorf("connection reset"))
|
||||
|
||||
_, err := DropStaleQueueItems(context.Background(), "ws-err", 60)
|
||||
if err == nil {
|
||||
t.Fatal("expected error on DB failure, got nil")
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDropStaleQueueItems_Global_DBError(t *testing.T) {
|
||||
mock := setupTestDBForQueueTests(t)
|
||||
mock.ExpectQuery(sqlDropStaleGlobal).
|
||||
WithArgs(60).
|
||||
WillReturnError(fmt.Errorf("deadlock detected"))
|
||||
|
||||
_, err := DropStaleQueueItems(context.Background(), "", 60)
|
||||
if err == nil {
|
||||
t.Fatal("expected error on DB failure, got nil")
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,400 +1,317 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
"github.com/Molecule-AI/molecule-monorepo/platform/internal/db"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// PatchAbilities handler tests
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// setupAbilitiesDB creates a sqlmock DB with QueryMatcherEqual for exact SQL matching.
|
||||
func setupAbilitiesDB(t *testing.T) sqlmock.Sqlmock {
|
||||
t.Helper()
|
||||
mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual))
|
||||
if err != nil {
|
||||
t.Fatalf("sqlmock.New: %v", err)
|
||||
}
|
||||
prevDB := db.DB
|
||||
db.DB = mockDB
|
||||
t.Cleanup(func() { db.DB = prevDB; mockDB.Close() })
|
||||
return mock
|
||||
}
|
||||
|
||||
func TestPatchAbilities_InvalidWorkspaceID(t *testing.T) {
|
||||
mock := setupTestDB(t)
|
||||
_ = mock // no DB calls for invalid ID
|
||||
// Exact SQL strings used by the production handler.
|
||||
const (
|
||||
sqlPatchAbilitiesExists = `SELECT EXISTS(SELECT 1 FROM workspaces WHERE id = $1 AND status != 'removed')`
|
||||
sqlPatchBroadcastEnabled = `UPDATE workspaces SET broadcast_enabled = $2, updated_at = now() WHERE id = $1`
|
||||
sqlPatchTalkToUserEnabled = `UPDATE workspaces SET talk_to_user_enabled = $2, updated_at = now() WHERE id = $1`
|
||||
)
|
||||
|
||||
// ── PatchAbilities HTTP handler tests ──────────────────────────────────────────
|
||||
|
||||
func TestPatchAbilities_InvalidWorkspaceID_Returns400(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
setupAbilitiesDB(t)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: "not-a-uuid"}}
|
||||
c.Request = httptest.NewRequest("PATCH", "/workspaces/not-a-uuid/abilities",
|
||||
bytes.NewReader([]byte(`{"broadcast_enabled":true}`)))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
c.Request = httptest.NewRequest(http.MethodPatch, "/workspaces/not-a-uuid/abilities", nil)
|
||||
|
||||
PatchAbilities(c)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp map[string]string
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
if resp["error"] != "invalid workspace ID" {
|
||||
t.Errorf("expected 'invalid workspace ID', got %v", resp)
|
||||
t.Errorf("got %d, want 400", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchAbilities_InvalidBody(t *testing.T) {
|
||||
mock := setupTestDB(t)
|
||||
_ = mock // ShouldBindJSON fails before any DB call
|
||||
|
||||
wid := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
func TestPatchAbilities_InvalidBody_Returns400(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
setupAbilitiesDB(t)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: wid}}
|
||||
c.Request = httptest.NewRequest("PATCH", "/workspaces/"+wid+"/abilities",
|
||||
bytes.NewReader([]byte(`{broken json`)))
|
||||
c.Params = gin.Params{{Key: "id", Value: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"}}
|
||||
c.Request = httptest.NewRequest(http.MethodPatch,
|
||||
"/workspaces/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa/abilities",
|
||||
newFakeCloser([]byte("not json")))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
PatchAbilities(c)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp map[string]string
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
if resp["error"] != "invalid request body" {
|
||||
t.Errorf("expected 'invalid request body', got %v", resp)
|
||||
t.Errorf("got %d, want 400", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchAbilities_NoFields(t *testing.T) {
|
||||
mock := setupTestDB(t)
|
||||
_ = mock // handler returns early before DB call
|
||||
|
||||
wid := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
func TestPatchAbilities_NoAbilityFields_Returns400(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
setupAbilitiesDB(t)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: wid}}
|
||||
c.Request = httptest.NewRequest("PATCH", "/workspaces/"+wid+"/abilities",
|
||||
bytes.NewReader([]byte(`{}`)))
|
||||
c.Params = gin.Params{{Key: "id", Value: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"}}
|
||||
c.Request = httptest.NewRequest(http.MethodPatch,
|
||||
"/workspaces/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa/abilities",
|
||||
newFakeCloser([]byte(`{}`)))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
PatchAbilities(c)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp map[string]string
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
if resp["error"] != "at least one ability field required" {
|
||||
t.Errorf("expected 'at least one ability field required', got %v", resp)
|
||||
t.Errorf("got %d, want 400", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchAbilities_WorkspaceNotFound(t *testing.T) {
|
||||
mock := setupTestDB(t)
|
||||
wid := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
func TestPatchAbilities_WorkspaceNotFound_Returns404(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupAbilitiesDB(t)
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
mock.ExpectQuery("SELECT EXISTS").
|
||||
WithArgs(wid).
|
||||
mock.ExpectQuery(sqlPatchAbilitiesExists).
|
||||
WithArgs(wsID).
|
||||
WillReturnError(sql.ErrNoRows)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: wid}}
|
||||
c.Request = httptest.NewRequest("PATCH", "/workspaces/"+wid+"/abilities",
|
||||
bytes.NewReader([]byte(`{"broadcast_enabled":true}`)))
|
||||
c.Params = gin.Params{{Key: "id", Value: wsID}}
|
||||
c.Request = httptest.NewRequest(http.MethodPatch, "/workspaces/"+wsID+"/abilities",
|
||||
newFakeCloser([]byte(`{"broadcast_enabled":true}`)))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
PatchAbilities(c)
|
||||
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("expected 404, got %d: %s", w.Code, w.Body.String())
|
||||
t.Errorf("got %d, want 404: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchAbilities_WorkspaceRemoved(t *testing.T) {
|
||||
// A workspace with status='removed' also returns 404.
|
||||
mock := setupTestDB(t)
|
||||
wid := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
func TestPatchAbilities_WorkspaceNotFound_ExistsFalse_Returns404(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupAbilitiesDB(t)
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
mock.ExpectQuery("SELECT EXISTS").
|
||||
WithArgs(wid).
|
||||
mock.ExpectQuery(sqlPatchAbilitiesExists).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(false))
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: wid}}
|
||||
c.Request = httptest.NewRequest("PATCH", "/workspaces/"+wid+"/abilities",
|
||||
bytes.NewReader([]byte(`{"broadcast_enabled":true}`)))
|
||||
c.Params = gin.Params{{Key: "id", Value: wsID}}
|
||||
c.Request = httptest.NewRequest(http.MethodPatch, "/workspaces/"+wsID+"/abilities",
|
||||
newFakeCloser([]byte(`{"talk_to_user_enabled":false}`)))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
PatchAbilities(c)
|
||||
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("expected 404 for removed workspace, got %d: %s", w.Code, w.Body.String())
|
||||
t.Errorf("got %d, want 404: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchAbilities_UpdateBroadcastEnabled_Success(t *testing.T) {
|
||||
mock := setupTestDB(t)
|
||||
wid := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupAbilitiesDB(t)
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
// Workspace exists
|
||||
mock.ExpectQuery("SELECT EXISTS").
|
||||
WithArgs(wid).
|
||||
mock.ExpectQuery(sqlPatchAbilitiesExists).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true))
|
||||
|
||||
// Broadcast update
|
||||
mock.ExpectExec("UPDATE workspaces SET broadcast_enabled").
|
||||
WithArgs(wid, true).
|
||||
mock.ExpectExec(sqlPatchBroadcastEnabled).
|
||||
WithArgs(wsID, true).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: wid}}
|
||||
c.Request = httptest.NewRequest("PATCH", "/workspaces/"+wid+"/abilities",
|
||||
bytes.NewReader([]byte(`{"broadcast_enabled":true}`)))
|
||||
c.Params = gin.Params{{Key: "id", Value: wsID}}
|
||||
c.Request = httptest.NewRequest(http.MethodPatch, "/workspaces/"+wsID+"/abilities",
|
||||
newFakeCloser([]byte(`{"broadcast_enabled":true}`)))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
PatchAbilities(c)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
t.Errorf("got %d, want 200: %s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp map[string]string
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
if resp["status"] != "updated" {
|
||||
t.Errorf("expected status 'updated', got %v", resp)
|
||||
}
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchAbilities_UpdateTalkToUserEnabled_Success(t *testing.T) {
|
||||
mock := setupTestDB(t)
|
||||
wid := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupAbilitiesDB(t)
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
mock.ExpectQuery("SELECT EXISTS").
|
||||
WithArgs(wid).
|
||||
mock.ExpectQuery(sqlPatchAbilitiesExists).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true))
|
||||
|
||||
mock.ExpectExec("UPDATE workspaces SET talk_to_user_enabled").
|
||||
WithArgs(wid, true).
|
||||
mock.ExpectExec(sqlPatchTalkToUserEnabled).
|
||||
WithArgs(wsID, false).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: wid}}
|
||||
c.Request = httptest.NewRequest("PATCH", "/workspaces/"+wid+"/abilities",
|
||||
bytes.NewReader([]byte(`{"talk_to_user_enabled":true}`)))
|
||||
c.Params = gin.Params{{Key: "id", Value: wsID}}
|
||||
c.Request = httptest.NewRequest(http.MethodPatch, "/workspaces/"+wsID+"/abilities",
|
||||
newFakeCloser([]byte(`{"talk_to_user_enabled":false}`)))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
PatchAbilities(c)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
t.Errorf("got %d, want 200: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchAbilities_UpdateBothAbilities_Success(t *testing.T) {
|
||||
// When both fields are provided, two separate UPDATE statements are issued.
|
||||
mock := setupTestDB(t)
|
||||
wid := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupAbilitiesDB(t)
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
mock.ExpectQuery("SELECT EXISTS").
|
||||
WithArgs(wid).
|
||||
mock.ExpectQuery(sqlPatchAbilitiesExists).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true))
|
||||
|
||||
mock.ExpectExec("UPDATE workspaces SET broadcast_enabled").
|
||||
WithArgs(wid, true).
|
||||
mock.ExpectExec(sqlPatchBroadcastEnabled).
|
||||
WithArgs(wsID, true).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
|
||||
mock.ExpectExec("UPDATE workspaces SET talk_to_user_enabled").
|
||||
WithArgs(wid, false).
|
||||
mock.ExpectExec(sqlPatchTalkToUserEnabled).
|
||||
WithArgs(wsID, false).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: wid}}
|
||||
c.Request = httptest.NewRequest("PATCH", "/workspaces/"+wid+"/abilities",
|
||||
bytes.NewReader([]byte(`{"broadcast_enabled":true,"talk_to_user_enabled":false}`)))
|
||||
c.Params = gin.Params{{Key: "id", Value: wsID}}
|
||||
c.Request = httptest.NewRequest(http.MethodPatch, "/workspaces/"+wsID+"/abilities",
|
||||
newFakeCloser([]byte(`{"broadcast_enabled":true,"talk_to_user_enabled":false}`)))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
PatchAbilities(c)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
t.Errorf("got %d, want 200: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchAbilities_UpdateBroadcastEnabled_DBError(t *testing.T) {
|
||||
mock := setupTestDB(t)
|
||||
wid := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
func TestPatchAbilities_BroadcastEnabledDBError_Returns500(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupAbilitiesDB(t)
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
mock.ExpectQuery("SELECT EXISTS").
|
||||
WithArgs(wid).
|
||||
mock.ExpectQuery(sqlPatchAbilitiesExists).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true))
|
||||
|
||||
mock.ExpectExec("UPDATE workspaces SET broadcast_enabled").
|
||||
WithArgs(wid, true).
|
||||
mock.ExpectExec(sqlPatchBroadcastEnabled).
|
||||
WithArgs(wsID, true).
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: wid}}
|
||||
c.Request = httptest.NewRequest("PATCH", "/workspaces/"+wid+"/abilities",
|
||||
bytes.NewReader([]byte(`{"broadcast_enabled":true}`)))
|
||||
c.Params = gin.Params{{Key: "id", Value: wsID}}
|
||||
c.Request = httptest.NewRequest(http.MethodPatch, "/workspaces/"+wsID+"/abilities",
|
||||
newFakeCloser([]byte(`{"broadcast_enabled":true}`)))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
PatchAbilities(c)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected 500 on DB error, got %d: %s", w.Code, w.Body.String())
|
||||
t.Errorf("got %d, want 500: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchAbilities_UpdateTalkToUserEnabled_DBError(t *testing.T) {
|
||||
// If broadcast update succeeds but talk_to_user update fails, the function
|
||||
// returns early with 500. Both fields must succeed.
|
||||
mock := setupTestDB(t)
|
||||
wid := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
func TestPatchAbilities_TalkToUserEnabledDBError_Returns500(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupAbilitiesDB(t)
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
mock.ExpectQuery("SELECT EXISTS").
|
||||
WithArgs(wid).
|
||||
mock.ExpectQuery(sqlPatchAbilitiesExists).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true))
|
||||
|
||||
mock.ExpectExec("UPDATE workspaces SET broadcast_enabled").
|
||||
WithArgs(wid, false).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
|
||||
mock.ExpectExec("UPDATE workspaces SET talk_to_user_enabled").
|
||||
WithArgs(wid, true).
|
||||
mock.ExpectExec(sqlPatchTalkToUserEnabled).
|
||||
WithArgs(wsID, true).
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: wid}}
|
||||
c.Request = httptest.NewRequest("PATCH", "/workspaces/"+wid+"/abilities",
|
||||
bytes.NewReader([]byte(`{"broadcast_enabled":false,"talk_to_user_enabled":true}`)))
|
||||
c.Params = gin.Params{{Key: "id", Value: wsID}}
|
||||
c.Request = httptest.NewRequest(http.MethodPatch, "/workspaces/"+wsID+"/abilities",
|
||||
newFakeCloser([]byte(`{"talk_to_user_enabled":true}`)))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
PatchAbilities(c)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected 500 when second update fails, got %d: %s", w.Code, w.Body.String())
|
||||
t.Errorf("got %d, want 500: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchAbilities_DisableBroadcast(t *testing.T) {
|
||||
// Explicitly disable (set to false) is a valid operation.
|
||||
mock := setupTestDB(t)
|
||||
wid := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
// ── Helpers ────────────────────────────────────────────────────────────────────
|
||||
|
||||
mock.ExpectQuery("SELECT EXISTS").
|
||||
WithArgs(wid).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true))
|
||||
|
||||
mock.ExpectExec("UPDATE workspaces SET broadcast_enabled").
|
||||
WithArgs(wid, false).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: wid}}
|
||||
c.Request = httptest.NewRequest("PATCH", "/workspaces/"+wid+"/abilities",
|
||||
bytes.NewReader([]byte(`{"broadcast_enabled":false}`)))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
PatchAbilities(c)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
}
|
||||
// newFakeCloser wraps a byte slice as an io.ReadCloser for request body injection.
|
||||
func newFakeCloser(data []byte) *fakeReadCloser {
|
||||
return &fakeReadCloser{data: data}
|
||||
}
|
||||
|
||||
func TestPatchAbilities_ExistsQueryDBError(t *testing.T) {
|
||||
// If the EXISTS check itself fails, return 404 (not 500).
|
||||
mock := setupTestDB(t)
|
||||
wid := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
mock.ExpectQuery("SELECT EXISTS").
|
||||
WithArgs(wid).
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: wid}}
|
||||
c.Request = httptest.NewRequest("PATCH", "/workspaces/"+wid+"/abilities",
|
||||
bytes.NewReader([]byte(`{"broadcast_enabled":true}`)))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
PatchAbilities(c)
|
||||
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("expected 404 on exists-check error, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
}
|
||||
type fakeReadCloser struct {
|
||||
data []byte
|
||||
pos int
|
||||
}
|
||||
|
||||
func TestAbilitiesPayload_PointerSemantics(t *testing.T) {
|
||||
// Verify that nil vs false are distinct in the payload.
|
||||
// This documents the pointer semantics used in the handler.
|
||||
|
||||
// nil = field omitted → handler skips update
|
||||
nilPayload := AbilitiesPayload{}
|
||||
if nilPayload.BroadcastEnabled != nil {
|
||||
t.Error("nil payload: BroadcastEnabled should be nil")
|
||||
}
|
||||
if nilPayload.TalkToUserEnabled != nil {
|
||||
t.Error("nil payload: TalkToUserEnabled should be nil")
|
||||
}
|
||||
|
||||
// false = explicit false
|
||||
falseVal := false
|
||||
falsePayload := AbilitiesPayload{BroadcastEnabled: &falseVal}
|
||||
if falsePayload.BroadcastEnabled == nil {
|
||||
t.Fatal("falsePayload: BroadcastEnabled should not be nil")
|
||||
}
|
||||
if *falsePayload.BroadcastEnabled != false {
|
||||
t.Errorf("expected false, got %v", *falsePayload.BroadcastEnabled)
|
||||
}
|
||||
|
||||
// true = explicit true
|
||||
trueVal := true
|
||||
truePayload := AbilitiesPayload{BroadcastEnabled: &trueVal}
|
||||
if truePayload.BroadcastEnabled == nil || *truePayload.BroadcastEnabled != true {
|
||||
t.Error("truePayload: BroadcastEnabled should be true")
|
||||
func (f *fakeReadCloser) Read(p []byte) (n int, err error) {
|
||||
if f.pos >= len(f.data) {
|
||||
return 0, nil
|
||||
}
|
||||
n = copy(p, f.data[f.pos:])
|
||||
f.pos += n
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (*fakeReadCloser) Close() error { return nil }
|
||||
|
||||
@@ -2,459 +2,402 @@ package handlers
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
"github.com/Molecule-AI/molecule-monorepo/platform/internal/events"
|
||||
"github.com/Molecule-AI/molecule-monorepo/platform/internal/ws"
|
||||
"github.com/Molecule-AI/molecule-monorepo/platform/internal/db"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// broadcastTruncate pure-function tests
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
func TestBroadcastTruncate_UnderLimit(t *testing.T) {
|
||||
got := broadcastTruncate("hello world", 20)
|
||||
if got != "hello world" {
|
||||
t.Errorf("under limit: got %q, want %q", got, "hello world")
|
||||
}
|
||||
// broadcastBody is a convenience that returns an io.ReadCloser wrapping JSON body.
|
||||
func broadcastBody(body string) io.ReadCloser {
|
||||
return &broadcastFakeCloser{data: []byte(body)}
|
||||
}
|
||||
|
||||
func TestBroadcastTruncate_ExactlyLimit(t *testing.T) {
|
||||
s := "hello"
|
||||
got := broadcastTruncate(s, 5)
|
||||
if got != "hello" {
|
||||
t.Errorf("exact limit: got %q, want %q", got, "hello")
|
||||
}
|
||||
type broadcastFakeCloser struct {
|
||||
data []byte
|
||||
pos int
|
||||
}
|
||||
|
||||
func TestBroadcastTruncate_OverLimit(t *testing.T) {
|
||||
got := broadcastTruncate("hello world this is long", 10)
|
||||
if !strings.HasSuffix(got, "…") {
|
||||
t.Errorf("over limit: got %q, want trailing ellipsis", got)
|
||||
}
|
||||
// 10 chars + 1 ellipsis rune
|
||||
if len([]rune(got)) != 11 {
|
||||
t.Errorf("over limit: got len %d runes, want 11 (10 + ellipsis)", len([]rune(got)))
|
||||
func (f *broadcastFakeCloser) Read(p []byte) (n int, err error) {
|
||||
if f.pos >= len(f.data) {
|
||||
return 0, io.EOF
|
||||
}
|
||||
n = copy(p, f.data[f.pos:])
|
||||
f.pos += n
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func TestBroadcastTruncate_Unicode(t *testing.T) {
|
||||
// 5 Unicode runes but 15 bytes
|
||||
got := broadcastTruncate("hello 世界", 4)
|
||||
if !strings.HasSuffix(got, "…") {
|
||||
t.Errorf("unicode over limit: got %q, want trailing ellipsis", got)
|
||||
}
|
||||
if len([]rune(got)) != 5 {
|
||||
t.Errorf("unicode over limit: got %d runes, want 5", len([]rune(got)))
|
||||
}
|
||||
}
|
||||
func (*broadcastFakeCloser) Close() error { return nil }
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Broadcast handler tests
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
func makeBroadcastHandler(t *testing.T) *BroadcastHandler {
|
||||
// setupBroadcastDB creates a sqlmock DB with QueryMatcherEqual.
|
||||
func setupBroadcastDB(t *testing.T) sqlmock.Sqlmock {
|
||||
t.Helper()
|
||||
hub := ws.NewHub(func(callerID, targetID string) bool { return true })
|
||||
broadcaster := events.NewBroadcaster(hub)
|
||||
return NewBroadcastHandler(broadcaster)
|
||||
mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual))
|
||||
if err != nil {
|
||||
t.Fatalf("sqlmock.New: %v", err)
|
||||
}
|
||||
prevDB := db.DB
|
||||
db.DB = mockDB
|
||||
t.Cleanup(func() { db.DB = prevDB; mockDB.Close() })
|
||||
return mock
|
||||
}
|
||||
|
||||
func TestBroadcast_InvalidWorkspaceID(t *testing.T) {
|
||||
mock := setupTestDB(t)
|
||||
_ = mock // no DB calls expected for invalid ID
|
||||
// Exact SQL strings from the production handler (whitespace must match verbatim).
|
||||
const (
|
||||
sqlBroadcastWorkspaceLookup = `SELECT name, broadcast_enabled FROM workspaces WHERE id = $1 AND status != 'removed'`
|
||||
sqlBroadcastRecipients = `SELECT id FROM workspaces WHERE status != 'removed' AND id != $1`
|
||||
sqlBroadcastReceiveInsert = `
|
||||
INSERT INTO activity_logs (workspace_id, activity_type, method, source_id, summary, status)
|
||||
VALUES ($1, 'broadcast_receive', 'broadcast', $2, $3, 'ok')`
|
||||
sqlBroadcastSentInsert = `
|
||||
INSERT INTO activity_logs (workspace_id, activity_type, method, summary, status)
|
||||
VALUES ($1, 'broadcast_sent', 'broadcast', $2, 'ok')`
|
||||
)
|
||||
|
||||
h := makeBroadcastHandler(t)
|
||||
// ── Broadcast HTTP handler tests ───────────────────────────────────────────────
|
||||
|
||||
func TestBroadcast_InvalidWorkspaceID_Returns400(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
setupBroadcastDB(t)
|
||||
h := NewBroadcastHandler(newTestBroadcaster())
|
||||
|
||||
r := gin.New()
|
||||
r.POST("/workspaces/:id/broadcast", h.Broadcast)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/workspaces/not-a-uuid/broadcast",
|
||||
broadcastBody(`{"message":"hello"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: "not-a-uuid"}}
|
||||
c.Request = httptest.NewRequest("POST", "/workspaces/not-a-uuid/broadcast", strings.NewReader(`{"message":"hello"}`))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
h.Broadcast(c)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp map[string]string
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
if resp["error"] != "invalid workspace ID" {
|
||||
t.Errorf("expected 'invalid workspace ID', got %v", resp)
|
||||
t.Errorf("got %d, want 400: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBroadcast_MissingMessage(t *testing.T) {
|
||||
mock := setupTestDB(t)
|
||||
_ = mock // no DB calls expected before binding failure
|
||||
func TestBroadcast_MissingMessage_Returns400(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
setupBroadcastDB(t)
|
||||
h := NewBroadcastHandler(newTestBroadcaster())
|
||||
|
||||
h := makeBroadcastHandler(t)
|
||||
r := gin.New()
|
||||
r.POST("/workspaces/:id/broadcast", h.Broadcast)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost,
|
||||
"/workspaces/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa/broadcast",
|
||||
broadcastBody(`{}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"}}
|
||||
c.Request = httptest.NewRequest("POST", "/broadcast", strings.NewReader(`{}`))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
h.Broadcast(c)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())
|
||||
t.Errorf("got %d, want 400: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBroadcast_WorkspaceNotFound(t *testing.T) {
|
||||
mock := setupTestDB(t)
|
||||
wid := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
func TestBroadcast_EmptyMessage_Returns400(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
setupBroadcastDB(t)
|
||||
h := NewBroadcastHandler(newTestBroadcaster())
|
||||
|
||||
mock.ExpectQuery("SELECT name, broadcast_enabled").
|
||||
WithArgs(wid).
|
||||
r := gin.New()
|
||||
r.POST("/workspaces/:id/broadcast", h.Broadcast)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost,
|
||||
"/workspaces/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa/broadcast",
|
||||
broadcastBody(`{"message":""}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("got %d, want 400: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBroadcast_WorkspaceNotFound_Returns404(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupBroadcastDB(t)
|
||||
h := NewBroadcastHandler(newTestBroadcaster())
|
||||
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
mock.ExpectQuery(sqlBroadcastWorkspaceLookup).
|
||||
WithArgs(wsID).
|
||||
WillReturnError(sql.ErrNoRows)
|
||||
|
||||
h := makeBroadcastHandler(t)
|
||||
r := gin.New()
|
||||
r.POST("/workspaces/:id/broadcast", h.Broadcast)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/workspaces/"+wsID+"/broadcast",
|
||||
broadcastBody(`{"message":"hello"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: wid}}
|
||||
c.Request = httptest.NewRequest("POST", "/broadcast", strings.NewReader(`{"message":"hello"}`))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
h.Broadcast(c)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("expected 404, got %d: %s", w.Code, w.Body.String())
|
||||
t.Errorf("got %d, want 404: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBroadcast_Disabled(t *testing.T) {
|
||||
mock := setupTestDB(t)
|
||||
wid := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
func TestBroadcast_BroadcastDisabled_Returns403(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupBroadcastDB(t)
|
||||
h := NewBroadcastHandler(newTestBroadcaster())
|
||||
|
||||
mock.ExpectQuery("SELECT name, broadcast_enabled").
|
||||
WithArgs(wid).
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
mock.ExpectQuery(sqlBroadcastWorkspaceLookup).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"name", "broadcast_enabled"}).
|
||||
AddRow("Test Agent", false))
|
||||
AddRow("test-workspace", false))
|
||||
|
||||
h := makeBroadcastHandler(t)
|
||||
r := gin.New()
|
||||
r.POST("/workspaces/:id/broadcast", h.Broadcast)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/workspaces/"+wsID+"/broadcast",
|
||||
broadcastBody(`{"message":"hello"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: wid}}
|
||||
c.Request = httptest.NewRequest("POST", "/broadcast", strings.NewReader(`{"message":"hello"}`))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
h.Broadcast(c)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Errorf("expected 403, got %d: %s", w.Code, w.Body.String())
|
||||
t.Errorf("got %d, want 403: %s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp map[string]string
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
if resp["error"] != "broadcast_disabled" {
|
||||
t.Errorf("expected 'broadcast_disabled', got %v", resp)
|
||||
}
|
||||
if resp["hint"] == "" {
|
||||
t.Errorf("expected hint field, got none")
|
||||
}
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBroadcast_Success_NoRecipients(t *testing.T) {
|
||||
mock := setupTestDB(t)
|
||||
wid := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
func TestBroadcast_NoRecipients_Success(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupBroadcastDB(t)
|
||||
h := NewBroadcastHandler(newTestBroadcaster())
|
||||
|
||||
// Sender lookup
|
||||
mock.ExpectQuery("SELECT name, broadcast_enabled").
|
||||
WithArgs(wid).
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
mock.ExpectQuery(sqlBroadcastWorkspaceLookup).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"name", "broadcast_enabled"}).
|
||||
AddRow("Test Agent", true))
|
||||
AddRow("test-workspace", true))
|
||||
|
||||
// No other workspaces
|
||||
rows := sqlmock.NewRows([]string{"id"})
|
||||
mock.ExpectQuery("SELECT id FROM workspaces").
|
||||
WithArgs(wid).
|
||||
WillReturnRows(rows)
|
||||
// No recipients (sender is the only non-removed workspace)
|
||||
mock.ExpectQuery(sqlBroadcastRecipients).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}))
|
||||
|
||||
// Sender's own activity log
|
||||
mock.ExpectExec("INSERT INTO activity_logs").
|
||||
WithArgs(wid, "Broadcast sent to 0 workspace(s)").
|
||||
// Sender's own activity log: 2 args (workspaceID, summary)
|
||||
mock.ExpectExec(sqlBroadcastSentInsert).
|
||||
WithArgs(wsID, sqlmock.AnyArg()).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
|
||||
h := makeBroadcastHandler(t)
|
||||
r := gin.New()
|
||||
r.POST("/workspaces/:id/broadcast", h.Broadcast)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/workspaces/"+wsID+"/broadcast",
|
||||
broadcastBody(`{"message":"hello everyone"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: wid}}
|
||||
c.Request = httptest.NewRequest("POST", "/broadcast", strings.NewReader(`{"message":"hello everyone"}`))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
h.Broadcast(c)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
t.Errorf("got %d, want 200: %s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp map[string]interface{}
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
if resp["status"] != "sent" {
|
||||
t.Errorf("expected status 'sent', got %v", resp["status"])
|
||||
}
|
||||
if resp["delivered"] != float64(0) {
|
||||
t.Errorf("expected delivered 0, got %v", resp["delivered"])
|
||||
}
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBroadcast_Success_WithRecipients(t *testing.T) {
|
||||
mock := setupTestDB(t)
|
||||
wid := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
func TestBroadcast_WithRecipients_Success_DeliversToAll(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupBroadcastDB(t)
|
||||
h := NewBroadcastHandler(newTestBroadcaster())
|
||||
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
recipient1 := "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
|
||||
recipient2 := "cccccccc-cccc-cccc-cccc-cccccccccccc"
|
||||
|
||||
// Sender lookup
|
||||
mock.ExpectQuery("SELECT name, broadcast_enabled").
|
||||
WithArgs(wid).
|
||||
mock.ExpectQuery(sqlBroadcastWorkspaceLookup).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"name", "broadcast_enabled"}).
|
||||
AddRow("Test Agent", true))
|
||||
AddRow("broadcaster-ws", true))
|
||||
|
||||
// Two recipients
|
||||
rows := sqlmock.NewRows([]string{"id"}).AddRow(recipient1).AddRow(recipient2)
|
||||
mock.ExpectQuery("SELECT id FROM workspaces").
|
||||
WithArgs(wid).
|
||||
WillReturnRows(rows)
|
||||
mock.ExpectQuery(sqlBroadcastRecipients).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).
|
||||
AddRow(recipient1).
|
||||
AddRow(recipient2))
|
||||
|
||||
// Activity log inserts for each recipient (2x)
|
||||
mock.ExpectExec("INSERT INTO activity_logs").
|
||||
WithArgs(recipient1, wid, sqlmock.AnyArg()).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec("INSERT INTO activity_logs").
|
||||
WithArgs(recipient2, wid, sqlmock.AnyArg()).
|
||||
// broadcast_receive: 3 args (recipientID, senderID, summary)
|
||||
mock.ExpectExec(sqlBroadcastReceiveInsert).
|
||||
WithArgs(recipient1, sqlmock.AnyArg(), sqlmock.AnyArg()).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
|
||||
// Sender's own activity log
|
||||
mock.ExpectExec("INSERT INTO activity_logs").
|
||||
WithArgs(wid, "Broadcast sent to 2 workspace(s)").
|
||||
mock.ExpectExec(sqlBroadcastReceiveInsert).
|
||||
WithArgs(recipient2, sqlmock.AnyArg(), sqlmock.AnyArg()).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
|
||||
h := makeBroadcastHandler(t)
|
||||
// broadcast_sent: 2 args (workspaceID, summary)
|
||||
mock.ExpectExec(sqlBroadcastSentInsert).
|
||||
WithArgs(wsID, sqlmock.AnyArg()).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
|
||||
r := gin.New()
|
||||
r.POST("/workspaces/:id/broadcast", h.Broadcast)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/workspaces/"+wsID+"/broadcast",
|
||||
broadcastBody(`{"message":"hello team"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: wid}}
|
||||
c.Request = httptest.NewRequest("POST", "/broadcast", strings.NewReader(`{"message":"urgent alert"}`))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
h.Broadcast(c)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
t.Errorf("got %d, want 200: %s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp map[string]interface{}
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
if resp["delivered"] != float64(2) {
|
||||
t.Errorf("expected delivered 2, got %v", resp["delivered"])
|
||||
}
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBroadcast_RecipientQueryError(t *testing.T) {
|
||||
mock := setupTestDB(t)
|
||||
wid := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
func TestBroadcast_RecipientInsertError_ContinuesAndSucceeds(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupBroadcastDB(t)
|
||||
h := NewBroadcastHandler(newTestBroadcaster())
|
||||
|
||||
// Sender lookup succeeds
|
||||
mock.ExpectQuery("SELECT name, broadcast_enabled").
|
||||
WithArgs(wid).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"name", "broadcast_enabled"}).
|
||||
AddRow("Test Agent", true))
|
||||
|
||||
// Recipient query fails
|
||||
mock.ExpectQuery("SELECT id FROM workspaces").
|
||||
WithArgs(wid).
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
|
||||
h := makeBroadcastHandler(t)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: wid}}
|
||||
c.Request = httptest.NewRequest("POST", "/broadcast", strings.NewReader(`{"message":"hello"}`))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
h.Broadcast(c)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected 500, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBroadcast_ActivityLogInsertError_Continues(t *testing.T) {
|
||||
// Even if one recipient's activity_log insert fails, we continue to the
|
||||
// next recipient rather than returning an error.
|
||||
mock := setupTestDB(t)
|
||||
wid := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
recipient1 := "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
|
||||
recipient2 := "cccccccc-cccc-cccc-cccc-cccccccccccc"
|
||||
|
||||
mock.ExpectQuery("SELECT name, broadcast_enabled").
|
||||
WithArgs(wid).
|
||||
mock.ExpectQuery(sqlBroadcastWorkspaceLookup).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"name", "broadcast_enabled"}).
|
||||
AddRow("Test Agent", true))
|
||||
AddRow("broadcaster-ws", true))
|
||||
|
||||
rows := sqlmock.NewRows([]string{"id"}).AddRow(recipient1).AddRow(recipient2)
|
||||
mock.ExpectQuery("SELECT id FROM workspaces").
|
||||
WithArgs(wid).
|
||||
WillReturnRows(rows)
|
||||
mock.ExpectQuery(sqlBroadcastRecipients).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).
|
||||
AddRow(recipient1).
|
||||
AddRow(recipient2))
|
||||
|
||||
// First recipient insert fails — but we continue
|
||||
mock.ExpectExec("INSERT INTO activity_logs").
|
||||
WithArgs(recipient1, wid, sqlmock.AnyArg()).
|
||||
// First recipient insert fails — handler logs and continues
|
||||
mock.ExpectExec(sqlBroadcastReceiveInsert).
|
||||
WithArgs(recipient1, sqlmock.AnyArg(), sqlmock.AnyArg()).
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
|
||||
// Second recipient succeeds
|
||||
mock.ExpectExec("INSERT INTO activity_logs").
|
||||
WithArgs(recipient2, wid, sqlmock.AnyArg()).
|
||||
mock.ExpectExec(sqlBroadcastReceiveInsert).
|
||||
WithArgs(recipient2, sqlmock.AnyArg(), sqlmock.AnyArg()).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
|
||||
// Sender activity log succeeds
|
||||
mock.ExpectExec("INSERT INTO activity_logs").
|
||||
WithArgs(wid, "Broadcast sent to 1 workspace(s)").
|
||||
mock.ExpectExec(sqlBroadcastSentInsert).
|
||||
WithArgs(wsID, sqlmock.AnyArg()).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
|
||||
h := makeBroadcastHandler(t)
|
||||
r := gin.New()
|
||||
r.POST("/workspaces/:id/broadcast", h.Broadcast)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/workspaces/"+wsID+"/broadcast",
|
||||
broadcastBody(`{"message":"partial delivery"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: wid}}
|
||||
c.Request = httptest.NewRequest("POST", "/broadcast", strings.NewReader(`{"message":"partial delivery"}`))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
h.Broadcast(c)
|
||||
|
||||
// Should still return 200 with delivered=1
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
t.Errorf("got %d, want 200: %s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp map[string]interface{}
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
if resp["delivered"] != float64(1) {
|
||||
t.Errorf("expected delivered 1 (one failed), got %v", resp["delivered"])
|
||||
}
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBroadcast_DBSenderQueryError(t *testing.T) {
|
||||
// Any DB error on the sender lookup returns 404
|
||||
mock := setupTestDB(t)
|
||||
wid := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
func TestBroadcast_SenderActivityLogError_StillReturns200(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupBroadcastDB(t)
|
||||
h := NewBroadcastHandler(newTestBroadcaster())
|
||||
|
||||
mock.ExpectQuery("SELECT name, broadcast_enabled").
|
||||
WithArgs(wid).
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
mock.ExpectQuery(sqlBroadcastWorkspaceLookup).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"name", "broadcast_enabled"}).
|
||||
AddRow("broadcaster-ws", true))
|
||||
|
||||
mock.ExpectQuery(sqlBroadcastRecipients).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}))
|
||||
|
||||
mock.ExpectExec(sqlBroadcastSentInsert).
|
||||
WithArgs(wsID, sqlmock.AnyArg()).
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
|
||||
h := makeBroadcastHandler(t)
|
||||
r := gin.New()
|
||||
r.POST("/workspaces/:id/broadcast", h.Broadcast)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/workspaces/"+wsID+"/broadcast",
|
||||
broadcastBody(`{"message":"hello"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: wid}}
|
||||
c.Request = httptest.NewRequest("POST", "/broadcast", strings.NewReader(`{"message":"hello"}`))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
h.Broadcast(c)
|
||||
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("expected 404 on DB error, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBroadcast_MessageTruncatedInActivityLog(t *testing.T) {
|
||||
// Verify that long messages are truncated to 120 chars in the activity log.
|
||||
mock := setupTestDB(t)
|
||||
wid := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
longMsg := strings.Repeat("x", 200)
|
||||
|
||||
mock.ExpectQuery("SELECT name, broadcast_enabled").
|
||||
WithArgs(wid).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"name", "broadcast_enabled"}).
|
||||
AddRow("Test Agent", true))
|
||||
|
||||
rows := sqlmock.NewRows([]string{"id"})
|
||||
mock.ExpectQuery("SELECT id FROM workspaces").
|
||||
WithArgs(wid).
|
||||
WillReturnRows(rows)
|
||||
|
||||
// Verify the handler doesn't panic and returns 200.
|
||||
// The truncation is covered by TestBroadcastTruncate_OverLimit.
|
||||
mock.ExpectExec("INSERT INTO activity_logs").
|
||||
WithArgs(wid, "Broadcast sent to 0 workspace(s)").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
|
||||
h := makeBroadcastHandler(t)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: wid}}
|
||||
c.Request = httptest.NewRequest("POST", "/broadcast", strings.NewReader(`{"message":"`+longMsg+`"}`))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
// Patch ExecContext to capture the summary arg for the sender insert
|
||||
// Instead: just verify the handler doesn't panic and returns 200.
|
||||
// The truncation is covered by TestBroadcastTruncate_OverLimit.
|
||||
|
||||
h.Broadcast(c)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
// Handler logs error but still returns 200
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
t.Errorf("got %d, want 200: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
// Verify broadcastTruncate: 200 ASCII chars → 120 runes + 1 ellipsis = 121 bytes
|
||||
truncated := broadcastTruncate(longMsg, 120)
|
||||
if len([]rune(truncated)) != 121 {
|
||||
t.Errorf("expected 121 runes (120 + ellipsis), got %d: %q", len([]rune(truncated)), truncated)
|
||||
}
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewBroadcastHandler(t *testing.T) {
|
||||
hub := ws.NewHub(func(callerID, targetID string) bool { return true })
|
||||
broadcaster := events.NewBroadcaster(hub)
|
||||
h := NewBroadcastHandler(broadcaster)
|
||||
if h == nil {
|
||||
t.Fatal("NewBroadcastHandler returned nil")
|
||||
}
|
||||
if h.broadcaster == nil {
|
||||
t.Error("broadcaster is nil")
|
||||
// ── broadcastTruncate pure function tests ─────────────────────────────────────
|
||||
|
||||
func TestBroadcastTruncate_UnderLimit(t *testing.T) {
|
||||
input := "short message"
|
||||
got := broadcastTruncate(input, 50)
|
||||
if got != input {
|
||||
t.Errorf("broadcastTruncate(%q, 50) = %q, want %q", input, got, input)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBroadcastTruncate_ExactlyAtLimit(t *testing.T) {
|
||||
input := "exactly fifty char"
|
||||
got := broadcastTruncate(input, 18)
|
||||
if got != input {
|
||||
t.Errorf("broadcastTruncate(%q, 18) = %q, want %q", input, got, input)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBroadcastTruncate_OverLimit_TruncatesAndAddsEllipsis(t *testing.T) {
|
||||
// 150 ASCII chars → over 120 rune limit → truncate to 120 + ellipsis
|
||||
input := strings.Repeat("x", 150)
|
||||
got := broadcastTruncate(input, 120)
|
||||
if len([]rune(got)) != 121 { // 120 + 1 ellipsis rune
|
||||
t.Errorf("len(broadcastTruncate) = %d, want 121 (120 + ellipsis)", len([]rune(got)))
|
||||
}
|
||||
if got[:len(got)-len("…")] != strings.Repeat("x", 120) {
|
||||
t.Errorf("broadcastTruncate did not truncate correctly")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBroadcastTruncate_UnicodeChars_TreatsAsRunes(t *testing.T) {
|
||||
// Each emoji is 1 rune but multiple bytes. 50 emojis > 30 limit.
|
||||
input := strings.Repeat("🎉", 50)
|
||||
got := broadcastTruncate(input, 30)
|
||||
if len([]rune(got)) != 31 { // 30 + ellipsis
|
||||
t.Errorf("len(broadcastTruncate with emoji) = %d, want 31", len([]rune(got)))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBroadcastTruncate_ZeroLimit_ReturnsEllipsis(t *testing.T) {
|
||||
got := broadcastTruncate("hello", 0)
|
||||
if got != "…" {
|
||||
t.Errorf("broadcastTruncate with max=0 = %q, want …", got)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user