Skip to content

Commit

Permalink
Test marshalling empty structs and slices (#46)
Browse files Browse the repository at this point in the history
  • Loading branch information
trobro authored Jul 23, 2022
1 parent ef94b56 commit 84d00df
Showing 1 changed file with 80 additions and 3 deletions.
83 changes: 80 additions & 3 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,30 @@ import (
"testing"
)

func marshalUnmarshalExpected(
t *testing.T,
expectedHjson string,
expectedDst,
src,
dst interface{},
) {
buf, err := Marshal(src)
if err != nil {
t.Error(err)
}
if string(buf) != expectedHjson {
t.Errorf("Expected:\n%s\nGot:\n%s\n\n", expectedHjson, string(buf))
}

err = Unmarshal(buf, dst)
if err != nil {
t.Error(err)
}
if !reflect.DeepEqual(expectedDst, dst) {
t.Errorf("Expected:\n%#v\nGot:\n%#v\n\n", expectedDst, dst)
}
}

type TestStruct struct {
A int
B uint
Expand Down Expand Up @@ -124,6 +148,59 @@ func checkMissing(t *testing.T, m map[string]interface{}, key string) {
}
}

func TestEmptyMapsAndSlices(t *testing.T) {
type S2 struct {
S2Field int
}

type S1 struct {
MapNil map[string]interface{}
MapEmpty map[string]interface{}
IntSliceNil []int
IntSliceEmpty []int
S2Pointer *S2
}
ts := S1{
MapEmpty: map[string]interface{}{},
IntSliceEmpty: []int{},
}

ts2 := map[string]interface{}{
"MapNil": map[string]interface{}{},
"MapEmpty": map[string]interface{}{},
"IntSliceNil": []interface{}{},
"IntSliceEmpty": []interface{}{},
"S2Pointer": nil,
}

ds2 := map[string]interface{}{}

marshalUnmarshalExpected(t, `{
MapNil: {}
MapEmpty: {}
IntSliceNil: []
IntSliceEmpty: []
S2Pointer: null
}`, &ts2, &ts, &ds2)

ts3 := map[string]interface{}{
"MapNil": ts.MapNil,
"MapEmpty": ts.MapEmpty,
"IntSliceNil": ts.IntSliceNil,
"IntSliceEmpty": ts.IntSliceEmpty,
"S2Pointer": ts.S2Pointer,
}
ds3 := map[string]interface{}{}

marshalUnmarshalExpected(t, `{
IntSliceEmpty: []
IntSliceNil: []
MapEmpty: {}
MapNil: {}
S2Pointer: null
}`, &ts2, &ts3, &ds3)
}

type TestMarshalStruct struct {
TestStruct
}
Expand Down Expand Up @@ -151,9 +228,9 @@ func TestEncodeMarshal(t *testing.T) {
}

func TestEncodeSliceOfPtrOfPtrOfString(t *testing.T) {
s:="1"
s1:=&s
input:=[]**string{&s1}
s := "1"
s1 := &s
input := []**string{&s1}
buf, err := Marshal(input)
if err != nil {
t.Error(err)
Expand Down

0 comments on commit 84d00df

Please sign in to comment.