spud/daemon/api_test.go

99 lines
2.4 KiB
Go
Raw Normal View History

2024-10-02 02:56:25 +00:00
package daemon
import (
"context"
2024-10-02 02:56:25 +00:00
"net/http"
"net/http/httptest"
service_definition "spud/service_definition"
2024-10-02 02:56:25 +00:00
"testing"
)
type MockClient struct {
calls struct {
Create []service_definition.ServiceDefinition
Stop []string
}
}
func (c *MockClient) Create(s service_definition.ServiceDefinition) {
c.calls.Create = append(c.calls.Create, s)
}
func (c *MockClient) Stop(n string) {
c.calls.Stop = append(c.calls.Stop, n)
}
func TestServiceListPostCreatesService(t *testing.T) {
mockClient := &MockClient{}
daemonContext := context.WithValue(context.Background(), "client", mockClient)
req := httptest.NewRequest(http.MethodPost, "/service/", nil)
resp := httptest.NewRecorder()
ServiceList(resp, req, daemonContext)
response := resp.Result()
if response.StatusCode != 201 {
t.Errorf("Expected status 201, got %d", response.StatusCode)
}
if len(mockClient.calls.Create) != 1 {
t.Error("Expected a call to Create")
}
}
2024-10-02 02:56:25 +00:00
func TestServiceListUnsupportedMethods(t *testing.T) {
for _, method := range []string{http.MethodGet, http.MethodPut, http.MethodHead, http.MethodDelete} {
2024-10-02 02:56:25 +00:00
t.Run(method, func(t *testing.T) {
req := httptest.NewRequest(method, "/service/", nil)
2024-10-02 02:56:25 +00:00
resp := httptest.NewRecorder()
ServiceList(resp, req, context.Background())
2024-10-02 02:56:25 +00:00
response := resp.Result()
if response.StatusCode != 501 {
t.Errorf("Expected status 501, got %d.", response.StatusCode)
}
})
}
}
func TestServiceDetailsDeleteStopsService(t *testing.T) {
mockClient := &MockClient{}
daemonContext := context.WithValue(context.Background(), "client", mockClient)
req := httptest.NewRequest(http.MethodDelete, "/service/service-name/", nil)
resp := httptest.NewRecorder()
ServiceDetails(resp, req, daemonContext)
response := resp.Result()
if response.StatusCode != 204 {
t.Errorf("Expected status 204, got %d", response.StatusCode)
}
if len(mockClient.calls.Stop) != 1 {
t.Error("Expected a call to Stop")
}
}
func TestServiceDetailUnsupportedMethods(t *testing.T) {
for _, method := range []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodHead} {
t.Run(method, func(t *testing.T) {
req := httptest.NewRequest(method, "/service/service-name/", nil)
resp := httptest.NewRecorder()
ServiceDetails(resp, req, context.Background())
response := resp.Result()
if response.StatusCode != 501 {
t.Errorf("Expected status 501, got %d.", response.StatusCode)
}
})
}
}