test(render): add comprehensive tests for MsgPack render

This commit is contained in:
AmirHossein Fallah 2026-02-16 14:45:39 +03:30 committed by AmirHossein Fallah
parent f5c267d2f8
commit fd02a3a487

View File

@ -8,6 +8,7 @@ package render
import (
"bytes"
"errors"
"net/http/httptest"
"testing"
@ -16,9 +17,6 @@ import (
"github.com/ugorji/go/codec"
)
// TODO unit tests
// test errors
func TestRenderMsgPack(t *testing.T) {
w := httptest.NewRecorder()
data := map[string]any{
@ -42,3 +40,43 @@ func TestRenderMsgPack(t *testing.T) {
assert.Equal(t, w.Body.String(), buf.String())
assert.Equal(t, "application/msgpack; charset=utf-8", w.Header().Get("Content-Type"))
}
func TestWriteMsgPack(t *testing.T) {
w := httptest.NewRecorder()
data := map[string]any{
"foo": "bar",
"num": 42,
}
err := WriteMsgPack(w, data)
require.NoError(t, err)
assert.Equal(t, "application/msgpack; charset=utf-8", w.Header().Get("Content-Type"))
// Verify the encoded data is correct
h := new(codec.MsgpackHandle)
buf := bytes.NewBuffer([]byte{})
err = codec.NewEncoder(buf, h).Encode(data)
require.NoError(t, err)
assert.Equal(t, buf.String(), w.Body.String())
}
type failWriter struct {
*httptest.ResponseRecorder
}
func (w *failWriter) Write(data []byte) (int, error) {
return 0, errors.New("write error")
}
func TestRenderMsgPackError(t *testing.T) {
w := httptest.NewRecorder()
data := map[string]any{
"foo": "bar",
}
err := (MsgPack{data}).Render(&failWriter{w})
require.Error(t, err)
assert.Contains(t, err.Error(), "write error")
}