package daemon import ( "context" "net/http" "net/http/httptest" service_definition "spud/service_definition" "testing" ) type MockClient struct { calls struct { Create []service_definition.ServiceDefinition Stop []string } } func (c *MockClient) Create(s service_definition.ServiceDefinition) error { c.calls.Create = append(c.calls.Create, s) return nil } func (c *MockClient) Stop(n string) error { c.calls.Stop = append(c.calls.Stop, n) return nil } 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") } } func TestServiceListUnsupportedMethods(t *testing.T) { for _, method := range []string{http.MethodGet, http.MethodPut, http.MethodHead, http.MethodDelete} { t.Run(method, func(t *testing.T) { req := httptest.NewRequest(method, "/service/", nil) resp := httptest.NewRecorder() ServiceList(resp, req, context.Background()) 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) } }) } }