Skip to content

Commit

Permalink
Added mj-endpoints URL for future JS based UI fun
Browse files Browse the repository at this point in the history
  • Loading branch information
quii committed Nov 7, 2015
1 parent eeae306 commit 13adeb5
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 3 deletions.
22 changes: 19 additions & 3 deletions mockingjay/server.go
Expand Up @@ -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)
Expand Down Expand Up @@ -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")
}
31 changes: 31 additions & 0 deletions mockingjay/server_test.go
@@ -1,8 +1,10 @@
package mockingjay

import (
"encoding/json"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
)
Expand Down Expand Up @@ -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)
}
}

0 comments on commit 13adeb5

Please sign in to comment.