tests and cleanup

This commit is contained in:
Livio Amstutz 2021-10-28 15:21:47 +02:00
parent d0b8dfe340
commit 1d72aff00a
11 changed files with 468 additions and 123 deletions

View file

@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"net/http"
"reflect"
)
func MarshalJSON(w http.ResponseWriter, i interface{}) {
@ -14,7 +15,7 @@ func MarshalJSON(w http.ResponseWriter, i interface{}) {
func MarshalJSONWithStatus(w http.ResponseWriter, i interface{}, status int) {
w.Header().Set("content-type", "application/json")
w.WriteHeader(status)
if i == nil {
if i == nil || (reflect.ValueOf(i).Kind() == reflect.Ptr && reflect.ValueOf(i).IsNil()) {
return
}
err := json.NewEncoder(w).Encode(i)

View file

@ -2,7 +2,10 @@ package http
import (
"bytes"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestConcatenateJSON(t *testing.T) {
@ -88,3 +91,66 @@ func TestConcatenateJSON(t *testing.T) {
})
}
}
func TestMarshalJSONWithStatus(t *testing.T) {
type args struct {
i interface{}
status int
}
type res struct {
statusCode int
body string
}
tests := []struct {
name string
args args
res res
}{
{
"empty ok",
args{
nil,
200,
},
res{
200,
"",
},
},
{
"string ok",
args{
"ok",
200,
},
res{
200,
`"ok"
`,
},
},
{
"struct ok",
args{
struct {
Test string `json:"test"`
}{"ok"},
200,
},
res{
200,
`{"test":"ok"}
`,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
w := httptest.NewRecorder()
MarshalJSONWithStatus(w, tt.args.i, tt.args.status)
assert.Equal(t, tt.res.statusCode, w.Result().StatusCode)
assert.Equal(t, "application/json", w.Header().Get("content-type"))
assert.Equal(t, tt.res.body, w.Body.String())
})
}
}