test(render): improve test coverage

This commit is contained in:
2024-03-17 23:07:12 +00:00
parent 2ad77f0b1b
commit 7df40b1578
12 changed files with 648 additions and 62 deletions

View File

@@ -2,6 +2,8 @@ package render_test
import (
"bytes"
"encoding/json"
"errors"
"testing"
"github.com/jimeh/go-render"
@@ -9,6 +11,17 @@ import (
"github.com/stretchr/testify/require"
)
type mockJSONMarshaler struct {
data []byte
err error
}
var _ json.Marshaler = (*mockJSONMarshaler)(nil)
func (mjm *mockJSONMarshaler) MarshalJSON() ([]byte, error) {
return mjm.data, mjm.err
}
func TestJSON_Render(t *testing.T) {
tests := []struct {
name string
@@ -29,18 +42,35 @@ func TestJSON_Render(t *testing.T) {
{
name: "simple object with pretty",
pretty: true,
indent: " ",
value: map[string]int{"age": 30},
want: "{\n \"age\": 30\n}\n",
},
{
name: "with prefix and indent",
name: "pretty with prefix and indent",
pretty: true,
prefix: "// ",
indent: "\t",
value: map[string]int{"age": 30},
want: "{\n// \t\"age\": 30\n// }\n",
},
{
name: "prefix and indent without pretty",
pretty: false,
prefix: "// ",
indent: "\t",
value: map[string]int{"age": 30},
want: "{\"age\":30}\n",
},
{
name: "implements json.Marshaler",
value: &mockJSONMarshaler{data: []byte(`{"age":30}`)},
want: "{\"age\":30}\n",
},
{
name: "error from json.Marshaler",
value: &mockJSONMarshaler{err: errors.New("marshal error!!1")},
wantErrIs: []error{render.Err},
},
{
name: "invalid value",
pretty: false,
@@ -49,7 +79,6 @@ func TestJSON_Render(t *testing.T) {
wantErrIs: []error{render.Err},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
j := &render.JSON{
@@ -57,9 +86,10 @@ func TestJSON_Render(t *testing.T) {
Prefix: tt.prefix,
Indent: tt.indent,
}
var buf bytes.Buffer
err := j.Render(&buf, tt.value)
got := buf.String()
if tt.wantErr != "" {
require.Error(t, err)
@@ -71,7 +101,6 @@ func TestJSON_Render(t *testing.T) {
if tt.wantErr == "" && len(tt.wantErrIs) == 0 {
require.NoError(t, err)
got := buf.String()
assert.Equal(t, tt.want, got)
}
})