diff --git a/mockingjay/server.go b/mockingjay/server.go index ecfab050..19403aef 100644 --- a/mockingjay/server.go +++ b/mockingjay/server.go @@ -21,11 +21,16 @@ func NewServer(endpoints []FakeEndpoint) *Server { return s } -func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { +const requestsURL = "/requests" +const endpointsURL = "/mj-endpoints" - if r.RequestURI == "/requests" { +func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { + switch r.URL.String() { + case endpointsURL: + s.serveEndpoints(w) + case requestsURL: s.listAvailableRequests(w) - } else { + default: mjRequest := NewRequest(r) s.requests = append(s.requests, mjRequest) cannedResponse := s.getResponse(mjRequest) @@ -69,3 +74,14 @@ func requestMatches(a Request, b Request) bool { return bodyOk && urlOk && methodOk && headersOk } + +func (s *Server) serveEndpoints(w http.ResponseWriter) { + endpointsBody, err := json.Marshal(s.endpoints) + + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + } + + w.Write(endpointsBody) + w.Header().Set("Content-Type", "application/json") +} diff --git a/mockingjay/server_test.go b/mockingjay/server_test.go index 653094ce..316bde47 100644 --- a/mockingjay/server_test.go +++ b/mockingjay/server_test.go @@ -1,8 +1,10 @@ package mockingjay import ( + "encoding/json" "net/http" "net/http/httptest" + "reflect" "strings" "testing" ) @@ -238,3 +240,32 @@ func TestItRespectsURLencoding(t *testing.T) { t.Errorf("It looks like it didnt respect the escaped url, got a %d", responseReader.Code) } } + +func TestItReturnsListOfEndpoints(t *testing.T) { + endpoint := FakeEndpoint{testEndpointName, cdcDisabled, Request{testURL, "GET", nil, ""}, response{http.StatusCreated, cannedResponse, nil}} + server := NewServer([]FakeEndpoint{endpoint}) + + request, _ := http.NewRequest("GET", endpointsURL, nil) + responseReader := httptest.NewRecorder() + + server.ServeHTTP(responseReader, request) + + if responseReader.Code != http.StatusOK { + t.Error("Didnt get a 200 from the endpoints url, got", responseReader.Code) + } + + if responseReader.HeaderMap["Content-Type"][0] != "application/json" { + t.Error("Expected content type header to be set to json") + } + + var endpointResponse []FakeEndpoint + err := json.Unmarshal(responseReader.Body.Bytes(), &endpointResponse) + + if err != nil { + t.Fatal("Unable to parse JSON from endpoints URL", err) + } + + if !reflect.DeepEqual(endpointResponse[0], endpoint) { + t.Error("The endpoint returned doesnt match what the server was set up with, got", endpointResponse, "expected", endpoint) + } +}