76 lines
1.6 KiB
Go
76 lines
1.6 KiB
Go
package server
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"gopkg.in/mgo.v2/bson"
|
|
)
|
|
|
|
func TestResponse(t *testing.T) {
|
|
cases := map[string]struct {
|
|
foo func(*REST, http.ResponseWriter)
|
|
body string
|
|
status int
|
|
}{
|
|
"OK": {
|
|
foo: func(rest *REST, w http.ResponseWriter) {
|
|
rest.respOK(w)
|
|
},
|
|
body: `{"ok":true}`,
|
|
status: http.StatusOK,
|
|
},
|
|
"not found": {
|
|
foo: func(rest *REST, w http.ResponseWriter) {
|
|
rest.respNotFound(w)
|
|
},
|
|
body: `{"error":"not found"}`,
|
|
status: http.StatusNotFound,
|
|
},
|
|
"conflict": {
|
|
foo: func(rest *REST, w http.ResponseWriter) {
|
|
rest.respConflict(w)
|
|
},
|
|
body: `{"error":"collision found"}`,
|
|
status: http.StatusConflict,
|
|
},
|
|
"error": {
|
|
foo: func(rest *REST, w http.ResponseWriter) {
|
|
rest.respError(w, errors.New("my err"))
|
|
},
|
|
body: `{"error":"my err"}`,
|
|
status: http.StatusInternalServerError,
|
|
},
|
|
"bad req": {
|
|
foo: func(rest *REST, w http.ResponseWriter) {
|
|
rest.respBadRequest(w, "bad dog")
|
|
},
|
|
body: `{"error":"bad dog"}`,
|
|
status: http.StatusBadRequest,
|
|
},
|
|
}
|
|
|
|
for name, d := range cases {
|
|
c := d
|
|
t.Run(name, func(t *testing.T) {
|
|
rest := &REST{}
|
|
w := httptest.NewRecorder()
|
|
c.foo(rest, w)
|
|
if w.Code != c.status {
|
|
t.Fatalf("want status %d, got %d", c.status, w.Code)
|
|
}
|
|
var m bson.M
|
|
if err := json.NewDecoder(w.Body).Decode(&m); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
body, _ := json.Marshal(m)
|
|
if s := string(body); s != c.body {
|
|
t.Fatalf("want body %q, got %q", c.body, s)
|
|
}
|
|
})
|
|
}
|
|
}
|