mirror of
https://github.com/outbackdingo/matchbox.git
synced 2026-01-27 10:19:35 +00:00
59 lines
1.5 KiB
Go
59 lines
1.5 KiB
Go
package api
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
)
|
|
|
|
func TestRenderJSON(t *testing.T) {
|
|
w := httptest.NewRecorder()
|
|
data := map[string][]string{
|
|
"a": []string{"b", "c"},
|
|
}
|
|
renderJSON(w, data)
|
|
assert.Equal(t, http.StatusOK, w.Code)
|
|
assert.Equal(t, jsonContentType, w.HeaderMap.Get(contentType))
|
|
assert.Equal(t, `{"a":["b","c"]}`, w.Body.String())
|
|
}
|
|
|
|
func TestRenderJSON_EncodingError(t *testing.T) {
|
|
w := httptest.NewRecorder()
|
|
// channels cannot be JSON encoded
|
|
renderJSON(w, make(chan struct{}))
|
|
assert.Equal(t, http.StatusInternalServerError, w.Code)
|
|
assert.Empty(t, w.Body.String())
|
|
}
|
|
|
|
func TestRenderJSON_EncodeError(t *testing.T) {
|
|
w := httptest.NewRecorder()
|
|
// channels cannot be JSON encoded
|
|
renderJSON(w, make(chan struct{}))
|
|
assert.Equal(t, http.StatusInternalServerError, w.Code)
|
|
assert.Empty(t, w.Body.String())
|
|
}
|
|
|
|
func TestRenderJSON_WriteError(t *testing.T) {
|
|
w := NewUnwriteableResponseWriter()
|
|
renderJSON(w, map[string]string{"a": "b"})
|
|
assert.Equal(t, http.StatusInternalServerError, w.Code)
|
|
assert.Empty(t, w.Body.String())
|
|
}
|
|
|
|
// UnwritableResponseWriter is a http.ResponseWriter for testing Write
|
|
// failures.
|
|
type UnwriteableResponseWriter struct {
|
|
*httptest.ResponseRecorder
|
|
}
|
|
|
|
func NewUnwriteableResponseWriter() *UnwriteableResponseWriter {
|
|
return &UnwriteableResponseWriter{httptest.NewRecorder()}
|
|
}
|
|
|
|
func (w *UnwriteableResponseWriter) Write([]byte) (int, error) {
|
|
return 0, fmt.Errorf("Unwriteable ResponseWriter")
|
|
}
|