40 lines
1.0 KiB
Go
40 lines
1.0 KiB
Go
package handlers
|
|
|
|
import "bytes"
|
|
import "encoding/json"
|
|
import "net/http"
|
|
import "net/http/httptest"
|
|
import "testing"
|
|
|
|
func TestWriteJSON(t *testing.T) {
|
|
var recorder *httptest.ResponseRecorder
|
|
var payload map[string]string
|
|
recorder = httptest.NewRecorder()
|
|
payload = map[string]string{"status": "ok"}
|
|
WriteJSON(recorder, http.StatusAccepted, payload)
|
|
if recorder.Code != http.StatusAccepted {
|
|
t.Fatalf("unexpected status: %d", recorder.Code)
|
|
}
|
|
if recorder.Header().Get("Content-Type") != "application/json" {
|
|
t.Fatalf("unexpected content-type: %s", recorder.Header().Get("Content-Type"))
|
|
}
|
|
}
|
|
|
|
func TestDecodeJSON(t *testing.T) {
|
|
var body []byte
|
|
var req *http.Request
|
|
var target struct {
|
|
Name string `json:"name"`
|
|
}
|
|
var err error
|
|
body, _ = json.Marshal(map[string]string{"name": "bob"})
|
|
req = httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(body))
|
|
err = DecodeJSON(req, &target)
|
|
if err != nil {
|
|
t.Fatalf("DecodeJSON error: %v", err)
|
|
}
|
|
if target.Name != "bob" {
|
|
t.Fatalf("unexpected decoded value: %s", target.Name)
|
|
}
|
|
}
|