aides-repo-api/internal/controllers/taskcontroller/create_test.go
Maxim Slipenko e4f9743dea
Some checks failed
Format and Lint / format-check (push) Failing after 2s
Format and Lint / test (push) Successful in 52s
chore: change code.alt-gnome to code.aides.space
2025-01-07 17:54:16 +03:00

84 lines
1.9 KiB
Go

package taskcontroller_test
import (
"bytes"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
"gorm.io/gorm"
"code.aides.space/aides-infra/aides-repo-api/internal/controllers/taskcontroller"
"code.aides.space/aides-infra/aides-repo-api/internal/models"
)
func TestCreate(t *testing.T) {
tests := []struct {
name string
inputBody interface{}
mockService *TaskServiceMock
expectedStatus int
}{
{
name: "Valid request",
inputBody: map[string]string{
"repo": "example-foo",
},
mockService: &TaskServiceMock{
CreateFunc: func(repo string) (*models.Task, error) {
return &models.Task{
Model: gorm.Model{
ID: 1,
},
Status: models.StatusInProgress,
}, nil
},
},
expectedStatus: http.StatusOK,
},
{
name: "Invalid JSON",
inputBody: "invalid-json",
mockService: &TaskServiceMock{},
expectedStatus: http.StatusBadRequest,
},
{
name: "Service error",
inputBody: map[string]string{
"repo": "example-foo",
},
mockService: &TaskServiceMock{
CreateFunc: func(repo string) (*models.Task, error) {
return nil, errors.New("internal error")
},
},
expectedStatus: http.StatusInternalServerError,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
controller := taskcontroller.New(tt.mockService)
var body []byte
if tt.inputBody != nil {
body, _ = json.Marshal(tt.inputBody)
}
req, err := http.NewRequest(http.MethodPost, "/", bytes.NewBuffer(body))
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
rr := httptest.NewRecorder()
handler := http.HandlerFunc(controller.Create)
handler.ServeHTTP(rr, req)
if status := rr.Code; status != tt.expectedStatus {
t.Errorf("handler returned wrong status code: got %v want %v", status, tt.expectedStatus)
}
})
}
}