118 lines
2.7 KiB
Go
118 lines
2.7 KiB
Go
package handlers
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"git.threesix.ai/jordan/sp4-v2-1770499323/pkg/logging"
|
|
"git.threesix.ai/jordan/sp4-v2-1770499323/services/chat-svc/internal/port"
|
|
)
|
|
|
|
// mockTaskProducer implements port.TaskProducer for testing.
|
|
type mockTaskProducer struct {
|
|
lastAction string
|
|
lastPayload map[string]any
|
|
jobID string
|
|
err error
|
|
}
|
|
|
|
var _ port.TaskProducer = (*mockTaskProducer)(nil)
|
|
|
|
func (m *mockTaskProducer) EnqueueTask(ctx context.Context, action string, payload map[string]any) (string, error) {
|
|
m.lastAction = action
|
|
m.lastPayload = payload
|
|
if m.err != nil {
|
|
return "", m.err
|
|
}
|
|
return m.jobID, nil
|
|
}
|
|
|
|
func TestTask_Enqueue(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
body any
|
|
producer *mockTaskProducer
|
|
wantStatus int
|
|
wantJobID string
|
|
}{
|
|
{
|
|
name: "valid request",
|
|
body: EnqueueRequest{
|
|
Action: "send_notification",
|
|
Payload: map[string]any{"user_id": "user-123", "message": "Hello"},
|
|
},
|
|
producer: &mockTaskProducer{jobID: "job-456"},
|
|
wantStatus: http.StatusAccepted,
|
|
wantJobID: "job-456",
|
|
},
|
|
{
|
|
name: "empty body",
|
|
body: nil,
|
|
producer: &mockTaskProducer{},
|
|
wantStatus: http.StatusBadRequest,
|
|
},
|
|
{
|
|
name: "producer error",
|
|
body: EnqueueRequest{
|
|
Action: "send_notification",
|
|
},
|
|
producer: &mockTaskProducer{err: errors.New("queue unavailable")},
|
|
wantStatus: http.StatusInternalServerError,
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
handler := NewTask(tt.producer, logging.Nop())
|
|
|
|
var body []byte
|
|
if tt.body != nil {
|
|
var err error
|
|
body, err = json.Marshal(tt.body)
|
|
if err != nil {
|
|
t.Fatalf("failed to marshal body: %v", err)
|
|
}
|
|
}
|
|
|
|
req := httptest.NewRequest(http.MethodPost, "/api/chat-svc/tasks", bytes.NewReader(body))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
w := httptest.NewRecorder()
|
|
|
|
err := handler.Enqueue(w, req)
|
|
if err != nil {
|
|
if tt.wantStatus == http.StatusAccepted {
|
|
t.Fatalf("unexpected error: %v", err)
|
|
}
|
|
return
|
|
}
|
|
|
|
if tt.wantStatus != http.StatusAccepted {
|
|
t.Fatalf("expected error but got nil")
|
|
}
|
|
|
|
if w.Code != http.StatusAccepted {
|
|
t.Errorf("expected status %d, got %d", http.StatusAccepted, w.Code)
|
|
}
|
|
|
|
var resp map[string]any
|
|
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
|
|
t.Fatalf("failed to decode response: %v", err)
|
|
}
|
|
|
|
data, ok := resp["data"].(map[string]any)
|
|
if !ok {
|
|
t.Fatal("expected 'data' field in response")
|
|
}
|
|
|
|
if data["job_id"] != tt.wantJobID {
|
|
t.Errorf("expected job_id %q, got %q", tt.wantJobID, data["job_id"])
|
|
}
|
|
})
|
|
}
|
|
}
|