85 lines
1.9 KiB
Go
85 lines
1.9 KiB
Go
|
package taskcontroller_test
|
||
|
|
||
|
import (
|
||
|
"bytes"
|
||
|
"encoding/json"
|
||
|
"errors"
|
||
|
"net/http"
|
||
|
"net/http/httptest"
|
||
|
"testing"
|
||
|
|
||
|
"gorm.io/gorm"
|
||
|
|
||
|
"code.alt-gnome.ru/aides-infra/aides-repo-api/internal/controllers/taskcontroller"
|
||
|
"code.alt-gnome.ru/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)
|
||
|
}
|
||
|
})
|
||
|
}
|
||
|
}
|