kat/internal/api/node_status_handler_test.go
Tanishq Dubey 92fb052594
All checks were successful
Unit Tests / unit-tests (pull_request) Successful in 9m58s
Integration Tests / integration-tests (pull_request) Successful in 9m58s
more fixes before final part
2025-05-18 11:35:22 -04:00

107 lines
2.7 KiB
Go

package api
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
func TestNodeStatusHandler(t *testing.T) {
// Create mock state store
mockStore := new(MockStateStore)
mockStore.On("Put", mock.Anything, mock.MatchedBy(func(key string) bool {
return key == "/kat/nodes/status/test-node"
}), mock.Anything).Return(nil)
// Create node status handler
handler := NewNodeStatusHandler(mockStore)
// Create test request
statusReq := NodeStatusRequest{
NodeName: "test-node",
NodeUID: "test-uid",
Timestamp: time.Now(),
Resources: struct {
Capacity map[string]string `json:"capacity"`
Allocatable map[string]string `json:"allocatable"`
}{
Capacity: map[string]string{
"cpu": "2000m",
"memory": "4096Mi",
},
Allocatable: map[string]string{
"cpu": "1800m",
"memory": "3800Mi",
},
},
OverlayNetwork: struct {
Status string `json:"status"`
LastPeerSync string `json:"lastPeerSync"`
}{
Status: "connected",
LastPeerSync: time.Now().Format(time.RFC3339),
},
}
reqBody, err := json.Marshal(statusReq)
if err != nil {
t.Fatalf("Failed to marshal status request: %v", err)
}
// Create HTTP request
req := httptest.NewRequest("POST", "/v1alpha1/nodes/test-node/status", bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
// Call handler
handler(w, req)
// Check response
resp := w.Result()
defer resp.Body.Close()
assert.Equal(t, http.StatusOK, resp.StatusCode)
// Verify mock was called
mockStore.AssertExpectations(t)
}
func TestNodeStatusHandlerNameMismatch(t *testing.T) {
// Create mock state store
mockStore := new(MockStateStore)
// Create node status handler
handler := NewNodeStatusHandler(mockStore)
// Create test request with mismatched node name
statusReq := NodeStatusRequest{
NodeName: "wrong-node", // This doesn't match the URL path
NodeUID: "test-uid",
Timestamp: time.Now(),
}
reqBody, err := json.Marshal(statusReq)
if err != nil {
t.Fatalf("Failed to marshal status request: %v", err)
}
// Create HTTP request
req := httptest.NewRequest("POST", "/v1alpha1/nodes/test-node/status", bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
// Call handler
handler(w, req)
// Check response - should be bad request due to name mismatch
resp := w.Result()
defer resp.Body.Close()
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
// Verify mock was not called
mockStore.AssertNotCalled(t, "Put", mock.Anything, mock.Anything, mock.Anything)
}