Skip to content
Myr

render_msgpack_test.go

This file

Path

render/render_msgpack_test.go

80 lines · 1.9 KiB · Go

Last changed by

test(render): add comprehensive tests for MsgPack render (#4537)Amirhfbefore adoption216a4a7

History of this file

Take it

1// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2// Use of this source code is governed by a MIT style3// license that can be found in the LICENSE file.45//go:build !nomsgpack67package render89import (10	"errors"11	"net/http/httptest"12	"testing"1314	"github.com/stretchr/testify/assert"15	"github.com/stretchr/testify/require"16	"github.com/ugorji/go/codec"17)1819func TestRenderMsgPack(t *testing.T) {20	w := httptest.NewRecorder()21	data := map[string]any{22		"foo": "bar",23	}2425	(MsgPack{data}).WriteContentType(w)26	assert.Equal(t, "application/msgpack; charset=utf-8", w.Header().Get("Content-Type"))2728	err := (MsgPack{data}).Render(w)2930	require.NoError(t, err)3132	var decoded map[string]any33	var mh codec.MsgpackHandle34	mh.RawToString = true35	err = codec.NewDecoderBytes(w.Body.Bytes(), &mh).Decode(&decoded)36	require.NoError(t, err)37	assert.Equal(t, data, decoded)38	assert.Equal(t, "application/msgpack; charset=utf-8", w.Header().Get("Content-Type"))39}4041func TestWriteMsgPack(t *testing.T) {42	w := httptest.NewRecorder()43	data := map[string]any{44		"foo": "bar",45		"num": 42,46	}4748	err := WriteMsgPack(w, data)49	require.NoError(t, err)5051	assert.Equal(t, "application/msgpack; charset=utf-8", w.Header().Get("Content-Type"))5253	var decoded map[string]any54	var mh codec.MsgpackHandle55	mh.RawToString = true56	err = codec.NewDecoderBytes(w.Body.Bytes(), &mh).Decode(&decoded)57	require.NoError(t, err)58	assert.Len(t, decoded, 2)59	assert.Equal(t, "bar", decoded["foo"])60	assert.EqualValues(t, 42, decoded["num"])61}6263type failWriter struct {64	*httptest.ResponseRecorder65}6667func (w *failWriter) Write(data []byte) (int, error) {68	return 0, errors.New("write error")69}7071func TestRenderMsgPackError(t *testing.T) {72	w := httptest.NewRecorder()73	data := map[string]any{74		"foo": "bar",75	}7677	err := (MsgPack{data}).Render(&failWriter{w})78	require.Error(t, err)79	assert.Contains(t, err.Error(), "write error")80}