100 lines
2.4 KiB
Go
100 lines
2.4 KiB
Go
package api
|
|
|
|
import (
|
|
"3588AdminBackend/internal/config"
|
|
"3588AdminBackend/internal/models"
|
|
"3588AdminBackend/internal/service"
|
|
"bytes"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
)
|
|
|
|
func TestHandler_ListDevices(t *testing.T) {
|
|
cfg := &config.Config{}
|
|
agent := service.NewAgentClient(cfg)
|
|
reg := service.NewRegistryService(cfg, agent)
|
|
reg.UpdateDevice(&models.Device{DeviceID: "dev1", IP: "127.0.0.1"})
|
|
|
|
h := NewHandler(nil, reg, agent, nil, nil)
|
|
|
|
req, _ := http.NewRequest("GET", "/api/devices", nil)
|
|
rr := httptest.NewRecorder()
|
|
|
|
h.ListDevices(rr, req)
|
|
|
|
if rr.Code != http.StatusOK {
|
|
t.Errorf("expected status 200, got %d", rr.Code)
|
|
}
|
|
|
|
var resp map[string][]models.Device
|
|
json.Unmarshal(rr.Body.Bytes(), &resp)
|
|
|
|
if len(resp["items"]) != 1 {
|
|
t.Errorf("expected 1 item, got %d", len(resp["items"]))
|
|
}
|
|
}
|
|
|
|
func TestHandler_CreateTask(t *testing.T) {
|
|
cfg := &config.Config{Concurrency: 1}
|
|
agent := service.NewAgentClient(cfg)
|
|
reg := service.NewRegistryService(cfg, agent)
|
|
tasks := service.NewTaskService(cfg, agent, reg)
|
|
|
|
h := NewHandler(nil, reg, agent, tasks, nil)
|
|
|
|
body := map[string]interface{}{
|
|
"type": "config_apply",
|
|
"device_ids": []string{"dev1"},
|
|
"payload": map[string]string{"foo": "bar"},
|
|
}
|
|
b, _ := json.Marshal(body)
|
|
|
|
req, _ := http.NewRequest("POST", "/api/tasks", bytes.NewBuffer(b))
|
|
rr := httptest.NewRecorder()
|
|
|
|
h.CreateTask(rr, req)
|
|
|
|
if rr.Code != http.StatusOK {
|
|
t.Errorf("expected status 200, got %d", rr.Code)
|
|
}
|
|
|
|
var resp map[string]string
|
|
json.Unmarshal(rr.Body.Bytes(), &resp)
|
|
|
|
if resp["task_id"] == "" {
|
|
t.Error("expected task_id in response")
|
|
}
|
|
}
|
|
|
|
func TestHandler_ListTasks(t *testing.T) {
|
|
cfg := &config.Config{Concurrency: 1}
|
|
agent := service.NewAgentClient(cfg)
|
|
reg := service.NewRegistryService(cfg, agent)
|
|
tasks := service.NewTaskService(cfg, agent, reg)
|
|
|
|
// Create a task so list is non-empty
|
|
if _, err := tasks.CreateTask("config_apply", []string{"dev1"}, map[string]string{"foo": "bar"}); err != nil {
|
|
t.Fatalf("failed to create task: %v", err)
|
|
}
|
|
|
|
h := NewHandler(nil, reg, agent, tasks, nil)
|
|
|
|
req, _ := http.NewRequest("GET", "/api/tasks", nil)
|
|
rr := httptest.NewRecorder()
|
|
|
|
h.ListTasks(rr, req)
|
|
|
|
if rr.Code != http.StatusOK {
|
|
t.Errorf("expected status 200, got %d", rr.Code)
|
|
}
|
|
|
|
var resp map[string][]models.Task
|
|
json.Unmarshal(rr.Body.Bytes(), &resp)
|
|
|
|
if len(resp["items"]) < 1 {
|
|
t.Errorf("expected at least 1 item, got %d", len(resp["items"]))
|
|
}
|
|
}
|