Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 37bb04136c |
@@ -1,408 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -1,317 +0,0 @@
|
||||
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"
|
||||
)
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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(http.MethodPatch, "/workspaces/not-a-uuid/abilities", nil)
|
||||
|
||||
PatchAbilities(c)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("got %d, want 400", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
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: "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("got %d, want 400", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
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: "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("got %d, want 400", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchAbilities_WorkspaceNotFound_Returns404(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupAbilitiesDB(t)
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
mock.ExpectQuery(sqlPatchAbilitiesExists).
|
||||
WithArgs(wsID).
|
||||
WillReturnError(sql.ErrNoRows)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
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("got %d, want 404: %s", w.Code, w.Body.String())
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchAbilities_WorkspaceNotFound_ExistsFalse_Returns404(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupAbilitiesDB(t)
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
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: 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("got %d, want 404: %s", w.Code, w.Body.String())
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchAbilities_UpdateBroadcastEnabled_Success(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupAbilitiesDB(t)
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
mock.ExpectQuery(sqlPatchAbilitiesExists).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(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: 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("got %d, want 200: %s", w.Code, w.Body.String())
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchAbilities_UpdateTalkToUserEnabled_Success(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupAbilitiesDB(t)
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
mock.ExpectQuery(sqlPatchAbilitiesExists).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(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: 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("got %d, want 200: %s", w.Code, w.Body.String())
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchAbilities_UpdateBothAbilities_Success(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupAbilitiesDB(t)
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
mock.ExpectQuery(sqlPatchAbilitiesExists).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true))
|
||||
|
||||
mock.ExpectExec(sqlPatchBroadcastEnabled).
|
||||
WithArgs(wsID, true).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
|
||||
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: 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("got %d, want 200: %s", w.Code, w.Body.String())
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchAbilities_BroadcastEnabledDBError_Returns500(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupAbilitiesDB(t)
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
mock.ExpectQuery(sqlPatchAbilitiesExists).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true))
|
||||
|
||||
mock.ExpectExec(sqlPatchBroadcastEnabled).
|
||||
WithArgs(wsID, true).
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
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("got %d, want 500: %s", w.Code, w.Body.String())
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchAbilities_TalkToUserEnabledDBError_Returns500(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupAbilitiesDB(t)
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
mock.ExpectQuery(sqlPatchAbilitiesExists).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true))
|
||||
|
||||
mock.ExpectExec(sqlPatchTalkToUserEnabled).
|
||||
WithArgs(wsID, true).
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
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("got %d, want 500: %s", w.Code, w.Body.String())
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Helpers ────────────────────────────────────────────────────────────────────
|
||||
|
||||
// newFakeCloser wraps a byte slice as an io.ReadCloser for request body injection.
|
||||
func newFakeCloser(data []byte) *fakeReadCloser {
|
||||
return &fakeReadCloser{data: data}
|
||||
}
|
||||
|
||||
type fakeReadCloser struct {
|
||||
data []byte
|
||||
pos int
|
||||
}
|
||||
|
||||
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 }
|
||||
@@ -1,403 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
"github.com/Molecule-AI/molecule-monorepo/platform/internal/db"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// broadcastBody is a convenience that returns an io.ReadCloser wrapping JSON body.
|
||||
func broadcastBody(body string) io.ReadCloser {
|
||||
return &broadcastFakeCloser{data: []byte(body)}
|
||||
}
|
||||
|
||||
type broadcastFakeCloser struct {
|
||||
data []byte
|
||||
pos int
|
||||
}
|
||||
|
||||
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 (*broadcastFakeCloser) Close() error { return nil }
|
||||
|
||||
// setupBroadcastDB creates a sqlmock DB with QueryMatcherEqual.
|
||||
func setupBroadcastDB(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 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')`
|
||||
)
|
||||
|
||||
// ── 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()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("got %d, want 400: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBroadcast_MissingMessage_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/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa/broadcast",
|
||||
broadcastBody(`{}`))
|
||||
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_EmptyMessage_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/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)
|
||||
|
||||
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()
|
||||
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 TestBroadcast_BroadcastDisabled_Returns403(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupBroadcastDB(t)
|
||||
h := NewBroadcastHandler(newTestBroadcaster())
|
||||
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
mock.ExpectQuery(sqlBroadcastWorkspaceLookup).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"name", "broadcast_enabled"}).
|
||||
AddRow("test-workspace", false))
|
||||
|
||||
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()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Errorf("got %d, want 403: %s", w.Code, w.Body.String())
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet sqlmock expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBroadcast_NoRecipients_Success(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupBroadcastDB(t)
|
||||
h := NewBroadcastHandler(newTestBroadcaster())
|
||||
|
||||
wsID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
|
||||
mock.ExpectQuery(sqlBroadcastWorkspaceLookup).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"name", "broadcast_enabled"}).
|
||||
AddRow("test-workspace", true))
|
||||
|
||||
// No recipients (sender is the only non-removed workspace)
|
||||
mock.ExpectQuery(sqlBroadcastRecipients).
|
||||
WithArgs(wsID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}))
|
||||
|
||||
// Sender's own activity log: 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 everyone"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
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 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"
|
||||
|
||||
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"}).
|
||||
AddRow(recipient1).
|
||||
AddRow(recipient2))
|
||||
|
||||
// broadcast_receive: 3 args (recipientID, senderID, summary)
|
||||
mock.ExpectExec(sqlBroadcastReceiveInsert).
|
||||
WithArgs(recipient1, sqlmock.AnyArg(), sqlmock.AnyArg()).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
|
||||
mock.ExpectExec(sqlBroadcastReceiveInsert).
|
||||
WithArgs(recipient2, sqlmock.AnyArg(), sqlmock.AnyArg()).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
|
||||
// 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()
|
||||
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 TestBroadcast_RecipientInsertError_ContinuesAndSucceeds(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"
|
||||
|
||||
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"}).
|
||||
AddRow(recipient1).
|
||||
AddRow(recipient2))
|
||||
|
||||
// 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(sqlBroadcastReceiveInsert).
|
||||
WithArgs(recipient2, sqlmock.AnyArg(), sqlmock.AnyArg()).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
|
||||
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":"partial delivery"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
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 TestBroadcast_SenderActivityLogError_StillReturns200(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
mock := setupBroadcastDB(t)
|
||||
h := NewBroadcastHandler(newTestBroadcaster())
|
||||
|
||||
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)
|
||||
|
||||
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()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
// Handler logs error but still returns 200
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// ── 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)
|
||||
}
|
||||
}
|
||||
@@ -653,3 +653,239 @@ func TestSanitizeUTF8(t *testing.T) {
|
||||
t.Errorf("sanitizeUTF8 did not produce valid UTF-8: %x", []byte(out))
|
||||
}
|
||||
}
|
||||
|
||||
// ── extractResponseSummary coverage ───────────────────────────────────────────
|
||||
|
||||
func TestExtractResponseSummary_EmptyBody(t *testing.T) {
|
||||
s := New(nil, nil)
|
||||
if got := s.extractResponseSummary(nil); got != "" {
|
||||
t.Errorf("nil body: got %q, want %q", got, "")
|
||||
}
|
||||
if got := s.extractResponseSummary([]byte{}); got != "" {
|
||||
t.Errorf("empty body: got %q, want %q", got, "")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractResponseSummary_InvalidJSON(t *testing.T) {
|
||||
s := New(nil, nil)
|
||||
got := s.extractResponseSummary([]byte(`not json`))
|
||||
if got != "" {
|
||||
t.Errorf("invalid JSON: got %q, want %q", got, "")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractResponseSummary_NoResultKey(t *testing.T) {
|
||||
s := New(nil, nil)
|
||||
got := s.extractResponseSummary([]byte(`{"error": "oops"}`))
|
||||
if got != "" {
|
||||
t.Errorf("no result key: got %q, want %q", got, "")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractResponseSummary_EmptyResult(t *testing.T) {
|
||||
s := New(nil, nil)
|
||||
got := s.extractResponseSummary([]byte(`{"result": {}}`))
|
||||
if got != "" {
|
||||
t.Errorf("empty result: got %q, want %q", got, "")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractResponseSummary_NoPartsKey(t *testing.T) {
|
||||
s := New(nil, nil)
|
||||
got := s.extractResponseSummary([]byte(`{"result": {"data": "hello"}}`))
|
||||
if got != "" {
|
||||
t.Errorf("no parts key: got %q, want %q", got, "")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractResponseSummary_EmptyPartsArray(t *testing.T) {
|
||||
s := New(nil, nil)
|
||||
got := s.extractResponseSummary([]byte(`{"result": {"parts": []}}`))
|
||||
if got != "" {
|
||||
t.Errorf("empty parts: got %q, want %q", got, "")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractResponseSummary_PartsWithText(t *testing.T) {
|
||||
s := New(nil, nil)
|
||||
got := s.extractResponseSummary([]byte(`{"result": {"parts": [{"text": "Hello world"}]}}`))
|
||||
if got != "Hello world" {
|
||||
t.Errorf("got %q, want %q", got, "Hello world")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractResponseSummary_MultipleParts(t *testing.T) {
|
||||
// The function returns the FIRST non-empty text it finds.
|
||||
s := New(nil, nil)
|
||||
got := s.extractResponseSummary([]byte(`{"result": {"parts": [{"text": ""}, {"text": "second"}]}}`))
|
||||
if got != "second" {
|
||||
t.Errorf("got %q, want %q", got, "second")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractResponseSummary_NonStringText(t *testing.T) {
|
||||
s := New(nil, nil)
|
||||
got := s.extractResponseSummary([]byte(`{"result": {"parts": [{"text": 42}]}}`))
|
||||
if got != "" {
|
||||
t.Errorf("non-string text: got %q, want %q", got, "")
|
||||
}
|
||||
}
|
||||
|
||||
// ── isEmptyResponse coverage ─────────────────────────────────────────────────────
|
||||
|
||||
func TestIsEmptyResponse_NilAndEmpty(t *testing.T) {
|
||||
if !isEmptyResponse(nil) {
|
||||
t.Error("nil body should be empty")
|
||||
}
|
||||
if !isEmptyResponse([]byte{}) {
|
||||
t.Error("empty body should be empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsEmptyResponse_SentinelMarkers(t *testing.T) {
|
||||
cases := []string{
|
||||
`(no response generated)`,
|
||||
`"text": "(no response generated)"`,
|
||||
`"text":""`,
|
||||
`"text": ""`,
|
||||
}
|
||||
for _, marker := range cases {
|
||||
body := []byte(`{"result":{"parts":[{"text":"` + marker + `"}]}}`)
|
||||
if !isEmptyResponse(body) {
|
||||
t.Errorf("body with marker %q should be empty", marker)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsEmptyResponse_RealContent(t *testing.T) {
|
||||
// Any body containing a sentinel marker is treated as empty.
|
||||
// Bodies with no marker and with non-empty text are NOT empty.
|
||||
cases := []struct {
|
||||
body string
|
||||
isEmpty bool
|
||||
}{
|
||||
{`{"result":{"parts":[{"text":"Hello world"}]}}`, false},
|
||||
{`{"result":{"parts":[{"text":"goodbye"}]}}`, false},
|
||||
{`{"text":"hello"}`, false},
|
||||
{`{"result":{"parts":[]}}`, false},
|
||||
// sentinel markers trigger empty=true
|
||||
{`{"result":{"parts":[{"text":"(no response generated) plus more"}]}}`, true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
got := isEmptyResponse([]byte(tc.body))
|
||||
if got != tc.isEmpty {
|
||||
t.Errorf("isEmptyResponse(%q) = %v, want %v", tc.body, got, tc.isEmpty)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsEmptyResponse_PartialMarker(t *testing.T) {
|
||||
// The marker must appear as a complete substring. Partial matches don't count.
|
||||
body := []byte(`{"result":{"parts":[{"text":"(no response gen"}]}}`)
|
||||
if isEmptyResponse(body) {
|
||||
t.Error(`partial marker "(no response gen" should NOT match`)
|
||||
}
|
||||
}
|
||||
|
||||
// ── maybeSweepPhantomBusy coverage ─────────────────────────────────────────────
|
||||
|
||||
// phantomSweepInterval = 5 minutes. maybeSweepPhantomBusy skips the DB query
|
||||
// when lastSweepAt is within the interval.
|
||||
|
||||
func TestMaybeSweepPhantomBusy_SkipsWithinInterval(t *testing.T) {
|
||||
mock := setupTestDB(t)
|
||||
// No DB calls expected since we skip within the interval.
|
||||
|
||||
s := New(nil, nil)
|
||||
s.mu.Lock()
|
||||
s.lastSweepAt = time.Now() // just swept
|
||||
s.mu.Unlock()
|
||||
|
||||
s.maybeSweepPhantomBusy(context.Background())
|
||||
|
||||
// Verify no DB calls were made.
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unexpected DB call: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaybeSweepPhantomBusy_RunsWhenStale(t *testing.T) {
|
||||
mock := setupTestDB(t)
|
||||
|
||||
// Return a row so the sweep logs one reset.
|
||||
rows := sqlmock.NewRows([]string{"id", "name"}).
|
||||
AddRow("ws-phantom", "Phantom Agent")
|
||||
mock.ExpectQuery(`UPDATE workspaces`).
|
||||
WillReturnRows(rows)
|
||||
|
||||
s := New(nil, nil)
|
||||
s.mu.Lock()
|
||||
s.lastSweepAt = time.Now().Add(-6 * time.Minute) // older than 5 min interval
|
||||
s.mu.Unlock()
|
||||
|
||||
s.maybeSweepPhantomBusy(context.Background())
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet DB expectations: %v", err)
|
||||
}
|
||||
|
||||
// Verify lastSweepAt was updated.
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
if time.Since(s.lastSweepAt) > time.Second {
|
||||
t.Error("lastSweepAt should be updated to time.Now() after a sweep")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaybeSweepPhantomBusy_StaleFirstSweep(t *testing.T) {
|
||||
// Zero time.Time is treated as "never swept" — time.Since(zero) is many years,
|
||||
// which is > 5 min, so the sweep runs on first call.
|
||||
mock := setupTestDB(t)
|
||||
|
||||
rows := sqlmock.NewRows([]string{"id", "name"})
|
||||
mock.ExpectQuery(`UPDATE workspaces`).
|
||||
WillReturnRows(rows)
|
||||
|
||||
s := New(nil, nil)
|
||||
// lastSweepAt is zero (never swept) — this should trigger the sweep.
|
||||
s.maybeSweepPhantomBusy(context.Background())
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet DB expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// ── sweepPhantomBusy DB-error coverage ──────────────────────────────────────────
|
||||
|
||||
func TestSweepPhantomBusy_QueryError(t *testing.T) {
|
||||
mock := setupTestDB(t)
|
||||
|
||||
mock.ExpectQuery(`UPDATE workspaces`).
|
||||
WillReturnError(errDBDown)
|
||||
|
||||
s := New(nil, nil)
|
||||
// Should not panic — error is logged and function returns.
|
||||
s.sweepPhantomBusy(context.Background())
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet DB expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSweepPhantomBusy_RowsError(t *testing.T) {
|
||||
// Query succeeds but rows.Next() returns an error.
|
||||
mock := setupTestDB(t)
|
||||
|
||||
rows := sqlmock.NewRows([]string{"id", "name"}).
|
||||
AddRow("ws-1", "Test Agent").
|
||||
RowError(0, errDBDown)
|
||||
mock.ExpectQuery(`UPDATE workspaces`).
|
||||
WillReturnRows(rows)
|
||||
|
||||
s := New(nil, nil)
|
||||
s.sweepPhantomBusy(context.Background())
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet DB expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user